Skip to content

[Test][Zeta] Activate coordinator fixtures after scheduler cleanup - #12051

Merged
davidzollo merged 4 commits into
apache:devfrom
CryoThrust:codex/seatunnel-12045-test-lifecycle
Nov 22, 2026
Merged

davidzollo merged 4 commits into
apache:devfrom
CryoThrust:codex/seatunnel-12045-test-lifecycle

Conversation

@CryoThrust

@CryoThrust CryoThrust commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Yes, I am contributing to Apache SeaTunnel.

Purpose

Make the CoordinatorServiceTest fixture finish construction before master activation can begin. Related to #12045.

The scheduler shutdownNow() / awaitTermination() fix already landed through #12050. This PR keeps a guard that scheduler teardown must leave the coordinator executor usable, and removes the remaining constructor-time activation window in four tests.

Changes

  • Start the failover, idempotent activation, WAIT and REJECT fixtures as non-master. Enable master ownership only after the fixture has stopped its automatic listeners and queued the test job, immediately before explicit activation.
  • Explain and assert the coordinator executor invariant after listener cleanup.
  • Sync with current dev; production scheduling, configuration, serialization and public APIs are unchanged.

Verification

On JDK 11:

./mvnw -pl seatunnel-engine/seatunnel-engine-server -Dtest=CoordinatorServiceTest test
./mvnw -pl seatunnel-engine/seatunnel-engine-server -DskipTests verify

The complete test class reports 37 tests, zero failures/errors and two skips. Scoped Spotless and module verification pass. This is a test-fixture correction; no full engine E2E or full-repository pass is claimed. GitHub Build on the updated head is pending.

@github-actions github-actions Bot added the Zeta label Sep 3, 2026
@CryoThrust

Copy link
Copy Markdown
Contributor Author

CI note: the required Build status currently reports Unable to detect the workflow run for testing the changes in your PR. Actions permissions are enabled on the fork, but no Build run was created for this branch. I have not added an empty trigger commit. Could a maintainer advise or re-trigger the fork workflow when convenient?

@davidzollo davidzollo added the First-time contributor First-time contributor label Sep 3, 2026
@davidzollo

Copy link
Copy Markdown
Contributor

Good job.

Thanks a lot for your valuable contribution to Apache SeaTunnel!

To pass the automated CI checks for this PR, could you please enable CI workflows in your forked repository first? You can refer to the check run link below as a reference for the required CI configuration

https://github.com/apache/seatunnel/pull/12051/checks?check_run_id=100500757250

If you run into any trouble enabling CI or encounter related errors during the process, feel free to leave a comment here. Contributors are always ready to offer help~

image

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

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

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

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What Problem Does This PR Solve?

CoordinatorServiceTest shares one CoordinatorService fixture-construction helper (newMockCoordinatorService) across dozens of test methods, and that CoordinatorService starts a background masterActiveListener scheduler (scheduleAtFixedRate(this::checkNewActiveMaster, 0, 100, TimeUnit.MILLISECONDS)) with a zero-millisecond initial delay the instant it is constructed. The old fixture cleanup (stopCoordinatorSchedulers) called shutdownNow() on that scheduler but never waited for it to actually terminate. That left a race window: the zero-delay tick could still be queued (or already running) when newMockCoordinatorService() returned control to the test, and if the test then flipped isActive = true via reflection before that stray tick fired, the tick would observe isActive == true && !isMasterNode() and call clearCoordinatorService(), which does executorService.shutdownNow() — killing the very coordinator thread pool the test was about to submit work to. That is exactly the failure captured in linked issue #12045 (RejectedExecutionException on the second invokePendingJobScheduler() call in testPendingJobSchedulerCanAdvanceNextJobWhenPreviousResourceCheckBlocks, "completed tasks = 1" being the tell that a sibling scheduler tick sneaked in and shut the pool down between the two invocations).

This PR closes that race by making scheduler teardown synchronous (shutdownNow() + awaitTermination(5s)) and adds a fixture-level assertion that immediately flags the executor if it was ever shut down as a side effect of cleanup.

One Simple Example

Before:

CoordinatorService cs = newMockCoordinatorService(server); // masterActiveListener shutdownNow() issued but not awaited
ReflectionUtils.setField(cs, "isActive", true);             // race: stray tick can still be in flight here
invokePendingJobScheduler(cs);                               // 1st submit: OK
invokePendingJobScheduler(cs);                               // 2nd submit: RejectedExecutionException if the stray
                                                               // tick fired clearCoordinatorService() in between

After:

CoordinatorService cs = newMockCoordinatorService(server); // masterActiveListener guaranteed fully terminated
                                                              // (assertFalse(...isShutdown()) fixture check passes)
ReflectionUtils.setField(cs, "isActive", true);              // no scheduler thread left to race with this
invokePendingJobScheduler(cs);
invokePendingJobScheduler(cs);                                // deterministic, no rejected submission

Runtime Flow (test-only, no production path)

newMockCoordinatorService()
  -> new CoordinatorService(...)                 // constructor schedules masterActiveListener @ 0ms/100ms
  -> stopCoordinatorSchedulers(coordinatorService)
       -> shutdownAndAwaitTermination(masterActiveListener)   // shutdownNow() + awaitTermination(5s)
       -> shutdownAndAwaitTermination(pipelineCleanupScheduler)
       -> assertFalse(executorService.isShutdown())           // fixture sanity check
  -> return coordinatorService  // guaranteed: no background scheduler thread can touch isActive/executorService anymore

