Repository navigation
[Test][Zeta] Activate coordinator fixtures after scheduler cleanup - #12051
Conversation
|
CI note: the required |
|
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~
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. 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
left a comment
There was a problem hiding this comment.
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 betweenAfter:
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 submissionRuntime 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 newshutdownAndAwaitTerminationhelper and adds the post-condition assertion), called fromnewMockCoordinatorService(:734-756), which is the shared fixture factory used by essentially every test in this class.- Production code touched: none.
CoordinatorService.javaitself is unchanged; the race lives entirely between test-fixture teardown ordering and the real (and correctly-designed) production behavior ofcheckNewActiveMaster()/clearCoordinatorService()atseatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/CoordinatorService.java:257-283(constructor scheduling) and:1241-1270(checkNewActiveMaster,synchronized, flipsisActiveand callsclearCoordinatorService()on step-down) and:1281-1313(clearCoordinatorService()doesexecutorService.shutdownNow()). - This is purely a test-boundary/race path, not the normal production user path — production
CoordinatorServiceinstances are never subjected to reflection-drivenisActivemutation; 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:
CoordinatorServiceconstructor (CoordinatorService.java:270-271) schedulescheckNewActiveMasterwith initial delay 0, so the first tick can fire essentially immediately after construction, before the caller (newMockCoordinatorService) gets a chance to callstopCoordinatorSchedulers.checkNewActiveMaster()(CoordinatorService.java:1241-1258) issynchronizedbut has no gate against test-driven state mutation —else if (isActive && !this.seaTunnelServer.isMasterNode())will callclearCoordinatorService()wheneverisActiveistrueand the mockedisMasterNode()isfalse(the default, unstubbed Mockito return value in most tests here).clearCoordinatorService()(CoordinatorService.java:1281,1312) unconditionally callsexecutorService.shutdownNow().- The old
stopCoordinatorSchedulerscalledmasterActiveListener.shutdownNow()but returned immediately without confirming the in-flight/queued tick had actually stopped — so the window between fixture construction and a test'sReflectionUtils.setField(coordinatorService, "isActive", true)call was genuinely racy. - Issue #12045's stack trace (
RejectedExecutionExceptionon the secondinvokePendingJobSchedulercall, "completed tasks = 1") is fully consistent with exactly this race: one task completed (the scheduler's own doomed tick, or the firstpendingJobScheduleTask), then the pool wentTerminatedbefore 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-threadScheduledExecutorServicewith 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-diagnoseRejectedExecutionExceptiondeep 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:
shutdownAndAwaitTerminationis invoked from the test's own thread while holding no lock on theCoordinatorServiceinstance, so it can safely wait for the scheduler's worker thread (which may itself be blocked briefly inside thesynchronized 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
shutdownAndAwaitTerminationcorrectly restores the interrupt flag (Thread.currentThread().interrupt()) before failing onInterruptedException, rather than swallowing it — good practice.- Both failure paths (
awaitTerminationtiming out, or being interrupted) fail the test explicitly viaAssertionsrather 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 bareshutdownNow()withshutdownNow()+ boundedawaitTermination(), 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;
CoordinatorServiceinstances 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 flipsisActiveshortly 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
awaitTerminationbound 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 mockedcheckNewActiveMastertick), 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
-
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 currentBuildcheck status isaction_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--forceafter a rebase onto the latestdev) to trigger a real run so we can see actual green/red results.
- The fork's GitHub Actions workflow needs to actually run and pass (
-
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!
|
I rechecked the fork configuration: GitHub Actions is enabled on |
|
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 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 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
Once a real |
Signed-off-by: Yohanes <CryoThrust@users.noreply.github.com>
70cfb3f to
2ddc721
Compare
|
Rebased onto current Verified locally: The push created fork workflow run |
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point:
CoordinatorServiceTestintermittently fails withRejectedExecutionException(tracked in #12045) because the sharedCoordinatorServicefixture starts a zero-initial-delay scheduler the instant it is constructed, and the old teardown helper issuedshutdownNow()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 insidestopCoordinatorSchedulers, 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.javaitself is unchanged in this diff). - I re-verified the assertion is deterministic, not just "probably fine":
checkNewActiveMaster()(CoordinatorService.java:1241) only callsclearCoordinatorService()(which shuts downexecutorService) via theelse if (isActive && !isMasterNode())branch. At the pointstopCoordinatorSchedulersruns (immediately after construction, before any test usesReflectionUtilsto flipisActive),isActiveis stillfalseand the mockedseaTunnelServer.isMasterNode()defaults tofalse— so neither branch ofcheckNewActiveMaster()can callclearCoordinatorService()yet, regardless of how many zero-delay ticks fire during this window. The assertion is checking an invariant that genuinely cannot fail once #12050'sawaitTerminationfix 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'sawaitTermination. What this assertion buys is future-regression protection: if a later change toCoordinatorServiceadds a third zero-delay scheduler, or someone "simplifies"shutdownSchedulerback to a bareshutdownNow(), this fixture will fail immediately and unambiguously at setup time instead of resurfacing as an unexplainedRejectedExecutionExceptionseveral 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
devvia #12050)awaitTermination-basedshutdownScheduler, 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 onisActive/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
-
Blockers — must be fixed (process only, not code):
- Wait for the fork's
Buildrun (queued as of this review, triggered by the2ddc721f4push) to actually finish and come back green. There is no code-side blocker from my re-review.
- Wait for the fork's
-
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.
|
The fork Build run
This PR only changes |
|
Thanks for pushing this through, @CryoThrust — I pulled run Confirmed both are unrelated to this diff:
This PR only changes 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. |
|
Pushed merge commit 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
left a comment
There was a problem hiding this comment.
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:
CoordinatorServiceTestflaked withRejectedExecutionException(#12045) because the fixture builds aCoordinatorServicewhosemasterActiveListenerstarts with zero delay, and the old teardown shut it down without waiting. - Current state: the actual wait-for-termination fix (
shutdownScheduler:shutdownNow()plusawaitTermination(5s)) already landed indevthrough #12050. What is left in this PR is a 6-line diff instopCoordinatorSchedulers: an explanatory comment and anassertFalse(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 intestFailoverStopsOldPendingQueueAndNewCoordinatorCanSchedule),:688-693(testPendingJobWithInsufficientResourceRespectsWaitStrategy) and:717-722(testPendingJobWithInsufficientResourceRespectsRejectStrategy); the hazard is described in the comment insidetestConcurrentMasterActivationActivatesOnceAndKeepsPendingJob. - 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 withshutdownScheduler, whoseshutdownNow()interrupts that thread. If the interrupted activation throws, thecatchblock callsclearCoordinatorService()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, callnewMockCoordinatorService, thenmasterFlag.set(true)before the explicitinvokeCheckNewActiveMaster(...). The tests already callinvokeCheckNewActiveMasterexplicitly, 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
masterActiveListenerandpipelineCleanupSchedulerwithshutdownNow()and waits for termination" and "Fixes #12045"; both are already indevvia #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.
- Blockers: none from source, tests or docs.
- 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.
|
Updated in 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 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 |
|
Thanks for the update in 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 Your comment doesn't mention a few of the earlier points, so could you confirm where each stands in
The earlier points about the termination helper and the 5-second 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. |
|
Thanks for checking. I traced all callers on
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: 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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
+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

Yes, I am contributing to Apache SeaTunnel.
Purpose
Make the
CoordinatorServiceTestfixture 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
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 verifyThe 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.