Skip to content

[Improve][Zeta] Isolate coordinator admission from job lifecycle execution - #12265

Open
jjj-n wants to merge 12 commits into
apache:devfrom
jjj-n:codex/issue-12117-coordinator-lifecycle
Open

jjj-n wants to merge 12 commits into
apache:devfrom
jjj-n:codex/issue-12117-coordinator-lifecycle

Conversation

@jjj-n

@jjj-n jjj-n commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Purpose of this pull request

Separate coordinator admission from job lifecycle execution as the first slice of #12117.

JobMaster.run() waits for the job to finish, and completion/control paths can submit more work and wait for it. They currently share the executor used to initialize new submissions. This change gives lifecycle work its own cached executor and the permanent pending-job scheduler its own single-thread executor, so admission saturation does not prevent existing jobs from completing, being canceled, taking checkpoints/savepoints, or recovering after master reactivation.

Both newly submitted and restored JobMasters receive the lifecycle executor. Job lifetime waiting, connector-JAR cleanup, and exceptional completion retain their existing ordering. The running-master entry is removed by instance identity so a late exit cannot remove a replacement master. All three executors are stopped on step-down and recreated before reactivation.

This PR keeps the existing configuration keys and defaults. It does not bound lifecycle threads or eliminate the per-job lifetime waiter. The lifecycle executor deliberately retains an unbounded maximum with direct handoff while nested blocking dependencies remain. A finite admission default and queue/rejection policy are deferred until this slice has merged and its saturation/recovery contract is established. #12165 is out of scope.

Does this PR introduce any user-facing change?

The coordinator core/max settings and existing job_thread_pool_* metrics now apply to admission work. Separate job_lifecycle_thread_pool_* metrics report lifecycle workers without waiting for coordinator activation. Lifecycle/control and recovery work use a separate executor; these settings are not a limit on running jobs or total master threads.

English and Chinese deployment guides, telemetry references, and upgrade notes describe the new scope. Each telemetry reference lists all eight admission metrics and all eight lifecycle metrics emitted by the exporter. No configuration keys, default values, or submission rejection policy are changed.

Review follow-up

CI status and failure diagnosis

Current head 9197c3bc merges dev at deb16a3c into this branch without conflicts. The merge changes only upstream connector tests/code and connector documentation; every file owned by this PR is byte-identical to the previously reviewed ebdf7cbf head. The effective PR diff remains the same 17 files. A new Build for 9197c3bc is pending; it is not counted as passed.

On the preceding ebdf7cbf head, the fork Build did not produce an all-green workflow. In its first attempt, Java 11 engine-v2-it passed, while Java 8 engine-v2-it failed only in CheckpointEnableIT.testZetaStreamingCheckpointInterval after a successful savepoint and restore. SavepointBusySourceBarrierIT passed on Java 8. The Java 8 engine job passed in a single-job rerun, with no reported test failures. The first attempt's PostgreSQL CDC E2E timeout after restore also passed in a single-job rerun. These outcomes suggest intermittent test failures but do not turn the cancelled/failed full workflow into a pass. The new-head Build remains the final CI check.

How was this patch tested?

  • Repository-wide ./mvnw spotless:apply completed successfully on Windows Java 17.
  • The connector-seatunnel-e2e-base dependency reactor installed successfully with tests skipped, so focused tests used artifacts from the synced source.
  • SavepointBusySourceBarrierIT and CoordinatorExecutorMassFailoverStormIT each passed locally on the code-identical ebdf7cbf head: 1 test, 0 failures, 0 errors per class.
  • Four related engine-server test classes ran locally on Java 17 with the required java.base/java.lang opening for environment-variable tests: 74 tests, 0 failures, 0 errors, 4 existing skips.
  • The PR-scope 66-module dependency reactor completed install (including verify) with tests skipped. A broader repository-wide verify was attempted on Windows Java 17: the first run stopped in the UI npm subprocess; the -Dskip.ui=true run was stopped after about one hour while building unrelated connector modules, with no build error observed up to that point. It is not counted as a completed full-repository pass.
  • Repository-wide spotless:apply and git diff --check passed after the latest dev merge; the working tree is clean.