Real Call Chain

  • seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/CoordinatorServiceTest.java:759-782 — stopCoordinatorSchedulers (now delegates to the new shutdownAndAwaitTermination helper and adds the post-condition assertion), called from newMockCoordinatorService (:734-756), which is the shared fixture factory used by essentially every test in this class.
  • Production code touched: none. CoordinatorService.java itself is unchanged; the race lives entirely between test-fixture teardown ordering and the real (and correctly-designed) production behavior of checkNewActiveMaster() / clearCoordinatorService() at seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/CoordinatorService.java:257-283 (constructor scheduling) and :1241-1270 (checkNewActiveMaster, synchronized, flips isActive and calls clearCoordinatorService() on step-down) and :1281-1313 (clearCoordinatorService() does executorService.shutdownNow()).
  • This is purely a test-boundary/race path, not the normal production user path — production CoordinatorService instances are never subjected to reflection-driven isActive mutation; only this test class does that. So the fix is scoped correctly: it hardens test determinism without touching runtime semantics.

Verifying The Claimed Problem Is Real

I traced this independently rather than taking the PR description at face value:

  1. CoordinatorService constructor (CoordinatorService.java:270-271) schedules checkNewActiveMaster with initial delay 0, so the first tick can fire essentially immediately after construction, before the caller (newMockCoordinatorService) gets a chance to call stopCoordinatorSchedulers.
  2. checkNewActiveMaster() (CoordinatorService.java:1241-1258) is synchronized but has no gate against test-driven state mutation — else if (isActive && !this.seaTunnelServer.isMasterNode()) will call clearCoordinatorService() whenever isActive is true and the mocked isMasterNode() is false (the default, unstubbed Mockito return value in most tests here).
  3. clearCoordinatorService() (CoordinatorService.java:1281,1312) unconditionally calls executorService.shutdownNow().
  4. The old stopCoordinatorSchedulers called masterActiveListener.shutdownNow() but returned immediately without confirming the in-flight/queued tick had actually stopped — so the window between fixture construction and a test's ReflectionUtils.setField(coordinatorService, "isActive", true) call was genuinely racy.
  5. Issue #12045's stack trace (RejectedExecutionException on the second invokePendingJobScheduler call, "completed tasks = 1") is fully consistent with exactly this race: one task completed (the scheduler's own doomed tick, or the first pendingJobScheduleTask), then the pool went Terminated before the second submit.

Conclusion: the claimed race is real, correctly diagnosed, and the fix (make teardown synchronous via awaitTermination) directly closes the window rather than papering over the symptom.

Side Effects (CPU/Memory/GC/Locks/Concurrency)

  • awaitTermination(5, TimeUnit.SECONDS) is called twice per fixture construction (once per scheduler). In the success path (no in-flight task, which will be the overwhelming majority once the race is closed) this returns near-instantly — shutdownNow() on a single-thread ScheduledExecutorService with no other work queued terminates in well under a millisecond. This should not introduce measurable slowdown to a test class of this size on CI.
  • Worst case (if the race were somehow still present, or a tick is genuinely mid-execution and slow), each fixture construction could add up to 5s twice (10s) before failing outright via the assertTrue(awaitTermination(...)) — that is an acceptable trade-off: it converts an intermittent, hard-to-diagnose RejectedExecutionException deep inside an unrelated test body into an immediate, clearly-labeled fixture failure ("Coordinator test scheduler did not terminate after shutdown" / "...cleanup must not shut down the coordinator executor").
  • No new shared mutable state, no new threads left running past fixture construction, no resource leak — if anything this is strictly safer than before, since pipelineCleanupScheduler (60s period) is now also awaited rather than merely asked to stop, reducing the odds of a stray thread lingering across the ~1500-line test class.
  • No deadlock risk: shutdownAndAwaitTermination is invoked from the test's own thread while holding no lock on the CoordinatorService instance, so it can safely wait for the scheduler's worker thread (which may itself be blocked briefly inside the synchronized checkNewActiveMaster()) to exit.

Compatibility

Fully compatible. This is test-only code (src/test/java), touches no public API, no Option, no config default, no serialization format, no SPI/plugin registration, no production class. No entry in docs/en/introduction/concepts/incompatible-changes.md is needed.

Error Handling and Logging

  • shutdownAndAwaitTermination correctly restores the interrupt flag (Thread.currentThread().interrupt()) before failing on InterruptedException, rather than swallowing it — good practice.
  • Both failure paths (awaitTermination timing out, or being interrupted) fail the test explicitly via Assertions rather than silently continuing with an unknown scheduler state — this is exactly the right behavior for a test fixture; a silent continue here would just move the flake somewhere else.
  • No sensitive data involved.

Test Coverage and Test Stability Analysis (Section 9 — mandatory, UT changed)

This PR is the stability fix, so I evaluated it as such:

  • No Thread.sleep-based waits introduced. The change replaces a bare shutdownNow() with shutdownNow() + bounded awaitTermination(), which is the correct polling-free way to synchronize with executor shutdown (no busy-wait, no fixed sleep).
  • No new nondeterministic assertions. The added assertFalse(...isShutdown()) is a deterministic post-condition on the just-completed synchronous teardown, not a race-prone check.
  • Shared static state: none touched; CoordinatorService instances are per-test, not shared across test methods.
  • Order-dependent tests: this fix, if anything, reduces order-dependence — before this change, the outcome of testPendingJobSchedulerCanAdvanceNextJobWhenPreviousResourceCheckBlocks (and by the same mechanism, any other test in the class that flips isActive shortly after fixture construction) depended on OS thread-scheduling timing relative to sibling executor state, which is precisely how #12045 was categorized as "load-dependent... depend[ing] on a neighbouring test."
  • New timing assumption introduced: the 5-second awaitTermination bound is a new timing assumption, but it is a generous upper bound on a trivial, non-blocking shutdown (no I/O, no real work in the mocked checkNewActiveMaster tick), so the risk of a false failure under normal CI load is low. I could not find a reason this would be tighter than needed even on a constrained CI runner.

Rating: Stable. seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/CoordinatorServiceTest.java:759-782. This is a genuine root-cause fix for the race documented in #12045, not a symptom mask (no retry loop, no Thread.sleep padding, no widened tolerance, no disabled assertion).

Documentation

None required — no user-facing behavior, config, or API changed.

Section 11 (SinkWriter multi-table contract)

Not applicable — no SinkWriter/Sink code is touched.


1. Code Change Review

1.1 Core Logic Analysis

See "Verifying The Claimed Problem Is Real" above — the fix correctly targets the actual race (zero-delay scheduler tick vs. fixture-return timing vs. test's own isActive mutation), not a downstream symptom.

1.2 Compatibility Impact

Fully compatible — test-only change, see "Compatibility" above.

1.3 Performance / Side-Effect Analysis

Negligible added latency in the success path; bounded (10s) added latency only in a failure path that would previously have manifested as a much harder-to-diagnose flake elsewhere in the suite. See "Side Effects" above.

1.4 Error Handling and Logging

Correct interrupt handling, explicit Assertions.fail/assertTrue/assertFalse rather than silent continuation. See above.

2. Code Quality Assessment

2.1 Coding Standards

Clean small refactor: extracts the shared shutdownAndAwaitTermination(ScheduledExecutorService) helper instead of duplicating shutdown+await logic for the two schedulers — good reuse. Comment above stopCoordinatorSchedulers clearly documents why (not just what), matching the project's comment-quality expectations for non-trivial fixture code.

2.2 Test Coverage and Test Stability

See Section 9 analysis above — Stable, and this change is itself a positive contribution to the file's overall stability rating going forward (it hardens the shared fixture used by essentially every test in the class).

2.3 Documentation Updates

Not applicable (test-only, no user-facing change).

3. Architectural Soundness

3.1 Elegance of the Solution

The fix is minimal, scoped to the exact fixture method responsible for the race, and adds a defensive fixture-level assertion so that if this exact race pattern is ever reintroduced (e.g., a future PR adds a third zero-delay scheduler to CoordinatorService), the class will fail loudly at fixture setup instead of flaking nondeterministically deep inside an unrelated test. That is a genuinely good root-cause-plus-guardrail approach.

3.2 Maintainability

Improves maintainability: future readers of stopCoordinatorSchedulers now have both a comment explaining the race and an assertion that actively verifies the invariant it depends on.

3.3 Extensibility

No concerns — this is local to the test fixture and does not constrain future CoordinatorService production changes.

3.4 Historical-Version Compatibility

Not applicable (test-only change, no serialization/checkpoint/upgrade path involved).

4. Issue Summary

# Issue Location Severity
1 Fork CI ("Build" check) has never actually run for this branch — GitHub Actions is not enabled on CryoThrust/seatunnel, so the check shows action_required ("Unable to detect the workflow run"), not a genuine test failure. This is not caused by the code in this PR; I independently confirmed there is no workflow run at all for codex/seatunnel-12045-test-lifecycle in the fork's Actions history. davidzollo has already left the standard guidance comment on enabling Actions. Fork repository settings (CryoThrust/seatunnel) Low (process blocker, not a code defect)
2 awaitTermination(5, TimeUnit.SECONDS) timeout is a reasonable but somewhat arbitrary bound; consider whether a project-wide constant is warranted if this pattern gets reused elsewhere in the file (optional, non-blocking). CoordinatorServiceTest.java:781 Low

No High or Medium severity issues found. No other reviewer has left comments/reviews on this PR (only the author's own CI-help comment and davidzollo's standard first-time-contributor CI-enablement message), so there is nothing to deduplicate against.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed (process only, not code):

    • The fork's GitHub Actions workflow needs to actually run and pass (unit-test / relevant Zeta jobs) before this can be merged. The current Build check status is action_required, meaning no CI has executed yet for this branch — it has not failed due to anything in this diff. @CryoThrust — please enable Actions on your fork (Settings → Actions → General → "Allow all actions and reusable workflows", as davidzollo's earlier comment linked), then push a follow-up commit (or push --force after a rebase onto the latest dev) to trigger a real run so we can see actual green/red results.
  2. Recommended fixes — non-blocking:

    • None required. Issue #2 above (the 5s constant) is a nitpick you can take or leave.

Overall assessment: This is a well-diagnosed, correctly-scoped, root-cause fix for a real, previously-reported flake (#12045). The change is entirely confined to test fixture teardown ordering, does not touch any production code path, does not weaken any existing assertion, and actually adds a new defensive assertion that makes the class more resilient to regressions of the same race in the future. Once the fork's CI is enabled and a real run comes back green, I'd be happy to see this merged. Thanks for tracking down and fixing a genuinely tricky concurrency-timing bug in the test suite — nice work isolating the zero-delay scheduler as the root cause rather than just retrying or sleeping around the symptom!

@CryoThrust

Copy link
Copy Markdown
Contributor Author

I rechecked the fork configuration: GitHub Actions is enabled on CryoThrust/seatunnel with allowed_actions=all, but the fork still has no workflow run for head 70cfb3ff704d0e218c51d1f8485d5afdf0a327e9. The required Build check remains action_required because no run was created. I have not added an empty trigger commit; could a maintainer re-trigger the workflow or advise the expected event for this fork-based check?

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for digging further into this, @CryoThrust. I checked your fork's Actions history directly rather than just taking the check status at face value.

You're right that Actions is genuinely enabled on CryoThrust/seatunnel — I can see other branches on your fork (your other codex/seatunnel-* branches) have real, completed Build workflow runs, so this isn't a repo-wide Actions-disabled problem like the usual first-time-contributor case.

The specific issue is narrower: I searched the fork's full run history and there is no workflow run at all — not even a failed or cancelled one — for codex/seatunnel-12045-test-lifecycle at any commit, including the current head 70cfb3ff704d. That matches what the apache-side check shows (action_required / "unable to detect the workflow run"): GitHub never received a push event for this branch that it turned into a run, so there's nothing for the required check to attach to.

Since Actions is enabled and other branches on the same fork work fine, the lowest-cost fix here isn't a settings change — it's just getting one real push event onto this exact branch. I'd suggest:

  1. Sync this branch with the latest dev (git fetch upstream dev && git rebase upstream/dev, or merge if you prefer to avoid a force-push) and push the result. A rebase is a legitimate, non-empty commit (not just a trigger no-op) and will also pick up any CI stabilization fixes that have landed on dev since this branch was created.
  2. If that still doesn't produce a run, it's worth double-checking under your fork's Settings → Actions → General that "Allow all actions and reusable workflows" is selected specifically for this branch's workflow file version (not just the account-level toggle), since occasionally a fork-level Actions permission change doesn't retroactively apply to a ref that was pushed before the setting was flipped.

Once a real Build run lands (pass or fail), ping me and I'll take another look — my code-side review already came back clean (see my previous comment), so this really is just the last procedural gate.

Signed-off-by: Yohanes <CryoThrust@users.noreply.github.com>
@CryoThrust
CryoThrust force-pushed the codex/seatunnel-12045-test-lifecycle branch from 70cfb3f to 2ddc721 Compare September 5, 2026 10:32
@CryoThrust

Copy link
Copy Markdown
Contributor Author

Rebased onto current dev and force-pushed the resolved branch at 2ddc721f4. The rebase kept the upstream scheduler-shutdown helper and retained this PR's zero-delay listener ordering assertion.

Verified locally:

./mvnw spotless:check -pl seatunnel-engine/seatunnel-engine-server -DskipTests
./mvnw -s /Users/yohanes/.m2/settings-public-central.xml -pl seatunnel-engine/seatunnel-engine-server -DskipCheckstyleTests -Dlicense.skip=true -Dspotless.check.skip=true -Dtest=CoordinatorServiceTest -DfailIfNoTests=false test

The push created fork workflow run 33960949015, so the previously missing Build signal is now queued. Once it finishes, the procedural gate should have a real result for review.

@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: CoordinatorServiceTest intermittently fails with RejectedExecutionException (tracked in #12045) because the shared CoordinatorService fixture starts a zero-initial-delay scheduler the instant it is constructed, and the old teardown helper issued shutdownNow() without waiting for it to actually finish — leaving a race window where a stray tick could shut down the coordinator's own executor out from under a test.
  • Fix approach: this PR adds a comment documenting why the ordering matters, plus a defensive Assertions.assertFalse(getCoordinatorExecutor(...).isShutdown(), ...) check inside stopCoordinatorSchedulers, so that if a future regression ever lets a scheduler tick sneak past teardown and shut down the coordinator's real executor, the fixture fails loudly and immediately instead of surfacing as an unrelated flake deep in some other test.
  • One-sentence summary: it turns an implicit invariant ("the shared fixture never gets its executor shut down behind a test's back") into an explicit, self-checking guardrail.

1. Code Change Review

1.1 Core Logic Analysis

I re-reviewed the current head (2ddc721f4527c493d1bede6b2ddcdcf5475da3e1) from scratch rather than trusting my previous round, and traced through the rebase to understand what actually changed. This is important context that isn't obvious from the diff alone: between my last review (at 70cfb3ff7) and now, dev merged #12050 ("[Fix][Zeta] Stabilize CI test isolation"), which independently added the shutdownScheduler(ScheduledExecutorService) helper (shutdownNow() + bounded awaitTermination(5s)) that this PR originally proposed to stopCoordinatorSchedulers. @CryoThrust rebased this PR onto that new dev HEAD, and the earlier 70cfb3ff7 diff (the helper extraction + await logic) collapsed away because it's now already upstream. The PR's own remaining diff against the current dev merge-base is exactly this:

private void stopCoordinatorSchedulers(CoordinatorService coordinatorService) {
+    // The listener starts with zero delay. It must be fully stopped before tests mutate
+    // isActive; otherwise a late ownership poll can call clearCoordinatorService() and shut
+    // down the executor that the test uses to run its scheduler.
     ReflectionUtils.getField(coordinatorService, "masterActiveListener")
             .map(ScheduledExecutorService.class::cast)
             .ifPresent(this::shutdownScheduler);
     ReflectionUtils.getField(coordinatorService, "pipelineCleanupScheduler")
             .map(ScheduledExecutorService.class::cast)
             .ifPresent(this::shutdownScheduler);
+    Assertions.assertFalse(
+            getCoordinatorExecutor(coordinatorService).isShutdown(),
+            "Coordinator test scheduler cleanup must not shut down the coordinator executor");
 }

shutdownScheduler (the awaitTermination-based helper that actually closes the #12045 race) already lives in dev via #12050 — CoordinatorServiceTest.java:774-781 in the current head — so this PR is no longer the change that fixes the race; it is a follow-up guardrail on top of an already-landed fix.

Key findings

  • The normal path this touches is test-fixture construction (newMockCoordinatorService), invoked by essentially every method in the ~1500-line test class; no production code is touched (CoordinatorService.java itself is unchanged in this diff).
  • I re-verified the assertion is deterministic, not just "probably fine": checkNewActiveMaster() (CoordinatorService.java:1241) only calls clearCoordinatorService() (which shuts down executorService) via the else if (isActive && !isMasterNode()) branch. At the point stopCoordinatorSchedulers runs (immediately after construction, before any test uses ReflectionUtils to flip isActive), isActive is still false and the mocked seaTunnelServer.isMasterNode() defaults to false — so neither branch of checkNewActiveMaster() can call clearCoordinatorService() yet, regardless of how many zero-delay ticks fire during this window. The assertion is checking an invariant that genuinely cannot fail once #12050's awaitTermination fix works correctly — it is not a coin-flip check.
  • getCoordinatorExecutor(...) is a pre-existing helper (already used at lines 382/417 for a different test), so this isn't introducing a new reflection surface.
  • In-depth correctness: the assertion takes effect on every call to newMockCoordinatorService, i.e. on every test in the class. It does not take effect for the actual production race in #12045 today — that race is already closed by #12050's awaitTermination. What this assertion buys is future-regression protection: if a later change to CoordinatorService adds a third zero-delay scheduler, or someone "simplifies" shutdownScheduler back to a bare shutdownNow(), this fixture will fail immediately and unambiguously at setup time instead of resurfacing as an unexplained RejectedExecutionException several methods away.

1.2 Compatibility Impact

Fully compatible. Test-only file (src/test/java), no production code, no Option, no config default, no serialization/checkpoint format, no SPI/plugin registration touched. No incompatible-changes.md entry needed.

1.3 Performance / Side-Effect Analysis

Negligible. The added assertFalse is a single, already-computed boolean read (ThreadPoolExecutor.isShutdown()), no I/O, no additional waiting. No new threads, no new shared state, no resource-leak risk — if anything the added assertion can only ever fail loudly, it can't introduce a new hang.

1.4 Error Handling and Logging

The assertion failure message ("Coordinator test scheduler cleanup must not shut down the coordinator executor") is specific and actionable — a future maintainer hitting it will immediately know which invariant broke, rather than having to reverse-engineer a RejectedExecutionException stack trace from an unrelated test method the way #12045 originally had to be diagnosed. No exceptions are swallowed.

No formal issues found in this round — see Section 4.

2. Code Quality Assessment

2.1 Coding Standards

Clean, minimal diff. The new comment explains why (the zero-delay/ordering hazard), not just what, matching this project's comment-density expectations for non-trivial test-fixture code.

2.2 Test Coverage and Test Stability

Mandatory Section 5.10.2 analysis (test-only PR):

  • No Thread.sleep, no fixed waits, no new timing assumption introduced by this diff — the added check is a synchronous post-condition on work that has already completed by the time it runs.
  • No shared/static mutable state, no order dependence between test methods, no new nondeterministic input.
  • The assertion is deterministic given the (already-merged, in dev via #12050) awaitTermination-based shutdownScheduler, per the branch analysis in 1.1 above — it cannot flake under normal CI load because it does not depend on scheduler timing at all; it depends only on isActive/isMasterNode() defaults, which are fixed at construction time.

Rating: Stable. seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/CoordinatorServiceTest.java:759-772. This is a genuine root-cause-adjacent guardrail, not a symptom mask — it doesn't retry, doesn't sleep, doesn't widen any tolerance, and doesn't touch an existing assertion's strictness.

2.3 Documentation Updates

Not applicable — no user-facing behavior, config, or API changed.

3. Architectural Soundness

3.1 Elegance of the Solution

Long-term solution (defensive guardrail), correctly scoped. Given the actual race-closing fix landed separately in #12050, this PR's remaining value is exactly the guardrail + explanatory comment, and that's a legitimate, low-risk contribution in its own right.

3.2 Maintainability

Improves it: a future reader of stopCoordinatorSchedulers now has both a comment explaining the historical hazard and an assertion that actively verifies the invariant the comment describes.

3.3 Extensibility

No concerns — local to the test fixture, does not constrain future CoordinatorService changes.

3.4 Historical-Version Compatibility

Not applicable — test-only change, no serialization/checkpoint/upgrade path involved.

4. Issue Summary

No blocking issues found. No other reviewer has left a technical finding on this PR to reconcile (only the author's own CI-troubleshooting comments and davidzollo's standard first-time-CI-enablement template), so there is nothing to deduplicate against.

The only open item is procedural, not a code issue: the fork's Build workflow run for the current head (33960949015 on CryoThrust/seatunnel) is still queued at the time of this review — it has not produced a pass/fail result yet.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed (process only, not code):

    • Wait for the fork's Build run (queued as of this review, triggered by the 2ddc721f4 push) to actually finish and come back green. There is no code-side blocker from my re-review.
  2. Recommended fixes — non-blocking: none.

Overall assessment: Sorry for the slightly unusual situation here, @CryoThrust — through no fault of your rebase, the substantive part of your original fix (the awaitTermination-based scheduler shutdown) landed in dev via #12050 while this PR was waiting on CI, so your rebase correctly picked that up and this PR's own diff shrank down to the comment + defensive assertion. I independently re-traced why that assertion is deterministic (not just "probably fine") rather than taking the smaller diff at face value, and it holds up. This is a nice, low-risk piece of future-regression insurance on top of an already-fixed race. Once the queued Build run comes back green, I'm happy to see this merged.

@CryoThrust

Copy link
Copy Markdown
Contributor Author

The fork Build run 33960949015 has now completed. All license/style, unit-test, engine-v2, and the other connector jobs passed; the only failures were unrelated integration jobs:

  • all-connectors-it-7 (8, ubuntu-latest)
  • rocketmq-connector-it (11, ubuntu-latest)

This PR only changes CoordinatorServiceTest under seatunnel-engine-server, and the changed module's unit/engine checks are green. Could a maintainer re-run or inspect those two connector jobs when convenient?

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for pushing this through, @CryoThrust — I pulled run 33960949015 directly (job logs, not just the summary) to check your read on the two failures myself rather than taking it at face value.

Confirmed both are unrelated to this diff:

  • all-connectors-it-7 (8, ubuntu-latest): the only failure in that shard is AmazondynamodbIT.testAmazondynamodb — AssertionFailedError: table sink_table is empty. That's an Amazon DynamoDB Local container/data-visibility issue in an entirely unrelated connector module.
  • rocketmq-connector-it (11, ubuntu-latest): all 43 failures/errors trace back to RocketMqConnectorException: ErrorCode:[ROCKETMQ-11] Failed to get topic min and max topic and waitConsumedOffsetsSynced timeouts — a RocketMQ test-container connectivity flake, not a code issue, and again a module this PR's diff never touches.

This PR only changes CoordinatorServiceTest under seatunnel-engine-server (test-only, no production code), and every check that could plausibly be affected by that — license/style, unit tests, and the engine-v2 suite — is green. There's no plausible mechanism by which a test-fixture change in seatunnel-engine-server could cause a DynamoDB or RocketMQ container to misbehave, so I'm treating these two as pre-existing environmental flakes rather than something introduced here.

From my side there's no remaining code-level blocker — my last review already confirmed the fix is correct and deterministic, and this closes out the only open item (waiting on the real Build result). I'll leave the final "ignore vs. rerun those two IT jobs" call to a maintainer with rerun access, but as far as this PR's own content goes, I'm satisfied.

@DanielLeens

Copy link
Copy Markdown
Contributor

Pushed merge commit 4416fe9832d (current dev into your branch), @CryoThrust. No conflicts; CoordinatorServiceTest.java auto-merged and the PR diff against dev is still the same 6 added lines. The last Build result is from 2026-09-05 (fork run 33960949015) with only the AmazondynamodbIT / RocketMqIT / Kudu reds we already attributed to the environment, so this is just to get a fresh run.

Your fork did not create a Build run for this push; if none appears, please start one from the Actions tab ("Run workflow" on Build). I started a verification run of the same head on my fork: https://github.com/DanielLeens/seatunnel/actions?query=branch%3Apr12051-verify-4416fe9832d

@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 for your work on this, @CryoThrust! I re-reviewed the current head 4416fe983 (a merge of current dev into your branch) from scratch against the dev merge base, including re-reading the test class and the CoordinatorService code it exercises. This is static analysis only; I did not run anything locally.

I need to correct part of my previous review: I rated the new assertion "deterministic because isMasterNode() defaults to false", and that only holds for some of the tests that use this fixture (Issue 1 below). Sorry for the overstatement.

What Problem Does This PR Solve?

  • Pain point: CoordinatorServiceTest flaked with RejectedExecutionException (#12045) because the fixture builds a CoordinatorService whose masterActiveListener starts with zero delay, and the old teardown shut it down without waiting.
  • Current state: the actual wait-for-termination fix (shutdownScheduler: shutdownNow() plus awaitTermination(5s)) already landed in dev through #12050. What is left in this PR is a 6-line diff in stopCoordinatorSchedulers: an explanatory comment and an assertFalse(getCoordinatorExecutor(coordinatorService).isShutdown(), ...) guard.
  • Summary: a fail-fast guard that makes "scheduler cleanup must not shut down the coordinator executor" an explicit post-condition of the shared fixture.

1. Code Change Review

1.1 Core Logic Analysis

The PR diff against dev is test-only (CoordinatorServiceTest.java, +6/-0); the merge commit brought in nothing that touches it.

newMockCoordinatorService(server, config)
  -> new CoordinatorService(...)  // starts masterActiveListener: scheduleAtFixedRate(checkNewActiveMaster, 0, 100ms)
  -> stopCoordinatorSchedulers
       -> shutdownScheduler(masterActiveListener)       // shutdownNow + awaitTermination (from #12050)
       -> shutdownScheduler(pipelineCleanupScheduler)
       -> NEW: assertFalse(coordinator executor isShutdown)

What can shut the coordinator executor down in this window: checkNewActiveMaster() (CoordinatorService.java:1262-1290) reaches clearCoordinatorService() only (a) in the isActive && !isMasterNode() branch, or (b) in the catch block when activation throws. With a default Mockito SeaTunnelServer, isMasterNode() is false and isActive is false, so neither can happen and the assertion is deterministic. That covers testPendingJobSchedulerCanAdvanceNextJobWhenPreviousResourceCheckBlocks (the test named in #12045, CoordinatorServiceTest.java:573-576) and the other default-mock tests.

Issue 1 (Medium, non-blocking): for tests that start with the master flag already true, the window is not closed

  • Location: CoordinatorServiceTest.java:399-400 (the second coordinator in testFailoverStopsOldPendingQueueAndNewCoordinatorCanSchedule), :688-693 (testPendingJobWithInsufficientResourceRespectsWaitStrategy) and :717-722 (testPendingJobWithInsufficientResourceRespectsRejectStrategy); the hazard is described in the comment inside testConcurrentMasterActivationActivatesOnceAndKeepsPendingJob.
  • Problem: in these three cases isMasterNode() already answers true when the constructor schedules its zero-delay tick. The tick can enter the activation branch (initCoordinatorService(), startPendingJobScheduleThread()) concurrently with shutdownScheduler, whose shutdownNow() interrupts that thread. If the interrupted activation throws, the catch block calls clearCoordinatorService() and shuts down the coordinator executor. That is the same family of failure as #12045, just in a different test. With this PR the failure would move earlier (to the new assertion) rather than disappear. I cannot say from reading alone how often the activation actually throws with these mocks, so this is a hypothesis, not an observed flake.
  • Risk: the test class may still flake in those three tests, and the new assertion could be reported as the failure site, which could look like a regression introduced by this PR.
  • Best improvement: the neighbouring test already documents the pattern ("Start as non-master so the constructor-scheduled masterActiveListener cannot activate before we stop it"). Do the same here: create the server with masterFlag = false, call newMockCoordinatorService, then masterFlag.set(true) before the explicit invokeCheckNewActiveMaster(...). The tests already call invokeCheckNewActiveMaster explicitly, so their behavior does not change.
  • Raised by other reviewer: no.

Issue 2 (Low, non-blocking): the PR title and description are stale

  • Location: PR description.
  • Problem: the description says the PR "stops masterActiveListener and pipelineCleanupScheduler with shutdownNow() and waits for termination" and "Fixes #12045"; both are already in dev via #12050, so the remaining diff is only the guard and comment. Issue #12045 is still open.
  • Risk: a reader will think this PR is the fix for #12045.
  • Best improvement: reword the description to what the diff does today and use "Related to #12045" unless a maintainer wants this PR to close it (after Issue 1 is handled).
  • Raised by other reviewer: no.

1.2 Compatibility Impact

Fully compatible: test-only file, no production code, option, serialization, checkpoint, SPI or registration change.

1.3 Performance / Side-Effect Analysis

One boolean read per fixture construction; no new threads, sleeps or shared state.

1.4 Error Handling and Logging

The assertion message names the broken invariant, which makes a future regression easy to diagnose. No exception is swallowed.

2. Code Quality Assessment

2.1 Coding Standards

Minimal diff. The comment explains the zero-delay hazard (why), not what the line does.

2.2 Test Coverage and Test Stability

Stability rating: Risk present (downgraded from my earlier "Stable" because of Issue 1). Evidence: CoordinatorServiceTest.java:399-400, :688-693, :717-722 construct the coordinator with isMasterNode() == true. No Thread.sleep is added, no fixed ports, and the assertion itself does not depend on timing for the default-mock tests. Failure-capability of the new assertion: if shutdownScheduler were reverted to a bare shutdownNow() or a third zero-delay scheduler were added, a late tick that clears the coordinator would make the assertion fail at fixture setup, which is exactly the regression it is meant to catch.

2.3 Documentation Updates

Not applicable (test-only).

3. Architectural Soundness

3.1 Elegance

Defensive guardrail on top of an already-landed fix. Small and low-risk; Issue 1 is where a more complete fix of the fixture would live.

3.2 - 3.3 Maintainability and Extensibility

The comment plus assertion make the fixture's invariant explicit. No constraint on future CoordinatorService changes.

3.4 Historical-Version Compatibility

Not applicable.

4. Issue Summary

Number Issue Location Severity
1 Tests that start with isMasterNode() == true still race the zero-delay tick; new assertion may surface it CoordinatorServiceTest.java:399-400, :688-693, :717-722 Medium
2 PR description says it fixes #12045 and lists changes already merged via #12050 PR description Low

5. Merge Recommendation

Conclusion: Ready to merge

No blocking source or test issue found; the diff is a safe, test-only guard. CI is the only open item.

  1. Blockers: none from source, tests or docs.
  2. Recommended fixes - non-blocking: Issue 1 (start the three master-flag-true tests as non-master and flip the flag after construction), Issue 2 (update the description).

CI status (a fact, not a code issue): the Apache-side Build check on this head shows action_required, meaning your fork did not create a Build run for the merge commit. Please start one from the Actions tab of your fork ("Run workflow" on Build). The verification run I started on my fork was still queued when I checked. Your last fork run was on an older head (2ddc721f4), and its reds were unrelated connector jobs (AmazondynamodbIT, RocketMQ). Current dev also has unrelated red unit-test jobs at the moment, so please do not chase those. A committer with write access still has to approve.

Overall: a small, careful guardrail; thanks for the patience through the rebases.

@CryoThrust CryoThrust changed the title [Test][Zeta] Make CoordinatorServiceTest scheduler cleanup deterministic [Test][Zeta] Activate coordinator fixtures after scheduler cleanup Nov 16, 2026
@CryoThrust

Copy link
Copy Markdown
Contributor Author

Updated in 022e216e6, after syncing current dev.

The three fixtures named in Issue 1 now construct as non-master and switch to master just before explicit activation. I found the same constructor window in testCheckNewActiveMasterIsIdempotentWhenAlreadyActive and corrected that fourth fixture too. The existing scheduling assertions remain intact.

The title and description now distinguish this fixture/guard follow-up from the scheduler termination fix already merged via #12050, and use “Related to #12045”.

On JDK 11, the complete CoordinatorServiceTest passes: 37 tests, zero failures/errors, two skips. Scoped Spotless and server-module -DskipTests verify pass. The updated head still needs its GitHub Build result; these local checks are not full engine E2E coverage.

@SEZ9

SEZ9 commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the update in 022e216e6, @CryoThrust.

Constructing the fixtures as non-master and switching to master just before explicit activation sounds like the right approach for the constructor window from Issue 1; I'll confirm against the diff. Thanks also for catching the same window in testCheckNewActiveMasterIsIdempotentWhenAlreadyActive, and for updating the title and description to separate this follow-up from the scheduler termination fix that was already merged.

Your comment doesn't mention a few of the earlier points, so could you confirm where each stands in 022e216e6?

  1. Assertion in the shared cleanup helper: the executor-alive check could mask the real test failure or break unrelated callers. Can it still fire for any caller of the helper after the fixture changes?
  2. Unintended NPE or reflection failure: if the coordinator service was already cleared, the executor lookup could throw one of these instead of the intended diagnostic. Is that case guarded?
  3. Ordering contract: is "stop schedulers before mutating isActive" enforced by the code, or is it still documented only in the comment?

The earlier points about the termination helper and the 5-second awaitTermination budget appear to concern logic that, as noted in the review of 4416fe983, had already landed in dev, so I don't expect changes for them in this PR. Nothing is needed on the security point either, since the change is confined to test fixture cleanup.

Thanks for sharing the local JDK 11 run (37 tests, zero failures/errors, two skips). As you noted, the updated head still needs its GitHub Build result, so please post here once that is in.

@CryoThrust

CryoThrust commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for checking. I traced all callers on 022e216e6:

  1. stopCoordinatorSchedulers() has one call site, inside newMockCoordinatorService(), before the fixture is returned. It is not called from test teardown or a finally block, so its assertion cannot replace a failure from the test body. All ownership-controlled fixtures now start with isMasterNode() == false; the other mock servers also return false by default. The assertion would still deliberately reject a fixture whose executor was unexpectedly shut down during construction.
  2. The constructor assigns executorService before starting either scheduler. clearCoordinatorService() shuts that executor down but does not null it, so an already-cleared instance reaches the shutdown assertion. The existing getter reports an absent/inaccessible field as AssertionError("Failed to get coordinator executorService by reflection"). It is not a general null-safe reflection utility: ReflectionUtils.getField() uses Optional.of, but the current coordinator lifecycle never assigns null to this field. No extra reflection or null guard was added in this revision.
  3. The ordering is enforced by the existing calls: the fixture factory calls stopCoordinatorSchedulers() before returning; shutdownScheduler() calls shutdownNow() and requires awaitTermination(5, SECONDS) to succeed. A timeout or interruption throws rather than returning a fixture. The test only enables master ownership or mutates isActive after the factory returns. The comment explains that ordering; the synchronous termination checks enforce it. Those checks already landed via [Fix][Zeta] Stabilize CI test isolation #12050.

The fork Build for this exact head completed with 84 successful jobs, 11 conditional skips and two failures. All four Linux/Windows JDK 11/17 unit jobs and both JDK 11/17 engine-v2 integration jobs passed. I downloaded both failed job logs: all-connectors-it-4 (17) could not download Maven Wrapper after repeated Central HTTP 429 responses and produced no test reports; jdbc-connectors-it-part-2 (17) stopped resolving the Milvus SDK POM with Central HTTP 429. These are dependency/bootstrap failures, not failed fixture assertions. This is fork evidence, not a green Apache-side Build.

Final update: both retries have completed, and the entire exact-head fork Build is now successful (attempt 3). No source or assertion changes were made for these download failures. The earlier failure details above are retained for context; fork success does not replace upstream approval or merge.

@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 confirming the ordering and covering the fourth fixture. I checked the one-file diff, all factory callers, the constructor and the exact-head retry evidence. @SEZ9's questions about the guard are addressed below.

What problem does this PR solve?

The test coordinator starts a zero-delay ownership listener. When a fixture starts as the master, that tick can activate it before the test owns setup. The fixture now stays non-master until after listeners stop. For example, the pending-job wait strategy is set up before the explicit activation that schedules it.

1. Code changes

1.1 Core logic

CoordinatorService installs the immediate listener (288-300) -> CoordinatorServiceTest.newMockCoordinatorService:765-781 constructs and stops both schedulers -> shutdownScheduler:799-808 requires termination -> test enqueues its job, flips the master flag and calls checkNewActiveMaster:1262-1274. Previously four fixtures exposed true during construction. Now they start false and flip at the explicit activation. The executor assertion runs only in factory setup (794-796), not teardown. The production clears can shut the executor down but do not null it; the getter's reflection failure is a separate helper diagnostic. The test harness changes; the normally running production scheduler is unchanged.

1.2 Compatibility

Fully compatible. No job/config/API/state or protocol changes.

1.3 Performance and side effects

No production allocation, resource, scheduler cadence, retry or network change. The existing bounded test shutdown is retained.

1.4 Errors, logging, and findings

The new assertion fails when setup leaves the executor shut down, before yielding a broken fixture. It cannot replace an already-failed test-body assertion. The main fixture objection is resolved.

2. Code quality

2.1 Conventions

The short comment explains the ordering dependency, and the revised description separates this from #12050.

2.2 Test coverage and stability

Stability: stable on static inspection of the change. The ownership flag is atomic; construction and scheduler termination complete before fixture use (CoordinatorServiceTest.java:778-808). Existing latches and bounded assertions stay in place. The author reports four passing unit lanes and two passing engine integration lanes, with the other failures during Maven Central downloads in the previous attempt; the fork is still retrying. Local results are author-reported, not my execution.

2.3 Documentation

No user-facing docs change. The PR description now identifies the fixture follow-up.

3. Architecture

3.1 Change location

This is a focused fixture ownership fix. The production listener must still start promptly; introducing a sleep or weakening the scheduler test would miss the race.

3.2 Maintainability

The synchronous factory guard makes future invalid fixture changes fail in setup.

3.3 Extensibility

Future ownership-controlled tests should follow the same construction-then-activation order.

3.4 Upgrade impact

No upgrade impact.

4. Findings summary

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

5. Merge recommendation

Do not merge before the required current-head CI passes.

Blocking items: No source or test blocker remains. Follow the current exact-head retry for the Maven Wrapper and Milvus dependency fetch failures. Those failures are outside the coordinator code; a dependency patch or a base sync is not warranted by the available download errors.

Non-blocking suggestions: None.

The fixture sequencing preserves the original scheduling assertions. If the current retry still fails before test execution, retain those job links for diagnosis.

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

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

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The CI fact in my previous review has changed on unchanged 022e216e693fd67187a71868aa91bb52607bc311: fork Build 43884520828 is now successful, rather than queued/in progress. No source blocker remained in my earlier review. The current Apache check rollup still reports no Build, so a write-capable maintainer must reconcile/adopt the successful fork result and provide effective approval.

This updates the earlier gate statement; it is not another complete source review or a new source finding. Daniel has READ repository permission, so this COMMENT does not change the effective write-level approval/dismissal gate. No local PR build or test was run.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for following this through! The CI fact in my previous review has changed on this unchanged head: the exact-head Build is successful and Apache now reports a successful Build too. I checked the final job manifest: no failed, cancelled or incomplete jobs remain. My previous complete review had no unresolved source blocker; the remaining technical blocker was CI/check adoption. That CI-only blocker is now cleared, so I am changing my technical review to approve.

Conclusion: Can merge from Daniel's technical perspective once the effective repository review gate is satisfied.

Blocking source items: None from my existing complete review.

Non-blocking suggestions: Those already recorded remain optional. This is a CI/discussion follow-up, not another full source review. Daniel's READ permission does not provide write-level approval/dismissal controls or prove that historical requested changes have disappeared. A write-capable maintainer must handle the remaining effective gate.

Checked unchanged head 022e216e693fd67187a71868aa91bb52607bc311 against dev: compare diverged, ahead 4 / behind 41. This drift is recorded independently; it does not by itself request synchronization. This is a discussion/CI follow-up, not another full source review. No local build, test or runtime execution was performed. Daniel has READ repository permission; effective maintainer approval/dismissal remains a separate repository gate. Checked 2026-11-21T11:49:26.872558+00:00.

@davidzollo davidzollo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

+1
LGTM

Thanks for your contribution!

Please join our Apache SeaTunnel #contributors channel on Slack for technical discussions and collaboration: https://s.apache.org/seatunnel-slack

@davidzollo
davidzollo added this pull request to the merge queue Nov 22, 2026
Merged via the queue into apache:dev with commit 31a99d9 Nov 22, 2026
2 checks passed
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