Check list

  • No new JAR dependency.
  • English and Chinese configuration and telemetry documentation updated.
  • Existing configuration keys and defaults retained.
  • Backpressure test strictness retained from dev.
  • Local verification results recorded before submission.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What Problem Does This PR Solve?

  • User pain point: CoordinatorService currently runs both (a) admission of newly-submitted jobs and (b) the actual long-lived lifecycle work for jobs already running — JobMaster.run() blocking until completion, cancellation, checkpoint/savepoint waits, and master-switch restore fan-out — on the same bounded executor (core-thread-num/max-thread-num). When that shared pool saturates (many jobs submitted, or a mass-failover restore fanning out many JobMaster.run() calls at once, each of which blocks its thread for the job's entire lifetime), new admissions, cancels, savepoints, and restores can all stall or deadlock behind each other on the same limited thread budget.
  • Fix approach: Split the single executorService into three: the existing bounded executorService now handles admission only (new-job initialization + enqueue), a new unbounded cached lifecycleExecutor handles job execution/cancellation/checkpoint/savepoint/restore work, and a new dedicated single-thread pendingJobSchedulerExecutor runs the permanent pending-job scheduler loop (previously it shared a thread from the admission pool too). Config keys/defaults are unchanged; docs and an incompatible-changes entry explain the new semantics.
  • One-sentence summary: A real, source-verified concurrency-isolation improvement whose underlying design is sound and whose new saturation tests convincingly prove the fix — but the PR as submitted breaks at least one pre-existing E2E test that encodes the old single-pool assumption, and I found two more engine-level test failures and a flaky new Windows test on the same CI run that must be resolved before merge.

1. Code Change Review

1.1 Core Logic Analysis

Files/methods changed:

  • seatunnel-engine/seatunnel-engine-server/.../CoordinatorService.java: new fields lifecycleExecutor, pendingJobSchedulerExecutor; new factory methods createLifecycleExecutor(), createPendingJobSchedulerExecutor(); every call site that previously ran job-execution/cancel/checkpoint/savepoint/restore work on executorService now uses lifecycleExecutor; startPendingJobScheduleThread() now submits to pendingJobSchedulerExecutor; checkNewActiveMaster() recreates all three executors on reactivation; clearCoordinatorService() shuts down and awaits all three; runningJobMasterMap.remove(jobId) → runningJobMasterMap.remove(jobId, jobMaster) (identity-based removal).
  • New test files: CoordinatorServiceAdmissionSaturationTest.java (new, real-cluster integration test) and additions to CoordinatorServiceTest.java (mock-based unit tests).
  • Docs: hybrid-cluster-deployment.md / separated-cluster-deployment.md (en/zh) and incompatible-changes.md (en/zh).

Before / after (the core wiring change, CoordinatorService.java):

// before: job lifecycle execution ran on the same bounded pool as admission
MDCExecutorService mdcExecutorService = MDCTracer.tracing(jobId, executorService);
mdcExecutorService.submit(() -> { ... jobMaster.run(); ... runningJobMasterMap.remove(jobId); ... });

// after: lifecycle work moves to its own unbounded pool; admission executor is untouched by it
MDCExecutorService mdcExecutorService = MDCTracer.tracing(jobId, lifecycleExecutor);
mdcExecutorService.submit(() -> { ... jobMaster.run(); ... runningJobMasterMap.remove(jobId, jobMaster); ... });

Key findings:

  1. I traced every call site and confirmed the wiring is complete and consistent. Both new JobMaster(...) construction sites (submitJob at CoordinatorService.java:1459 and restoreJobFromMasterActiveSwitch at CoordinatorService.java:1157) now pass MDCTracer.tracing(jobId, lifecycleExecutor) as the JobMaster's own executor. I fetched JobMaster.java and confirmed its constructor stores this as this.executorService, which is then handed into PlanUtils.fromLogicalDAG(...) (physical-plan construction) and into new CheckpointManager(...) — so checkpoint coordination and physical-plan task submission for a running job now correctly run off the admission pool, not competing with new-job admission. submitJob's own outer initialization task (dedup check, deserialize, validate, construct JobMaster, enqueue to pendingJobQueue) deliberately still runs on the admission executorService — consistent with the stated design ("admission = init + enqueue only"), and I confirmed that task does not block on job completion, so it cannot itself be starved by long-running jobs.
  2. The runningJobMasterMap.remove(jobId, jobMaster) change is a genuine, valuable side-fix, not merely mechanical churn: the PR body's own Javadoc (checkNewActiveMaster, CoordinatorService.java:1257-1267) documents a related epoch race, and the identity-based removal specifically prevents a delayed/late-exiting lifecycle task from evicting a different JobMaster instance that has since replaced it in the map after a master reactivation — a real latent race in the old single-arg remove(jobId). I traced this against the new testLateLifecycleExitDoesNotRemoveReplacementMaster test, which exercises exactly this scenario and passes.
  3. Real scenario covered: the new CoordinatorServiceAdmissionSaturationTest deliberately saturates a real single-threaded admission pool (core=1, max=1) with a permanently blocked task, then proves (against a real Hazelcast cluster, not mocks) that an already-running job can still checkpoint, savepoint, get cancelled, and be found via waitForJobComplete after removal from the running-map — this is precisely the failure mode the PR claims to fix, and it is a meaningful, non-trivial regression test, not a token unit test.
  4. This is a precise, well-targeted fix for the specific problem statement (admission saturation blocking lifecycle progress) rather than a broad refactor — the PR explicitly and honestly scopes out a related, harder problem (bounding the now-unbounded lifecycle executor and giving it a queue/rejection policy), deferring it to a future slice (#12165). I agree that scoping decision is reasonable for reviewability, but see Issue 3 below on the resulting observability/capacity-semantics gap it creates.
  5. Blind spot found in review (not disclosed by the author): at least one pre-existing E2E test's assertions directly encode the old single-pool behavior and are not updated by this PR — see Issue 1, which I verified is a real, deterministic (not flaky) CI failure directly caused by this change, not a coincidental environmental flake.

In-depth correctness analysis: The separation takes effect for every job once CoordinatorService is constructed (lifecycleExecutor/pendingJobSchedulerExecutor are created unconditionally in the constructor alongside executorService, CoordinatorService.java:263-265), so this is not opt-in — every job submission, restore, cancel, savepoint, and checkpoint-triggered task on every cluster running this code is affected, not just a boundary/recovery-only path. The one thing that does not change is the admission executor's own capacity semantics under normal (non-restore, non-cancel, non-checkpoint) load — admission remains bounded exactly as before. The change is fully in effect on both fresh master activation and reactivation after failover (checkNewActiveMaster rebuilds all three executors identically on both paths, CoordinatorService.java:1274-1282), and clearCoordinatorService correctly tears down and awaits all three on step-down (CoordinatorService.java:1346-1353), both synchronized on the same monitor so there's no activation/step-down race.

Complete runtime path (this PR touches seatunnel-engine, master-switch recovery, and checkpoint-adjacent wiring, so a full path is required per Section 6):

Job admission
  -> CoordinatorService.submitJob(jobId, ...) [L1414]
      -> mdcExecutorService = MDCTracer.tracing(jobId, executorService)   // ADMISSION pool (bounded)
      -> mdcExecutorService.submit(() -> {
             deserialize + validate + new JobMaster(..., MDCTracer.tracing(jobId, lifecycleExecutor), ...)
             jobMaster.init(...); pendingJobQueue.put(pendingJobInfo); jobSubmitFuture.complete(null);
         })   // this task never blocks on job completion -> admission pool cannot be starved by it

Pending-job scheduling (dedicated single thread, was previously sharing admission pool)
  -> pendingJobSchedulerExecutor.submit(pendingJobScheduleTask) [L353]
      -> pendingJobSchedule(scheduleEpoch) [L454] dequeues once resources are available
          -> runningJobMasterMap.put(jobId, jobMaster)
          -> MDCTracer.tracing(jobId, lifecycleExecutor).submit(() -> {
                 jobMaster.run();                                    // LIFECYCLE pool (unbounded), blocks for job's life
                 // internally: PlanUtils.fromLogicalDAG(..., executorService=lifecycleExecutor, ...)
                 //             new CheckpointManager(..., executorService=lifecycleExecutor, ...)
                 if (jobMasterCompletedSuccessfully(...)) runningJobMasterMap.remove(jobId, jobMaster);  // identity-safe
             })

Master-switch restore (failover / reactivation)
  -> checkNewActiveMaster() [synchronized, L1269]
      -> recreate executorService/lifecycleExecutor/pendingJobSchedulerExecutor if shut down
      -> initCoordinatorService() -> restoreAllRunningJobFromMasterNodeSwitchFuture =
             CompletableFuture.runAsync(this::restoreAllRunningJobFromMasterNodeSwitch, lifecycleExecutor) [L680]
      -> restoreAllRunningJobFromMasterNodeSwitch() fans out one lifecycleExecutor task per restored job [L1102]
         -- BEFORE this PR: this fan-out ran on the same bounded admission executorService, which is exactly
            what the pre-existing CoordinatorExecutorMassFailoverStormIT test asserts grows past core-pool-size
            during a 30-job mass restore -- see Issue 1, this assertion is now false because the fan-out moved.

Step-down
  -> clearCoordinatorService() [synchronized, L1315]
      -> interrupt all JobMaster instances (running + pending)
      -> pendingJobSchedulerExecutor.shutdownNow(); executorService.shutdownNow(); lifecycleExecutor.shutdownNow();
      -> awaitExecutorTermination(...) x3, each up to 20s

1.2 Compatibility Impact

Partially incompatible, and correctly disclosed as such in the PR:

  • Configuration keys and defaults (core-thread-num, max-thread-num) are unchanged, and I confirmed the author is accurate that they now govern admission only.
  • Real behavioral/semantic change: an operator who previously set a finite max-thread-num specifically to cap the number of concurrently running jobs (which the old docs literally described as "The max job count can be executed at same time") loses that capacity control silently in terms of behavior — running jobs now execute on the new lifecycleExecutor, which is an unbounded Executors.newCachedThreadPool() with no config knob at all in this PR.
  • This is properly documented: docs/en/introduction/concepts/incompatible-changes.md and its zh counterpart both call this out explicitly ("If you configured a finite max-thread-num, it no longer constrains lifecycle workers... Review master capacity and thread monitoring before upgrading"), and the deployment docs (en/zh, both cluster-topology pages) are updated consistently between languages with matching content — I checked both language versions side by side and they say the same thing.
  • I'd still flag one gap in the migration guidance itself as Issue 3 below (loss of an equivalent metric for the now-unbounded pool), which is a real operational risk for exactly the class of operator this incompatible-changes entry is trying to warn.

1.3 Performance / Side-Effect Analysis

  • CPU/Memory: lifecycleExecutor is an unbounded newCachedThreadPool, so in the worst case it creates one OS thread per concurrently running job (since jobMaster.run() blocks its lifecycle-pool thread for the job's full duration) plus whatever transient threads its internal checkpoint/physical-plan submissions need. I want to be precise about the actual severity here: this is not a new class of risk introduced by this PR — the previous executorService had the exact same default max-thread-num = Integer.MAX_VALUE (confirmed in CoordinatorService.createCoordinatorExecutor(), unchanged by this diff), so a default-configuration cluster already had effectively unbounded thread growth for concurrently running jobs before this PR. What changes is that an operator who had configured a finite cap to bound this specific risk loses that lever (see 1.2). At genuinely extreme concurrent-job counts (thousands of simultaneously running streaming jobs), unbounded native-thread creation on either the old or the new design risks OutOfMemoryError: unable to create new native thread — this is a pre-existing architectural characteristic of the coordinator that this PR does not introduce, but also does not close off, consistent with the PR's own admitted scope boundary (deferred to #12165).
  • Networking / lock contention: No new RPC calls; synchronized usage on checkNewActiveMaster/clearCoordinatorService is unchanged in kind (already synchronized before this PR), just now guarding three executors instead of one.
  • Retries/idempotency: No retry-policy change. Shutdown ordering in clearCoordinatorService (pendingJobSchedulerExecutor → executorService → lifecycleExecutor, each shutdownNow() then later awaited) is reasonable — shutdownNow() interrupts in-flight tasks and stops accepting new ones immediately for each pool in turn, and the JobMaster interrupt loop runs before any executor shutdown, so lifecycle tasks should already be responding to interruption by the time their executor is torn down.
  • Resource release: all three executors are correctly shut down and awaited (with a bounded 20s wait and a warning log on timeout) in clearCoordinatorService, matching the pre-existing pattern for the original executorService. Recreation-on-reactivation guards against reusing a shut-down pool (checkNewActiveMaster, CoordinatorService.java:1274-1282) — I did note the lifecycleExecutor/pendingJobSchedulerExecutor recreation checks only test isShutdown() while the pre-existing executorService check also tests isTerminated(); since isShutdown() becomes true at the start of shutdownNow() (a strict superset condition reached no later than isTerminated()), this inconsistency is stylistic only and not a functional gap — Low severity, non-blocking.

1.4 Error Handling and Logging

  • awaitExecutorTermination(name, executor) (new helper, CoordinatorService.java:1369-1379) correctly logs a warning on timeout and preserves interrupt status (Thread.currentThread().interrupt()) on InterruptedException, consistent with the pre-existing single-executor version it replaces — good, no regression here, and it removes the previous duplication between the (formerly single) shutdown block by generalizing it into a shared helper reused three times.
  • No exception is newly swallowed and no success is falsely reported; submitJob's admission-pool task still propagates failures through jobSubmitFuture.completeExceptionally(...) exactly as before, unaffected by this change.
  • The docs/incompatible-changes entries do not overstate or understate the change — they're appropriately specific about what is and isn't still bounded, which I verified matches my own source-level analysis.

2. Code Quality Assessment

2.1 Coding Standards

Generally good. The two new factory methods (createLifecycleExecutor, createPendingJobSchedulerExecutor) and the new fields carry short, useful inline comments explaining why each pool exists and why the lifecycle pool is deliberately left unbounded for now (CoordinatorService.java:161-166) — this is exactly the kind of "explain why, not what" comment the project's conventions call for. The checkNewActiveMaster Javadoc addition (documenting the epoch race it guards against) is a genuinely useful piece of institutional-knowledge documentation that will help the next person who touches this method. No missing-comment issues found on the new/changed core methods or fields.

2.2 Test Coverage and Test Stability

Coverage: Good intent and design — CoordinatorServiceAdmissionSaturationTest is a real, non-mocked saturation test exercising checkpoint/savepoint/cancel/restore-after-reactivation while the admission pool is deliberately starved, which is exactly the scenario this PR claims to fix, and the author's negative control (routing savePoint() back to the saturated admission executor to prove the old code would fail) is a genuinely convincing piece of evidence that I'd commend. However, coverage has a real gap: no pre-existing test that encodes assumptions about which executor performs restore fan-out or thread-pool metrics was updated, and I found that gap manifests as an actual CI failure (Issue 1).

Mandatory stability analysis (Section 5.10.2), since this PR changes both production concurrency wiring and adds substantial new UT/E2E code:

I pulled the actual CI run from the contributor's fork for this exact head commit (1b1cb94aff4f20b1cc2c921e0c6ffddce44a0b76) rather than relying on the PR description's own "69 tests passed" claim, and found the picture is materially different from what's described:

  • unit-test (8, windows-latest): FAIL
  • unit-test (11, windows-latest): FAIL
  • unit-test (8, ubuntu-latest) / unit-test (11, ubuntu-latest): pass
  • engine-v2-it (8, ubuntu-latest) / engine-v2-it (11, ubuntu-latest): FAIL (both JDKs)
  • all-connectors-it-2 (8, ubuntu-latest): FAIL, but this is CouchbaseIT — a known, unrelated, pre-existing environmental flake (documented container-bootstrap breakage on ubuntu-latest, unrelated to this PR's diff).

a) Assertion-risk / timing analysis on the failures I traced:

  • CoordinatorExecutorMassFailoverStormIT.testCoordinatorExecutorGrowsPastCoreDuringMassFailoverRestore (pre-existing test, not modified by this PR) fails deterministically with: Expected the mass-failover restore of 30 concurrent jobs to push the shared coordinator executor past its configured core pool size (observed core=10, peak=0)... expected: <true> but was: <false>. This is not flaky — it is a direct, logical consequence of this PR's own design: restore fan-out (restoreAllRunningJobFromMasterNodeSwitch) now runs on lifecycleExecutor, so the admission executorService this test inspects via getThreadPoolStatusMetrics() correctly stays completely idle (activeCount=0, poolSize=0) during a mass restore — which is precisely the isolation this PR is trying to achieve. The test's own premise is now obsolete, and it will fail every time, deterministically, not intermittently.
  • CoordinatorServiceAdmissionSaturationTest.testCheckpointSavepointAndTerminalHistoryWhileAdmissionIsSaturated and testRestoreAndCompletionAfterReactivationWithSaturatedAdmission (both new tests added by this PR) time out on windows-latest waiting up to 60s for the job to reach RUNNING, with an accompanying task group ... not found warning in the log — this looks like a real Hazelcast/engine job-startup slowness on Windows CI rather than a logic bug in the new saturation-blocking mechanism itself (the timeout fires before the interesting saturation assertions are even reached), consistent with previously-observed Windows-CI engine-startup flakiness in this repository, but it is still a new test that is not currently green on the full CI matrix.
  • I did not have time within this review to fully root-cause CheckpointCoordinatorFailoverIT.testStreamJobFailsAfterCheckpointTriggerDispatchFailure (fails asserting CHECKPOINT_INSIDE_ERROR attribution but gets a different CheckpointException message) beyond confirming it is checkpoint/coordinator-adjacent and therefore plausibly sensitive to this PR's change in which executor drives checkpoint-triggered callbacks — I'm flagging it as needing the author's/a maintainer's explicit investigation rather than asserting a root cause I haven't fully verified.

b) Flaky-anti-pattern check on the new tests: Both new test files are well-constructed by the project's usual standards — they use Awaitility.await().atMost(N, TimeUnit.SECONDS).until(...) throughout rather than fixed sleeps, CountDownLatch-based deterministic blocking (AdmissionBlock) rather than timing guesses, and proper finally-block cleanup (coordinator.cancelJob(...)/coordinator.shutdown()). I don't see Thread.sleep misuse, hard-coded ports, shared static state, or order-dependent assertions in the new code itself. The Windows timeout above looks environmental rather than a design flaw in the new tests, but I can't fully rule out interaction with the PR's own threading change without a clean re-run.

c) Stability rating: High risk, and this is promoted to Issue 1/Issue 2 below as blockers — not because the new test code itself is poorly written (it's actually good), but because (1) a pre-existing, unmodified E2E test now fails deterministically as a direct logical consequence of this PR's design and must be updated or removed as part of this PR, and (2) the new saturation test is not currently passing on the full CI matrix (Windows) and needs investigation, per Section 5.10.2's explicit prohibition on letting a flaky/failing test pass review just because coverage intent is good.

2.3 Documentation Updates

Both docs/en and docs/zh are updated, and I compared them line-by-line for consistency — the English and Chinese hybrid-cluster-deployment.md, separated-cluster-deployment.md, and incompatible-changes.md pages all convey the same content (admission-only scope of core-thread-num/max-thread-num, the new unbounded lifecycle pool, and the metrics caveat). This is exactly the kind of bilingual-consistency check the project requires, and it passes.

4. Issue Summary

# Issue Location Severity
1 Pre-existing E2E test CoordinatorExecutorMassFailoverStormIT now fails deterministically because restore fan-out moved off the pool it inspects seatunnel-e2e (test not touched by this diff; verified via fork CI log for head 1b1cb94a) High
2 New CoordinatorServiceAdmissionSaturationTest is not green on the full CI matrix (2 of 3 tests time out on windows-latest) CoordinatorServiceAdmissionSaturationTest.java (new); fork CI job unit-test (8/11, windows-latest) High
3 No metric equivalent is exposed for the new unbounded lifecycleExecutor; getThreadPoolStatusMetrics() still only reports the admission pool, which the docs now say is the wrong thing to watch for overall thread usage CoordinatorService.java:2293-2308; incompatible-changes.md Medium
4 CheckpointCoordinatorFailoverIT.testStreamJobFailsAfterCheckpointTriggerDispatchFailure fails on this head; root cause not fully confirmed within this review seatunnel-e2e (test not touched by this diff); fork CI job engine-v2-it (8/11, ubuntu-latest) Medium
5 Reactivation-recreate check for lifecycleExecutor/pendingJobSchedulerExecutor tests only isShutdown(), inconsistent with the pre-existing executorService check that also tests isTerminated() CoordinatorService.java:1277-1282 Low

Issue 1 detail:

  • Problem description: CoordinatorExecutorMassFailoverStormIT.testCoordinatorExecutorGrowsPastCoreDuringMassFailoverRestore asserts that a 30-job mass-failover restore pushes the (admission) coordinator executor's pool size past core=10. I confirmed this test is not part of this PR's diff, yet it fails on this PR's head with observed core=10, peak=0 — the admission pool it inspects is now completely untouched by restore fan-out, which moved to lifecycleExecutor by design.
  • Potential risk: This is a deterministic failure, not a flake — merging this PR without addressing it would permanently break this E2E test on dev, and worse, it signals that the test's encoded expectation about how mass-failover restore consumes threads is stale and could mask a real future regression in restore fan-out behavior if left un-migrated.
  • Best improvement: Update this test's assertion to inspect lifecycleExecutor's activity during mass restore instead of (or in addition to) the admission executor's — this likely requires exposing a way to observe the lifecycle pool (which ties directly into Issue 3), or at minimum exposing a package-private/test-visible accessor. This test should almost certainly be renamed or re-scoped since "coordinator executor" no longer unambiguously means "the pool that does restore work."
  • Severity: High.
  • Raised by another reviewer: No — I found this independently by pulling and reading the actual fork CI run for this PR's head commit rather than trusting the PR description's test-result summary.

Issue 3 detail:

  • Problem description: getThreadPoolStatusMetrics() (CoordinatorService.java:2293-2308) still reports activeCount/poolSize/queueTaskSize/rejectionCount only for the admission executorService. Post-PR, this metric no longer reflects "how many jobs are effectively occupying coordinator threads" (which is what operators most likely built dashboards/alerts around, given the pre-existing docs literally said max-thread-num was "the max job count can be executed at same time") — it now reflects only transient admission activity, which the incompatible-changes doc correctly warns will look artificially idle.
  • Potential risk: An operator monitoring this metric to gauge coordinator load will see a misleadingly low/idle signal even when hundreds of jobs are genuinely running and consuming lifecycleExecutor threads, right at the moment (mass restore, high job churn) when visibility matters most. The docs tell the operator to fall back to "JVM/process thread metrics," which is a real but much blunter substitute (can't distinguish coordinator lifecycle threads from everything else in the JVM).
  • Best improvement: Option A: extend getThreadPoolStatusMetrics() (or add a sibling method) to also report lifecycleExecutor's ThreadPoolExecutor-style stats — this requires changing lifecycleExecutor's type from a plain ExecutorService (Executors.newCachedThreadPool() return type) to something that exposes pool-size introspection, e.g. constructing it as an explicit ThreadPoolExecutor with Integer.MAX_VALUE max and a SynchronousQueue, matching what newCachedThreadPool() already does internally, just declared as ThreadPoolExecutor instead of the ExecutorService interface. Option B (smaller, could ship in this PR or immediately after): at minimum, log the lifecycleExecutor's approximate size periodically or expose it via an existing metrics/telemetry hook, so operators aren't left with zero visibility into the pool that now does all the actual work.
  • Severity: Medium (does not block correctness, but is a real, foreseeable operational gap directly created by this PR's own architecture change, and ties directly into fixing Issue 1's test).
  • Raised by another reviewer: No.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed

    • Issue 1 (High): update or re-scope CoordinatorExecutorMassFailoverStormIT so it reflects the new admission/lifecycle split instead of asserting a now-false premise about the admission pool.
    • Issue 2 (High): get CoordinatorServiceAdmissionSaturationTest green on the full CI matrix, including windows-latest — either fix the underlying startup-timing sensitivity or confirm (with evidence, not assumption) that the Windows timeout is a pre-existing, unrelated environmental flake and handle it the same way the project already handles other known Windows flakes.
    • Issue 4 (Medium, but I'm listing it as a blocker pending investigation): confirm whether CheckpointCoordinatorFailoverIT.testStreamJobFailsAfterCheckpointTriggerDispatchFailure's failure on this head is caused by this PR's executor change or is an unrelated pre-existing flake — I was not able to fully confirm either way within this review, and given it's checkpoint/coordinator-adjacent, it should not be waved through without that confirmation.
  2. Recommended fixes — non-blocking

    • Issue 3 (Medium): add (or explicitly plan, in a fast-follow) a metrics equivalent for lifecycleExecutor, since the current metrics gap is a foreseeable operational blind spot directly caused by this PR, even though it doesn't affect correctness.
    • Issue 5 (Low): align the isShutdown()/isTerminated() recreation checks across all three executors for consistency; not a functional bug.

Overall assessment: I want to be clear that the core engineering idea here is good and, as far as I traced it, correctly implemented — the admission/lifecycle separation is exactly the right fix for the saturation-blocks-everything problem it describes, the identity-based runningJobMasterMap removal is a genuine bonus correctness fix, and the new saturation test's negative control is a convincing piece of evidence that the old code really did have this problem. My concern is entirely about CI truthfulness: the PR description states "69 selected regression tests passed with no failures or skips" and "Final -q -DskipTests verify passed," but the actual CI run on this exact head commit shows real, non-environmental failures, including one deterministic failure directly caused by this PR's own design change to a test that ships with the repository today. Per this project's review standard, a PR is not ready to merge on the strength of local/selected test runs when the full CI matrix on the same head shows real, unaddressed failures — please reconcile the pre-existing CoordinatorExecutorMassFailoverStormIT expectations with the new design, get the new Windows-run tests green (or conclusively show they're pre-existing flakiness), and confirm the CheckpointCoordinatorFailoverIT failure's relationship (or lack thereof) to this change. I'd be glad to take another pass as soon as those are addressed — I don't expect this to require touching the core design, just reconciling the test suite with it.

@github-actions github-actions Bot added the e2e label Sep 18, 2026

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

Sorry for the delay getting back to this — and thank you for the thorough, evidence-based response to the last round. I re-verified every claim against the actual diff on this head rather than taking the commit message at face value, and I'm glad to report all three blockers from my previous review check out.

What Problem Does This PR Solve?

  • User pain point: CoordinatorService ran both new-job admission and long-lived job lifecycle work (JobMaster.run(), cancel, checkpoint/savepoint waits, master-switch restore fan-out) on the same bounded executor. When that shared pool saturated, admissions/cancels/savepoints/restores could all stall behind each other.
  • Fix approach: unchanged from my last review — admission stays on the existing bounded executorService, lifecycle work moves to a new unbounded lifecycleExecutor, and the pending-job scheduler loop gets its own dedicated single thread (pendingJobSchedulerExecutor).
  • One-sentence summary: The core design was already sound last round; this update replaces every piece of evidence I previously found missing — the stale E2E assertion, the Windows-flaky saturation test, and the unconfirmed checkpoint-failover failure — with concrete, verifiable fixes, and adds a real (if narrow and previously undisclosed) production bug fix along the way that still needs a test before merge.

1. Code Change Review

1.1 Core Logic Analysis

What changed since my last review (I diffed 1b1cb94af → current head 4a5fbc946, not just re-reading the whole PR, to see exactly what the response commit touched):

  1. CoordinatorService.java:308-319 — createLifecycleExecutor() now builds an explicit new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60s, SynchronousQueue, ..., RejectionCountingHandler) instead of Executors.newCachedThreadPool(...). Functionally equivalent pool shape, but now wired with the same RejectionCountingHandler the admission pool uses, which is what makes getLifecycleThreadPoolStatusMetrics() (CoordinatorService.java:2315) able to report a real rejection count for this pool too. I confirmed RejectionCountingHandler extends ThreadPoolExecutor.AbortPolicy and still delegates to super.rejectedExecution(...) after counting (telemetry/metrics/entity/ThreadPoolStatus.java:38-46), so this is purely additive instrumentation, not a behavior change.
  2. CoordinatorService.java:1286-1291 — reactivation now checks isShutdown() || isTerminated() for lifecycleExecutor and pendingJobSchedulerExecutor too, consistent with the pre-existing executorService check. This is exactly my old Issue 5 (Low) — resolved.
  3. CoordinatorService.java:906-913 — new, not discussed in the PR description: processPendingJobCleanup previously just returned when isCleanupDelayElapsed(record) was false, permanently dropping that job's cleanup record since the delayed task was a one-shot ScheduledExecutorService.schedule(...) call and nothing else re-triggers cleanup for that job id. The fix now calls schedulePendingJobCleanup(jobId, record) again to reschedule the remaining delay instead of dropping it. I traced this: I confirmed this exact defect (silent drop, no reschedule) already existed on dev before this PR (verified against c7304ace6:CoordinatorService.java), so it is a pre-existing, unrelated bug, not something this PR's executor split introduced. It's a real fix — a scheduler firing even a few ms early relative to System.currentTimeMillis() (clock skew, NTP step, or nanoTime/currentTimeMillis conversion slop inside ScheduledThreadPoolExecutor) would previously leak that job's entry in pendingJobCleanupIMap forever. See Issue 3 below — this needs disclosure and a test before merge, it's currently silent and untested.
  4. Test/doc changes address my three blockers directly — details below.

Verifying Issue 1 is fixed (CoordinatorExecutorMassFailoverStormIT, seatunnel-e2e/.../CoordinatorExecutorMassFailoverStormIT.java): the test is rewritten, not patched around. It now calls awaitAllJobsInStatus(engineClient, jobIds, JobStatus.RUNNING, 180) before sampling (previously sampling raced the restore burst in a tight 20s loop right after failover), then asserts lifecycle.getActiveCount() >= CONCURRENT_JOB_COUNT and, critically, admission.getTaskCount() == 0. I want to call out that this is actually a more deterministic test than the original, not just a fixed one: ThreadPoolExecutor.getTaskCount() is a monotonically-increasing, synchronous JVM counter, so asserting it's 0 well after the restore burst is exactly as strong a proof that admission was never touched as sampling during the burst would have been — there's no race window being papered over here.

Verifying Issue 2 is fixed (Windows flake, CoordinatorServiceAdmissionSaturationTest.java): the fix is config.getEngineConfig().getCheckpointConfig().getStorage().setStorage("localfile") backed by @TempDir (previously the default checkpoint storage was used). This is a plausible and well-targeted root cause for a Windows-only timeout — the default Hadoop-backed checkpoint storage path is a known source of native-dependency slowness/hangs on windows-latest runners (consistent with the task group ... not found warning I saw in the original failing run), and switching to plain local-file storage removes that dependency entirely rather than just widening a timeout.

Verifying Issue 4 is fixed (CheckpointCoordinatorFailoverIT.testStreamJobFailsAfterCheckpointTriggerDispatchFailure): this is the strongest fix of the three. The old test removed the pipeline's ownedSlotProfilesIMap entry as soon as the checkpoint-id counter reached 2, with no synchronization against the coordinator's own trigger cycle — so the removal could land during an in-flight checkpoint (pendingCounter > 0) instead of between checkpoints, hitting a different error path (completion-notification failure) than the one the test claims to exercise (barrier-dispatch lookup failure). The fix uses ReflectionUtils to grab the coordinator's own lock and pendingCounter fields and performs the fault injection inside synchronized (triggerLock) only once pendingCounter.get() == 0. I checked CheckpointCoordinator.java:800-822 (tryTriggerPendingCheckpoint) and confirmed it synchronizes on that same lock and re-checks pendingCounter.get() > 0 before starting a new checkpoint — so holding the lock while pendingCounter == 0 genuinely guarantees the next trigger attempt is the one that observes the missing IMap entry. This is a real root-cause fix for a racy fault-injection test, not a timeout bump.

Metrics gap (my old Issue 3, Medium) is now fully closed, not just documented: JobThreadPoolStatusExports.java was refactored into a shared addThreadPoolMetrics(...) helper (nice dedup — the original had 7x near-identical blocks) and now emits both job_thread_pool_* (admission, unchanged names) and new job_lifecycle_thread_pool_* metrics. SeaTunnelServer.getLifecycleThreadPoolStatusMetrics() is a thin pass-through. TelemetryCollectorCoordinatorGuardTest.java gained assertions that both metric families are emitted and that collection still doesn't call getCoordinatorService() (i.e., doesn't block on coordinator activation) — good, this preserves the existing "don't block Hazelcast operation threads" guarantee the surrounding test class enforces.

1.2 Compatibility Impact

Unchanged from my last review, and still accurately disclosed: config keys/defaults unchanged, job_thread_pool_* metric names unchanged (semantics narrowed to admission-only), new job_lifecycle_thread_pool_* metrics added. docs/en and docs/zh for incompatible-changes.md, hybrid-cluster-deployment.md, and separated-cluster-deployment.md are all updated and — I compared them side by side again on this head — consistently worded between languages, and now explicitly state the default values (10 / 2147483647) which the previous version didn't. This is a genuine improvement in doc quality over the last round.

One new, undisclosed compatibility-adjacent point: the schedulePendingJobCleanup reschedule fix (Issue 3 below) changes cleanup-record lifecycle behavior for anyone relying on today's (buggy) silent-drop behavior — I can't think of a legitimate reason anyone would depend on a stuck cleanup record, so I don't consider this a compatibility blocker, just something that should be called out in the PR description like the rest of the behavior changes are.

1.3 Performance / Side-Effect Analysis

No new concerns beyond what I already noted last round (lifecycle executor is unbounded by design, deferred to #12165, consistent with the old executorService's existing default of max-thread-num = Integer.MAX_VALUE). The RejectionCountingHandler swap for lifecycleExecutor (1.1 above) adds one AtomicLong.incrementAndGet() on the rejection path only — negligible, and rejection is not structurally reachable today since max is unbounded.

The schedulePendingJobCleanup reschedule fix adds a bounded, self-limiting retry: on each early-fire it reschedules for Math.max(0, createTime + delay - now), which will be at or near zero on the very next attempt, so this cannot spin or busy-loop — worst case it's a handful of near-instant re-schedules, not a tight loop.

1.4 Error Handling and Logging

No regressions. The rescheduled-cleanup path silently retries with no new log line — I'd suggest (non-blocking) a debug-level log on this branch so a real, sustained instance of this (e.g. a genuinely broken clock) would be diagnosable rather than invisible, but I won't block on this alone since it's not a correctness gap.

2. Code Quality Assessment

2.1 Coding Standards

Good, same assessment as last round. The new schedulePendingJobCleanup(jobId, record) reschedule call (CoordinatorService.java:911) has an inline comment explaining why ("executor can run slightly before the wall-clock deadline... preserve the record") which is exactly the right kind of comment — my only ask is for this fix to also be mentioned in the PR description, since right now a future reader of the PR history has no way to know this fix exists or why, only the inline comment in the diff.

2.2 Test Coverage and Test Stability

Coverage of the three blockers I raised: all three now have either a rewritten deterministic test (CoordinatorExecutorMassFailoverStormIT) or a root-cause fix to the test's fault-injection timing (CheckpointCoordinatorFailoverIT) or a root-cause fix to the code path the test exercises (CoordinatorServiceAdmissionSaturationTest storage backend). CoordinatorServiceTest.java also gained real new coverage: testLifecycleAndPendingSchedulerProgressWithSaturatedAdmission, testLateLifecycleExitDoesNotRemoveReplacementMaster, and testReactivationRebuildsAllExecutorsAndPreservesAdmissionSettings — I read all three and they use CountDownLatch/Awaitility/mocked blocking run() throughout, no Thread.sleep polling, no shared static state, no order dependence.

Coverage gap: the schedulePendingJobCleanup reschedule fix (1.1 #3) has zero dedicated test. Nothing in the diff exercises isCleanupDelayElapsed(record) == false and asserts the record survives and is eventually cleaned up. Given this is new, untested, production-code behavior change to a core lifecycle path (job cleanup bookkeeping), and given this project's stated bar of "critical logic changes need a test covering the main path and the key risk," I'm listing this as a blocking issue (Issue 3 below) — it should be a small, self-contained addition (mock/fake clock or a record with a future createTimeMillis, then verify a second schedule call happens and the record is eventually removed), not a redesign.

Mandatory stability analysis (this PR still touches production concurrency wiring and adds/modifies E2E tests): I re-read every new and modified test for anti-patterns — BackpressureSlowSinkIT.java's change (widening a fixed 90s window into a "minimum 90s + progress-based extension up to 3 minutes" loop) does not weaken the assertion (MIN_NEW_COMPLETED_CHECKPOINTS stays at 3); it only gives slower CI runners more time to reach the same bar, using Awaitility-style incremental polling rather than a single long sleep. I did not find this test's failure in the CI runs I inspected from the earlier commit, so I can't independently confirm it was actually flaking — it doesn't look like it was, but the change is harmless and doesn't regress test strictness either way, so I'm not blocking on it, just flagging that it's scope beyond what my last review asked for and should ideally be explained in the PR description too (see Issue 4, Low).

CI status on this exact head: the fork's Build run (https://github.com/jjj-n/seatunnel/actions/runs/35302309118) was still in_progress at review time — I could not pull a completed pass/fail breakdown for 4a5fbc946 the way I did for the previous head. Everything above is a source-level verification that the fixes are logically sound and correctly target the failures I saw last round, not a claim that I've seen this exact head go green. Please make sure the full matrix (including windows-latest) is actually green before merge, and if CoordinatorExecutorMassFailoverStormIT or CheckpointCoordinatorFailoverIT fail again on this head for a different reason, that needs another look.

Stability rating: Stable for the rewritten/fixed tests based on static analysis (no anti-patterns, root-cause fixes rather than timing bumps for 2 of 3), pending final confirmation from a completed CI run.

2.3 Documentation Updates

Both docs/en and docs/zh updated and consistent, now with more detail (explicit defaults) than the version I reviewed last time. No further gaps found.

3. Architectural Soundness

3.1 Elegance of the Solution

Unchanged, still good: three cleanly separated executors, each with a single clear responsibility, and this round's JobThreadPoolStatusExports refactor into a shared addThreadPoolMetrics(...) helper is a nice bonus cleanup (removed ~90 lines of duplication while adding a second metric family).

3.2 Maintainability

Good. The awaitExecutorTermination(name, executor) helper (CoordinatorService.java:1382) continues to reduce duplication across three shutdown paths, and the consistent isShutdown() || isTerminated() checks across all three executors removes a subtle inconsistency a future maintainer could otherwise trip over.

3.3 Extensibility

No change from last round — the design leaves room for a future bounded/queued lifecycle executor (#12165) without further restructuring.

3.4 Historical-Version Compatibility

No checkpoint/savepoint serialization format changes, no protocol changes. The schedulePendingJobCleanup fix only affects an internal IMap bookkeeping record's retry timing, not its schema — no restore/upgrade compatibility concern there either.

4. Issue Summary

# Issue Location Severity Raised by another reviewer
1 schedulePendingJobCleanup reschedule fix has no dedicated test CoordinatorService.java:906-913 Medium No
2 This same fix is undisclosed in the PR description (unrelated pre-existing bug, bundled silently) PR description / CoordinatorService.java:906-913 Low No
3 Rescheduled-cleanup branch has no log line, making a real recurring instance hard to diagnose CoordinatorService.java:908-912 Low No
4 BackpressureSlowSinkIT window-widening change is unexplained scope beyond the three blockers from my last review BackpressureSlowSinkIT.java Low No

(Renumbered from my previous review since Issues 1/2/4 there are now resolved and Issue 5 there is now resolved; this table reflects only what's still open.)

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed

    • Issue 1 (Medium): add a unit test for the schedulePendingJobCleanup early-fire reschedule path (CoordinatorService.java:906-913) — assert that when isCleanupDelayElapsed is false the record is not dropped, a follow-up schedule happens, and the record is eventually cleaned up once the delay truly elapses. This is core lifecycle bookkeeping code with a real (if narrow) leak fixed by this change; it shouldn't ship untested.
  2. Recommended fixes — non-blocking

    • Issue 2 (Low): mention the cleanup-reschedule fix explicitly in the PR description (what the bug was, why it's unrelated to the executor split) so it doesn't read as silent scope creep to a future bisector.
    • Issue 3 (Low): add a debug-level log line on the reschedule branch.
    • Issue 4 (Low): briefly note in the PR description why BackpressureSlowSinkIT's window was widened, if it was observed flaking, or drop the change if it wasn't and isn't needed for this PR's stated goal.
    • Confirm the full CI matrix (especially windows-latest) is green on this exact head before merge, since I could not pull a completed run at review time.

Overall assessment: this is a strong response to my last review — not a single one of the three blockers was papered over with a timeout bump or a @Disabled; CoordinatorExecutorMassFailoverStormIT was rewritten to assert the correct (and more deterministic) new semantics, CheckpointCoordinatorFailoverIT's fault injection was fixed at its actual root cause (a race against the coordinator's own trigger lock), and the Windows saturation-test timeout was fixed by removing a native-dependency-heavy storage backend rather than just waiting longer. The metrics gap I flagged as Medium is now fully closed with real Prometheus metrics and test coverage, and a nice duplication cleanup on the side. The only thing keeping me from a clean approve is that this same commit quietly fixes an unrelated, real, narrow-window pre-existing bug in job-cleanup bookkeeping with zero test coverage and no mention in the PR description — that's a small ask to close out (one test, one description line), not a design concern, and I'd expect to be able to approve on the next pass once it's added. Nice work chasing all three issues down to their actual root causes instead of the easier path of just adjusting thresholds.

@jjj-n

jjj-n commented Sep 20, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the second review. I checked the cleanup branch against the merged dev parent and the remaining CI failures.

The early-fire cleanup rescheduling at processPendingJobCleanup was introduced upstream by #11503, commit ec1b1b8 (September 13). It is already present in this merge's dev parent c7304ac and is unchanged by this PR relative to that parent. It appeared between reviewed heads because 4a5fbc9 merged dev. I agree dedicated coverage would be useful, but it is not a cleanup behavior change introduced by the executor split. Could you reassess that blocking item against the base-to-head diff?

The BackpressureSlowSinkIT change has a local differential result: the original 90-second loop observed only two additional completed checkpoints both with this PR and with only CoordinatorService replaced by the unmodified dev version. Observed checkpoint duration reached 34 seconds despite a 15-second trigger interval, and the old loop did not sample after its final sleep. The revised loop preserves at least 90 seconds of stress, at least three additional checkpoints, zero failed checkpoints and the backpressure metric assertions, with a 180-second upper bound. The final three embedded-engine integration tests passed together (154.707 seconds). This reproduces the completion-count failure; it does not claim to reproduce the earlier CI first-checkpoint timeout.

The completed CI run on 4a5fbc9 is not fully green: https://github.com/jjj-n/seatunnel/actions/runs/35302309118 . All four Java 8/11 Windows/Ubuntu unit-test jobs and both Java 8/11 engine-v2-it jobs passed. Remaining failed jobs:

  • all-connectors-it-2 / Java 8: Maven Central timed out downloading hadoop-common:3.3.4 before connector-cdc-mongodb-e2e dependency resolution completed (job 105468814056).
  • all-connectors-it-1 / Java 8 and 11: NebulaGraphIT.startUp:109 fails at adminPool.init after the graph client cannot ping the server, before connector job execution (jobs 105468814101 and 105468814191).
  • rocketmq-connector-it / Java 11: 87 tests, 14 failures and 29 errors; logs show missing topic routes, including failures in producer data generation and across Flink/Spark/Zeta executions (job 105468814771). This points to shared broker/topic setup rather than establishing an executor regression, but I am not treating it as a confirmed harmless flake or claiming the full matrix passes.

I am rerunning the failed/cancelled checks on the same head to distinguish transient failures from repeatable setup problems. The PR remains draft while those results are pending.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks a lot for the update, @jjj-n, and for the very detailed validation notes and the explanation of the cleanup branch. The new commit 49e09cbf (the early-cleanup rescheduling test) is a clean, deterministic test, and the executor split itself still reads well. I re-read the whole PR from scratch at this head rather than only the new commit, and I need to correct two things from my last round: sorry for missing them earlier. They are marked as carryovers below (Issue 1 and Issue 2). They are small and localized, and I expect to approve quickly once they are settled.

What Problem Does This PR Solve?

  • User pain point: CoordinatorService used one executor for two very different jobs: admitting new submissions (short, bounded work) and running the long-lived job lifecycle (JobMaster.run() blocks for the whole job, plus cancel/savepoint/restore fan-out and the pending-job scheduler loop). If that shared pool is configured with a finite max-thread-num and saturates, cancel, savepoint, completion callbacks and master-switch restore can queue or be rejected behind admission work.
  • Fix approach: executorService keeps only admission (new-job initialization + enqueue); a new cached lifecycleExecutor (core 0, max Integer.MAX_VALUE, SynchronousQueue) carries JobMaster.run(), restore, cancel/stop/savepoint/history lookups and the executor handed to every JobMaster; the pending-job scheduler gets its own single-thread executor. All three are shut down on step-down and recreated on reactivation. runningJobMasterMap.remove(jobId, jobMaster) now removes by identity. Separate job_lifecycle_thread_pool_* metrics are exported.
  • One-sentence summary: A sound and well-tested isolation slice; what remains before merge is one test-strictness point in BackpressureSlowSinkIT and the missing metrics reference docs.
  • Before/after: before, max-thread-num: 10 plus 10 blocked JobMaster.run() threads meant a cancel or savepoint task had no thread to run on; after, the 10 admission threads can all be busy and cancel/savepoint/restore still run on the lifecycle pool.

1. Code Change Review

1.1 Core Logic Analysis

Status of my earlier points (previous review at 4a5fbc94)

Earlier point Status at 49e09cbf Evidence
Medium: early-fire cleanup reschedule has no dedicated test FIXED (test added). Correction: my premise was wrong, see below CoordinatorServiceJobCleanupTest.java:359-444
Low: the reschedule fix is undisclosed in the PR description WITHDRAWN (my mistake) see below
Low: no log line on the reschedule branch WITHDRAWN (branch is not part of this PR's diff) the same branch is present at the merge base (CoordinatorService.java:909-911 at this head)
Low: BackpressureSlowSinkIT window widening is unexplained PARTIALLY: now explained in the description, but on re-verification I judge it a test-strictness change, see Issue 1 BackpressureSlowSinkIT.java:89-92, 202-240

Correction on the cleanup branch: last round I described the processPendingJobCleanup reschedule as a pre-existing defect that this PR fixes silently. That was wrong. I re-checked: the schedulePendingJobCleanup(jobId, record) call in the early-fire branch was introduced by #11503 (ec1b1b8b51a), it is present at the merge base c7304ace6 and at the current dev tip, and git diff dev...head has no hunk in processPendingJobCleanup. So it is not something this PR changes. The added test is still a welcome coverage improvement, and I reviewed it as such: it captures the scheduled callback from a mocked monitor service, fires it before the deadline, asserts the record and all job state survive and a second schedule with 0 < delay <= configured delay is registered, then ages the persisted record past the deadline, fires the retry, and asserts full cleanup with no third schedule (CoordinatorServiceJobCleanupTest.java:359-444). No sleeps, and the mutated monitor service and delay are restored in finally. Nothing in that test needs to change. Sorry for the confusion my earlier wording caused.

Earlier round-1 items (stale mass-failover assertion, Windows checkpoint storage, checkpoint-dispatch fault injection, metrics gap, reactivation isTerminated() check) stay fixed; I re-read them at this head (CoordinatorService.java:1283-1291, JobThreadPoolStatusExports.java, TelemetryCollectorCoordinatorGuardTest.java:191-235).

Changed production logic (re-verified from source at the pinned head)

before: executorService (core-thread-num / max-thread-num, SynchronousQueue)
          <- submitJob init, JobMaster.run(), restore, cancel, savepoint, scheduler loop
after:  executorService            <- submitJob init only                        (CoordinatorService.java:1439)
        lifecycleExecutor          <- JobMaster.run(), restore, cancel/stop/savepoint,
                                      JobMaster's own executor                   (499, 686, 1111, 1170, 1473, 1580, 1593, 1632, 1654)
        pendingJobSchedulerExecutor<- the scheduler loop                         (359)

Key findings:

  • The only remaining executorService submission is the admission task in submitJob (CoordinatorService.java:1439); every other former use was moved (I grepped all uses at the head). JobMaster receives the lifecycle executor in both the submit path (:1473) and the restore path (:1170), so its internal callbacks (physical plan, checkpoint manager) no longer depend on admission capacity.
  • Ordering that matters is preserved: the lifetime wait (jobMaster.run()), connector-JAR cleanup and exceptional completion are unchanged inside the same lambda (:500-522); only the executor and the identity-based map removal changed.
  • Step-down (clearCoordinatorService, :1325-1363) interrupts JobMasters, clears the queue, then shutdownNow() on all three executors before awaiting each; reactivation (checkNewActiveMaster, :1278-1291) recreates any shut-down executor before initCoordinatorService() (which is what starts restore on the lifecycle pool) and before startPendingJobScheduleThread(). A stale scheduler thread from an old epoch can no longer queue behind, or occupy, the new generation's scheduler executor. That is a real improvement over the shared pool.
  • Removing Thread.currentThread().setName("pending-job-schedule-runner") in favor of a named factory is safe: the e2e thread-leak whitelist matches by prefix (SeaTunnelContainer.java:677-679).

Runtime path (normal user path reaches the change):

client submit -> SubmitJobOperation -> CoordinatorService.submitJob
  -> executorService (admission): deserialize, JobMaster ctor(lifecycleExecutor), init, pendingJobQueue.put
  -> pendingJobSchedulerExecutor: pendingJobSchedule() -> preApplyResources()
       -> runningJobMasterMap.put; lifecycleExecutor.submit { jobMaster.run() ; finally remove(jobId, jobMaster) }
cancel/stop/savepoint/waitForJobComplete history -> lifecycleExecutor (does not need an admission thread)
master switch -> checkNewActiveMaster: recreate executors -> initCoordinatorService
  -> restoreAllRunningJobFromMasterNodeSwitch on lifecycleExecutor, each restore also on lifecycleExecutor

This is the mainstream path for every job, not an edge path, so the changed logic is exercised by normal usage.

Correctness: the lifecycle pool keeps direct handoff with an unbounded maximum, so the nested blocking pattern (outer restore task waits on inner restore tasks; JobMaster.run() waits on callbacks that need their own thread) cannot deadlock on pool size, which matches the previous default behavior. I found no functional defect in the production diff.

1.2 Compatibility Impact

Partially incompatible (documented). Config keys and defaults are unchanged and no serialization, checkpoint or savepoint format is touched. Two operator-visible semantics change: (a) a finite max-thread-num no longer bounds lifecycle threads, and (b) job_thread_pool_* metrics now describe admission only, so dashboards/alerts that used job_thread_pool_activeCount as a proxy for "running jobs" will read near zero. Both are called out in incompatible-changes.md (en and zh) and in the deployment guides. The reference table in telemetry.md is not updated (Issue 2). I did not find a regression in the 2.x to 3.0 upgrade path: no persisted state changes.

1.3 Performance / Side-Effect Analysis

  • With defaults (core-thread-num=10, max-thread-num=Integer.MAX_VALUE) thread behavior is essentially unchanged: threads are created lazily, the lifecycle pool has core 0 and a 60s keep-alive, and the scheduler executor starts its thread on first submit, so a standby master creates no idle threads. Thread count is still one blocked thread per running job plus callbacks.
  • Step-down now awaits three executors sequentially, each up to 20s, inside synchronized clearCoordinatorService() on the single masterActiveListener thread (Issue 5). This is the only new latency exposure.
  • No new locks, no hot-path allocation, and metrics collection reads the executors directly without touching coordinator activation (verified by the updated guard test).

1.4 Error Handling and Logging

Issue 1: Test-strictness change in BackpressureSlowSinkIT, unrelated to the executor split (carryover I missed)

  • Location: seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/BackpressureSlowSinkIT.java:89-92, 202-240, 257-263 and .../resources/stream_fast_fakesource_to_slow_inmemory_backpressure.conf
  • Problem: on dev, the test requires at least 3 additional completed checkpoints within a fixed 90s window (BACKPRESSURE_WINDOW_MS, dev :89, :200). The PR replaces the fixed deadline with MIN 90s / MAX 3 min and breaks out once 90s has elapsed and 3 checkpoints completed, so the same threshold can now be met up to 180s after the job starts. The number stays 3 but the time budget doubles. Last round I wrote that this "does not weaken the assertion"; that was too generous, sorry. The PR description itself says the original assertion also fails with an unmodified upstream CoordinatorService, so this change is independent of the executor split.
  • Potential risk: it lowers the test's power to catch a real checkpoint-latency regression under sustained backpressure, and it papers over a known engine/fixture race instead of fixing it. Per the description of #12313 and #12316, the failure on dev comes from FakeSourceReader re-entering the checkpoint monitor back-to-back with a single large split, so barrier injection can be starved on an unfair intrinsic lock; #12313 fixes the fixture (split sizing) and #12316 hands the lock to barrier injectors. Both touch the same IT and the same conf, so this PR will also conflict with them. The class Javadoc still says checkpoints "keep completing on schedule", which no longer matches the relaxed loop.
  • Best improvement: drop the BackpressureSlowSinkIT.java and .conf changes from this PR and keep it focused on the executor split; let #12313/#12316 land the root-cause fix. If you want to keep a change here, please state why the original 90s/3 bound is wrong (not just late) and keep an equivalent bound.
  • Severity: Medium (test-strictness reduction, blocks merge until resolved)
  • Raised by another reviewer: No

Issue 2: Metrics reference docs not updated for the new metric family and the narrowed semantics (carryover I missed)

  • Location: docs/en/engines/zeta/telemetry.md:142-149 and docs/zh/engines/zeta/telemetry.md:141-148
  • Problem: this PR adds a new user-visible Prometheus family (job_lifecycle_thread_pool_activeCount, _corePoolSize, _maximumPoolSize, _poolSize, _queueTaskCount, _completedTask_total, _task_total, _rejection_total) and changes the meaning of job_thread_pool_* to admission-only. The deployment guides and incompatible-changes describe this in prose, but the metrics reference table still describes job_thread_pool_* as "the seatunnel coordinator job's executor cached thread pool" and lists no lifecycle metrics; git diff dev...head does not touch either telemetry file.
  • Potential risk: operators look at the metrics reference, not the deployment guide, when building dashboards and alerts, so they would keep alerting on the wrong pool and would not discover the lifecycle metrics.
  • Best improvement: add the eight job_lifecycle_thread_pool_* rows and reword the existing job_thread_pool_* descriptions to "admission" in both docs/en and docs/zh.
  • Severity: Medium (project rule: user-visible changes must update en and zh docs)
  • Raised by another reviewer: No

Issue 3: CoordinatorExecutorMassFailoverStormIT failed on this head; teardown ceiling is tight

  • Location: .../CoordinatorExecutorMassFailoverStormIT.java:178, 292 (get(150, TimeUnit.SECONDS)), CI job engine-v2-it (8, ubuntu-latest)
  • Problem: the test this PR rewrote failed at cancelAllAndAwaitTerminal:294 ("did not reach a terminal status in time") after all the new assertions (idle admission pool, active lifecycle workers, zero rejections) had already passed. In the log the last task group of that job (taskGroupId=4) sat in a ReportMetricsOperation invocation for invocationLatencyMs=92978 and only exited when the test's own finally shut the cluster down (HazelcastInstanceNotActiveException at 02:49:15). Just before, SinkRegisterOperation had exhausted its 30 retries (60s) on a worker generic-operation thread. I found no RejectedExecutionException or lifecycle-thread error from CoordinatorService. The same teardown code passed on engine-v2-it (11) of this same head and on both JDKs for 4a5fbc94 (the only diff between those heads is a unit test), so this looks intermittent. That is an inference; I could not establish the exact stall.
  • Potential risk: the per-job 150s ceiling is close to the worker-side operation-retry tail the test's own comment describes (~120s), so this IT can flake on a slow runner; because the PR owns the rewrite, it becomes the PR's flake.
  • Best improvement: rerun only the failed job first. If the test flakes again, widen the teardown budget or use one overall deadline instead of a sequential 150s per job, and consider shutting the cluster down rather than waiting on every job. No production change is indicated by this log.
  • Severity: Medium (should be resolved or shown to be a flake by a green rerun; not a blocker by itself)
  • Raised by another reviewer: No

Issue 4: A finite max-thread-num no longer caps concurrent jobs, with no replacement knob (documented, tracked follow-up)

  • Location: docs/en/engines/zeta/hybrid-cluster-deployment.md:181-194, CoordinatorService.java:308-319
  • Problem: before, max-thread-num was documented as "The max job count can be executed at same time", and with a finite value it acted as a (fragile) guard on running jobs. After this PR nothing bounds lifecycle threads, and the doc examples still show max-thread-num: 1000. The PR states this is deliberate and deferred, and incompatible-changes tells operators to review capacity before upgrading, so this is not a defect in the PR.
  • Potential risk: an operator relying on the old cap can hit thread exhaustion on the master after upgrading.
  • Best improvement: keep as is for this slice, but please make sure the follow-up (#12117 next slice) lands before a release, or mention it in the release notes; optionally soften the 1000 examples so they do not imply a job cap.
  • Severity: Low
  • Raised by another reviewer: No

Issue 5: Three sequential 20s waits inside synchronized clearCoordinatorService()

  • Location: CoordinatorService.java:1356-1363, 1382-1392
  • Problem: the three awaitTermination(20s) calls are sequential; worst case step-down blocks the masterActiveListener thread for 60s instead of 20s, and it is not hypothetical: on this head CheckpointCoordinatorFailoverIT.testStreamJobContinuesAfterMasterFailover logged "Coordinator lifecycle executor did not terminate within 20 seconds".
  • Potential risk: slower re-activation after a flap, and a longer synchronized hold on the coordinator monitor.
  • Best improvement: use a single shared deadline (for example 20s total) across the three executors.
  • Severity: Low
  • Raised by another reviewer: No

Issue 6: Executor fields are replaced on reactivation but are not volatile

  • Location: CoordinatorService.java:226-231, 1283-1291
  • Problem: executorService, lifecycleExecutor and pendingJobSchedulerExecutor are reassigned under synchronized checkNewActiveMaster but read without synchronization from Hazelcast operation threads. This follows the existing executorService pattern and isActive (volatile) is written after the assignments, so in practice readers that gate on isActive see the new value; it is only fragile for readers that do not.
  • Best improvement: mark the three fields volatile (or add a comment stating the isActive happens-before contract).
  • Severity: Low
  • Raised by another reviewer: No

Issue 7: Two test-maintainability nits

  • Location: CoordinatorExecutorMassFailoverStormIT.java:152, 169 and CheckpointCoordinatorFailoverIT.java (Javadoc of testStreamJobFailsAfterCheckpointTriggerDispatchFailure)
  • Problem: (a) the pool-size safety ceiling is now checked once, after every job is RUNNING, instead of on a sampled peak, so a transient burst above the ceiling would not be seen; (b) about 100 lines of design rationale on the real-fault-injection technique were replaced by a 4-line Javadoc, and the injection now reflects into the private lock and pendingCounter fields of CheckpointCoordinator. The strictness is not reduced (the added pendingCounter == 0 precondition is stricter and the assertNotNull on the removed slot profile is kept), but a short comment that the reflection is intentional would help future readers.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Good. New fields have explanatory comments (CoordinatorService.java:225-231), the lifecycle metric getter is documented (:2314), and the new test class has the ASF header and a class Javadoc. createLifecycleExecutor() and createPendingJobSchedulerExecutor() have no method comments; the field comment covers them, so this is only a nit.

2.2 Test Coverage and Test Stability

Coverage is strong for the changed behavior: CoordinatorServiceTest (testLifecycleAndPendingSchedulerProgressWithSaturatedAdmission, testLateLifecycleExitDoesNotRemoveReplacementMaster, testReactivationRebuildsAllExecutorsAndPreservesAdmissionSettings), the real-engine CoordinatorServiceAdmissionSaturationTest (checkpoint, savepoint, cancel and restore with the only admission worker held), telemetry guard assertions, and the new cleanup-reschedule test. The late-exit test is meaningful, not vacuous: the mocked completion future returns isCancelled() == false, so the finally really reaches remove(jobId, jobMaster). The unit-test jobs (Windows and Ubuntu, Java 8/11) all passed on this head.

Stability rating: Risk present. Evidence: BackpressureSlowSinkIT.java:202-240 (time budget relaxed, Issue 1; the loop also relies on Thread.sleep polling), CoordinatorExecutorMassFailoverStormIT.java:292 (150s sequential ceiling, red on this head, Issue 3). The new unit tests themselves are stable: latches and Awaitility with bounded waits, no fixed ports beyond the base class's, and the cleanup test uses a mocked scheduler with no sleeps.

2.3 Documentation Updates

Deployment guides (en/zh) and incompatible-changes (en/zh) are updated, consistent with each other, and match the code (defaults 10 and 2147483647 verified against CoordinatorServiceConfig). The metrics reference (telemetry.md, en/zh) is missing, see Issue 2.

3. Architectural Soundness

3.1 Elegance of the Solution

Long-term solution (first slice). Three executors with one job each is clean, and it fixes the real ownership bug (admission and lifecycle sharing capacity) without touching semantics of the lifecycle path. The unbounded lifecycle pool is an explicit, documented interim.

3.2 Maintainability

Good: one shutdown helper, one metrics helper (addThreadPoolMetrics), and the identity-based map removal closes a real late-exit race. Issues 5 and 6 are small polish items.

3.3 Extensibility

The design leaves room for a later bounded lifecycle pool or queue and a finite admission default, as the description says.

3.4 Historical-Version Compatibility

No persisted-state, protocol, checkpoint or savepoint changes; upgrade from 2.x to 3.0 is unaffected by this diff. The only historical-behavior changes are the operator-facing ones in 1.2.

4. Issue Summary

# Issue Location Severity
1 BackpressureSlowSinkIT time budget doubled; unrelated to this PR and overlaps #12313/#12316 BackpressureSlowSinkIT.java:89-92, 202-240 Medium
2 Metrics reference docs not updated for job_lifecycle_thread_pool_* and admission-only job_thread_pool_* docs/en/engines/zeta/telemetry.md:142-149, docs/zh/engines/zeta/telemetry.md:141-148 Medium
3 CoordinatorExecutorMassFailoverStormIT red on this head; 150s sequential teardown ceiling CoordinatorExecutorMassFailoverStormIT.java:178, 292 Medium
4 Finite max-thread-num no longer caps running jobs; no replacement knob yet (documented) hybrid-cluster-deployment.md:181-194 Low
5 Three sequential 20s waits inside synchronized clearCoordinatorService() CoordinatorService.java:1356-1363, 1382 Low
6 Executor fields reassigned on reactivation but not volatile CoordinatorService.java:226-231 Low
7 Pool-size ceiling checked once; large IT Javadoc removed CoordinatorExecutorMassFailoverStormIT.java:152, 169, CheckpointCoordinatorFailoverIT.java Low

CI on this head (fork run Build, attempt 1; the apache-side Build check is only a pointer): 75 jobs passed, 13 skipped, 5 failed. Diagnosis of the 5 failures: all-connectors-it-1 (11): NebulaGraphIT.startUp graphd startup race, fixed on dev by #12329 which is not in this branch (18 commits behind dev), unrelated; all-connectors-it-2 (8) and (11): OpengaussCDCIT.testAddFieldWithRestore (a column is missing after CDC restore), a connector E2E that does not exercise the coordinator; the symptom matches the CDC restore-schema issue that #12321 addresses (my inference); doris-connector-it (8): DorisSchemaChangeIT container never opened its ports, environmental; engine-v2-it (8): two failures, SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck (expected CANCELED but was FAILED when a worker crashes before the cancel ack; this matches the worker-loss race that #12311 addresses, and this diff does not touch that path; my inference) and CoordinatorExecutorMassFailoverStormIT (Issue 3). engine-v2-it (11) and all unit-test jobs passed. Please rerun only the failed jobs; syncing dev would help only for the Nebula one.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed
    • Issue 1: remove (or justify with an equivalent bound) the BackpressureSlowSinkIT and .conf changes; keep this PR to the executor split and let #12313/#12316 fix the root cause.
    • Issue 2: add the lifecycle metrics rows and the admission wording to telemetry.md in both languages.
  2. Recommended fixes - non-blocking
    • Issue 3: rerun the failed engine-v2-it (8) job; if CoordinatorExecutorMassFailoverStormIT flakes again, widen or restructure its teardown.
    • Issues 4 to 7 as described above.

Overall assessment: the production change is small, correct in the paths I traced (submit, scheduler, restore, cancel/savepoint, step-down, reactivation), and the added tests exercise the real critical path. I found no functional defect in src/main. The remaining work is a test-strictness question and one docs table, both quick. Better alternative? Option A (recommended): drop the Backpressure changes and add the two doc tables. Option B: keep the Backpressure edit but justify the relaxed bound and coordinate ordering with #12313/#12316. There is no other maintainer approval or change request on this PR to respond to besides my own earlier reviews, and the author comment (cleanup branch inherited from #11503) is correct.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks a lot for the update, @jjj-n, and for the careful follow-up. I re-read the whole effective diff (git diff dev...head, 17 files) at f716321a, not only the new commit a39f8822. The two items I asked for last round are done: the BackpressureSlowSinkIT and .conf changes are gone (the files are byte-identical to dev again), and telemetry.md now documents both pool families in English and Chinese. I also see that this PR is still a draft, so please read everything below as early feedback to help before you mark it ready; nothing here is meant to rush you.

What Problem Does This PR Solve?

  • User pain point: CoordinatorService used one executor for two very different jobs: admitting new submissions (short work) and running the long-lived job lifecycle (JobMaster.run() blocks for the whole job, plus cancel/savepoint/restore fan-out and the pending-job scheduler loop). With a finite max-thread-num, a saturated shared pool could make cancel, savepoint, completion callbacks and master-switch restore queue up or be rejected behind admission work.
  • Fix approach: executorService keeps only admission; a new cached lifecycleExecutor (core 0, max Integer.MAX_VALUE, SynchronousQueue) runs JobMaster.run(), restore, cancel/stop/savepoint/history lookups and is handed to every JobMaster; the pending-job scheduler gets its own single-thread executor. All three are shut down on step-down and recreated on reactivation; the running-master entry is removed by instance identity. A second metric family job_lifecycle_thread_pool_* is exported.
  • One-sentence summary: A sound, well-tested isolation slice; I found no functional defect in src/main, and what remains is test-stability hardening plus a few small polish items.
  • Before/after: before, max-thread-num: 10 plus 10 blocked JobMaster.run() threads left cancel/savepoint with no thread to run on; after, all 10 admission threads can be busy and cancel/savepoint/restore still run on the lifecycle pool.

1. Code Change Review

1.1 Core Logic Analysis

Status of my previous review (at 49e09cbf)

Earlier point Status at f716321a Evidence
Issue 1 (Medium): BackpressureSlowSinkIT time budget doubled, unrelated to the executor split FIXED a39f8822 restores the original loop; git diff dev...head has no hunk for BackpressureSlowSinkIT.java or stream_fast_fakesource_to_slow_inmemory_backpressure.conf. At head the fixed 90 s window and the 3-checkpoint threshold are back (BackpressureSlowSinkIT.java:89, 107, 200).
Issue 2 (Medium): metrics reference docs missing the new family FIXED docs/en/engines/zeta/telemetry.md:142-157 and docs/zh/engines/zeta/telemetry.md:141-156: 8 admission rows reworded, 8 job_lifecycle_thread_pool_* rows added. Metric names match JobThreadPoolStatusExports.java:43-49 (counters get the usual _total suffix).
Issue 3 (Medium): CoordinatorExecutorMassFailoverStormIT red on JDK 8 NOT FIXED (test unchanged; failed again on attempt 1 of this head, passed on attempt 2) see Issue 1 below and the CI notes in section 4
Issue 4 (Low): finite max-thread-num no longer caps running jobs UNCHANGED, by design and documented hybrid-cluster-deployment.md:181-193, incompatible-changes.md en/zh; kept below as Issue 5 for tracking
Issue 5 (Low): three sequential 20 s waits under the coordinator monitor NOT FIXED CoordinatorService.java:1361-1363, 1382-1391
Issue 6 (Low): executor fields reassigned on reactivation but not volatile NOT FIXED CoordinatorService.java:226-231
Issue 7 (Low): pool-size ceiling checked once; reflection into CheckpointCoordinator NOT FIXED (nit) CoordinatorExecutorMassFailoverStormIT.java:152, 169; CheckpointCoordinatorFailoverIT.java

Changed production logic (re-verified at the pinned head)

before: executorService (core-thread-num / max-thread-num, SynchronousQueue)
          <- submitJob init, JobMaster.run(), restore, cancel, savepoint, scheduler loop
after:  executorService             <- submitJob admission only                (CoordinatorService.java:1439)
        lifecycleExecutor           <- JobMaster.run(), restore, cancel/stop/savepoint/history,
                                       and the executor handed to each JobMaster
                                       (499, 686, 1111, 1170, 1473, 1580, 1593, 1632, 1654)
        pendingJobSchedulerExecutor <- the scheduler loop                      (359)

Key findings:

  • I grepped every use of the three fields: the only remaining executorService submission is the admission task in submitJob (:1439). JobMaster receives the lifecycle executor on both the submit path (:1473) and the restore path (:1170).
  • The lambda that waits for the job (jobMaster.run()), the connector-jar cleanup and the exceptional completion are unchanged (:500-522); only the executor and remove(jobId, jobMaster) changed. JobMaster does not override equals/hashCode, so the two-argument ConcurrentHashMap.remove really compares by identity and a late exit of an old master cannot drop a replacement.
  • Step-down (clearCoordinatorService, :1325-1363) interrupts masters, clears the queue, calls shutdownNow() on all three executors and only then awaits them; reactivation (checkNewActiveMaster, :1278-1292) recreates any shut-down executor before initCoordinatorService() (which starts restore on the lifecycle pool) and before startPendingJobScheduleThread(). A stale scheduler thread from an old epoch can no longer queue behind or occupy the new generation's scheduler executor.
  • Removing Thread.currentThread().setName("pending-job-schedule-runner") in favour of a named factory is safe: the e2e thread-leak whitelist matches by prefix (SeaTunnelContainer.java:677-679 covers both seatunnel-coordinator-service* and pending-job-schedule-runner*).

Strict checklist for the engine threading change

  • Executor sizing: admission keeps the configured core/max, SynchronousQueue and the counting AbortPolicy (:295-306); lifecycle is core 0, max Integer.MAX_VALUE, 60 s keep-alive, SynchronousQueue (:308-319). There is no work queue anywhere, so no unbounded backlog can build; the thread count is unbounded exactly as the previous default was, and the PR states this is a deliberate interim.
  • Rejection policy: unchanged RejectionCountingHandler (ThreadPoolStatus.java:38-51). For the lifecycle pool a rejection is only reachable after shutdownNow(). If admission is saturated, the RejectedExecutionException from executorService.submit still propagates synchronously out of submitJob (:1439, not inside the try block); this is existing behaviour, but it is now reachable only by concurrent admissions, not by running jobs.
  • Exception propagation: the scheduler loop still catches Throwable, re-checks the epoch and sleeps 3 s (:335-357); submitJob still completes the future exceptionally and cleans up (:1503-1521).
  • Lifecycle ordering and failover: restore outer task and inner tasks both run on the lifecycle pool (:686, :1111); with a SynchronousQueue and an unbounded max the outer-waits-for-inner pattern cannot deadlock on pool size. waitForJobComplete and savePoint also nest blocking work on this pool (:1550-1611), which is the reason the unbounded direct handoff is needed.
  • Failed activation: if activation throws after the executors were used, the catch block calls clearCoordinatorService() (:1305-1315), which shuts all three down, and the next poll recreates them because of the isShutdown() checks.

Runtime path (normal user path reaches the change):

client submit -> SubmitJobOperation -> CoordinatorService.submitJob
  -> executorService (admission): deserialize, JobMaster ctor(lifecycleExecutor), init, pendingJobQueue.put
  -> pendingJobSchedulerExecutor: pendingJobSchedule() -> preApplyResources()
       -> runningJobMasterMap.put; lifecycleExecutor.submit { jobMaster.run(); finally remove(jobId, jobMaster) }
cancel / stop / savepoint / history lookup -> lifecycleExecutor (needs no admission thread)
master switch -> checkNewActiveMaster: recreate executors -> initCoordinatorService
  -> restoreAllRunningJobFromMasterNodeSwitch on lifecycleExecutor; each restore also on lifecycleExecutor

This is the mainstream path for every job, so the changed logic is exercised by normal usage, not only by edge cases.

1.2 Compatibility Impact

Partially incompatible (documented). Config keys and defaults are unchanged and no serialization, checkpoint or savepoint format is touched. Two operator-visible semantics change: (a) a finite max-thread-num no longer bounds lifecycle threads, and (b) job_thread_pool_* now describes admission only, so dashboards that used job_thread_pool_activeCount as a proxy for running jobs will read near zero. Both are called out in incompatible-changes.md (en and zh) and the deployment guides, and the metrics reference is now consistent with them. No persisted state changes, so I see no impact on the 2.x to 3.0 upgrade path.

1.3 Performance / Side-Effect Analysis

  • With defaults (core-thread-num=10, max-thread-num=2147483647) thread behaviour is essentially unchanged: threads are created lazily, the lifecycle pool has core 0, and the scheduler executor starts its thread on first submit, so a node that never becomes master creates no idle threads. One blocked thread per running job remains, as before.
  • Step-down awaits three executors in sequence, each up to 20 s, inside synchronized clearCoordinatorService() (Issue 3). This is the only new latency exposure, and only when a thread refuses to exit.
  • printExecutionInfo() now logs two tables per periodic print instead of one (:2197-2205); negligible.
  • No new locks and no hot-path allocation; metrics collection reads the executors directly without touching activation state.

1.4 Error Handling and Logging

Issue 1: CoordinatorExecutorMassFailoverStormIT still failed on JDK 8 at this head (earlier Issue 3)

  • Location: seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/CoordinatorExecutorMassFailoverStormIT.java:148-178, 292-294
  • Problem: on fork run Build attempt 1 for this head, engine-v2-it (8, ubuntu-latest) failed with testMassFailoverRestoreDoesNotOccupyAdmissionWorkers:178->cancelAllAndAwaitTerminal:294 Job ... did not reach a terminal status in time, the same assertion as at 49e09cbf. All the new isolation assertions (idle admission pool, active lifecycle workers, zero rejections) had already passed. In the log, job mass_retry_job_29 was cancelled at 03:25:39.399 (RUNNING to CANCELING at job level), while its single pipeline was still being re-scheduled (CREATED to SCHEDULED at 03:25:39.874, DEPLOYING to RUNNING and immediately RUNNING to CANCELING at 03:25:40.08). Task group 3 of that pipeline then did nothing for about 120 s (its next log line, starting seatunnel transform task, is at 03:27:40.675, while task group 4 logged the same step at 03:25:40.645), and it only ended when the test's finally shut the cluster down (03:28:12). No RejectedExecutionException and no lifecycle-thread error appears for that job. On attempt 2 of the same head the test passed (20.9 s), and engine-v2-it (11) passed every time, so this is intermittent. My reading of the mechanism (a cancel that races a pipeline re-deploy, followed by a roughly 120 s worker-side invocation wait) is an inference from the timestamps, not something I could prove.
  • One change in this PR plausibly makes the race easier to hit: on dev the test slept through a 20 s sampling window and only then waited for RUNNING and cancelled; now it cancels right after all 30 jobs first report RUNNING (:148 then :178), so pipelines that are still restarting get a cancel. That is also an inference.
  • Potential risk: the PR owns this rewrite, so its flake becomes the PR's flake; a 150 s ceiling per job, applied sequentially (:292), can also stretch the teardown to a very long time when several jobs stall.
  • Best improvement: before cancelAllAndAwaitTerminal, wait until the pipelines have been stable (for example every job RUNNING and no state change for a few seconds), or restore a short settle window; and use one overall teardown deadline plus cluster shutdown instead of get(150s) per job. If you prefer to show that the flake predates this PR, a dev-only run of the same IT on JDK 8 in your fork would settle it.
  • Severity: Medium (test stability; should be resolved or shown to predate the PR)
  • Raised by another reviewer: No

Issue 2: PR description still describes the removed BackpressureSlowSinkIT change

  • Location: PR description, "How was this patch tested?" section
  • Problem: the description still says the revised loop keeps 90 s of stress with a 180 s upper bound and cites the WSL result for that loop, and it lists 49e09cbf as the latest follow-up. After a39f8822 the loop is the original one and the telemetry docs change is not mentioned.
  • Potential risk: reviewers and release-note readers will believe a test change exists that does not.
  • Best improvement: update the description to the current head: drop the Backpressure paragraphs (or say they were withdrawn, with #12313 and #12316 as the tracking items) and mention the telemetry docs.
  • Severity: Low
  • Raised by another reviewer: No

Issue 3: Three sequential 20 s waits inside synchronized clearCoordinatorService() (earlier Issue 5)

  • Location: CoordinatorService.java:1361-1363, 1382-1391
  • Problem: all three executors get shutdownNow() first (:1356-1358), so the waits overlap in normal cases; but if a thread never exits (for example one blocked in a non-interruptible join()), the total is 3 x 20 s = 60 s instead of the previous 20 s, all while holding the coordinator monitor on the single masterActiveListener thread.
  • Potential risk: slower re-activation after a master flap.
  • Best improvement: one shared deadline (for example 20 s in total) across the three executors.
  • Severity: Low
  • Raised by another reviewer: No

Issue 4: Executor fields are replaced on reactivation but are not volatile (earlier Issue 6)

  • Location: CoordinatorService.java:226-231, 1283-1291
  • Problem: the three fields are reassigned under synchronized checkNewActiveMaster and read without synchronization by operation threads and by SeaTunnelServer.printExecutionInfo() / the metrics getters. Readers that go through getCoordinatorService() are safe because isActive (volatile) is written after the assignments; readers that do not (the periodic log print, getLifecycleThreadPoolStatusMetrics(), which the PR intentionally keeps free of activation waits) could see a stale, terminated pool after a reactivation.
  • Best improvement: mark the three fields volatile, or add a comment stating the isActive happens-before contract.
  • Severity: Low
  • Raised by another reviewer: No

Issue 5: A finite max-thread-num no longer caps concurrent jobs, with no replacement knob (documented follow-up, earlier Issue 4)

  • Location: docs/en/engines/zeta/hybrid-cluster-deployment.md:181-201, CoordinatorService.java:308-319
  • Problem: nothing bounds lifecycle threads now, and the doc examples still show max-thread-num: 1000. The PR and incompatible-changes.md state this openly and defer the bound to a later slice, so this is not a defect.
  • Best improvement: keep as is for this slice; please make sure the bounded follow-up under #12117 lands before a release (or mention it in the release notes), and optionally soften the 1000 example so it does not read as a job cap.
  • Severity: Low
  • Raised by another reviewer: No

Issue 6: Two test-maintainability nits (earlier Issue 7)

  • Location: CoordinatorExecutorMassFailoverStormIT.java:152, 169; CheckpointCoordinatorFailoverIT.java (Javadoc of testStreamJobFailsAfterCheckpointTriggerDispatchFailure)
  • Problem: (a) the lifecycle pool-size safety ceiling is read once after all jobs are RUNNING instead of as a sampled peak; (b) about 100 lines of rationale for the fault-injection technique became a 4-line Javadoc, and the injection now reflects into the private lock and pendingCounter fields of CheckpointCoordinator. Strictness is not reduced (the added pendingCounter == 0 precondition is stricter and the assertNotNull on the removed slot profile is kept), but a short comment saying the reflection is intentional would help future readers.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Good. New fields and the metrics getter have comments (CoordinatorService.java:225-231, 2314), new files carry the ASF header, and createLifecycleExecutor() / createPendingJobSchedulerExecutor() are covered by the field comment (a method-level line would be a nice-to-have). Nit: threadPoolStatus(...) starts with a blank line (:2319-2320).

2.2 Test Coverage and Test Stability

Coverage of the changed behaviour is strong: CoordinatorServiceTest (testLifecycleAndPendingSchedulerProgressWithSaturatedAdmission, testLateLifecycleExitDoesNotRemoveReplacementMaster, testReactivationRebuildsAllExecutorsAndPreservesAdmissionSettings), the real-engine CoordinatorServiceAdmissionSaturationTest (checkpoint, savepoint, cancel and restore with the only admission worker held; a new test class is justified because it needs its own core=1, max=1 engine config), the telemetry guard assertions (16 metric families, and getCoordinatorService() must never be called), and the early-cleanup reschedule test. That last test covers logic inherited from #11503, so it is unrelated to the split; it is a welcome test, but if you want a tighter PR it could be moved out. All four unit-test jobs (Ubuntu and Windows, Java 8 and 11) passed on attempt 2 of this head.

Stability rating: Risk present. Evidence: CoordinatorExecutorMassFailoverStormIT.java:178, 292-294 (Issue 1: failed on JDK 8 on attempt 1, passed on attempt 2; sequential 150 s ceilings). The other new tests are stable by construction: latches and bounded Awaitility waits, no sleeps, mocked scheduler in the cleanup test, state restored in finally. The unchanged BackpressureSlowSinkIT also failed on this head (see section 4); it is the upstream issue tracked by #12313 and #12316 and is not touched by this diff.

2.3 Documentation Updates

Deployment guides, incompatible-changes.md and now telemetry.md, in both en and zh, are updated and consistent with each other and with the code (defaults 10 and 2147483647, metric names, admission versus lifecycle wording). Nothing else in docs/ mentions job_thread_pool_* or max-thread-num (I grepped). The only documentation gap is the stale PR description (Issue 2).

3. Architectural Soundness

3.1 Elegance of the Solution

Long-term solution (first slice). Three executors with one job each is clean and fixes the real ownership bug (admission and lifecycle sharing capacity) without changing the semantics of the lifecycle path. The unbounded lifecycle pool is an explicit, documented interim.

3.2 Maintainability

Good: one shutdown helper, one metrics helper, and identity-based removal closes a real late-exit race. One optional observation outside this diff: the failure branch of submitJob still calls runningJobMasterMap.remove(jobId) unconditionally (:1519); it is only reachable for a racing duplicate submit of the same job id, so I am not asking for a change here, but it would be the same identity treatment if you touch it.

3.3 Extensibility

The design leaves room for a bounded lifecycle pool, a queue or a finite admission default later, exactly as the description says.

3.4 Historical-Version Compatibility

No persisted-state, protocol, checkpoint or savepoint changes; upgrade from 2.x to 3.0 is unaffected. The only historical-behaviour changes are the operator-facing ones in section 1.2, and they are documented.

4. Issue Summary

# Issue Location Severity
1 CoordinatorExecutorMassFailoverStormIT failed on JDK 8 (attempt 1 of this head); cancel races pipeline re-deploy, sequential 150 s teardown CoordinatorExecutorMassFailoverStormIT.java:148-178, 292-294 Medium
2 PR description still describes the removed Backpressure change PR description Low
3 Three sequential 20 s waits inside synchronized clearCoordinatorService() CoordinatorService.java:1361-1363, 1382-1391 Low
4 Executor fields reassigned on reactivation but not volatile CoordinatorService.java:226-231 Low
5 Finite max-thread-num no longer caps running jobs (documented, tracked follow-up) hybrid-cluster-deployment.md:181-201 Low
6 Pool-size ceiling checked once; reflection Javadoc trimmed CoordinatorExecutorMassFailoverStormIT.java:152, 169, CheckpointCoordinatorFailoverIT.java Low

CI on this head (fork run Build #35554918326 in jjj-n/seatunnel; the apache-side Build check only points at it):

  • Why the apache-side check shows "cancelled": the head was not superseded (it is still f716321a) and this is not a concurrency cancel. Run / kudu-connector-it (11, ubuntu-latest) hit the job time limit ("The job has exceeded the maximum execution time of 1h30m0s") on both attempt 1 and attempt 2, and a cancelled job makes the whole run report cancelled. On attempt 2 the log shows KuduIT.testKuduMultipleReadWithRegex as the last test started (08:19:58), Flink taskmanager heartbeat timeouts at 08:22 and read timeouts at 08:50, and no further test progress until the limit killed the job at 09:34. kudu-connector-it (8) passed in 34 minutes on attempt 2, and the diff does not touch the Kudu connector, so this is environmental and unrelated to the PR.
  • Real failures: attempt 1 had 3 failures (engine-v2-it (8), all-connectors-it-4 (8), transform-v2-it-part-1 (8)) and 2 cancelled (both kudu jobs); after "rerun failed jobs" attempt 2 has 78 passed, 13 skipped, 1 failed and 1 cancelled. all-connectors-it-4 (8) and transform-v2-it-part-1 (8) passed on rerun (I did not diagnose their first failure).
  • engine-v2-it (8), attempt 2 (204 tests, 1 failure, 1 error): (a) BackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressure:247 observed only 2 additional checkpoints (samples [1, 1, 1, 1, 1, 2, 2, 3, 3]); the test and conf are byte-identical to dev, so this is the known upstream problem tracked by #12313 and #12316 (both open), not caused by this diff. (b) SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck:449 expected CANCELED but was FAILED; this matches the worker-loss race addressed by open PR #12311 (my inference) and the diff does not touch that path. Attempt 1 of the same head instead failed on CoordinatorExecutorMassFailoverStormIT (Issue 1) plus the same SplitClusterFaultToleranceIT.
  • engine-v2-it (11) and all four unit-test jobs passed, as did License header, Dependency licenses, Sanity check and Dead links. Please rerun only the failed jobs; syncing dev would not change the Backpressure, SplitCluster or Kudu outcomes. Since the PR is a draft, no action is needed before you are ready.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed
    • None from the source review: I found no functional, compatibility or resource-lifecycle defect in the production diff, and both blockers from the last round are resolved. Before it can merge, the PR still needs a green (or clearly attributable) CI run; the remaining red jobs are unrelated except for the StormIT one below.
  2. Recommended fixes - non-blocking
    • Issue 1: harden or explain the JDK 8 flake of CoordinatorExecutorMassFailoverStormIT (stable-RUNNING wait or settle window before cancel, one overall teardown deadline), or show with a dev-only run that it predates this PR.
    • Issue 2: refresh the PR description for the current head.
    • Issues 3 to 6 as described above.

Overall assessment: the production change is small, correct on every path I traced (submit, scheduler, restore, cancel/savepoint, step-down, reactivation, failed activation) and the tests exercise the real critical path. Better alternative? Option A (recommended): keep the design and harden the StormIT teardown as described. Option B: leave the test as is and demonstrate, with a dev-only JDK 8 run, that the flake is inherited; then it should not gate this PR. There is no other maintainer approval or change request to respond to besides my own earlier reviews; my verdict here is a comment rather than an approval because the PR is still a draft and CI has not settled.

@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 again, @jjj-n. Sorry for one thing up front: my previous review cited TaskExecutionService.java:880 and 893-901 for the ReportMetricsOperation/updateMetricsContextInImap mechanism in the teardown comment of CoordinatorExecutorMassFailoverStormIT, and I should have checked those line numbers at the time instead of only verifying the mechanism. They are off (the real method starts at line 936); I'm marking that as a carryover documentation nit below, not something newly introduced.

I re-read the complete effective diff at the current head 0fd7e7b2 (git diff dev...head, still 17 files excluding the dev-merge's own unrelated files) rather than just the incremental change, and re-traced the production call chain again from submitJob through step-down/reactivation. Everything I verified in my previous round at f716321a is byte-identical at this head: CoordinatorService.java, SeaTunnelServer.java and JobThreadPoolStatusExports.java all show a zero-line diff between f716321a and 0fd7e7b2, and the doc files only changed where the merge from dev (bringing in the Fluss/Redis/Tablestore/RocketMQ/health-monitor commits already on dev) touched unrelated sections; this PR's own max-thread-num / telemetry content is untouched by that merge. The only genuine new work by the author since my last review is one commit, 8a31e448eeb ("Stabilize mass failover storm teardown"), which is a 49-line addition to CoordinatorExecutorMassFailoverStormIT.java.

What Problem Does This PR Solve?

  • User pain point: CoordinatorService used one executor for two very different jobs: admitting new submissions (short work) and running the long-lived job lifecycle (JobMaster.run() blocks for the whole job, plus cancel/savepoint/restore fan-out and the pending-job scheduler loop). With a finite max-thread-num, a saturated shared pool could make cancel, savepoint, completion callbacks and master-switch restore queue up or be rejected behind admission work.
  • Fix approach: executorService keeps only admission; a new cached lifecycleExecutor (core 0, max Integer.MAX_VALUE, SynchronousQueue) runs JobMaster.run(), restore, cancel/stop/savepoint/history lookups and is handed to every JobMaster; the pending-job scheduler gets its own single-thread executor. All three are shut down on step-down and recreated on reactivation. A second metric family job_lifecycle_thread_pool_* is exported.
  • One-sentence summary: A sound, well-tested isolation slice; the production code is unchanged since my last full review and I still find no functional defect in src/main; the only new work this round is a targeted fix to the previously-flagged JDK 8 test flake.

1. Code Change Review

1.1 Core Logic Analysis

Production code: no changes since f716321a. CoordinatorService.java, SeaTunnelServer.java and JobThreadPoolStatusExports.java diff to zero lines against the commit I already reviewed in depth (executor split, identity-based remove(jobId, jobMaster), shutdown/recreate ordering on step-down and reactivation, rejection/exception propagation, the SynchronousQueue-only unbounded lifecycle pool). I re-walked the same runtime path again this round and reached the same conclusions; I am not repeating the full method-by-method notes here since nothing changed, but happy to re-expand them if asked.

New test-only change (8a31e448eeb), re-verified in full:

before: awaitAllJobsInStatus(..., RUNNING, 180)        // single-sample check
        entry.getValue().get(150, TimeUnit.SECONDS)    // independent 150s per job in teardown

after:  awaitAllJobsStableInStatus(..., RUNNING, 180)  // Awaitility .during(5s).atMost(180s)
        shared teardownDeadlineNanos, remaining budget computed per job, assertTrue(remaining > 0)

Key findings:

  • This directly implements both remediations I suggested last round for Issue 1: (a) require the restored jobs to stay RUNNING for a 5-second settle window (awaitAllJobsStableInStatus, using Awaitility.await().during(...).atMost(...)) before triggering the mass-cancel, instead of accepting a single point-in-time sample that could race a pipeline re-deploy; (b) replace the 30 independent 150-second get() calls in cancelAllAndAwaitTerminal with one shared 150-second deadline (teardownDeadlineNanos), computing remainingNanos per job and failing fast with assertTrue(remainingNanos > 0, ...) instead of silently calling get() with a non-positive timeout.
  • The .during(..).atMost(..) chaining is an established pattern already used elsewhere in this file family (e.g. SplitClusterPendingJobLifecycleFailoverIT.java:192-193, CoordinatorServiceTest.java), so this is not a novel or risky use of the library.
  • The old awaitAllJobsInStatus single-sample helper is kept and still used correctly for the pre-failover "all 30 jobs reached RUNNING" gate (before killing the active master), where a settle window is not needed since nothing is about to cancel them; only the post-restore, pre-cancel check was upgraded to the stable variant. No dead code left behind.
  • The shared-deadline loop is correct: teardownDeadlineNanos is computed once before the loop starts, and each iteration recomputes remainingNanos from System.nanoTime(), so a job that is slow to reach terminal status eats into the budget of the jobs still to come, matching "one overall teardown deadline" rather than "150s x 30 potential worst case" as before.
  • I could not get fresh CI evidence for this exact fix: the fork's Build run for head 0fd7e7b2 (jjj-n/seatunnel run 35711199146) is still queued at the time of this review, and the apache-side Build check is IN_PROGRESS. My assessment that this resolves the flake is a reasoned inference from re-reading the fix against the failure mechanism I diagnosed last round (cancel racing a pipeline re-deploy, then a ~120s worker-side invocation wait), not a confirmed CI result yet.

Runtime path relevant to this round's change (test-only, does not touch src/main):

30 jobs RUNNING (single sample) -> kill active master -> standby promoted
  -> awaitAllJobsStableInStatus: require RUNNING held continuously for 5s (new)
  -> assert admission idle / lifecycle busy / zero rejections (unchanged)
  -> cancelAllAndAwaitTerminal: cancel all, then await each job's completion future
       against one shared 150s deadline instead of independent 150s each (new)

1.2 Compatibility Impact

Fully compatible for this round's change (test-only). Production compatibility is unchanged from my last review: config keys/defaults are unchanged, no serialization/checkpoint/savepoint format is touched, and the two documented operator-visible semantics changes (unbounded lifecycle threads, job_thread_pool_* now admission-only) are already covered in incompatible-changes.md (en/zh), untouched by this round.

1.3 Performance / Side-Effect Analysis

No change from last round for production code. For the test itself: the new settle window adds a fixed 5s to the test's happy path (bounded by atMost(180s) as before), and the shared teardown deadline can only make worst-case teardown shorter than the old per-job 150s x 30 potential, never longer.

1.4 Error Handling and Logging

Issue 1 (was Medium, now believed resolved pending CI): CoordinatorExecutorMassFailoverStormIT JDK 8 flake

  • Location: CoordinatorExecutorMassFailoverStormIT.java:148-183, 256-289, 324-345
  • Status: the fix in 8a31e448eeb implements exactly the two remediations I proposed last round (settle window before cancel, shared teardown deadline). I re-verified the implementation is correct (see 1.1). I have not yet seen a green CI run on this exact head to confirm the flake no longer reproduces; the fork's run for 0fd7e7b2 was still queued when I checked. Please treat this as "fix landed and looks right", not yet "confirmed by CI" - I'd suggest re-checking once the current fork run completes, ideally across a couple of reruns given this was intermittent (failed on attempt 1, passed on attempt 2 at the previous head).
  • Severity: Low (implementation is sound; only CI confirmation is outstanding, which is a normal part of landing any flake fix)
  • Raised by another reviewer: No

Issue 2 (new, carryover - my apology above applies here): stale line citation in the teardown comment

  • Location: CoordinatorExecutorMassFailoverStormIT.java:318 (comment text), citing TaskExecutionService.java:880 and 893-901
  • Problem: the real updateMetricsContextInImap() method is at TaskExecutionService.java:936 (with the blocking invoke.get() around line 946-950), not 880/893-901. I confirmed the mechanism the comment describes (a synchronous invoke.get() on a ReportMetricsOperation sent to the master, which only fails via the Hazelcast operation-heartbeat timeout rather than fast, when the master is killed mid-RPC) is accurate - only the cited line numbers are wrong. This comment was already present at f716321a, the head I reviewed last round, and I should have checked the citation then.
  • Potential risk: low - a reader following the citation to debug a similar failure would land in the wrong method and need to search, but the surrounding narrative (class name, method name, general area) is correct enough to still find it quickly.
  • Best improvement: update the two line numbers to the current dev positions (or drop the specific line numbers and keep just the method name, which is more resilient to drift).
  • Severity: Low
  • Raised by another reviewer: No

Issues 3-7 (unchanged from last round, still open, still Low, not re-numbered since production code is untouched):

  • Three sequential 20s waits inside synchronized clearCoordinatorService() - CoordinatorService.java:1361-1363, 1382-1391
  • Executor fields reassigned on reactivation but not volatile - CoordinatorService.java:226-231
  • Finite max-thread-num no longer caps running jobs, documented and tracked as a follow-up - hybrid-cluster-deployment.md
  • Pool-size ceiling checked once; reflection into CheckpointCoordinator in CheckpointCoordinatorFailoverIT - unchanged
  • PR description still needs a refresh to match the current head (it predates both the Backpressure revert and this teardown-stabilization commit)

2. Code Quality Assessment

2.1 Coding Standards

Good. The new awaitAllJobsStableInStatus and the teardown deadline logic each have a clear Javadoc/inline comment explaining why they exist (race with pipeline re-deploy; shared deadline vs. independent per-job timeout). No wildcard imports, license header already present on the file. The one nit is Issue 2 above (stale line citation in a pre-existing comment, not newly added).

2.2 Test Coverage and Test Stability

This round's change is entirely about hardening test stability, so it gets the anti-pattern check: no new sleeps were introduced (the settle window uses Awaitility.await().during(...), which polls rather than blindly sleeping), no reduction in assertion strictness (the stable-status check is strictly stronger than the single-sample check it replaces, and the shared teardown deadline is a tighter overall bound than 30 independent 150s windows), and failure messages were improved to say "within the shared teardown deadline" instead of a generic timeout message.

Stability rating: Risk present, trending to Stable. The fix targets the exact mechanism I diagnosed as the cause of the intermittent JDK 8 failure last round, and the implementation is correct on inspection. I am rating it "Risk present" rather than "Stable" only because I do not yet have a completed CI run on this head to confirm the flake is actually gone; once that lands green (ideally more than once, since the failure was intermittent), this should move to Stable.

2.3 Documentation Updates

No documentation files were touched by the author in this round; the doc diffs visible against f716321a are entirely from the dev merge (Fluss/Redis/Tablestore/RocketMQ/health-monitor docs already merged upstream) and do not affect this PR's own telemetry/deployment-guide content, which I re-confirmed is intact post-merge.

3. Architectural Soundness

3.1 Elegance of the Solution

Long-term solution (first slice), unchanged assessment. The production design is still a clean first slice with an explicit, documented interim (unbounded lifecycle pool). This round's test fix is a precise, minimal change targeted at the exact race it addresses - not a workaround (it doesn't loosen the assertions, it makes the pre-condition for triggering cancel more realistic and the teardown budget better modeled).

3.2 Maintainability

Unchanged from last round; still good.

3.3 Extensibility

Unchanged from last round.

3.4 Historical-Version Compatibility

Unchanged from last round: no persisted-state, protocol, checkpoint or savepoint changes; upgrade from 2.x to 3.0 is unaffected.

4. Issue Summary

# Issue Location Severity
1 CoordinatorExecutorMassFailoverStormIT JDK 8 flake - fix implemented and verified by inspection, CI confirmation still pending CoordinatorExecutorMassFailoverStormIT.java:148-183, 256-289, 324-345 Low
2 Stale line citation in teardown comment (carryover, pre-existing at f716321a) CoordinatorExecutorMassFailoverStormIT.java:318 Low
3 Three sequential 20s waits inside synchronized clearCoordinatorService() CoordinatorService.java:1361-1363, 1382-1391 Low
4 Executor fields reassigned on reactivation but not volatile CoordinatorService.java:226-231 Low
5 Finite max-thread-num no longer caps running jobs (documented, tracked follow-up) hybrid-cluster-deployment.md Low
6 Pool-size ceiling checked once; reflection Javadoc trimmed CoordinatorExecutorMassFailoverStormIT.java, CheckpointCoordinatorFailoverIT.java Low
7 PR description needs a refresh to match the current head PR description Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed
    • None from the source review. Production code is unchanged and still has no functional, compatibility or resource-lifecycle defect. Before merge, this head still needs a completed CI run (the fork run for 0fd7e7b2 was queued at review time) so the StormIT fix can be confirmed rather than assumed, and the PR is still marked draft.
  2. Recommended fixes - non-blocking
    • Issue 2: correct the stale line citation in the teardown comment (small, carryover from my last review).
    • Issue 7: refresh the PR description for the current head.
    • Issues 3-6 as previously described; none block merge.

Overall assessment: this round's only real change is a well-targeted, correctly-implemented fix for the test flake I raised last round; the production code remains sound on every path I re-traced. I'd like to see the fork's CI complete (ideally with a rerun or two given the failure was intermittent) before treating Issue 1 as fully closed, but I have no remaining objection to the design or the production implementation. No other reviewer has posted since my last review, so there is nothing else to reconcile here.

@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 quick follow-up! I re-checked the latest head and this round is refreshingly small: exactly one commit, one file, one line changed since my last review, which is exactly the citation fix I asked for. I re-verified the whole diff and the rest of the PR from scratch anyway rather than assuming it, and everything else is byte-identical to what I already reviewed.

What Problem Does This PR Solve?

  • User pain point: CoordinatorService used a single executor for two very different kinds of work: admitting new job submissions (short-lived) and running the full job lifecycle (JobMaster.run() blocks for the whole job duration, plus cancel/savepoint/restore fan-out and the pending-job scheduler loop). Under a finite max-thread-num, a burst of admissions could starve cancel, savepoint, completion callbacks, and master-switch restore behind that admission work.
  • Fix approach: keep executorService for admission only, add a dedicated cached lifecycleExecutor (core 0, max unbounded, direct handoff via SynchronousQueue) for JobMaster.run(), restore, cancel/stop/savepoint/history lookups, and give the permanent pending-job scheduler its own single-thread executor. All three pools are stopped on step-down and recreated on reactivation, and a parallel job_lifecycle_thread_pool_* metric family is exported.
  • One-sentence summary: a clean, well-scoped first slice that separates admission saturation from lifecycle progress; production code is unchanged from my previous review, and this round's only change is a small documentation fix.

1. Code Change Review

1.1 Core Logic Analysis

Production code: no changes since the head I already fully reviewed. CoordinatorService.java, SeaTunnelServer.java, and JobThreadPoolStatusExports.java are byte-for-byte identical to the commit I reviewed in depth previously (executor split, identity-based runningJobMasterMap.remove(jobId, jobMaster), shutdown/recreate ordering across all three pools, savePoint/cancelJob/stopJob/history lookups routed to lifecycleExecutor). I re-traced the same runtime path again this round and reached the same conclusions.

This round's only change, a one-line comment correction in CoordinatorExecutorMassFailoverStormIT.java:

before: // ... TaskExecutionService.java:880 and 893-901). That task still completes CANCELED
after:  // ... TaskExecutionService.java:936 and 946-950). That task still completes CANCELED

Key findings:

  • This is a direct, targeted fix for the stale line citation I flagged (and apologized for) in my previous review.
  • I checked it against the current dev tip: TaskExecutionService.updateMetricsContextInImap() does start at line 936 - that part is now exactly correct.
  • The range 946-950 is close but not perfectly precise - those lines are the invocation-building statements, while the actual blocking call that can wait out the full operation-heartbeat timeout is invoke.get() a few lines further down (around line 959). It's a minor imprecision, not a functional issue, and a big improvement over the previous citation which was off by ~56 lines. See Issue 2 below - Low severity, effectively resolved.
  • No other file changed. I re-diffed the full effective range (merge-base(dev, head)...head) and confirmed the same 17 files as last round: the executor-split production files, the two E2E test files, the four new unit test files, and the en/zh doc set - nothing outside that set moved.
  • The test this PR actually modifies for stability, CoordinatorExecutorMassFailoverStormIT, passed cleanly in the CI run for this exact head (Tests run: 1, Failures: 0, Time elapsed: 26.7s), which is a good sign for the fix I asked for last round.

Runtime path for this round's change: documentation-only, does not affect execution at all.

1.2 Compatibility Impact

Fully compatible. No production code changed since my last review, so nothing new to reassess: config keys/defaults are unchanged, no serialization/checkpoint/savepoint format is touched, and the two documented operator-visible semantics changes (unbounded lifecycle threads, job_thread_pool_* now admission-only) remain correctly captured in incompatible-changes.md (en/zh).

1.3 Performance / Side-Effect Analysis

No change from the previous round. This round's edit is a comment-only fix and has zero runtime effect.

1.4 Error Handling and Logging

Issue 1 (Low, carried forward from last round, updated with fresh CI evidence): CI still shows failures on this head, but none of them are in code this PR touches.

  • I pulled the fork's CI run for this exact head (35811144092) and diagnosed each failing job individually rather than treating "Build failed" as one opaque signal:
    • all-connectors-it-2 (JDK 8): Maven Central connection reset while resolving mysql-connector-java:8.0.16 for connector-cdc-mongodb-e2e - a network/infra flake, unrelated to this PR.
    • all-connectors-it-7 (JDK 8): AmazondynamodbIT.testAmazondynamodb failed with table sink_table is empty - a local-DynamoDB-container read-before-write-visible timing flake in a connector this PR never touches.
    • engine-v2-it (JDK 11): two failures out of 196 tests. BackpressureSlowSinkIT is the already-tracked, pre-existing flake (tracked separately upstream); the PR description and my own diff check both confirm that test and its config are byte-identical to dev. SavepointBusySourceBarrierIT is new to me this round - it's a test added by an unrelated, already-merged PR, not touched by this PR's diff, and it deliberately uses a tight 60-second checkpoint timeout by design (per its own class Javadoc) to detect barrier starvation. Its failure stack does go through JobMaster.savePoint(), which this PR now dispatches via the new lifecycleExecutor instead of the old shared pool - but that pool is unbounded with direct handoff, so it should if anything reduce scheduling delay relative to before, not increase it. Combined with this CI run's unusually long overall wall-clock time (6+ hours, several unrelated test classes running far longer than their typical local time), a loaded runner tripping a 60-second-margin test looks like the more likely explanation, though I want to flag this honestly as a reasoned inference rather than a confirmed root cause.
  • None of the four failures touch a file in this PR's diff, and the one test this PR does modify passed. Still, I'd like to see a rerun (or a couple, given the intermittency history here) land clean before calling CI fully resolved, and the SavepointBusySourceBarrierIT failure specifically deserves at least one more clean rerun given it does pass through code this PR reroutes onto a different executor.
  • Severity: Low (diagnosis strongly points away from this PR, but not yet CI-confirmed clean)
  • Raised by another reviewer: No

Issue 2 (Low, carryover, now effectively resolved): line citation in the teardown comment.

  • Location: CoordinatorExecutorMassFailoverStormIT.java:318 (comment text)
  • The method-start line number (936) is now exactly correct. The supporting range (946-950) points to the invocation-building statements rather than the actual blocking invoke.get() call a few lines further down (around line 959) - a small residual imprecision, not worth another round-trip on its own.
  • Potential risk: negligible - a reader following the citation will land in the right method either way.
  • Best improvement: if you touch this comment again, either point directly at the invoke.get() line, or drop specific line numbers in favor of just the method name (more resilient to future drift).
  • Severity: Low
  • Raised by another reviewer: No

Issues 3-6 (unchanged from last round, still open, still Low):

  • Three sequential 20-second waits inside synchronized clearCoordinatorService() - CoordinatorService.java:1361-1363, 1382-1391
  • Executor fields reassigned on reactivation but not volatile - CoordinatorService.java:226-231
  • Finite max-thread-num no longer caps running jobs, documented and tracked as a follow-up - hybrid-cluster-deployment.md
  • PR description could use a refresh to reflect the current head (small, non-blocking)

2. Code Quality Assessment

2.1 Coding Standards

No change from last round. The one-line fix in this round is a plain comment correction with no style implications.

2.2 Test Coverage and Test Stability

This round's change is comment-only and touches no assertions, timing, or control flow, so it cannot introduce new flakiness on its own.

Stability rating: Risk present. The CoordinatorExecutorMassFailoverStormIT stabilization fix from the previous commit (settle window + shared teardown deadline) passed cleanly in this round's CI run, which is a good sign, but the class has a documented history of intermittent failures on JDK 8, so one clean run isn't quite enough for me to call it Stable yet. I'd like to see it hold up over at least one more CI cycle before upgrading the rating.

2.3 Documentation Updates

No docs/en or docs/zh files changed in this round; the only touched file is a Java test comment.

3. Architectural Soundness

3.1 Elegance of the Solution

Long-term solution (first slice), unchanged assessment. Still a clean, explicitly-scoped first slice with a documented interim (unbounded lifecycle pool). This round's change is a trivial, precise correction, not a workaround.

3.2 Maintainability

Unchanged from last round - still good.

3.3 Extensibility

Unchanged from last round.

3.4 Historical-Version Compatibility

Unchanged: no persisted-state, protocol, checkpoint, or savepoint format changes; 2.x -> 3.0 upgrade path is unaffected.

4. Issue Summary

# Issue Location Severity
1 CI on this head still shows 4 job failures; all four are diagnosed as unrelated to this PR's diff (network flake, connector timing flake, one pre-existing tracked flake, one newly-observed timing-sensitive test in an unrelated, unmodified file) - not yet CI-confirmed clean Fork run 35811144092; SavepointBusySourceBarrierIT, BackpressureSlowSinkIT, AmazondynamodbIT, all-connectors-it-2 Low
2 Teardown comment's corrected line citation is close but not exact (946-950 vs. the actual blocking call near line 959) CoordinatorExecutorMassFailoverStormIT.java:318 Low
3 Three sequential 20s waits inside synchronized clearCoordinatorService() CoordinatorService.java:1361-1363, 1382-1391 Low
4 Executor fields reassigned on reactivation but not volatile CoordinatorService.java:226-231 Low
5 Finite max-thread-num no longer caps running jobs (documented, tracked follow-up) hybrid-cluster-deployment.md Low
6 PR description needs a refresh to match the current head PR description Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed

    • None from the source review. Production code is unchanged and I still find no functional, compatibility, or resource-lifecycle defect anywhere in it.
    • Before merge: this PR is still marked as a draft and is currently diverged from dev (8 commits ahead, 7 behind), so it isn't mergeable as-is regardless of review outcome. I'd also like to see a clean CI run (or two, given the intermittency history) that isolates the executor-split tests from the unrelated connector/infra failures before calling CI fully green.
  2. Recommended fixes - non-blocking

    • Issue 2: the line citation is close enough now that I wouldn't ask for another round just for this, but feel free to tighten it if you're back in that file anyway.
    • Issues 3-6 as previously described; none block merge.

Overall assessment: this is a tidy, minimal follow-up round - one line, fixing exactly the nit I raised - and it doesn't disturb anything I already verified. The design itself continues to hold up well: production code is sound, well-documented as an intentional first slice, and the test-stability fix from the prior commit is holding up in CI. My only asks before merge are procedural (take it out of draft, sync with dev, get one more clean CI run) rather than anything code-related. Nice work keeping the iterations tight!

@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 keeping this moving! I re-verified the whole PR from scratch on the current head rather than assuming last round's conclusions still hold, since the head commit changed again. Short version up front: the change since my last review (9c4e0e69 → ebdf7cbf0) is exactly one commit, and it's a routine merge dev into this branch — it does not touch a single file this PR owns. I diffed both commits against every file this PR's diff touches and confirmed byte-for-byte identity, so there is nothing new to re-litigate on the source side. I'm not flagging anything the previous six rounds missed — I re-derived every conclusion independently below and they match.

What Problem Does This PR Solve?

  • User pain point: CoordinatorService ran new-job admission and full job-lifecycle work (JobMaster.run() blocking for the job's entire duration, plus cancel/stop/savepoint/history-lookup and master-switch restore fan-out) on the same bounded executor. Under a finite max-thread-num, a burst of admissions (or a mass-failover restore) could starve cancel/savepoint/restore progress for jobs that were already running.
  • Fix approach: unchanged from every prior round — executorService now handles admission only; a new lifecycleExecutor (ThreadPoolExecutor(0, MAX_VALUE, 60s, SynchronousQueue, RejectionCountingHandler)) handles JobMaster.run(), restore fan-out, cancel/stop/savepoint/history; a new dedicated pendingJobSchedulerExecutor runs the permanent pending-job scheduler loop. All three are torn down and recreated together on step-down/reactivation, and a parallel job_lifecycle_thread_pool_* metric family now reports the new pool.
  • One-sentence summary: the design and implementation are sound and have already survived five rounds of review with every blocker resolved by root-cause fixes (not timeout bumps or disabled tests); this round's only change is a no-op dev sync, so the PR is exactly as close to mergeable as it was at my last review — the remaining gaps are procedural (draft status, branch is now 1 commit behind dev, full CI matrix not yet green on this head), not code.

1. Code Change Review

1.1 Core Logic Analysis

Diff since my last full review, verified directly:

git diff --stat 9c4e0e692b7487fc59a7975e7d10451093c45256 ebdf7cbf035aebffb5b89d14aafa3a7fcb8904d4 -- \
  seatunnel-engine/seatunnel-engine-server/src/main/java/.../CoordinatorService.java \
  seatunnel-engine/seatunnel-engine-server/src/main/java/.../SeaTunnelServer.java \
  seatunnel-engine/seatunnel-engine-server/src/main/java/.../JobThreadPoolStatusExports.java \
  seatunnel-engine/seatunnel-engine-server/src/test/java/.../CoordinatorService*Test.java \
  seatunnel-engine/seatunnel-engine-server/src/test/java/.../TelemetryCollectorCoordinatorGuardTest.java \
  seatunnel-e2e/.../CheckpointCoordinatorFailoverIT.java \
  seatunnel-e2e/.../CoordinatorExecutorMassFailoverStormIT.java
# -> empty, 0 files changed

Every file this PR's own diff (merge-base(dev, head)..head) touches is identical between the commit I last reviewed and the current head. The only commit in between is ebdf7cbf0 Merge remote-tracking branch 'origin/dev' into codex/issue-12117-coordinator-lifecycle, which pulls in 13 unrelated upstream commits (OceanBase CDC connector, several connector-doc/OptionRule fixes, MQTT source/sink tests, a Zeta WAL-recovery memory optimization, a Flink SchemaOperator fix, a NumericFunction test, CI workflow budget tweaks, benchmark-suite pruning). None of them touch seatunnel-engine-server's coordinator code, so there is no new production behavior to analyze this round.

I re-traced the full runtime path independently anyway (not just diffed) to make sure "unchanged" really means "still correct":

  • submitJob (CoordinatorService.java:1424) still dispatches the outer init/enqueue task on the admission executorService (line 1439) and constructs JobMaster with MDCTracer.tracing(jobId, lifecycleExecutor) — confirmed the admission task never blocks on job completion, so it can't itself be starved.
  • The pending-job scheduler now runs exclusively on pendingJobSchedulerExecutor (CoordinatorService.java:359), and pendingJobSchedule() submits the actual jobMaster.run() task to lifecycleExecutor with identity-safe removal, runningJobMasterMap.remove(jobId, jobMaster) (line 516) — still correctly guards against a late-exiting lifecycle task evicting a replacement JobMaster after reactivation.
  • restoreAllRunningJobFromMasterNodeSwitch fan-out (line 1107) and cancelJob/stopJob/savePoint/history lookups (lines 1577, 1590, 1629, 1651) are all still routed to lifecycleExecutor, not executorService.
  • checkNewActiveMaster() (line 1283) recreates all three executors on reactivation, now consistently checking isShutdown() || isTerminated() for all three (this was my old Low Issue 5 from the first round, and it's still fixed).
  • clearCoordinatorService() (line 1325) still shuts down and awaits all three pools via the shared awaitExecutorTermination(name, executor) helper (lines 1361-1391).

I did not find any code-side regression, and I did not find anything the last five reviews should have caught but didn't.

1.2 Compatibility Impact

Fully compatible relative to my last review — no production code changed, so nothing new to reassess. Config keys/defaults unchanged; job_thread_pool_* metric names unchanged (semantics narrowed to admission-only, as before); job_lifecycle_thread_pool_* metrics still present. docs/en and docs/zh incompatible-changes.md still correctly disclose the one real semantic change (finite max-thread-num no longer caps concurrently-running jobs).

1.3 Performance / Side-Effect Analysis

No change since last round. lifecycleExecutor is still an unbounded cached pool by explicit, documented design (deferred bounding to #12165); this is not a new risk class versus the pre-PR executorService, which already defaulted to max-thread-num = Integer.MAX_VALUE.

1.4 Error Handling and Logging

No regressions. One thing worth re-confirming since CI evidence has moved on since my last round:

Issue 1 (Low, carried forward, refreshed with new evidence): CI on this exact head is not yet fully green, but nothing failing touches this PR's diff.

  • I pulled the fork's live run for ebdf7cbf0 (https://github.com/jjj-n/seatunnel/actions/runs/35950793699) rather than trusting the apache-side "Build" check, which is only a pointer and currently shows cancelled/fail after ~6h — the real run is still in_progress at review time.
  • All four unit-test jobs (8/11 × ubuntu/windows) — where every test this PR adds actually lives (CoordinatorServiceAdmissionSaturationTest, CoordinatorServiceJobCleanupTest, CoordinatorServiceTest, TelemetryCollectorCoordinatorGuardTest are all under seatunnel-engine-server/src/test/java, not an E2E module) — are SUCCESS.
  • engine-v2-it (11, ubuntu-latest) — where CoordinatorExecutorMassFailoverStormIT and CheckpointCoordinatorFailoverIT live — is SUCCESS. engine-v2-it (8, ubuntu-latest) was still in_progress when I checked (started only at 09:29:53Z into a run that began at 03:16:53Z).
  • Two unrelated failures exist elsewhere on this run: all-connectors-it-7 (11, ubuntu-latest) fails on PostgresCDCIT.testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes (ConditionTimeout at line 625, a Postgres CDC connector test this PR's diff never touches), and kudu-connector-it (11, ubuntu-latest) shows cancelled. Neither is in a module this PR's diff reaches.
  • Severity: Low (every job that actually exercises this PR's own code is green so far; the only thing not yet confirmed is the still-running engine-v2-it (8) job).
  • Raised by another reviewer: No.

2. Code Quality Assessment

2.1 Coding Standards

No change from last round — still good, no missing-comment issues on core methods/fields.

2.2 Test Coverage and Test Stability

No test code changed since my last review. I re-read the cleanup-reschedule test added two rounds ago (CoordinatorServiceJobCleanupTest.testEarlyCleanupPreservesRecordAndReschedulesUntilDelayElapses) specifically to double check it has real failure-detecting power, since that was the blocker I closed out last time: it mocks ScheduledExecutorService and captures the actual Runnable/delay passed to schedule(...), invokes the callback synchronously (no sleeps), asserts the cleanup record survives an early fire and a second schedule() call happens, then advances createTimeMillis past the deadline and asserts the record and all four backing IMap entries are actually removed on the second fire. If the reschedule fix were reverted (record dropped on early fire instead of rescheduled), this test would fail on the Mockito.verify(scheduler, Mockito.times(2)) assertion and on assertEquals(record, pendingJobCleanupIMap.get(jobId)) — genuine failure capability, not a formalism.

Stability rating: Risk present, unchanged from last round — no new anti-patterns found, but I still want to see the currently-running engine-v2-it (8, ubuntu-latest) job (and ideally one more clean cycle overall, given this class's documented flake history) land green before calling it Stable.

2.3 Documentation Updates

No docs/en/docs/zh files changed this round.

3. Architectural Soundness

3.1 Elegance of the Solution

Unchanged — still a clean, explicitly-scoped first slice with a documented interim (unbounded lifecycle pool, follow-up tracked as #12165).

3.2 Maintainability

Unchanged — the shared awaitExecutorTermination helper and the addThreadPoolMetrics dedup in JobThreadPoolStatusExports still hold up well.

3.3 Extensibility

Unchanged from last round.

3.4 Historical-Version Compatibility

Unchanged: no checkpoint/savepoint/protocol format changes; the cleanup-reschedule fix only affects an internal IMap bookkeeping record's retry timing, not its schema.

4. Issue Summary

# Issue Location Severity Raised by another reviewer
1 CI on this exact head (ebdf7cbf0) not yet fully confirmed green: engine-v2-it (8, ubuntu-latest) still in progress at review time; two unrelated connector-module failures (PostgresCDCIT timeout, kudu-connector-it cancelled) present but out of this PR's diff Fork run 35950793699 Low No
2 Three sequential 20s waits inside synchronized clearCoordinatorService() — up to 60s theoretically held under that monitor during step-down CoordinatorService.java:1361-1363, 1382-1391 Low No
3 executorService/lifecycleExecutor/pendingJobSchedulerExecutor fields are reassigned on reactivation inside a synchronized block but are plain (non-volatile) fields; e.g. submitJob (CoordinatorService.java:1439) reads executorService directly with no isActive/synchronized gate immediately at that call site CoordinatorService.java:226-231, 1439 Low No
4 Finite max-thread-num no longer caps concurrently-running jobs (correctly documented and tracked as a follow-up, #12165) docs/en/engines/zeta/hybrid-cluster-deployment.md Low No
5 PR description could use a refresh to reflect the current head (small, non-blocking) PR description Low No

(Renumbered from my last review — the previous Issue 1/2 there, about the teardown comment's line citation, are fully resolved and dropped from this table since that file is untouched this round.)

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed

    • None from the source review. Production and test code are unchanged from the head I already fully verified, and I still find no functional, compatibility, or resource-lifecycle defect anywhere in them.
    • Procedural, not code: this PR is still marked draft, and per the compare API it's currently diverged (9 ahead, 1 behind dev — dev has advanced one more commit past this branch's last sync point). Please take it out of draft and sync once more before merge.
    • I'd like to see the currently-running engine-v2-it (8, ubuntu-latest) job finish green (it hadn't completed as of this review) before calling CI fully clean on this head, even though every other job that touches this PR's own code is already green.
  2. Recommended fixes — non-blocking

    • Issues 2-5 as previously described; none block merge, and none are new this round.

Overall assessment: this round is a routine dev sync with zero PR-authored changes, so there's genuinely nothing new to review on the code side — I verified that by diffing the exact file set this PR owns between the last head I reviewed and this one and confirming byte-for-byte identity, then re-traced the runtime path from scratch anyway rather than taking that diff on faith. The design has now survived five rounds of substantive review with every blocker closed by a real root-cause fix (rewritten deterministic test, fixed fault-injection race, storage-backend swap, a genuine untested-bugfix now covered by a test with real failure-detecting power) rather than a threshold bump or a skip. At this point I'd call this ready to merge as soon as the purely procedural items land: take it out of draft, sync the one commit dev has pulled ahead, and let the still-in-progress CI job finish. I don't expect another source-level round to be necessary unless that final CI run turns up something new.

@jjj-n
jjj-n marked this pull request as ready for review September 24, 2026 12:39

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the update! I re-reviewed the latest head at 9197c3bc5 from scratch rather than assuming my last review's conclusions still hold, since the head commit changed again. Short version up front: the change since my last review (ebdf7cbf0 → 9197c3bc5) is exactly one commit, and it's a routine dev merge that touches zero files this PR owns (I diffed both commits against every file this PR's diff touches and confirmed byte-for-byte identity, then re-traced the full runtime path independently anyway rather than taking that diff on faith). So there is nothing new to re-litigate on the source side this round — but CI for this exact head has now finished (it was still running last time), and the PR is out of draft and fully synced with dev, so I have two genuinely new things to report.

What Problem Does This PR Solve?

  • User pain point: CoordinatorService ran new-job admission and the full job lifecycle (JobMaster.run() blocking for the job's entire duration, plus cancel/stop/savepoint/history-lookup and master-switch restore fan-out) on the same bounded executor. Under a finite max-thread-num, a burst of admissions or a mass-failover restore could starve cancel/savepoint/restore progress for jobs that were already running.
  • Fix approach: executorService now handles admission only; a new lifecycleExecutor (unbounded cached pool, direct handoff) handles job execution, restore fan-out, and cancel/stop/savepoint/history-lookup; a new dedicated executor runs the permanent pending-job scheduler. All three are torn down and recreated together on step-down/reactivation, the running-master map is now cleared by instance identity so a late-exiting lifecycle task can't evict a replacement master, and a parallel job_lifecycle_thread_pool_* metric family reports the new pool.
  • Summary: a sound, well-tested isolation slice that has now survived seven rounds of review with every blocker resolved by a real root-cause fix. I found no functional, compatibility, or resource-lifecycle defect in src/main on this head.

1. Code Change Review

1.1 Core Logic Analysis

I re-traced the full path independently (not just diffed) to confirm "unchanged" really does mean "still correct":

  • submitJob's outer admission task still dispatches on executorService, but the JobMaster it constructs is wired to lifecycleExecutor — admission threads can never be occupied by lifecycle work.
  • The pending-job scheduler runs exclusively on its own executor, dispatches jobMaster.run() to lifecycleExecutor, and removes the map entry by identity on completion (runningJobMasterMap.remove(jobId, jobMaster)), correctly guarding against a late-exiting task evicting a replacement JobMaster installed after a reactivation.
  • Restore fan-out, cancel, stop, savepoint, and history lookups are all routed to lifecycleExecutor, not executorService.
  • checkNewActiveMaster() recreates all three executors on reactivation with a consistent isShutdown() || isTerminated() gate each; clearCoordinatorService() shuts down and awaits all three via a shared helper.

I verified the problem this PR targets is real by reading the pre-PR code directly: the old code passed the same admission-pool-backed executor into both the outer dispatch and every JobMaster instance, and cancel/savepoint/restore all used it too. With a SynchronousQueue (no buffering) and JobMaster.run() blocking for the job's whole life, a finite max-thread-num genuinely had no way to free up a thread for cancel/savepoint once all configured threads were occupied by running jobs. The fix is the right shape — a second, purpose-built executor — not a threshold workaround.

1.2 Compatibility Impact

Partially incompatible, and correctly disclosed: config keys and defaults are unchanged, but an operator-configured finite max-thread-num no longer caps the number of concurrently-running jobs (it only caps admission throughput now). Both docs/en and docs/zh incompatible-changes.md have a dedicated section spelling this out, including that neither setting bounds total master threads and pointing at the new metrics for monitoring. No checkpoint/savepoint/protocol changes.

1.3 Performance / Side-Effect Analysis

The unbounded lifecycleExecutor maximum is an explicit, documented, deferred-follow-up design choice (tracked as #12165), and not a new risk class versus pre-PR dev, whose shared executor already defaulted to max-thread-num = Integer.MAX_VALUE out of the box. The risk only changes for deployments that had explicitly configured a finite cap — exactly the case the incompatible-changes doc calls out.

1.4 Error Handling and Logging

No regressions; the new shared awaitExecutorTermination helper actually improves observability slightly, since termination of the two new pools is now logged the same way the admission pool's already was.

One long-standing, non-blocking observation, carried forward unchanged from my 2026-09-21 review (not new this round, and not something I missed before — I raised it then as an optional aside and I'm not asking for a change now either): submitJob's failure-cleanup branch still removes from runningJobMasterMap by jobId alone, not by the same instance-identity check this PR introduces at the pending-job-scheduler completion path. It's only reachable via a narrow race on a duplicate/retried submission for the same job ID, which submitJob's own top-of-method comment treats as an anticipated scenario. Low severity, untouched by this PR's diff — happy to see it get the same identity treatment if this area gets touched again, but not blocking.

2. Code Quality Assessment

2.1 Coding Standards

Good — every new field, factory method, and the new getLifecycleThreadPoolStatusMetrics() accessor carries a short comment or Javadoc explaining intent/constraints. No missing-comment gaps on core new methods or fields.

2.2 Test Coverage and Test Stability

Strong, and I checked this directly rather than taking it on faith: CoordinatorServiceAdmissionSaturationTest holds the sole admission thread with a real core=1,max=1 engine and a blocking latch, then proves checkpoint/savepoint, cancel, and post-reactivation restore-and-completion all still progress — reverting the split would hang every one of these against its timeout. testLateLifecycleExitDoesNotRemoveReplacementMaster directly targets the identity-safe-removal fix and would fail if that fix were reverted. testReactivationRebuildsAllExecutorsAndPreservesAdmissionSettings would fail if any of the three executor-recreation branches were dropped. The telemetry guard test now asserts full 16-metric-family output with specific sample values, not just non-emptiness.

Stability rating: Stable. I'm upgrading this from "Risk present" in my last review now that this exact head's CI has actually finished (see below) — this PR's own tests passed cleanly in the same job run that failed overall, and the failures there are unrelated.

2.3 Documentation Updates

docs/en/docs/zh for incompatible-changes.md, telemetry.md (all 16 metric names checked against the exporter code, including the _total counter suffix), and the hybrid/separated cluster deployment guides are all updated and consistent with the code.

3. Architectural Soundness

Elegance: a clean, explicitly-scoped first slice (#12117) with a documented interim (unbounded lifecycle pool, follow-up tracked as #12165) — long-term solution, not a workaround.
Maintainability: the shared termination-await and metrics-export helpers replace what would otherwise be triplicated blocks, without over-engineering beyond what's actually shared.
Extensibility: leaves an obvious extension point for a bounded lifecycle pool later without requiring another structural change.
Historical compatibility: no checkpoint/savepoint/protocol/schema changes; the one real behavioral change is documented.

4. Issue Summary

# Issue Location Severity
1 submitJob failure-cleanup removes from the running-master map by ID only, not identity (narrow duplicate-submit race) CoordinatorService.java, submitJob's catch/cleanup branch Low
2 Up to 3×20s sequential termination waits inside synchronized clearCoordinatorService() CoordinatorService.java, clearCoordinatorService() Low
3 Executor fields reassigned under synchronized on reactivation but not volatile CoordinatorService.java, executor fields + submitJob read site Low
4 Finite max-thread-num no longer caps running jobs (documented, tracked follow-up #12165) docs/en/engines/zeta/hybrid-cluster-deployment.md Low
5 engine-v2-it (8, ubuntu-latest) red on this head from two unrelated, already-tracked pre-existing flakes fork CI run Low

No High or Medium issues; no blocking issue.

CI status on this head (9197c3bc5): all four unit-test jobs (Ubuntu/Windows × Java 8/11) are green, engine-v2-it (11) is green. engine-v2-it (8) is red, but I pulled the full log and traced both failures individually: SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck (unrelated worker-crash/cancel race, fix tracked in still-open PR #12311) and CheckpointEnableIT.testZetaStreamingCheckpointNoInterval (task-transition state-entry-missing timeout, fix tracked in still-open PR #10551). Neither test file is touched by this PR's diff. This PR's own tests in that same job run — CoordinatorExecutorMassFailoverStormIT and CheckpointCoordinatorFailoverIT — both passed cleanly. Since both referenced fixes are still unmerged, a dev sync would not clear this; a plain rerun of the job is the right next step.

The PR is out of draft and fully synced with dev (0 commits behind). mergeStateStatus shows BLOCKED, which reflects that a human-approved review is still required for branch protection, not an actual conflict.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

1. Blockers — must be fixed

  • None from the source review — I found no functional, compatibility, or resource-lifecycle defect anywhere in src/main on this head.
  • I'd like to see engine-v2-it (8, ubuntu-latest) rerun and land green before calling CI fully clean, even though I've traced its current failures to two unrelated, already-tracked, still-open bugs and confirmed this PR's own tests in that job pass. That's a CI rerun, not a source change, which is why I'm not marking this a plain "Ready to merge."

2. Recommended fixes — non-blocking

  • Issues 1-4 above; none are new this round.

Overall assessment: this design has survived seven rounds of substantive review with every blocker closed by a real root-cause fix. This round's diff contribution is zero (a no-op dev sync), but it was worth the wait for CI to finish: I now have a definitive, traced explanation for the one red job, instead of "still running" from last time. I don't expect another source-level round to be necessary unless the engine-v2-it (8) rerun turns up something genuinely new. Thanks again for the very thorough validation notes across all these rounds!

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

Thank you for the continued updates and for keeping the PR description so precise. I re-read the whole PR at the new head (8f5e089) from scratch. Since my last approval at 9197c3b there are two new dev merges; the only PR-owned files that differ are the two incompatible-changes.md files and SeaTunnelServer.java, and those differences are entirely upstream content that came in through the merges (a Doris option-key entry in the docs, and the REST-port change from #12298 in SeaTunnelServer). The PR's own hunks are unchanged. My source conclusions from the previous round therefore still hold, but two new CI/merge facts need to be reported.

What Problem Does This PR Solve?

  • User pain point: CoordinatorService ran new-job admission and the whole job lifecycle (JobMaster.run() blocking for the job's entire life, cancel/stop/savepoint/history lookup, and master-switch restore fan-out) on one bounded executor. With a finite max-thread-num, a burst of admissions or a mass-failover restore could starve cancel, savepoint and restore progress of jobs that were already running.
  • Fix approach: executorService now handles admission only; a new cached, direct-handoff lifecycleExecutor runs job execution, restore fan-out and cancel/stop/savepoint/history work; a dedicated single-thread executor runs the pending-job scheduler. All three are stopped on step-down and recreated on reactivation, the running-master map entry is removed by instance identity, and a parallel job_lifecycle_thread_pool_* metric family is exported.
  • Example: core=max=1, one admission task blocked forever. Before: an already-running job cannot be savepointed or cancelled because those calls queue behind the blocked admission thread. After: they run on the lifecycle pool and complete.

1. Code Change Review

1.1 Core Logic Analysis

Re-derived on this head, not assumed from the delta:

  • CoordinatorService.java:496-522 (pendingJobSchedule): jobMaster.run() is submitted through MDCTracer.tracing(jobId, lifecycleExecutor), and the finally block removes with runningJobMasterMap.remove(jobId, jobMaster), so a late-exiting task cannot evict a replacement master installed after reactivation.
  • CoordinatorService.java:353-359: the pending-job scheduler loop is submitted to pendingJobSchedulerExecutor, so it no longer occupies an admission thread.
  • Both new JobMaster(...) sites (restore at about line 1167, submit at about line 1470) are given MDCTracer.tracing(jobId, lifecycleExecutor), so checkpoint coordination and physical-plan work spawned by JobMaster also leave the admission pool. The outer submit task (dedup, deserialize, validate, construct, enqueue) stays on executorService and does not block on job completion.
  • Restore fan-out (lines 683-686 and 1107-1111), savePoint (line 1580 area), getJobDetailState, cancelJob and stopJob all use lifecycleExecutor.
  • checkNewActiveMaster (lines 1283-1292) rebuilds each of the three executors when shut down or terminated; clearCoordinatorService (lines 1353-1367) shuts all three down and awaits each through the new awaitExecutorTermination helper.
  • Normal-path reachability: this is the main path. lifecycleExecutor and the scheduler executor are created unconditionally in the constructor (lines 263-265), so every submission, cancel, savepoint and restore on every cluster runs through the split, not only an edge case.
submitJob -> executorService (admission, bounded) -> new JobMaster(lifecycleExecutor) -> pendingJobQueue
pendingJobSchedulerExecutor -> pendingJobSchedule -> runningJobMasterMap.put
   -> lifecycleExecutor.submit { jobMaster.run() (blocks for job lifetime) ; remove(jobId, jobMaster) }
cancel / stop / savePoint / getJobDetailState -> lifecycleExecutor
master switch: checkNewActiveMaster -> recreate 3 executors -> restoreAllRunningJobFromMasterNodeSwitch -> lifecycleExecutor
step-down: clearCoordinatorService -> shutdownNow x3 -> awaitTermination (20s each) x3

Verdict: no functional, ordering, or resource-lifecycle defect in src/main on this head.

1.2 Compatibility Impact

Partially incompatible, and correctly disclosed. Config keys and defaults are unchanged and there is no checkpoint, savepoint or serialization change. The behavioral change is that an operator-configured finite max-thread-num no longer caps concurrently running jobs, only admission. Both incompatible-changes.md files describe this, and the new job_lifecycle_thread_pool_* metrics give operators a way to watch the lifecycle pool. The unbounded lifecycle maximum is an explicit, documented interim choice. Note that the documented default for max-thread-num is already effectively unbounded, so only deployments that set a finite cap see a difference.

1.3 Performance / Side-Effect Analysis

  • Threads: the lifecycle pool has an unbounded maximum with direct handoff (line 308-318), one blocked thread per running job, which matches the pre-PR behavior for default configs. The pending-job scheduler thread is now a dedicated thread instead of one borrowed from the admission pool, which is a net reduction of a permanent admission thread.
  • Shutdown: up to three sequential 20-second awaits run inside synchronized clearCoordinatorService() (worst case 60 seconds versus 20 before). Only reachable if tasks ignore interruption.
  • Logging: printExecutionInfo now prints two tables every cycle instead of one; negligible volume.
  • Locks, retries and idempotency: no new locks; identity-based remove is strictly safer than the previous key-only remove.

1.4 Error Handling and Logging

No blocking issues found. Remaining non-blocking observations (all Low), plus the two new items from this round:

Issue 1: Merge conflict with current dev in both incompatible-changes.md files

  • Location: docs/en/introduction/concepts/incompatible-changes.md and docs/zh/introduction/concepts/incompatible-changes.md, both directly under the ## dev heading.
  • Problem: GitHub reports the PR as not mergeable (DIRTY). I reproduced it with a three-way merge against current dev: only these two files conflict. Dev added a Helm-chart REST-API-v1 entry at the same insertion point as this PR's "Zeta Coordinator Executor Ownership" section. No source file conflicts.
  • Potential risk: the PR cannot be merged or enqueued until resolved; a careless resolution could drop either side's entry.
  • Best improvement: please sync latest dev and keep both entries (this PR's section and the Helm chart entry), in both the en and zh files.
  • Severity: High (merge blocker, mechanical)
  • Raised by another reviewer: No

Issue 2: SavePointTest.testSavePointButJobGoingToFail failed on this head and is not yet attributed

  • Location: seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/checkpoint/SavePointTest.java:87-92; fork CI job "Run / unit-test (11, ubuntu-latest)".
  • Problem: after three savepoint requests all correctly errored, the job never reached FAILED within the 120-second await (the assertion arguments are reversed in the test, so the message reads "expected RUNNING but was FAILED"; it means the status stayed RUNNING). This PR moves savePoint, cancel and JobMaster execution onto a new executor, so I cannot call this unrelated from the log alone. The test file is not touched by the PR, the PR-owned production hunks are unchanged from the head where all four unit-test jobs were green, and I could not find a mechanism in the diff that would keep a failing job RUNNING (the failure path goes through JobMaster/PhysicalPlan on the same lifecycle pool, and the pool is unbounded, so there is no thread starvation path). My best explanation is an existing race in that test, but this is an inference, not an observation.
  • Potential risk: if it is a real interaction with the executor split, it would be a savepoint-on-failing-job hang, which is exactly the class this PR claims to harden.
  • Best improvement: rerun only that failed unit-test job. If it passes, treat it as a flake; if it fails again, please attach the job-level log for the test's jobId so we can see whether the JobMaster ever left RUNNING.
  • Severity: Medium (unattributed CI signal on the touched area)
  • Raised by another reviewer: No

Issue 3: Executor fields are reassigned on reactivation but are not volatile (carried over, Low)

  • Location: CoordinatorService.java:226, 230, 231 and their read sites in submitJob/restore.
  • Problem: fields are written under synchronized checkNewActiveMaster but read without the lock. This matches how the existing executorService field already behaved, so it is not a regression.
  • Best improvement: declare the three fields volatile if this area is touched again.
  • Severity: Low
  • Raised by another reviewer: No

Issue 4: submitJob failure cleanup removes from the running-master map by id only (carried over, Low)

  • Location: CoordinatorService.java, catch/cleanup branch of submitJob.
  • Problem: the identity-based removal introduced here is not applied in this branch; only reachable through a narrow duplicate-submit race. I raised this as an optional aside in an earlier round; it is unchanged and not blocking.
  • Severity: Low
  • Raised by another reviewer: No

Issue 5: Up to three sequential 20s termination waits inside synchronized clearCoordinatorService (Low)

  • Location: CoordinatorService.java:1361-1363.
  • Problem: worst case step-down now holds the monitor for about 60 seconds. Only when tasks ignore interruption.
  • Best improvement: optional; await against a shared deadline as done in the storm IT.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Good. New fields, factory methods and the lifecycle metrics accessor carry short intent comments or Javadoc; the new helper is small and named for what it does. The thread name of the scheduler changed from a manually set name to a factory pattern pending-job-schedule-runner-%d; I searched the repo for consumers of the old name and found none.

2.2 Test Coverage and Test Stability

Strong. CoordinatorServiceAdmissionSaturationTest holds the only admission thread with a latch on a real cluster and proves checkpoint, savepoint, cancel and post-reactivation restore still complete; reverting the split would hang these. testLateLifecycleExitDoesNotRemoveReplacementMaster would fail if the identity-based remove were reverted, and the reactivation test would fail if any executor recreation branch were dropped. CoordinatorServiceJobCleanupTest covers early cleanup rescheduling. The storm IT now requires all restored jobs to stay RUNNING for five seconds before cancellation and uses one shared teardown deadline.

Stability rating: Risk present, but only because of the two CI items above, not because of the new tests themselves. BackpressureSlowSinkIT (only one additional checkpoint observed, samples 1 then 2 flat) is byte-identical to dev and fails on the known checkpoint-starvation issue tracked by the still-open #12313 and #12316; it is not caused by this PR. TestFilterRowKindIT.testFilterRowKindMultiTable failed on the Flink container and does not go through CoordinatorService.

2.3 Documentation Updates

Good and consistent: hybrid/separated deployment guides, telemetry references (all eight admission and eight lifecycle metric families) and the incompatible-changes entry exist in both en and zh. Only the merge conflict in Issue 1 needs resolving.

3. Architectural Soundness

3.1 Elegance of the Solution

Long-term solution for the isolation problem, explicitly scoped as the first slice of #12117 with bounding of the lifecycle pool deferred. The fix sits at the right place (the shared executor), not a threshold workaround.

3.2 Maintainability

Good: shared await and status helpers replace triplicated blocks. The three-executor lifecycle is reasonably clear from checkNewActiveMaster and clearCoordinatorService.

3.3 Extensibility

Leaves a natural point for a bounded lifecycle pool with a queue and rejection policy later without another structural change.

3.4 Historical-Version Compatibility

No checkpoint, savepoint, protocol or schema change; config keys and defaults retained. The one behavioral change (finite max-thread-num no longer caps running jobs) is documented.

4. Issue Summary

# Issue Location Severity
1 Merge conflict with current dev in both incompatible-changes.md files docs/en and docs/zh introduction/concepts/incompatible-changes.md High
2 SavePointTest.testSavePointButJobGoingToFail red on this head, not yet attributed SavePointTest.java:87-92 (fork CI) Medium
3 Executor fields reassigned but not volatile (carried over) CoordinatorService.java:226-231 Low
4 submitJob failure cleanup removes by id only (carried over) CoordinatorService.java, submitJob cleanup Low
5 Sequential 20s waits under synchronized step-down CoordinatorService.java:1361-1363 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

1. Blockers - must be fixed

  • Issue 1: sync latest dev and resolve the two documentation conflicts, keeping both entries. No source conflicts exist, so this should be a mechanical change; please make sure the merge does not alter any PR-owned source file.
  • Issue 2: rerun only the failed Java 11 unit-test job. If it stays red, please attach its job-level log for the test's jobId so the cause can be separated from the executor split. I have no evidence it is PR-caused, but I also cannot prove it is not, and this is the exact area the PR touches.

2. Recommended fixes - non-blocking

  • Issues 3, 4 and 5; none are new this round.

Overall assessment: my earlier approval of the source change stands; I found no functional, compatibility or resource-lifecycle defect in src/main on this head, and this round adds no new source concerns. The state is COMMENT rather than APPROVE only because the PR is currently unmergeable and one CI signal on the touched area is unexplained. Both are cheap to close.

Response to existing maintainer reviews: no other maintainer has posted findings on this PR beyond mine, so there is nothing to reconcile.

CI / sync status: fork CI on this head is red for three reasons. BackpressureSlowSinkIT is the known, tracked checkpoint-starvation issue (#12313 and #12316 are still open, so a dev sync will not clear it; a plain rerun is the right step). TestFilterRowKindIT ran on Flink and is unrelated. SavePointTest is covered by Issue 2. Branch state is 8 commits behind and 11 ahead of dev with conflicts limited to the two docs files; next step is to sync dev, resolve them, and rerun the failed jobs only.

@SEZ9

SEZ9 commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

Thanks for keeping the PR synced with dev and for the precise description throughout.

My understanding of the current state at head 8f5e089dd2: the change from ebdf7cbf0 to 9197c3bc5 was a single dev merge touching none of the files this PR owns, and the two dev merges since 9197c3bc58 only brought in upstream content in the few PR-owned files that differ. The PR's own hunks are unchanged, so the earlier source-level conclusions still hold.

The design itself reads well to me: executorService for admission only, a cached direct-handoff lifecycleExecutor for JobMaster.run(), restore fan-out and cancel/stop/savepoint/history work, a dedicated single-thread executor for the pending-job scheduler, all three torn down and recreated together across step-down/reactivation, removal from the running-master map by instance identity, and the parallel job_lifecycle_thread_pool_* metric family. The core=max=1 example (a blocked admission thread no longer blocks savepoint/cancel of a running job) is exactly the user-facing behavior I want from this slice.

Two small asks before merging:

  1. Could you share the CI status for 8f5e089dd2? If anything is red, a link to the failing job and a note on whether it's related to this change would help.
  2. Please confirm the incompatible-changes entries for this PR are still accurate after the merges — in particular that the new job_lifecycle_thread_pool_* metrics and the admission-only behavior of max-thread-num are documented there and in the user-facing config docs.

Once those are covered I'm happy to approve and merge.

Resolve the merge conflicts with dev: keep both sides' documentation entries.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for keeping this PR in sync, @jjj-n. I re-reviewed the latest head (fe8352648) from scratch rather than only the delta. The only commit since my last review is another plain "merge dev" commit, and the PR's own code is unchanged, so this round is short. I also answer @SEZ9's two questions below.

What I verified on this head

  • git diff 8f5e089dd2 fe8352648 restricted to the 16 files this PR owns (three src/main sources, four unit-test classes plus the storm IT, and eight docs files) is empty. The author-owned hunks are byte-for-byte what I reviewed last time.
  • I re-traced the production change against the current source: admission on executorService, job execution/restore/cancel/savepoint/history on lifecycleExecutor, the pending-job loop on its own thread, identity-based runningJobMasterMap.remove(jobId, jobMaster), and the three-executor recreate-on-reactivation/shutdown path. I found no functional, ordering or lifecycle defect in src/main, same as my previous round.
  • No new reviewer activity apart from @SEZ9's comment (answered below).

What Problem Does This PR Solve?

  • User pain point: CoordinatorService ran job admission and the whole job lifecycle (JobMaster.run() blocking for the job's life, cancel/stop/savepoint/history, master-switch restore fan-out) on one bounded executor, so a burst of admissions or a mass failover restore could starve cancel, savepoint and restore of jobs that were already running.
  • Fix approach: executorService handles admission only; a new cached direct-handoff lifecycleExecutor runs job execution and control calls; a dedicated single-thread executor runs the pending-job scheduler. All three are stopped on step-down and rebuilt on reactivation, with a parallel job_lifecycle_thread_pool_* metric family.
  • One-sentence summary: a blocked or saturated admission pool can no longer block control operations on already-running jobs.

1. Code Change Review

1.1 Core Logic Analysis

submitJob -> executorService (admission, bounded) -> new JobMaster(..., lifecycleExecutor) -> pendingJobQueue
pendingJobSchedulerExecutor -> pendingJobSchedule -> runningJobMasterMap.put
   -> lifecycleExecutor.submit { jobMaster.run() ; finally remove(jobId, jobMaster) }
cancel / stop / savePoint / getJobDetailState / restore fan-out -> lifecycleExecutor
master switch: checkNewActiveMaster -> recreate 3 executors; step-down: clearCoordinatorService -> shutdownNow x3 + await

The executors are created in the constructor, so every submit, cancel, savepoint and restore on every cluster passes through this split: this is the main path, not a boundary path. Behavior and conclusions are unchanged from my last review.

1.2 Compatibility Impact

Partially incompatible, and correctly disclosed. Config keys, defaults, checkpoint/savepoint state and serialization are unchanged. The behavioral change is that a finite max-thread-num now bounds admission only and no longer caps concurrently running jobs; the incompatible-changes.md entries (en and zh) describe this together with the new job_lifecycle_thread_pool_* metrics.

1.3 Performance / Side-Effect Analysis

Unchanged: one blocked lifecycle thread per running job (matches the previous default behavior), one permanent admission thread freed by the dedicated scheduler, and up to three sequential 20s waits inside the synchronized step-down (Issue 5 below). No new locks or retries; the identity-based removal is strictly safer than the old key-only removal.

1.4 Error Handling and Logging

No blocking issues in the production code.

Issue 1 (still open): merge conflict with current dev in both incompatible-changes.md files (carried over from my last review, still blocking)

  • Location: docs/en/introduction/concepts/incompatible-changes.md and docs/zh/introduction/concepts/incompatible-changes.md, directly under ## dev.
  • Problem: GitHub still reports the PR as DIRTY / not mergeable. I reproduced it with a three-way merge of this head against current dev: exactly these two files conflict, and nothing else. dev added new entries at the same insertion point since the last sync (the "Runtime Requirements" entry about the Java 11 minimum, plus the SQL TINYINT array schema entry), so this PR's "Zeta Coordinator Executor Ownership" section collides with them.
  • Risk: the PR cannot be merged or enqueued until resolved; a careless resolution could drop one side's entry.
  • Best improvement: please sync the latest dev and keep both sides in both language files, without touching any PR-owned source file.
  • Severity: High (merge blocker, mechanical)
  • Raised by another reviewer: No

Issue 2 from my last review (SavePointTest red) is cleared on this head. On this head's fork run, SavePointTest ran green (6 run, 0 failures, 1 pre-existing skip) in unit-test (8, ubuntu-latest), and unit-test (8, windows-latest) and (11, windows-latest) are green as well; the PR's own CoordinatorServiceAdmissionSaturationTest (3/3), CoordinatorServiceTest (40, 0 failures), CoordinatorServiceJobCleanupTest (12/12) and TelemetryCollectorCoordinatorGuardTest (19/19) also passed there. With the production code identical, the earlier red result looks like a flake of that test, which fits my earlier inference; I no longer treat it as a blocker.

Carried over, non-blocking (unchanged, Low): Issue 3 (executor fields are reassigned on reactivation but are not volatile, CoordinatorService.java:226-231), Issue 4 (the submitJob failure-cleanup branch still removes from runningJobMasterMap by id only), Issue 5 (up to three sequential 20s termination waits inside the synchronized clearCoordinatorService, around :1361-1363). These were all in my previous review and none is new.

2. Code Quality Assessment

2.1 Coding Standards

Good, unchanged: intent comments/Javadoc on the new fields, factories and the shared await helper.

2.2 Test Coverage and Test Stability

Strong, unchanged: CoordinatorServiceAdmissionSaturationTest holds the only admission thread and proves checkpoint, savepoint, cancel and post-reactivation restore still complete; testLateLifecycleExitDoesNotRemoveReplacementMaster guards the identity-based remove; the storm IT uses one shared teardown deadline. Stability rating: Stable for the tests this PR adds or changes.

2.3 Documentation Updates

docs/en and docs/zh are both updated (hybrid/separated deployment guides, telemetry metrics, incompatible-changes). Only the merge conflict in Issue 1 needs resolving.

3. Architectural Soundness

A long-term, correctly placed fix (the shared executor), explicitly scoped as the first slice of #12117, with bounding of the lifecycle pool left for later. No change to historical-version compatibility: config keys/defaults retained, no state or protocol change.

4. Issue Summary

Number Issue Location Severity
1 Merge conflict with current dev in both incompatible-changes.md files (still open) docs/en and docs/zh introduction/concepts/incompatible-changes.md High
3 Executor fields reassigned but not volatile (carryover) CoordinatorService.java:226-231 Low
4 submitJob failure cleanup removes by id only (carryover) CoordinatorService.java Low
5 Sequential 20s waits under synchronized step-down (carryover) CoordinatorService.java:~1361-1363 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed: Issue 1 only: sync the latest dev and resolve the two docs conflicts, keeping both entries in each file. Source-wise nothing blocks this PR.
  2. Recommended fixes - non-blocking: Issues 3, 4 and 5.

Answers to @SEZ9's questions

  • CI status for fe8352648: the fork run (jjj-n/seatunnel, run 37391699568) has three red jobs, none attributable to this PR as far as I can tell. (a) unit-test (11, ubuntu-latest) failed with the runner annotation "The hosted runner lost communication with the server", so it is infrastructure, and the other three unit-test variants are green. (b) engine-v2-it (8, ubuntu-latest) failed only BackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressure (expected at least 3 additional checkpoints, observed 2); that test is not touched here and is the checkpoint-starvation issue tracked by the still-open #12313 and #12316, so a dev sync will not clear it and a plain rerun is the right step. (c) kafka-connector-it (11, ubuntu-latest) failed at KafkaIT container startup (Text file busy / exit code 126 from the Testcontainers start script), a container-environment failure in a connector this PR does not touch. The Apache-side Build check is red because it mirrors this fork run. Syncing dev for Issue 1 will start a fresh run anyway, so please rerun only the failed jobs if they recur.
  • Incompatible-changes entries still accurate? Yes. Both language entries state that core-thread-num/max-thread-num now apply to admission only, that the lifecycle pool has an unbounded maximum, that job_thread_pool_* now covers admission only and that the new job_lifecycle_thread_pool_* metrics expose the lifecycle pool. The user-facing config docs (hybrid and separated deployment guides in en and zh) describe the admission-only meaning of both settings, and telemetry.md (en and zh) lists the eight lifecycle metric families. The only action is keeping them intact when resolving the conflict.

Merge-gate facts: the branch is diverged from dev (12 ahead, 43 behind) and mergeStateStatus is DIRTY, so this is a real conflict, not just an update-branch prompt. reviewDecision is REVIEW_REQUIRED; I only have read-level review rights, so a committer will need to give the final approval once the conflict is resolved and CI is rerun.

Overall: the source change remains sound and unchanged since my earlier approval, and the only thing standing between this PR and merge is the mechanical docs conflict plus a clean rerun. Thanks again for the careful work, @jjj-n!

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants