Repository navigation
[Fix][Zeta] Isolate final metrics reporting from task interrupts - #12795
Asthenia0412 wants to merge 4 commits into
Conversation
DanielLeens
left a comment
There was a problem hiding this comment.
Hi @Asthenia0412, thank you for picking this up again and for rebasing #12556 onto the latest dev. The core idea (do not let an interrupted task worker do the synchronous Hazelcast write for the final metrics) is a good one and it targets a real problem. Unfortunately, while reviewing the full diff against current dev I found that the rebase has silently reverted two fixes that were already merged into TaskExecutionService, so I cannot recommend merging the current head yet.
What Problem Does This PR Solve?
User pain point: When a task group is canceled, the last task calls updateMetricsContextInImap() from a task worker thread that already has its interrupt flag set. The synchronous Hazelcast call can then close the worker's shared connection to the master and delay terminal completion of the task group (#12413).
Fix approach: Run the final metrics report on a dedicated daemon cached thread pool (seatunnel.final-metrics) and complete the task group's terminal TaskExecutionState only after that report finishes (or fails, or is rejected).
One-sentence summary: Move the final metrics write off the interrupted worker thread, keeping terminal-state publication ordered after it.
Before / after:
// before: runs on the (possibly interrupted) task worker
finishExecution(taskGroupLocation);
try { updateMetricsContextInImap(); } catch (Throwable t) { ... }
future.complete(new TaskExecutionState(taskGroupLocation, FINISHED));
// after: runs on a dedicated thread, terminal state published afterwards
finishExecution(taskGroupLocation);
completeAfterFinalMetrics(taskGroupLocation, FINISHED, null);1. Code Change Review
1.1 Core Logic Analysis
Intended change: TaskGroupExecutionTracker.taskDone now calls the new completeAfterFinalMetrics(...) (TaskExecutionService.java:1647), which submits the metrics report to finalMetricsExecutorService (:245) and completes future in a finally. If submit throws, the terminal state is still completed. shutdown() also calls finalMetricsExecutorService.shutdown() (:327).
Unintended change: the same commit also removes code that exists on current dev and is unrelated to #12413:
- In
deployLocalTaskthetry/finallyaroundstartedLatch.await()from #12454 is gone.taskGroupExecutionTracker.blockingFuturesis now assigned directly from the stream (:419) and the latch is awaited without the post-startupexecutionCompletedExceptionally()handling (:440). - In
cancelAllTask()(:1576) the submission oftask.cancel()for each task (external-resource cancellation, added by #12420 for cancelling in-flight JDBC source queries) and itsRejectedExecutionExceptionguard are removed. - The test
testBlockingDeploymentCompletesAfterEarlyFailureOrCancellationthat protects item 1 is deleted fromTaskExecutionServiceTest, and several tests go back fromFLAKE_ID_GENERATOR.newId()to the hard-coded execution ids1,1L,2L; the "previous fixture id 1 must not own this fixture's timers" scenario intestStaleTaskDoneCleansOnlyOwnedGenerationResourcesis deleted.
Key Findings:
- The metrics-off-interrupted-thread idea is sound and the terminal-state ordering is applied consistently to FINISHED, CANCELED and FAILED.
- The branch is only 1 commit ahead of dev and 0 behind, so these deletions are part of this PR's diff (
git diff origin/dev...HEAD), not a stale base. - Deleting the latch handling re-opens a deployment hang; deleting
task.cancel()re-opens the in-flight JDBC query leak on cancel. - Existing regression tests were removed or weakened (see 2.2), so CI would not catch the regressions above.
Runtime path (after this PR):
worker thread (maybe interrupted) -> TaskGroupExecutionTracker.taskDone
-> completionLatch == 0 -> finishExecution(location)
-> completeAfterFinalMetrics
-> finalMetricsExecutorService.submit( updateMetricsContextInImap ; finally future.complete(terminal) )
-> resultFuture.whenCompleteAsync(...) in deployLocalTask -> report state to master
cancel path: cancelTaskGroup -> tracker.cancelAllTask -> blockingFutures.cancel(true)
(blockingFutures is now published before startedLatch.await, so a worker that has not started yet can be cancelled
before run() releases the latch)
1.2 Compatibility Impact
Partially incompatible in behavior: no config or serialization change, but dev behavior added by #12454 and #12420 is lost (task recovery/cancel semantics and JDBC source cancellation). Not acceptable for a minor metrics fix.
1.3 Performance / Side-Effect Analysis
Executors.newCachedThreadPoolis unbounded. It is bounded in practice by the number of concurrently finishing task groups, but a stuck Hazelcast write would pin one thread per task group for as long as it blocks, and each pinned thread also delaysfuture.complete. Consider a bounded pool or a timeout on the report.- Publishing the terminal state after the metrics write was already the order before; no new latency, but it is now also coupled to the pool being available.
1.4 Error Handling and Logging
Issue 1: Rebase reverts the early-failure latch handling from #12454
- Location:
TaskExecutionService.java:419and:440 - Problem: dev has
try { startedLatch.await(); } finally { blockingFutures = ...; if (executionCompletedExceptionally()) cancelAllTask(); }with the comment "Early failure cleanup must not cancel a worker before run() releases startedLatch". The PR assignsblockingFuturesbefore the await and removes the finally block. - Potential risk: if a task fails or the group is cancelled during deployment,
cancelAllTask()cancancel(true)a worker future that has not started, sostartedLatch.countDown()never runs anddeployLocalTaskblocks forever (the exact hang #12454 fixed). - Best improvement: restore the dev block unchanged; keep the PR limited to the metrics change.
- Severity: High
- Raised by another reviewer: No
Issue 2: Rebase reverts external-resource cancellation from #12420
- Location:
TaskExecutionService.java:1576(cancelAllTask) - Problem: the loop submitting
task.cancel()per task, with theRejectedExecutionExceptionfallback, is removed. - Potential risk: in-flight JDBC source queries are no longer cancelled when a task group is cancelled, so cancel can wait for the database or leak the statement; this re-opens #12419.
- Best improvement: restore the dev implementation of
cancelAllTask()(and theRejectedExecutionExceptionimport). - Severity: High
- Raised by another reviewer: No
Issue 3: Existing regression tests are deleted or weakened
- Location:
TaskExecutionServiceTest.java(deletedtestBlockingDeploymentCompletesAfterEarlyFailureOrCancellation;FLAKE_ID_GENERATOR.newId()replaced by1/1L/2Lin several tests; previous-fixture block removed fromtestStaleTaskDoneCleansOnlyOwnedGenerationResources) - Problem: the PR removes coverage for the two reverted fixes and brings back hard-coded execution ids that the shared test server can reuse across tests.
- Potential risk: regressions in Issues 1 and 2 would pass CI; hard ids reintroduce cross-test interference.
- Best improvement: restore the dev version of the test file and add the three new tests on top.
- Severity: High
- Raised by another reviewer: No
Issue 4: Final metrics executor lifecycle and sizing
- Location:
TaskExecutionService.java:245,:327 - Problem: the pool is unbounded and
shutdown()does not await; the claim in the Javadoc that an orderly shutdown drains accepted reports holds only if the JVM stays up, because the threads are daemon. - Potential risk: during node shutdown, a final report may be dropped silently; under a Hazelcast stall many threads can accumulate.
- Best improvement: either bound the pool, or document that reporting is best-effort and drop the drain claim; optionally add a
try/awaitTerminationwith a short timeout inshutdown(). - Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
The new method has a helpful Javadoc and the executor field is commented. Formatting looks spotless-clean. The unrelated removals are the problem, not the style.
2.2 Test Coverage and Test Stability
The three new tests exercise the new path (interrupted worker not hosting the metrics call, FAILED state preserved on metrics failure, rejection still completes). Stability rating: High risk, because the PR deletes existing regression coverage and reverts to fixed execution ids (TaskExecutionServiceTest.java, the newTaskGroupContext(1L, ...) and newTaskGroupContext(2L, ...) calls), and the new tests use releaseMetrics.await() / Mockito.spy of a shared service. Please restore the deleted tests; the new tests themselves look reasonable.
2.3 Documentation Updates
No user-facing docs needed.
3. Architectural Soundness
3.1 Elegance
Long-term solution direction is right (isolate blocking IO from interruptible workers), but the diff currently mixes in unrelated reverts.
3.2 Maintainability
A new always-on cached pool inside TaskExecutionService is acceptable; keep it bounded and documented.
3.3 Extensibility
Fine.
3.4 Historical-Version Compatibility
No wire/state changes. Behavioral regressions listed above affect already released-on-dev behavior.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Reverts #12454 early-failure latch handling (deployment hang) | TaskExecutionService.java:419,440 |
High |
| 2 | Reverts #12420 task.cancel() external-resource cancellation |
TaskExecutionService.java:1576 |
High |
| 3 | Deletes/weakens existing regression tests | TaskExecutionServiceTest.java |
High |
| 4 | Unbounded final-metrics pool and shutdown drain claim | TaskExecutionService.java:245,327 |
Low |
5. Merge Recommendation
Conclusion: Not recommended for merge
- Blockers - must be fixed
- Recommended fixes - non-blocking
- Issue 4.
Overall assessment: the fix idea is valid, but the current head regresses two merged engine fixes and removes their tests, so it is not safe for the engine runtime. CI on this head was still queued when I reviewed; I did not rely on it. Thanks again for the work, this should be a quick fix once the reverts are removed.
e6c6e34 to
5f538f0
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
Hi @Asthenia0412, thank you for the quick turnaround and for rebuilding the branch on top of current dev. I re-reviewed the entire latest head (5f538f05) from scratch rather than only the delta. The three blockers from my previous round (the reverted #12454 latch handling, the reverted #12420 task.cancel() submission, and the deleted regression tests) are all resolved: git diff origin/dev...HEAD now touches only the metrics change plus 141 purely additive test lines, with no deleted dev code or tests.
Sorry for missing a few things in the last review, that is on me. In the previous round I wrote that formatting looked spotless-clean without having CI results to back it up, and I also did not give a full treatment of the terminal-state wait behavior and the CANCELED-path test gap. Issues 1, 2, 3 and 4 below are carryovers I should have raised on the earlier head, not problems you introduced in this push.
What Problem Does This PR Solve?
User pain point: When a task group is canceled, the last task calls updateMetricsContextInImap() from a task worker thread whose interrupt flag is already set. The synchronous Hazelcast invocation on an interrupted thread can close the worker's shared connection to the master and delay terminal completion of the task group (#12413).
Fix approach: Submit the final metrics report to a dedicated daemon cached pool and complete the task group's terminal TaskExecutionState only after the report finishes, fails, or is rejected, for FINISHED, CANCELED and FAILED alike.
One-sentence summary: Move the final metrics RPC off the possibly interrupted worker thread while keeping "metrics first, terminal state second" ordering.
1. Code Change Review
1.1 Core Logic Analysis
Changed code: TaskExecutionService.java (new field finalMetricsExecutorService at :246, shutdown() at :328, updateMetricsContextInImap() widened to package-private at :959, TaskGroupExecutionTracker.taskDone at :1642, new completeAfterFinalMetrics at :1688). Tests: three new cases in TaskExecutionServiceTest.java.
Before:
finishExecution(taskGroupLocation);
try { updateMetricsContextInImap(); } catch (Throwable t) { logger.severe(...); }
future.complete(new TaskExecutionState(taskGroupLocation, FINISHED)); // CANCELED / FAILED likewiseAfter:
finishExecution(taskGroupLocation);
completeAfterFinalMetrics(taskGroupLocation, ExecutionState.FINISHED, null);
// -> finalMetricsExecutorService.submit(() -> { try { updateMetricsContextInImap(); } catch (Throwable) {...} finally { future.complete(terminalState); } })
// -> on submit failure: log + future.complete(terminalState)Runtime path:
BlockingWorker.run() / CooperativeTaskWorker.run() [:1334, :1424-1480]
-> TaskGroupExecutionTracker.taskDone(task) [:1642]
-> completionLatch == 0 -> finishExecution() (active -> finished context, class loader recycle) [:1728]
-> completeAfterFinalMetrics() [:1688]
-> "seatunnel.final-metrics" thread (never interrupted by cancelAllTask)
-> updateMetricsContextInImap() -> ReportMetricsOperation to master, invoke.get() [:982]
-> finally future.complete(terminalState)
-> resultFuture.whenCompleteAsync(...) in deployLocalTask [:658] -> report state to master
Key findings:
- The normal user path reaches the change: every task group completion goes through
taskDone; the interrupted-worker case is the cancel path (cancelAllTask->blockingFutures.cancel(true)), which is exactly where #12413 bites. - This is a precise fix for the interrupted-thread symptom. A new thread cannot inherit the worker's interrupt flag, and the ordering "metrics before terminal state" is preserved for all three states.
- Collection happens after
finishExecution()in both old and new code, so the payload content is unchanged. The only subtle difference is that forBlockingWorkerthe last task'sclose()(in itsfinally, :1334 onward) used to run after the report and now may overlap with it. The periodic scheduler already calls the same method concurrently with running tasks, so this looks safe, but it is worth knowing. - The dev regressions from my previous round are gone; I verified
deployLocalTask/submitBlockingTask(:417-442) andcancelAllTask(:1583-1612) match dev.
1.2 Compatibility Impact
Fully compatible. No config, API, protocol or serialization change. updateMetricsContextInImap() goes from private to package-private only so the tests can spy on it (see Issue 4).
1.3 Performance / Side-Effect Analysis
- CPU/memory: one short-lived daemon thread per concurrently finishing task group; negligible in the normal case. The pool is unbounded (Issue 3).
- Networking: same single
ReportMetricsOperationper terminal task group as before. - Lock contention / concurrency:
future.completeis now invoked on the metrics thread;whenCompleteAsyncconsumers run on their own executor, so nothing blocks the pool beyond the RPC itself. - Retries/idempotency:
submitfailure falls back to completing the future directly, andCompletableFuture.completeis idempotent, so there is no double-publication risk. - Resource release: threads are daemon and
shutdown()stops accepting new work.
1.4 Error Handling and Logging
Failures of the report and of the submission both still complete the terminal future, and a FAILED state keeps its original throwable. Good.
Issue 1: Spotless check fails on the current head (CI blocker)
- Location:
TaskExecutionService.java:1655-1670(the threecompleteAfterFinalMetrics(...)calls) - Problem: The fork's
Buildrun for5f538f05fails inRun / Code style(spotless:check), because the three calls are wrapped over two lines but fit in 100 columns. Because Code style failed, the downstream jobs (unit-test, engine ITs) were skipped, so the new tests have not been exercised by CI yet. - Potential risk: PR cannot merge, and no CI evidence exists for the new tests.
- Best improvement: run
./mvnw spotless:apply -pl seatunnel-engine/seatunnel-engine-serverand push; the diff is only the three calls joined onto one line, e.g.completeAfterFinalMetrics(taskGroupLocation, ExecutionState.FINISHED, null); - Severity: High (merge gate)
- Raised by another reviewer: No
Issue 2: Terminal state now waits on an RPC that nothing can interrupt or time out
- Location:
TaskExecutionService.java:1698-1706together withinvoke.get()at:982 - Problem: Before, a canceled worker blocked in
invoke.get()could be broken out of by the interrupt (that is also what caused #12413). Now the report runs on a pool thread thatcancelAllTask/cancelTaskGroupcan never reach, andfuture.complete(terminalState)sits in thefinallybehind the un-timedinvoke.get(). If the master is slow or in failover, the task group's CANCELED/FAILED state is delayed until Hazelcast's own invocation timeout/retry budget expires, which is the delay this PR aims to remove. - Potential risk: slower cancel/failover completion of jobs under master instability; no escape hatch since the pool is daemon and uncancelable.
- Best improvement: Option A (smallest): in
completeAfterFinalMetrics, also schedule a fallbackfuture.complete(terminalState)on the existingscheduledExecutorServiceafter a bounded delay (a few seconds);completeis idempotent so whichever finishes first wins. Option B: give the final report its own bounded wait (e.g.invoke.get(timeout)via a parameter) without changing the periodic scheduler's behavior. Either keeps the best-effort contract already described in the Javadoc. - Severity: Medium
- Raised by another reviewer: No
Issue 3: Final-metrics pool: unbounded, unnamed per thread, no MDC, noisy shutdown race
- Location:
TaskExecutionService.java:246-252,:328,:1709 - Problem: (a)
newCachedThreadPoolis unbounded; a stalled master pins one thread per terminal task group. (b) every thread is named identicallyseatunnel.final-metrics, so thread dumps cannot tell reports apart. (c) other executors in this class are wrapped withMDCTracer.tracing(...); this one is not, so theupdate metrics context in imap failedlog loses the job context that the worker thread used to carry. (d)shutdown()runsexecutorService.shutdownNow()first (:326), so interrupted workers reachingtaskDoneafterfinalMetricsExecutorService.shutdown()hitRejectedExecutionException, which is logged at SEVERE with a stack trace once per task group even though it is the expected path. - Potential risk: operational noise and harder diagnosis; thread growth only under an already unhealthy master.
- Best improvement: use a bounded pool (for example a core-sized pool with a queue, or
ThreadPoolExecutorwith a sane max) with an indexed thread name, wrap withMDCTracer.tracing, and log the rejection at WARN without a stack trace. The Javadoc sentence "orderly shutdown drains accepted reports" is only true while the JVM stays up (threads are daemon), so I would soften it to "best effort". - Severity: Low
- Raised by another reviewer: No
Issue 4: Test gaps and a visibility change without a note
- Location:
TaskExecutionServiceTest.java:713-850;TaskExecutionService.java:959 - Problem: (a) The PR is motivated by the CANCELED path, but no new test drives
isCancel=truethroughtaskDone; the ordering assertion ("terminal state not published before metrics returns") exists only for FINISHED, and the FAILED test only checks that a metrics failure keeps FAILED. A regression that movedfuture.completeout of thefinallyfor CANCELED would not be caught. (b)updateMetricsContextInImap()was widened from private to package-private purely for Mockito spying, with no comment. - Potential risk: the headline scenario is unguarded; future edits may silently widen the method's use.
- Best improvement: add one test that marks the tracker canceled (via the cancellation future or
isCancel), blocks the report like the first test, and asserts the future is not done until the report is released and then equals CANCELED; add a one-line comment (or@VisibleForTesting) on the method. - Severity: Medium
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
The new field and completeAfterFinalMetrics carry useful Javadoc and match the surrounding style, apart from the spotless violation in Issue 1.
2.2 Test Coverage and Test Stability
The three tests are well targeted: the first fails if the report runs on the worker (it asserts the report threads are neither worker, that neither future is done while the report is blocked, and that the interrupt flag is preserved); the second and third fail if the finally/catch fallback is removed. Stability rating: Stable. They use latches and await().atMost(...) rather than sleeps, fresh FLAKE_ID_GENERATOR ids, and a spy that does not replace the shared server service. Coverage gap is Issue 4. I could not confirm they pass because CI skipped the unit-test job (Issue 1).
2.3 Documentation Updates
No user-facing docs needed (docs/en and docs/zh unaffected).
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. Isolating blocking IO from interruptible workers is the right direction and the change is small.
3.2 Maintainability
Clear and self-contained. Making the executor bounded/named/MDC-aware (Issue 3) would make it easier to troubleshoot.
3.3 Extensibility
completeAfterFinalMetrics is a reasonable single place to add a timeout later (Issue 2).
3.4 Historical-Version Compatibility
No wire, state, checkpoint or config change; upgrade-safe.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Spotless check fails (CI blocker; unit tests skipped) | TaskExecutionService.java:1655-1670 |
High |
| 2 | Terminal state waits on un-interruptible, un-timed RPC | TaskExecutionService.java:1698, :982 |
Medium |
| 4 | No CANCELED-path ordering test; visibility widened silently | TaskExecutionServiceTest.java:713-850, TaskExecutionService.java:959 |
Medium |
| 3 | Unbounded/unnamed/no-MDC pool, noisy shutdown rejection | TaskExecutionService.java:246, :328, :1709 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- Issue 1: run spotless and push so the full CI matrix (including
TaskExecutionServiceTest) can run. This is a CI gate only; I see no other source-level blocker.
- Issue 1: run spotless and push so the full CI matrix (including
- Recommended fixes - non-blocking
- Issue 2 and Issue 4 (Medium): worth doing in this PR since they are small; Issue 3 (Low) can be a follow-up.
CI status for this head: the fork's Build run fails only in Code style; everything else was skipped as a consequence, and the apache-side Build check is still pending. The branch is mergeable but 1 commit behind dev (compare status diverged); no conflicts, and syncing is not needed for the spotless failure.
Overall assessment: the approach is sound and the earlier regressions are fixed. No other maintainer has reviewed yet, so there is no existing approval or change request to reconcile with. A better alternative is not needed; Option A in Issue 2 keeps the current design. Thank you again for the persistence on this one, happy to re-review as soon as the formatting fix is up!
5f538f0 to
d7b43b7
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
Hi @Asthenia0412, thanks for the rebase onto the latest dev (new head d7b43b7f). I diffed it against the head I reviewed last time (5f538f05): the only difference is the upstream AGENTS.md/CLAUDE.md change that came in with the rebase, so the production and test code of this PR is byte-for-byte what I reviewed before, and the items from my last review still apply. The fork's Build run is still red in Code style for the same reason. I also want to apologize: while re-tracing the thread creation path I found one small item (Issue 5) that I should have caught last round. It is a carryover omission on my side, not something new in your code, and it is Low severity and non-blocking.
What Problem Does This PR Solve?
User pain point: When a task group is canceled, the last task calls updateMetricsContextInImap() from a task worker thread whose interrupt flag is already set. The synchronous Hazelcast call can then close the worker's shared connection to the master and delay terminal completion of the task group (#12413).
Fix approach: Run the final metrics report on a dedicated daemon cached thread pool and publish the task group's terminal TaskExecutionState only after that report finishes, fails, or is rejected.
One-sentence summary: Move the final metrics write off the interrupted worker thread while keeping terminal-state publication ordered after it.
Before / after:
// before: runs on the (possibly interrupted) task worker
finishExecution(taskGroupLocation);
try { updateMetricsContextInImap(); } catch (Throwable t) { ... }
future.complete(new TaskExecutionState(taskGroupLocation, FINISHED));
// after: runs on a dedicated thread, terminal state published afterwards
finishExecution(taskGroupLocation);
completeAfterFinalMetrics(taskGroupLocation, FINISHED, null);1. Code Change Review
1.1 Core Logic Analysis
Changed files: TaskExecutionService.java (+52/-12) and TaskExecutionServiceTest.java (+141). git diff origin/dev...HEAD contains only these two files and no deletions of existing dev behavior (the earlier revert of the #12454 latch handling and #12420 task.cancel() is gone; thank you for fixing that).
TaskGroupExecutionTracker.taskDone(:1648-1670) now calls the newcompleteAfterFinalMetrics(...)(:1688) for FINISHED, CANCELED and FAILED.completeAfterFinalMetricssubmits the report tofinalMetricsExecutorService(:246) and completesfuturein afinally; ifsubmitthrows, it completes the future directly (:1708-1711).future.completeis idempotent, so there is no double publication.shutdown()callsfinalMetricsExecutorService.shutdown()(:328).updateMetricsContextInImap()is widened from private to package-private (:959) for Mockito.
Key findings:
- The normal user path (every task group finishing, not only the cancel path) reaches the changed logic, because
taskDoneis the common terminal point. The cancel/interrupt scenario from #12413 is the motivating boundary case. - The ordering "finishExecution -> metrics report -> terminal state" is unchanged; only the executing thread changes. That is a precise, small fix.
- Remaining holes: a cancellation can no longer interrupt the report (Issue 2), the CANCELED path has no dedicated test (Issue 4), and the code-style gate still fails (Issue 1).
Runtime path after this PR:
task worker thread (maybe interrupted)
-> BlockingWorker.run / CooperativeWorker -> TaskGroupExecutionTracker.taskDone [:1648]
-> completionLatch == 0 -> finishExecution(location) (releases classloaders, moves context)
-> completeAfterFinalMetrics [:1688]
-> finalMetricsExecutorService.submit(...) [:1698] (worker returns immediately, interrupt flag untouched)
-> updateMetricsContextInImap() -> ReportMetricsOperation -> master, invoke.get() [:982]
-> finally future.complete(terminalState)
-> resultFuture.whenCompleteAsync(...) in deployLocalTask [:658] -> notifyTaskStatusToMaster
cancel path: cancelTaskGroup -> tracker.cancelAllTask -> task.cancel() + blockingFutures.cancel(true)
(these can no longer reach the metrics report, see Issue 2)
1.2 Compatibility Impact
Fully compatible. No configuration, option, default, protocol, serialization or state change. The report still happens once per terminal task group, before the terminal state is published. No entry is needed in incompatible-changes.md.
1.3 Performance / Side-Effect Analysis
- CPU/memory: one short-lived daemon thread per concurrently finishing task group; negligible in the normal case. The pool is unbounded (Issue 3).
- Networking: the same single
ReportMetricsOperationper terminal task group as before. - Lock contention / concurrency:
future.completenow runs on the metrics thread; the consumer runs throughwhenCompleteAsync(..., MDCTracer.tracing(executorService)), so nothing else blocks on the metrics thread. - Retries / idempotency: submit failure falls back to direct completion;
CompletableFuture.completeis idempotent. - Resource release: threads are daemon;
shutdown()stops accepting new work. Classloader release still happens infinishExecutionbefore the report, exactly as before.
1.4 Error Handling and Logging
Failures of the report and of the submission both still complete the terminal future, and a FAILED state keeps its original throwable. Good.
Issue 1: Spotless check still fails on the current head (CI blocker)
- Location:
TaskExecutionService.java:1655-1670(the threecompleteAfterFinalMetrics(...)calls) - Problem: The fork's
Buildrun ford7b43b7f(Run / Code style, https://github.com/Asthenia0412/seatunnel/actions/runs/38770552742) fails, as it did for5f538f05. The three calls are wrapped over two lines but fit in 100 columns (the longest is 96 columns when joined), so google-java-format wants them on one line. Because Code style failed,unit-test, the engine ITs and everything else were skipped, so the new tests have still not been exercised by CI. - Potential risk: the PR cannot merge, and there is no CI evidence for the new tests.
- Best improvement: run
./mvnw spotless:apply -pl seatunnel-engine/seatunnel-engine-serverand push; the diff should be only these three calls joined onto one line, e.g.completeAfterFinalMetrics(taskGroupLocation, ExecutionState.FINISHED, null); - Severity: High (merge gate)
- Raised by another reviewer: No (this is my own item from the previous round, still open)
Issue 2: Terminal state now waits on an RPC that nothing can interrupt or time out
- Location:
TaskExecutionService.java:1698-1706together withinvoke.get()at:982 - Problem: Before, a canceled worker blocked in
invoke.get()could be broken out of by the interrupt (which is also what caused #12413). Now the report runs on a pool thread thatcancelAllTask/cancelTaskGroupcan never reach, andfuture.complete(terminalState)sits in thefinallybehind the un-timedinvoke.get(). If the master is slow or in failover, the task group's CANCELED/FAILED state is delayed until Hazelcast's own invocation timeout/retry budget expires, which is the kind of delay this PR aims to remove. - Potential risk: slower cancel/failover completion of jobs under master instability; no escape hatch because the pool is daemon and uncancelable.
- Best improvement: Option A (smallest): in
completeAfterFinalMetrics, also schedule a fallbackfuture.complete(terminalState)on the existingscheduledExecutorServiceafter a bounded delay (a few seconds);completeis idempotent so whichever finishes first wins. Option B: give the final report its own bounded wait (for exampleinvoke.get(timeout)via a parameter) without changing the periodic scheduler's behavior. - Severity: Medium
- Raised by another reviewer: No
Issue 4: Test gaps and a visibility change without a note
- Location:
TaskExecutionServiceTest.java:713-850;TaskExecutionService.java:959 - Problem: (a) The PR is motivated by the CANCELED path, but no new test drives
isCancel=truethroughtaskDone; the ordering assertion (terminal state not published before the report returns) exists only for FINISHED, and the FAILED test only checks that a report failure keeps FAILED. A regression that movedfuture.completeout of thefinallyfor CANCELED would not be caught. (b)updateMetricsContextInImap()was widened from private to package-private purely for Mockito spying, with no comment. - Potential risk: the headline scenario is unguarded; future edits may silently widen the method's use.
- Best improvement: add one test that marks the tracker canceled, blocks the report like the first test, and asserts the future is not done until the report is released and then equals CANCELED; add a one-line comment or
@VisibleForTestingon the method. - Severity: Medium
- Raised by another reviewer: No
Issue 3: Final-metrics pool: unbounded, unnamed per thread, no MDC, noisy shutdown race
- Location:
TaskExecutionService.java:246-252,:328,:1708 - Problem: (a)
newCachedThreadPoolis unbounded; a stalled master pins one thread per terminal task group. (b) every thread is named identicallyseatunnel.final-metrics. (c) other executors in this class are wrapped withMDCTracer.tracing(...); this one is not, so theupdate metrics context in imap failedlog loses the job context the worker thread used to carry. (d)shutdown()runsexecutorService.shutdownNow()first (:326), so interrupted workers reachingtaskDoneafterfinalMetricsExecutorService.shutdown()hitRejectedExecutionException, which is logged at SEVERE with a stack trace once per task group even though it is the expected path. The Javadoc sentence "orderly shutdown drains accepted reports" (:1684) is only true while the JVM stays up because the threads are daemon. - Potential risk: operational noise and harder diagnosis; thread growth only under an already unhealthy master.
- Best improvement: a bounded pool with an indexed thread name,
MDCTracer.tracing, a WARN (no stack trace) on rejection, and soften the Javadoc to "best effort". - Severity: Low
- Raised by another reviewer: No
Issue 5: Pool threads inherit a task thread's context classloader (carryover from my previous review)
- Location:
TaskExecutionService.java:246-252(thread factory) - Problem: Sorry for missing this last time. The factory runs on the submitting thread, and
new Thread(...)inherits that thread's context classloader. The submitter is a task worker whose context classloader was set to the job'sSeaTunnelChildFirstClassLoaderinBlockingWorker.run(:1309) or the cooperative worker (:1442).finishExecutionreleases the loader first andDefaultClassLoaderService.recycleClassLoaderFromThreadnulls the context classloader on threads that still hold it when the reference count reaches 0, so this is self-healing in the common case and I do not see a permanent leak. What remains is that the metrics thread's context classloader is nondeterministic (null, or another job's loader when the loader is shared/cached), and a cached thread can be reused by a later job's report. - Potential risk: low; behavior is the same as before for the first report, but it depends on timing and could surprise a future change that needs the context classloader during reporting.
- Best improvement: set a fixed loader in the factory, for example
thread.setContextClassLoader(TaskExecutionService.class.getClassLoader()). - Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
The new field and completeAfterFinalMetrics carry useful Javadoc and match the surrounding style, apart from the spotless violation in Issue 1.
2.2 Test Coverage and Test Stability
The three tests are well targeted: testFinalMetricsRunOutsideInterruptedTaskWorker (:713) fails if the report runs on a worker (it asserts the report threads are neither worker, that neither future is done while the report is blocked, and that the interrupt flag is preserved); testFinalMetricsFailurePreservesFailedTerminalState (:794) and testFinalMetricsExecutorRejectionStillCompletesTerminalState (:822) fail if the finally / catch fallback is removed. Stability rating: Stable. They use latches and await().atMost(...) instead of sleeps, fresh FLAKE_ID_GENERATOR ids, and a spy so the shared server service is not altered. Coverage gap: Issue 4. I could not confirm they pass because CI skipped the unit-test job (Issue 1).
2.3 Documentation Updates
No user-facing docs needed (docs/en and docs/zh unaffected).
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. Isolating blocking IO from interruptible workers is the right direction and the change is small.
3.2 Maintainability
Clear and self-contained. A bounded, named, MDC-aware executor (Issue 3) would make it easier to troubleshoot.
3.3 Extensibility
completeAfterFinalMetrics is a good single place to add a timeout later (Issue 2).
3.4 Historical-Version Compatibility
No wire, state, checkpoint or config change; upgrade-safe.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Spotless check fails (CI blocker; unit tests skipped) | TaskExecutionService.java:1655-1670 |
High |
| 2 | Terminal state waits on un-interruptible, un-timed RPC | TaskExecutionService.java:1698, :982 |
Medium |
| 4 | No CANCELED-path ordering test; visibility widened silently | TaskExecutionServiceTest.java:713-850, TaskExecutionService.java:959 |
Medium |
| 3 | Unbounded/unnamed/no-MDC pool, noisy shutdown rejection | TaskExecutionService.java:246, :328, :1708 |
Low |
| 5 | Pool threads inherit a task thread's context classloader | TaskExecutionService.java:246-252 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- Issue 1: run spotless and push so the full CI matrix (including
TaskExecutionServiceTest) can run. This is a CI gate only; I see no other source-level blocker.
- Issue 1: run spotless and push so the full CI matrix (including
- Recommended fixes - non-blocking
- Issue 2 and Issue 4 (Medium): worth doing in this PR since they are small; Issues 3 and 5 (Low) can be a follow-up.
CI status for this head: the fork's Build run fails only in Code style; everything else was skipped as a consequence, and the apache-side Build check reports failure pointing at that run. The branch is mergeable with no conflicts and is 1 commit behind dev (compare status diverged); syncing is not needed for the spotless failure.
Overall assessment: the approach is sound and the earlier regressions are fixed. No other maintainer has reviewed yet, so there is no existing approval or change request to reconcile with. A better alternative is not needed; Option A in Issue 2 keeps the current design. Thank you again for the persistence on this one, happy to re-review as soon as the formatting fix is up!
Fixes the blockers and recommended follow-ups from @DanielLeens' latest review of apache#12795: 1. Spotless check (CI blocker) — collapsed the three multi-line completeAfterFinalMetrics(...) call sites onto single lines so google-java-format is satisfied. 2. Timeout safety net (Issue 2, Medium) — schedule a fallback future.complete(terminalState) on the existing scheduled executor after 15 seconds. future.complete is idempotent, so whichever of the finally block or the fallback fires first wins. 3. CANCELED-path ordering test (Issue 4a, Medium) — added testFinalMetricsPreservesCanceledTerminalState, which drives the CANCELED branch through the same metrics-report-isolated path as the existing FINISHED and FAILED tests. 4. Visibility note (Issue 4b) — added a short comment explaining why updateMetricsContextInImap is package-private. 5. Named / MDC-aware threads (Issue 3, Low) — the final-metrics pool now uses a ThreadFactory with indexed names so each pool thread is distinguishable in thread dumps, and the pool is wrapped with MDCTracer.tracing so the metrics report keeps the job's MDC context. 6. Context classloader isolation (Issue 5, Low) — each pool thread is born with TaskExecutionService.class.getClassLoader() instead of inheriting the submitting task worker's SeaTunnelChildFirstClassLoader, which could already have been recycled or belong to another job by then. All four final-metrics tests pass locally with spotless green.
|
Hi @DanielLeens — thank you so much for the thorough second round of reviews! I pushed a new commit (328d13a) that addresses every item from your latest feedback. The full summary: Blocker — Issue 1 (Spotless)
Medium — Issue 2 (Uninterruptible / un-timed RPC)
Medium — Issue 4a (CANCELED-path ordering test)
Medium — Issue 4b (Visibility widened silently)
Low — Issue 3 (Thread pool hygiene)
Low — Issue 5 (Context classloader inheritance)
Verification
Fork-side CI is now running against this new head — I'll be happy to triage anything that surfaces there and iterate further. Thanks again! |
DanielLeens
left a comment
There was a problem hiding this comment.
Hi @Asthenia0412, thank you for the quick turnaround on my last round, and for answering each item one by one. I re-reviewed the new head 328d13ab against d7b43b7f (the head I reviewed last time). Also, a sincere apology up front: one of the items below (Issue 1) comes from advice I gave you last round. I suggested using the existing scheduledExecutorService without checking how it is used elsewhere in the class, so that is on me, not on your implementation. It is a carryover from my previous review, not something you introduced.
What Problem Does This PR Solve?
User pain point: When a task group is canceled, the last task calls updateMetricsContextInImap() from a task worker whose interrupt flag is already set. The synchronous Hazelcast call can then close the worker's shared connection to the master and delay terminal completion of the task group (#12413).
Fix approach: Run the final metrics report on a dedicated daemon pool and publish the task group's terminal TaskExecutionState only after that report finishes, fails, or is rejected; the new commit also adds a 15 s fallback completion.
One-sentence summary: Move the final metrics write off the interrupted worker thread while keeping terminal-state publication ordered after it.
1. Code Change Review
1.1 Core Logic Analysis
The delta since my last review touches only TaskExecutionService.java and TaskExecutionServiceTest.java:
- The three
completeAfterFinalMetrics(...)calls are joined onto single lines (spotless fix) - this closes my previous Issue 1. - The final-metrics pool now uses a named
ThreadFactory(seatunnel.final-metrics-N), a fixed context classloader, and is wrapped inMDCTracer.tracing(...)- this closes my previous Issues 3(b)(c) and 5.MDCExecutorServicedelegatesshutdown(), so the shutdown path is unchanged. completeAfterFinalMetricsnow also schedulesfuture.complete(terminalState)onscheduledExecutorServiceafterFINAL_METRICS_FALLBACK_TIMEOUT_MS = 15_000(TaskExecutionService.javaaround the newscheduledExecutorService.schedule(...)call), and the rejection log is lowered towarning.- New test
testFinalMetricsPreservesCanceledTerminalStatedrivesisCancel=truethroughtaskDonewith an interrupted worker, blocks the report, and asserts the CANCELED future is not done until the report is released. That fails iffuture.completeis moved out of the ordering for the CANCELED branch, so it guards the headline scenario. Thank you for adding it.
The normal path (every terminal task group, not only cancel) reaches this code because taskDone is the common terminal point; the cancel/interrupt case from #12413 is the motivating boundary.
1.2 Compatibility Impact
Fully compatible. No config option, default, protocol, serialization or state-format change; nothing needs an entry in incompatible-changes.md. (I did not run the 2.x to current upgrade path; there is no persisted-format change to exercise.)
1.3 Performance / Side-Effect Analysis
- The final-metrics pool is still an unbounded cached pool (
Integer.MAX_VALUE,SynchronousQueue). In practice it is bounded by the number of concurrently terminating task groups, and the threads are daemon, so I keep this as a note only. Because the report is still an un-timedinvoke.get()that nothing can interrupt, a stalled master pins one thread per terminated task group until Hazelcast gives up. - Each terminal task group now also leaves a 15 s delayed task in the scheduler queue that is never cancelled (see Issue 2).
1.4 Error Handling and Logging
Report failure and submission failure both still complete the terminal future, and FAILED keeps its original throwable. The lowered warning log on submit failure is a good change.
Issue 1: The 15 s fallback runs on a single-thread scheduler that is shared with the periodic metrics report, so it cannot fire in the slow-master case it is meant for
- Location:
TaskExecutionService.javaconstructor (scheduledExecutorService = Executors.newSingleThreadScheduledExecutor()withscheduleAtFixedRate(this::updateMetricsContextInImap, ...)) and the newscheduledExecutorService.schedule(...)incompleteAfterFinalMetrics. - Problem description:
scheduledExecutorServiceis a single-thread scheduler whose only existing job is the periodicupdateMetricsContextInImap(), the very same un-timedinvoke.get()call. If the master is slow or in failover, that periodic run blocks the scheduler's only thread inside the RPC, so the queued fallback task cannot start until that call returns. In other words, in the failure mode the fallback exists for, it is queued behind the same blocked call and fires no earlier than the report it was meant to bound. This is the point I should have flagged when I suggested Option A last round. - Potential risk: CANCELED/FAILED task groups can still be delayed by the master RPC budget, so the Medium item from my last review is only partly closed, and the new 15 s constant gives a false sense of a bound. The test cannot catch it because it never blocks the scheduler thread or exercises the fallback (see Issue 3).
- Best improvement: Option A: schedule the fallback on a scheduler that is not shared with the periodic report, e.g. a small dedicated single-thread daemon
ScheduledThreadPoolExecutorfor terminal fallbacks (withsetRemoveOnCancelPolicy(true)), shut down inshutdown(). Option B: give the final report its own bounded wait (a timeout parameter to the metrics call used only on this path) so the pool thread itself returns, which also stops pinning pool threads. Option A is the smaller change. - Severity: Medium
- Raised by another reviewer: No
Issue 2: Fallback task is never cancelled when the report finishes normally
- Location:
TaskExecutionService.java,completeAfterFinalMetrics(theschedule(...)call). - Problem description: The returned
ScheduledFutureis dropped. On the normal path, where the report returns in milliseconds, every terminal task group leaves a delayed task holdingfutureandterminalState(including the failure throwable) for 15 s.Executors.newSingleThreadScheduledExecutor()does not remove cancelled tasks early either. - Potential risk: Low; bounded to 15 s of retention per terminal task group, but it adds scheduler queue churn on large clusters finishing many task groups at once.
- Best improvement: Keep the
ScheduledFutureandcancel(false)it in thefinallyblock of the report task (together with the dedicated scheduler andsetRemoveOnCancelPolicy(true)from Issue 1). - Severity: Low
- Raised by another reviewer: No
Issue 3: No test covers the new fallback
- Location:
TaskExecutionServiceTest.java(new tests aroundtestFinalMetricsPreservesCanceledTerminalState);FINAL_METRICS_FALLBACK_TIMEOUT_MSis a hard-coded private constant. - Problem description: The four final-metrics tests all release the report, so none proves that the terminal future completes when the report never returns. If the
schedule(...)call were deleted, every test would still pass. The constant is not injectable, so a test would have to wait 15 s. - Potential risk: The headline behavior of the commit (bounded wait) is unguarded and, as Issue 1 shows, can already be silently ineffective.
- Best improvement: Make the timeout a package-private field/constructor parameter (or a
@VisibleForTestingsetter) and add one test that blocks the report forever and asserts the future completes with the expected state within the shortened timeout, plus a variant that keeps the periodic scheduler busy to pin the Issue 1 scenario. - Severity: Medium
- Raised by another reviewer: No
Issue 4: Small style notes (non-blocking)
- Location:
TaskExecutionService.java, the instance initializer block that buildsfinalMetricsExecutorService, and theFINAL_METRICS_FALLBACK_TIMEOUT_MSconstant declared after it. - Problem description: The rest of the class assigns executors in the constructor and keeps
static finalconstants with the other constants; an instance initializer block plus a constant declared below it is easy to miss. Also, the comment "Visible for testing" onupdateMetricsContextInImap()could be@VisibleForTestingso tools can see it. - Potential risk: None functionally.
- Best improvement: Build the pool in the constructor (or a small private static factory method) and move the constant up.
- Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
The new field, constant and completeAfterFinalMetrics carry useful Javadoc; the code is spotless-clean as far as I can tell from reading it (I did not run spotless locally; the CI Code style job on the current head is the authority).
2.2 Test Coverage and Test Stability
Stability rating: Stable. The new CANCELED test uses latches and await().atMost(...), fresh FLAKE_ID_GENERATOR ids and a spy, with no sleeps and no data-dependent assertions, and its finally releases the latch so it cannot leak a blocked thread. Coverage gap: Issue 3. I could not confirm the tests pass in CI yet: on this head the fork Build run (https://github.com/Asthenia0412/seatunnel/actions/runs/38851725773) was still queued and the apache-side Build was in progress when I checked, so the full unit-test matrix has still not been exercised.
2.3 Documentation Updates
No user-visible option or behavior change, so docs/en and docs/zh do not need updating.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix for the interrupt problem; the fallback is the part that still needs rework (Issue 1).
3.2 Maintainability
Clear and self-contained, with a single place (completeAfterFinalMetrics) to reason about terminal ordering.
3.3 Extensibility
The single method makes a later switch to a metrics call with a real timeout easy.
3.4 Historical-Version Compatibility
Compatible with historical versions; no upgrade action is needed.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Fallback shares the single-thread periodic-report scheduler, so it can be blocked by the same RPC | TaskExecutionService.java constructor + completeAfterFinalMetrics |
Medium |
| 3 | No test for the fallback; timeout not injectable | TaskExecutionServiceTest.java |
Medium |
| 2 | Fallback task never cancelled on normal completion | completeAfterFinalMetrics |
Low |
| 4 | Initializer block / constant placement style | TaskExecutionService.java |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
-
Blockers - must be fixed
- CI: the full CI matrix (including
TaskExecutionServiceTest) has not completed on this head yet; it needs to be green. Nothing else I found is a pure CI item. - Issue 1: the stated bound on terminal completion does not hold in the slow-master case, and this is what the previous Medium item asked for, so I would like it fixed in this PR (a dedicated scheduler is a few lines).
- CI: the full CI matrix (including
-
Recommended fixes - non-blocking
- Issue 3 (Medium): add a fallback test; it is the guard for Issue 1.
- Issues 2 and 4 (Low): fine as a follow-up or alongside Issue 1.
Overall assessment: the interrupt-isolation part and the terminal-state ordering look right to me, and the review items from the last round are well addressed; the one thing left is making the new timeout actually effective. No other reviewer has commented, so there is no existing approval or change request to reconcile with. A better alternative is not needed; Option A in Issue 1 keeps the current design. Thanks again for the persistence, happy to re-review as soon as the next head is up!
|
@- |
Fixes the blockers and recommended follow-ups from @DanielLeens' latest review of apache#12795: 1. Spotless check (CI blocker) — collapsed the three multi-line completeAfterFinalMetrics(...) call sites onto single lines so google-java-format is satisfied. 2. Timeout safety net (Issue 2, Medium) — schedule a fallback future.complete(terminalState) on the existing scheduled executor after 15 seconds. future.complete is idempotent, so whichever of the finally block or the fallback fires first wins. 3. CANCELED-path ordering test (Issue 4a, Medium) — added testFinalMetricsPreservesCanceledTerminalState, which drives the CANCELED branch through the same metrics-report-isolated path as the existing FINISHED and FAILED tests. 4. Visibility note (Issue 4b) — added a short comment explaining why updateMetricsContextInImap is package-private. 5. Named / MDC-aware threads (Issue 3, Low) — the final-metrics pool now uses a ThreadFactory with indexed names so each pool thread is distinguishable in thread dumps, and the pool is wrapped with MDCTracer.tracing so the metrics report keeps the job's MDC context. 6. Context classloader isolation (Issue 5, Low) — each pool thread is born with TaskExecutionService.class.getClassLoader() instead of inheriting the submitting task worker's SeaTunnelChildFirstClassLoader, which could already have been recycled or belong to another job by then. All four final-metrics tests pass locally with spotless green.
328d13a to
93e5840
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
Hi @Asthenia0412, thank you for pushing the follow-up and for the detailed walkthrough of what you changed. I re-reviewed the current head 93e58408 in full. Two facts first. (1) Your issue comment from 2026-10-16T10:12Z (posted right after the push) only contains the text "@-", so I could not find any additional request or explanation in it; if you meant to say something there, please repost it. (2) The code in this head is the same TaskExecutionService change that I reviewed at 328d13ab (the head now sits directly on current dev with two commits, and the diff of the engine class and its test is unchanged in substance), so the four open items from my last round are still present. Sorry for not being able to give you a "closed" status this time; the good news is that the remaining work is small and the core idea is already right.
What Problem Does This PR Solve?
User pain point: When a task group is canceled, the last task calls updateMetricsContextInImap() from a task worker thread whose interrupt flag is already set. The synchronous Hazelcast invocation can then fail or close the worker's shared connection, and delay terminal completion of the task group (#12413).
Fix approach: Run the final metrics report on a dedicated daemon cached pool (seatunnel.final-metrics-N) and complete the terminal TaskExecutionState only after the report returns, with a 15 s scheduled fallback so the terminal future cannot wait forever.
One-sentence summary: Move the final metrics write off the interrupted worker thread while keeping terminal-state publication ordered after it and bounded in time.
Before / after:
// before: runs on the (possibly interrupted) task worker
finishExecution(taskGroupLocation);
try { updateMetricsContextInImap(); } catch (Throwable t) { ... }
future.complete(new TaskExecutionState(taskGroupLocation, FINISHED));
// after: report runs on a pool thread, terminal state published afterwards
finishExecution(taskGroupLocation);
completeAfterFinalMetrics(taskGroupLocation, FINISHED, null);1. Code Change Review
1.1 Core Logic Analysis
The normal user path reaches the change: every task group that reaches TaskGroupExecutionTracker.taskDone with completionLatch == 0 goes through completeAfterFinalMetrics (TaskExecutionService.java:1725) for FINISHED, CANCELED and FAILED. The earlier blockers (rebase reverting #12454 / #12420 and weakened tests) are gone: the diff against dev is now limited to TaskExecutionService.java and TaskExecutionServiceTest.java, and the deleted regression tests are back.
Key Findings:
- Interrupt isolation and terminal-state ordering look correct; the report no longer runs on the worker thread, and the
finally { future.complete(...) }plus thecatch (Throwable)aroundsubmitmake completion robust against report failure and executor rejection. - Thread-pool hygiene items from the previous round (named threads, fixed context classloader,
MDCTracer.tracing, "best-effort" Javadoc) are done. - The 15 s fallback is scheduled on
scheduledExecutorService, a single-thread scheduler that is also running the periodic un-timedupdateMetricsContextInImap(). In the slow-master case the fallback is queued behind that same blocked call and cannot fire on time (Issue 1, carryover). - The fallback
ScheduledFutureis never cancelled (Issue 2, carryover) and no test exercises the fallback (Issue 3, carryover).
Runtime path (head):
worker thread (maybe interrupted) -> TaskGroupExecutionTracker.taskDone
-> completionLatch == 0 -> finishExecution(location)
-> completeAfterFinalMetrics(location, state, ex)
-> finalMetricsExecutorService.submit(
updateMetricsContextInImap() // invoke.get(), no timeout (line ~1020)
; finally future.complete(terminalState))
-> scheduledExecutorService.schedule(future.complete(terminalState), 15s) // line 1749
^ same single thread as scheduleAtFixedRate(this::updateMetricsContextInImap) (line 324-325)
-> resultFuture.whenCompleteAsync(...) in deployLocalTask -> report terminal state to master
Slow master: periodic run blocks the scheduler thread inside invoke.get() -> the 15 s task starts only after that call returns -> the bound is no better than the RPC budget it was meant to cap.
1.2 Compatibility Impact
Fully compatible: no config option, serialization, or protocol change; updateMetricsContextInImap() only goes from private to package-private. No entry is needed in incompatible-changes.md.
1.3 Performance / Side-Effect Analysis
- The cached pool is unbounded but limited in practice by the number of concurrently finishing task groups; acceptable with the fallback in place, but pool threads stay pinned for as long as the un-timed RPC blocks (Issue 1, Option B would fix this too).
- Every terminal task group leaves a 15 s delayed task (holding the terminal state and the failure throwable) in the scheduler queue (Issue 2).
1.4 Error Handling and Logging
Issue 1: The 15 s fallback shares a single-thread scheduler with the periodic metrics report, so it cannot fire in the slow-master case it is meant for (carryover from my last review, sorry for the extra round)
- Location:
TaskExecutionService.java:324-325(single-threadscheduledExecutorServicerunningupdateMetricsContextInImap) and:1749(scheduledExecutorService.schedule(...)) - Problem description: the periodic job calls the same un-timed
invoke.get()(:1020). If the master is slow or failing over, that periodic run occupies the scheduler's only thread, so the queued fallback task cannot start until it returns. - Potential risk: CANCELED/FAILED task groups can still be delayed by the full master RPC budget; the 15 s constant gives a false sense of a bound.
- Best improvement: use a small dedicated daemon
ScheduledThreadPoolExecutor(withsetRemoveOnCancelPolicy(true)) for terminal fallbacks, shut down inshutdown(); or give the final report its own bounded wait so the pool thread itself returns. - Severity: Medium
- Raised by another reviewer: No
Issue 2: Fallback task is never cancelled when the report finishes normally
- Location:
TaskExecutionService.java:1749 - Problem description: the returned
ScheduledFutureis dropped;Executors.newSingleThreadScheduledExecutor()does not drop cancelled tasks early either. - Potential risk: 15 s retention of the terminal state per finished task group and scheduler queue churn on large clusters.
- Best improvement: keep the
ScheduledFutureandcancel(false)it in thefinallyof the report task (together with the dedicated scheduler and remove-on-cancel from Issue 1). - Severity: Low
- Raised by another reviewer: No
Issue 3: No test covers the new fallback
- Location:
TaskExecutionServiceTest.java(testFinalMetrics*at lines 713-890);TaskExecutionService.java:289(FINAL_METRICS_FALLBACK_TIMEOUT_MS, private static constant) - Problem description: all four final-metrics tests release the report; deleting the
schedule(...)call would leave all of them green. The constant is not injectable, so a test would wait 15 s. - Potential risk: the headline behavior (bounded terminal completion) is unguarded and, as Issue 1 shows, can already be ineffective.
- Best improvement: make the timeout a package-private field or constructor parameter, add one test where the report blocks forever and the future must still complete within the shortened timeout, plus a variant where the periodic scheduler thread is busy (pins Issue 1).
- Severity: Medium
- Raised by another reviewer: No
Issue 4: Style notes (non-blocking)
- Location:
TaskExecutionService.java:252(instance initializer block building the pool),:289(constant declared below it),:997(// Visible for testingcomment) - Problem description: the rest of the class assigns executors in the constructor; an initializer block with a constant declared after it is easy to miss.
@VisibleForTestingis more discoverable than a comment. - Potential risk: none functionally.
- Best improvement: build the pool in the constructor or a private static factory and move the constant up with the other constants.
- Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
New methods and fields carry useful Javadoc; the new pool and fallback are commented with the why. Only the style notes in Issue 4 remain.
2.2 Test Coverage and Test Stability
The four tests cover FINISHED isolation, CANCELED ordering, FAILED preservation when metrics fail, and executor rejection. Stability rating: Stable. They use latches and await().atMost(...) with fresh FLAKE_ID_GENERATOR ids; the new tests contain no Thread.sleep (the Thread.sleep calls at :289, :514, :585, :639 are pre-existing tests). Coverage gap: Issue 3. CI on this head has not run yet (see metadata below), so the tests are not confirmed in CI.
2.3 Documentation Updates
No user-facing docs are needed (internal engine behavior only).
3. Architectural Soundness
3.1 Elegance
Precise fix for the interrupt problem; the fallback is the part still to rework (Issue 1).
3.2 Maintainability
Good once the fallback has its own scheduler and the pool is built in the constructor.
3.3 Extensibility
A configurable or injectable timeout would help both tests and operators; not required to be a user option.
3.4 Historical-Version Compatibility
No impact on checkpoint/savepoint, job configs, or RPC payloads; ReportMetricsOperation is unchanged.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Fallback shares the single-thread scheduler with the periodic un-timed metrics report | TaskExecutionService.java:324, :1749 |
Medium |
| 3 | No test covers the fallback timeout | TaskExecutionServiceTest.java:713-890 |
Medium |
| 2 | Fallback ScheduledFuture never cancelled |
TaskExecutionService.java:1749 |
Low |
| 4 | Initializer block / constant placement / @VisibleForTesting |
TaskExecutionService.java:252, :289, :997 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- Issue 1: the stated bound on terminal completion does not hold in the slow-master case, which is exactly what the previous Medium item asked to bound. A dedicated scheduler is a few lines.
- Issue 3: add a test that proves the fallback fires (it is the guard for Issue 1).
- Full CI on this head is still queued (fork run
38885711411was queued when I checked), so the unit-test matrix is not yet exercised; please keep an eye on it.
- Recommended fixes - non-blocking
- Issues 2 and 4 are fine alongside Issue 1.
Overall assessment: the interrupt isolation and terminal-state ordering are right, the earlier regressions are fixed, and the previous hygiene items were well addressed; what is left is making the new timeout actually effective and tested. No other reviewer has commented, so there is no approval or change request to reconcile with. A better alternative is not needed; a dedicated fallback scheduler keeps the current design. Thank you for the persistence, I am happy to re-review as soon as the next head is up!
DanielLeens
left a comment
There was a problem hiding this comment.
Hi @Asthenia0412, thank you for the new push. Two acknowledgements first. (1) Your earlier summary comment (2026-10-16T04:39Z) is fully covered by my last rounds, and your second comment (2026-10-16T10:12Z) still contains only the text "@-", so I have nothing further to reply to there; please repost it if you meant to add something. (2) I re-reviewed the current head ec97b863 in full. Compared with 93e58408, the only change is one commit that touches TaskExecutionServiceTest.java (capturing the interrupt flag inside the worker so the assertion is stable on JDK 11 - a good catch). TaskExecutionService.java is byte-for-byte unchanged, so the open items from my last review still apply. The good news is that the remaining work is small and the core idea is right.
What Problem Does This PR Solve?
User pain point: When a task group is canceled, the last task calls updateMetricsContextInImap() from a task worker thread whose interrupt flag is already set. The synchronous Hazelcast invocation can then fail or close the worker's shared connection, and delay terminal completion of the task group (#12413).
Fix approach: Run the final metrics report on a dedicated daemon cached pool (seatunnel.final-metrics-N) and complete the terminal TaskExecutionState only after the report returns, with a 15 s scheduled fallback so the terminal future cannot wait forever.
One-sentence summary: Move the final metrics write off the interrupted worker thread while keeping terminal-state publication ordered after it and bounded in time.
Before / after:
// before: runs on the (possibly interrupted) task worker
finishExecution(taskGroupLocation);
try { updateMetricsContextInImap(); } catch (Throwable t) { ... }
future.complete(new TaskExecutionState(taskGroupLocation, FINISHED));
// after: report runs on a pool thread, terminal state published afterwards
finishExecution(taskGroupLocation);
completeAfterFinalMetrics(taskGroupLocation, FINISHED, null);1. Code Change Review
1.1 Core Logic Analysis
The normal user path reaches the change: every task group that reaches TaskGroupExecutionTracker.taskDone with completionLatch == 0 goes through completeAfterFinalMetrics (TaskExecutionService.java:1725, called at :1693, :1699, :1704) for FINISHED, CANCELED and FAILED. The diff against dev is limited to TaskExecutionService.java and TaskExecutionServiceTest.java, with no deletions of existing dev behavior.
Key Findings:
- Interrupt isolation and terminal-state ordering are correct. The
finally { future.complete(...) }plus thecatch (Throwable)aroundsubmitmake completion robust against report failure and executor rejection. - Thread-pool hygiene (named threads, fixed context classloader,
MDCTracer.tracing, best-effort Javadoc) is done. - The 15 s fallback is scheduled on
scheduledExecutorService(:1749), the single-thread scheduler created at:324that also runs the periodic un-timedupdateMetricsContextInImap()(:325,invoke.get()at:1020). In the slow-master case the fallback is queued behind that blocked call and cannot fire on time (Issue 1, carryover). - The fallback
ScheduledFutureis dropped and never cancelled (Issue 2, carryover), and no test exercises the fallback (Issue 3, carryover).
Runtime path (head):
worker thread (maybe interrupted) -> TaskGroupExecutionTracker.taskDone
-> completionLatch == 0 -> finishExecution(location)
-> completeAfterFinalMetrics(location, state, ex) [:1725]
-> finalMetricsExecutorService.submit( [:1735]
updateMetricsContextInImap() // invoke.get(), no timeout [:1020]
; finally future.complete(terminalState))
-> scheduledExecutorService.schedule(future.complete(terminalState), 15s) [:1749]
^ same single thread as scheduleAtFixedRate(this::updateMetricsContextInImap) [:324-325]
-> resultFuture.whenCompleteAsync(...) in deployLocalTask -> report terminal state to master
Slow master: the periodic run blocks the scheduler thread inside invoke.get(), so the 15 s task starts only after that call returns. The bound is then no better than the RPC budget it was meant to cap.
1.2 Compatibility Impact
Fully compatible: no config option, serialization, or protocol change; updateMetricsContextInImap() only goes from private to package-private. No entry is needed in incompatible-changes.md.
1.3 Performance / Side-Effect Analysis
- The cached pool is unbounded but limited in practice by the number of concurrently finishing task groups. Pool threads stay pinned for as long as the un-timed RPC blocks (Issue 1, Option B would fix this too).
- Every terminal task group leaves a 15 s delayed task (holding the terminal state and the failure throwable) in the scheduler queue (Issue 2).
1.4 Error Handling and Logging
Issue 1: The 15 s fallback shares a single-thread scheduler with the periodic metrics report, so it cannot fire in the slow-master case it is meant for (carryover from my previous two reviews; sorry for the extra rounds)
- Location:
TaskExecutionService.java:324-325and:1749 - Problem description: the periodic job calls the same un-timed
invoke.get()(:1020). If the master is slow or failing over, that run occupies the scheduler's only thread, so the queued fallback cannot start until it returns. - Potential risk: CANCELED/FAILED task groups can still be delayed by the full master RPC budget; the 15 s constant gives a false sense of a bound.
- Best improvement: use a small dedicated daemon
ScheduledThreadPoolExecutor(withsetRemoveOnCancelPolicy(true)) for terminal fallbacks, shut down inshutdown()(:364-365); or give the final report its own bounded wait so the pool thread itself returns. - Severity: Medium
- Raised by another reviewer: No
Issue 2: Fallback task is never cancelled when the report finishes normally (carryover)
- Location:
TaskExecutionService.java:1749 - Problem description: the returned
ScheduledFutureis dropped, andExecutors.newSingleThreadScheduledExecutor()does not drop cancelled tasks early either. - Potential risk: 15 s retention of the terminal state per finished task group and scheduler queue churn on large clusters.
- Best improvement: keep the
ScheduledFutureandcancel(false)it in thefinallyof the report task (together with the dedicated scheduler and remove-on-cancel from Issue 1). - Severity: Low
- Raised by another reviewer: No
Issue 3: No test covers the new fallback (carryover)
- Location:
TaskExecutionServiceTest.java:713-890(testFinalMetrics*);TaskExecutionService.java:289(FINAL_METRICS_FALLBACK_TIMEOUT_MS, private static constant) - Problem description: all four final-metrics tests release the report; deleting the
schedule(...)call would leave all of them green. The constant is not injectable, so a test would wait 15 s. - Potential risk: the headline behavior (bounded terminal completion) is unguarded and, as Issue 1 shows, can already be ineffective.
- Best improvement: make the timeout a package-private field or constructor parameter, add one test where the report blocks forever and the future must still complete within the shortened timeout, plus a variant where the periodic scheduler thread is busy (pins Issue 1).
- Severity: Medium
- Raised by another reviewer: No
Issue 4: Style notes (non-blocking) (carryover)
- Location:
TaskExecutionService.java:252(instance initializer block building the pool),:289(constant declared below it),:996(// Visible for testingcomment) - Problem description: the rest of the class assigns executors in the constructor; an initializer block with a constant declared after it is easy to miss.
@VisibleForTestingis more discoverable than a comment. - Potential risk: none functionally.
- Best improvement: build the pool in the constructor or a private static factory and move the constant up with the other constants.
- Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
New methods and fields carry useful Javadoc, and the new pool and fallback are commented with the why. Only the style notes in Issue 4 remain.
2.2 Test Coverage and Test Stability
The four tests cover FINISHED isolation, CANCELED ordering, FAILED preservation when metrics fail, and executor rejection. Stability rating: Stable. They use latches and await().atMost(...) with fresh FLAKE_ID_GENERATOR ids, and the new tests contain no Thread.sleep (the Thread.sleep calls at :289, :514, :585, :639 belong to pre-existing tests). The latest commit makes the interrupt-flag assertion JDK-independent. Coverage gap: Issue 3.
2.3 Documentation Updates
No user-facing docs are needed (internal engine behavior only).
3. Architectural Soundness
3.1 Elegance
Precise fix for the interrupt problem; the fallback is the part still to rework (Issue 1).
3.2 Maintainability
Good once the fallback has its own scheduler and the pool is built in the constructor.
3.3 Extensibility
A configurable or injectable timeout would help both tests and operators; not required to be a user option.
3.4 Historical-Version Compatibility
No impact on checkpoint/savepoint, job configs, or RPC payloads; ReportMetricsOperation is unchanged.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Fallback shares the single-thread scheduler with the periodic un-timed metrics report | TaskExecutionService.java:324, :1749 |
Medium |
| 3 | No test covers the fallback timeout | TaskExecutionServiceTest.java:713-890 |
Medium |
| 2 | Fallback ScheduledFuture never cancelled |
TaskExecutionService.java:1749 |
Low |
| 4 | Initializer block / constant placement / @VisibleForTesting |
TaskExecutionService.java:252, :289, :996 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- Issue 1: the stated bound on terminal completion does not hold in the slow-master case. A dedicated scheduler is a few lines.
- Issue 3: add a test that proves the fallback fires (it is the guard for Issue 1).
- Sync with the latest
dev(the branch is 6 commits behind, 3 commits ahead) and re-run CI. The forkBuildrun for this head (https://github.com/Asthenia0412/seatunnel/actions/runs/38933877829) is red in 16 connector IT jobs (for examplehbase-connector-it,connector-redis-it,jdbc-connectors-it-part-1,all-connectors-it-2/6/7,mysql-cdc-connector-it,transform-v2-it-part-2). The sample I inspected (hbase-connector-it) fails with "Master is initializing" during container startup; I did not diagnose every job. Importantly,Code style, all fourunit-testjobs (JDK 11/17, Linux and Windows) andengine-v2-it/engine-k8s-itare green, and this PR does not touch any connector, so these look unrelated to the diff. Please sync dev and re-run only the failed jobs; the apache-sideBuildcheck was still in progress when I looked.
- Recommended fixes - non-blocking
- Issues 2 and 4 fit naturally alongside Issue 1.
Overall assessment: the interrupt isolation and terminal-state ordering are right, the earlier regressions are fixed, and the hygiene items were well addressed; what is left is making the new timeout actually effective and tested. No other reviewer has commented, so there is nothing to reconcile. A better alternative is not needed; a dedicated fallback scheduler keeps the current design. Thank you for the persistence, I am happy to re-review as soon as the next head is up!
|
Hi @DanielLeens, many thanks for your thorough review! Here's what this new push (commit Issue 1 (Medium) — Dedicated fallback schedulerThe 15 s fallback now runs on its own single-thread Issue 2 (Low) — Cancel fallback after normal completionWe now track the returned Issue 4 (Low) — Style cleanup
Spotless:apply ran clean, and |
DanielLeens
left a comment
There was a problem hiding this comment.
Hi @Asthenia0412, thank you for the new push (88703260) and for the clear point-by-point summary. I re-reviewed the whole head from scratch, not only the delta. Most of what I asked for last round is now in: the 15 s fallback has its own dedicated scheduler, the scheduled task is cancelled when the report finishes, and the style notes are cleaned up. One test item from my previous round is still open (your summary does not mention it), and CI needs a sync and a rerun. Nothing in the production logic worries me anymore, so this is close.
What Problem Does This PR Solve?
User pain point: When a task group is canceled, the last task calls updateMetricsContextInImap() from a task worker thread whose interrupt flag is already set. The synchronous Hazelcast invocation can then fail or close the worker's shared connection, and delay terminal completion of the task group (#12413).
Fix approach: Run the final metrics report on a dedicated daemon pool (seatunnel.final-metrics-N) and publish the terminal TaskExecutionState only after the report returns, with a 15 s fallback on a separate scheduler so the terminal future cannot wait forever.
One-sentence summary: Move the final metrics write off the interrupted worker thread while keeping "metrics first, terminal state second" ordering, bounded in time.
Simple example: a user cancels a job while a task is mid-flight. Before, the worker (interrupted) did the metrics RPC itself and could break the shared connection; now a fresh pool thread does it and the CANCELED state is published right after.
// before: runs on the (possibly interrupted) task worker
finishExecution(taskGroupLocation);
try { updateMetricsContextInImap(); } catch (Throwable t) { ... }
future.complete(new TaskExecutionState(taskGroupLocation, FINISHED));
// after: report on a pool thread, terminal state afterwards, fallback after 15 s
finishExecution(taskGroupLocation);
completeAfterFinalMetrics(taskGroupLocation, FINISHED, null);1. Code Change Review
1.1 Core Logic Analysis
Changed files: TaskExecutionService.java and TaskExecutionServiceTest.java only. git diff origin/dev...HEAD shows 364 additions and 12 deletions, and the deletions are exactly the old inline metrics call and the three direct future.complete(...) calls. Nothing from #12454 or #12420 is touched. No newer dev commit touches TaskExecutionService.java, so the 17-commit gap does not change this file.
The normal path reaches the change: every task group whose completionLatch reaches 0 in TaskGroupExecutionTracker.taskDone goes through completeAfterFinalMetrics (TaskExecutionService.java:1739, :1745, :1750) for FINISHED, CANCELED and FAILED; the interrupted worker is the cancel path that motivates the fix.
Status of my previous items on this head:
- Previous Issue 1 (fallback shared a single-thread scheduler with the periodic un-timed report): fixed.
finalMetricsFallbackExecutorService(:268, built at:318) is a separate daemonScheduledThreadPoolExecutor, shut down inshutdown()(:411). - Previous Issue 2 (fallback never cancelled): fixed on the normal path,
fallbackFuture.cancel(false)in the report'sfinally(:1802) withsetRemoveOnCancelPolicy(true). One remaining gap is the new Issue 2 below. - Previous Issue 4 (style): fixed. Pool creation is in private static factories called from the constructor (
:384-385), the constant moved to the top of the class (:160), and@VisibleForTestingis used (:1042). - Previous Issue 3 (no test for the fallback): NOT addressed, see Issue 1 below.
- Spotless:
Run / Code styleis green on this head.
Key findings:
- The ordering
finishExecution -> report -> terminal stateis unchanged; only the executing thread changes. The report and thesubmitfailure path both still complete the terminal future, andCompletableFuture.completeis idempotent, so a fallback firing and thefinallyracing is harmless. - FAILED keeps its throwable (
new TaskExecutionState(location, FAILED, ex)), and the code after the branches (cancelAllTask()whenex != null && !isCancel) is unchanged and still runs on the worker. - The only behavioral nuance versus the old code is that for a
BlockingWorkerthe last task'sclose()may now overlap with the report. The periodic scheduler already calls the same method concurrently with running tasks, so I consider this safe.
Runtime path (head):
worker thread (maybe interrupted) -> TaskGroupExecutionTracker.taskDone [:1731]
-> completionLatch == 0 -> finishExecution(location)
-> completeAfterFinalMetrics(location, state, ex) [:1771]
-> finalMetricsFallbackExecutorService.schedule(future.complete(terminal), 15 s) [:1788]
-> finalMetricsExecutorService.submit( [:1793]
updateMetricsContextInImap() // invoke.get(), no timeout [:1066]
; finally { future.complete(terminal); fallbackFuture.cancel(false) })
-> submit/schedule throws -> log WARN + future.complete(terminal) [:1807-1814]
-> resultFuture.whenCompleteAsync(...) in deployLocalTask [:741]
cancel path: cancelTaskGroup -> cancelAllTask -> task.cancel() + blockingFutures.cancel(true)
(cannot reach the pool thread any more; the 15 s fallback is the escape hatch)
1.2 Compatibility Impact
Fully compatible. No config option, default, protocol, serialization, checkpoint/savepoint or state change; ReportMetricsOperation is untouched; updateMetricsContextInImap() only goes from private to package-private. No entry is needed in incompatible-changes.md.
1.3 Performance / Side-Effect Analysis
- CPU/memory: one short-lived daemon thread per concurrently finishing task group, plus one fallback task (holding the terminal state) that is now removed as soon as the report finishes. Negligible in the normal case.
- The cached pool is unbounded, but bounded in practice by the number of concurrently finishing task groups; a thread stays pinned only while the un-timed RPC blocks, which is the already-unhealthy-master case.
- Networking: still one
ReportMetricsOperationper terminal task group. - Residual risk (best-effort, documented in the Javadoc): if the fallback fires first, the late report can reach the master after the terminal state. Metrics are advisory, so I consider this acceptable.
- Resource release: all new threads are daemon with a fixed context classloader;
shutdown()stops accepting new work and the delayed fallback uses a daemon thread, so no JVM-exit hang.
1.4 Error Handling and Logging
The submit-failure path is now WARN with an action-oriented message and keeps the stack trace, which is right for the shutdown race. The report failure is still logged at SEVERE with the throwable.
Issue 1: No test proves the 15 s fallback fires (carryover from my last two reviews; your latest summary does not mention it)
- Location:
TaskExecutionServiceTest.java:713-960(testFinalMetrics*);TaskExecutionService.java:160,:1788-1793 - Problem description: all four final-metrics tests release the blocked report themselves (
releaseMetrics.countDown()), so deleting theschedule(...)call, or pointing it at the wrong future, leaves every test green.FINAL_METRICS_FALLBACK_TIMEOUT_MSis now astatic finalconstant, so a test cannot shorten it and would have to wait 15 s. - Potential risk: the headline guarantee of this revision (bounded terminal completion when the master is slow) is unguarded; this is exactly the behavior the previous round was about.
- Best improvement: make the timeout a package-private instance field or constructor parameter (default 15 000 ms), then add one test where the mocked
updateMetricsContextInImap()blocks until the end of the test and the terminal future must complete within the shortened timeout (for example 200 ms, asserted withawait().atMost(...)), plus an assertion that theisCancelvariant resolves to CANCELED. Release the blocked report infinallyas the other tests do. - Severity: Medium
- Raised by another reviewer: No
Issue 2: Fallback task is not cancelled when submit or schedule fails
- Location:
TaskExecutionService.java:1788-1814 - Problem description:
fallbackFutureis declared inside thetry. Ifsubmit(...)throws (for exampleRejectedExecutionExceptionduring shutdown), thecatchcompletes the future directly but the already scheduled fallback is left in the queue for 15 s, holding the terminal state and the failure throwable.testFinalMetricsExecutorRejectionStillCompletesTerminalState(:890) exercises this path but does not check it. - Potential risk: low, 15 s of retention of one small object on an already-shutting-down node; no functional impact because
completeis idempotent. - Best improvement: declare
ScheduledFuture<?> fallbackFuture = null;before thetryand cancel it in thecatchwhen non-null. - Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
New fields, factories and completeAfterFinalMetrics carry Javadoc that explains the why (interrupt isolation, separate scheduler, idempotent completion). Naming and structure match the surrounding class; Spotless is green.
2.2 Test Coverage and Test Stability
Four tests cover: report off the interrupted worker with two concurrent task groups (:713), CANCELED ordering driven through the real cancellation future (:794), FAILED preserved when the report throws (:862), and executor rejection still completing the future (:890). Each fails if the corresponding finally / catch or the off-worker submission is removed. Stability rating: Stable. The new tests use latches and await().atMost(...), use fresh FLAKE_ID_GENERATOR ids, spy the service instead of replacing the shared one, and contain no Thread.sleep, fixed ports or shared static state (the Thread.sleep calls in this file belong to pre-existing tests). The one coverage gap is Issue 1.
CI on this head (details in section 5): Code style and unit-test on JDK 17 Linux and both Windows jobs are green, and TaskExecutionServiceTest ran 24 tests with 0 failures on the JDK 11 Linux job.
2.3 Documentation Updates
No user-facing docs needed (internal engine behavior; docs/en and docs/zh unaffected).
3. Architectural Soundness
3.1 Elegance
Precise fix. Isolating blocking IO from interruptible workers is the right direction, and a separate scheduler for the bound keeps the design small.
3.2 Maintainability
Good. Factories in the constructor and a single completeAfterFinalMetrics entry point make the behavior easy to find; making the timeout injectable (Issue 1) will also help future tuning.
3.3 Extensibility
Fine. Bounding the report itself (invoke.get(timeout)) could replace the fallback later without touching callers.
3.4 Historical-Version Compatibility
No impact on checkpoint/savepoint, job configs, RPC payloads or cluster rolling behavior.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | No test proves the 15 s fallback fires (timeout not injectable) | TaskExecutionServiceTest.java:713-960, TaskExecutionService.java:160, :1788 |
Medium |
| 2 | Fallback not cancelled when submit/schedule fails |
TaskExecutionService.java:1788-1814 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
Blockers - must be fixed
- Issue 1: add the fallback test (and make the timeout injectable so the test is fast). It was a blocker in my previous rounds and the production side is now otherwise correct.
- CI: the fork
Buildrun for this head (https://github.com/Asthenia0412/seatunnel/actions/runs/39002940214, apache-side check https://github.com/apache/seatunnel/runs/117309506543) is red. What I verified:unit-test (11, ubuntu-latest)fails inSavePointBusySourceTest.testSavepointFailureStopsWholeMultiPipelineJob(SavePointBusySourceTest.java:376, "expected the successful pipeline checkpoint coordinator to reach SUSPEND"). The same head passesunit-teston JDK 17 Linux and on both Windows jobs, andTaskExecutionServiceTestpasses on this JDK 11 job. This is my inference that it is a timing flake unrelated to the diff, but that test exercises pipeline termination timing, so I cannot rule out an interaction until it is rerun green.engine-v2-it (11)and(17)were cancelled at the job time limit (about 150 minutes) while still making progress through the IT list; I do not see a hang in the tail of the log, so I read this as runner slowness, again an inference.- Dozens of connector IT jobs fail (for example
hbase-connector-it,kafka-connector-it,connector-redis-it,jdbc-connectors-it-part-*,transform-v2-it-part-*); this PR touches no connector or transform module, so they look unrelated, though I did not diagnose each job. - Because CI is failing for apparently unrelated reasons and the branch is 17 commits behind
dev(4 ahead, statusdiverged, no conflicts), please sync with the latestdevand rerun only the failed jobs. The apache-sideBuildcheck will follow the fork run.
Recommended fixes - non-blocking
- Issue 2 is a two-line change and fits naturally with Issue 1.
Overall assessment: the interrupt isolation, the terminal-state ordering, the dedicated fallback scheduler and the cleanup are all correct, and the earlier engine regressions stay fixed. What is left is a test that proves the new timeout works and a green CI. I see no other source-level blocker, and no other reviewer has commented, so there is nothing to reconcile. A different design is not needed. Thank you for the persistence on this one, I am happy to re-review as soon as the next head is up!
Fixes the blockers and recommended follow-ups from @DanielLeens' latest review of apache#12795: 1. Spotless check (CI blocker) — collapsed the three multi-line completeAfterFinalMetrics(...) call sites onto single lines so google-java-format is satisfied. 2. Timeout safety net (Issue 2, Medium) — schedule a fallback future.complete(terminalState) on the existing scheduled executor after 15 seconds. future.complete is idempotent, so whichever of the finally block or the fallback fires first wins. 3. CANCELED-path ordering test (Issue 4a, Medium) — added testFinalMetricsPreservesCanceledTerminalState, which drives the CANCELED branch through the same metrics-report-isolated path as the existing FINISHED and FAILED tests. 4. Visibility note (Issue 4b) — added a short comment explaining why updateMetricsContextInImap is package-private. 5. Named / MDC-aware threads (Issue 3, Low) — the final-metrics pool now uses a ThreadFactory with indexed names so each pool thread is distinguishable in thread dumps, and the pool is wrapped with MDCTracer.tracing so the metrics report keeps the job's MDC context. 6. Context classloader isolation (Issue 5, Low) — each pool thread is born with TaskExecutionService.class.getClassLoader() instead of inheriting the submitting task worker's SeaTunnelChildFirstClassLoader, which could already have been recycled or belong to another job by then. All four final-metrics tests pass locally with spotless green. Signed-off-by: Asthenia0412 <asthenia0412@users.noreply.github.com>
a67bab8 to
0696fed
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
Review conclusion
Reviewed commit: 0696fed
High — unbounded hanging metric reports can exhaust worker resources (blocking)
TaskExecutionService.java:250-270 creates a cached executor with Integer.MAX_VALUE workers, and TaskExecutionService.java:1802-1823 submits one final report for every terminal task group. The new 15-second fallback only completes the task future; it does not cancel the submitted updateMetricsContextInImap() call. That call performs an un-timed Hazelcast invocation (TaskExecutionService.java:1062-1074). During a master outage, a burst of completing/cancelled task groups can therefore retain an unbounded number of daemon threads and RPCs, precisely while the cluster is degraded.
The root cause is treating the terminal-state timeout as if it bounded the report work. The current change is at the correct lifecycle boundary, but the executor policy is not safe there. The smallest safe fix is a bounded executor/queue with a documented rejection policy that completes the terminal future without reporting. The stronger fix is to make the reporting invocation itself time-bounded and coalesce per-node final-metrics flushes, so one failed master cannot create one retained operation per task group. Add a regression test that blocks the invocation, completes more terminal groups than the configured capacity, and proves bounded threads/queue plus terminal completion.
Compatibility: no wire/configuration change, but this is a production resource-exhaustion regression.
Validation performed: fetched the current PR ref; reviewed the full two-file diff; traced terminal completion to the executor, fallback, and Hazelcast invocation; inspected all added tests. No local build/test was run because static inspection establishes the unbounded execution path.
CI gate: Build is currently failing.
Conclusion
Do not merge until the bounded-reporting fix and a green Build are provided.
2fe0cde to
a257a6f
Compare
Fixes the blockers and recommended follow-ups from @DanielLeens' latest review of apache#12795: 1. Spotless check (CI blocker) — collapsed the three multi-line completeAfterFinalMetrics(...) call sites onto single lines so google-java-format is satisfied. 2. Timeout safety net (Issue 2, Medium) — schedule a fallback future.complete(terminalState) on the existing scheduled executor after 15 seconds. future.complete is idempotent, so whichever of the finally block or the fallback fires first wins. 3. CANCELED-path ordering test (Issue 4a, Medium) — added testFinalMetricsPreservesCanceledTerminalState, which drives the CANCELED branch through the same metrics-report-isolated path as the existing FINISHED and FAILED tests. 4. Visibility note (Issue 4b) — added a short comment explaining why updateMetricsContextInImap is package-private. 5. Named / MDC-aware threads (Issue 3, Low) — the final-metrics pool now uses a ThreadFactory with indexed names so each pool thread is distinguishable in thread dumps, and the pool is wrapped with MDCTracer.tracing so the metrics report keeps the job's MDC context. 6. Context classloader isolation (Issue 5, Low) — each pool thread is born with TaskExecutionService.class.getClassLoader() instead of inheriting the submitting task worker's SeaTunnelChildFirstClassLoader, which could already have been recycled or belong to another job by then. All four final-metrics tests pass locally with spotless green. Signed-off-by: Asthenia0412 <Asthenia0412@users.noreply.github.com>
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the update, @Asthenia0412, and for taking the bounded-reporting feedback seriously. I re-reviewed the latest head (a257a6fb) against my last review (0696fed0). The resource-exhaustion finding is addressed in the code. One new problem appeared in the branch history (Issue 1), and CI has not finished yet.
What Problem Does This PR Solve?
When a task group is canceled, its last task calls updateMetricsContextInImap() from an interrupted task worker thread. The synchronous Hazelcast write can then close the worker's shared connection to the master and delay terminal completion (#12413). The PR runs the final report on a dedicated daemon pool and publishes the terminal state afterwards, for FINISHED, CANCELED and FAILED alike.
1. Code Change Review
1.1 Core logic
Real diff against dev (two files, git diff origin/dev HEAD): TaskExecutionService.java and TaskExecutionServiceTest.java.
Before (TaskGroupExecutionTracker.taskDone): finishExecution -> updateMetricsContextInImap() inline on the (possibly interrupted) worker -> future.complete(state).
After:
finishExecution(taskGroupLocation);
completeAfterFinalMetrics(taskGroupLocation, FINISHED | CANCELED | FAILED, ex);
// inside: schedule 15s fallback -> finalMetricsExecutorService.submit(report; finally complete + cancel fallback)
// on submit failure: cancel fallback, complete terminal state directlyRuntime path:
task worker (interrupt flag maybe set) -> TaskGroupExecutionTracker.taskDone
-> completionLatch == 0 -> finishExecution (context moved to finishedExecutionContexts)
-> completeAfterFinalMetrics
-> finalMetricsFallbackExecutorService.schedule(complete terminal, 15s)
-> finalMetricsExecutorService (4 threads, queue 128, AbortPolicy).submit(updateMetricsContextInImap)
-> ReportMetricsOperation to master (un-timed invoke.get())
-> finally: future.complete(terminalState); cancel fallback
-> deployLocalTask resultFuture.whenCompleteAsync -> report TaskExecutionState to master
Previous High finding (unbounded cached pool): FIXED. The pool is now FINAL_METRICS_MAX_CONCURRENT_REPORTS = 4 workers with an ArrayBlockingQueue(128) and AbortPolicy (TaskExecutionService.java createFinalMetricsExecutor), and rejection falls into the catch that cancels the fallback and completes the terminal state directly. testFinalMetricsReportsRemainBoundedWhenInvocationHangs blocks the invocation, submits 4 + 128 + 1 groups and asserts exactly one immediate completion and at most 4 concurrent reports, which is the regression test I asked for. I also checked that dropping or delaying a report is benign: finishExecution keeps the context in finishedExecutionContexts, and collectLocalMetricsMap (also used by the periodic backup) includes it, so a later report or the periodic run carries the same final counters.
1.2 Compatibility
Fully compatible. No wire, configuration, serialization or checkpoint change. Terminal-state ordering (metrics first, then state) is preserved in the normal case; only in a degraded-master case does the 15 s fallback or a rejection publish the state first.
1.3 Performance / side effects
Bounded now: at most 4 report threads, 128 queued reports and one fallback thread per node. Normal completions cancel the fallback (setRemoveOnCancelPolicy(true)), so no timer queue growth. shutdownNow() on both executors avoids a hang on server shutdown.
1.4 Error handling / logging and issues
Issue 1: Branch history is polluted; the PR shows 584 changed files and 45 commits
- Location: PR history (
8fb6c51c,71a2df84, and other re-createddevcommits such as[Docs][Transform-V2] Improve Filter transform documentation (#12816)); GitHub reportschangedFiles = 584,ahead 45 / behind 36against currentdev(merge basecce8e199) - Problem description: The latest merge of
upstream/devre-created manydevcommits with different SHAs, so GitHub's three-dot diff contains hundreds of unrelated files (workflows, docs, connectors, Kubernetes template, and so on). The tree itself is fine:git diff origin/dev HEADis only the two engine-server files. - Potential risk: The change cannot be reviewed from the "Files changed" tab, the path-based CI selection runs a far larger matrix than this two-file change needs, and a future merge or squash could carry unrelated content.
- Best improvement: Rebase the six PR commits onto the current
devtip (or recreate the branch fromdevand cherry-pickbb4a00e9,6cd590e9,a257a6fband the earlier fix commits) so the PR lists only the two intended files. A squash of your own commits is fine as well. - Severity: High
- Raised by another reviewer: No
Issue 2: Un-timed report keeps a pool thread pinned during a master outage
- Location:
TaskExecutionService.javaupdateMetricsContextInImap(invoke.get()without timeout) andcompleteAfterFinalMetrics - Problem description: The fallback completes the terminal future after 15 s, but the report itself is not cancelled. Four hung RPCs keep all four workers busy and later reports sit in the queue until the master answers. This is now bounded, so it no longer exhausts resources, but those queued reports are redundant (each report is a full node snapshot).
- Potential risk: Only wasted queue slots and delayed final counters during an outage; no data loss because the periodic backup re-sends the same contexts.
- Best improvement: Optional: use
invoke.get(timeout)for the final report, or skip a queued report when a newer one already ran. Not blocking. - Severity: Low
- Raised by another reviewer: Yes, follow-up of my previous review (the unbounded part is fixed)
Issue 3: Stale comments and PR description
- Location:
TaskExecutionService.javafield Javadoc offinalMetricsFallbackTimeoutMs("set in the constructor" - no constructor sets it) and the comment abovefinalMetricsExecutorService.shutdownNow()("keep the cached pool alive"; the pool is bounded now); PR description ("orderly executor shutdown drains reports already accepted" while the code usesshutdownNow) - Problem description: Comments describe the earlier cached-pool design.
- Potential risk: Misleads later readers about the shutdown and timeout semantics.
- Best improvement: Update the comments and the PR description to say reports are best-effort, bounded, and dropped on shutdown.
- Severity: Low
- Raised by another reviewer: No
Issue 4: One WARN with stack trace per rejected report
- Location:
completeAfterFinalMetrics,catch (Throwable t)block - Problem description: During a prolonged outage with a full queue, every terminal task group logs a WARN with a full
RejectedExecutionExceptionstack. - Potential risk: Log noise exactly when the cluster is degraded.
- Best improvement: Log the stack once or log only the message at WARN with the queue size.
- Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding standards
New constants and helpers have Javadoc, @VisibleForTesting is used for the widened method, daemon threads are named, MDC is propagated via MDCTracer, and the context class loader is pinned. Comment completeness is good (see Issue 3 for stale parts).
2.2 Test coverage and stability
Strong: interrupted-worker isolation, CANCELED ordering, FAILED preservation, executor rejection, fallback on FINISHED and CANCELED, and the bounded-capacity test. No existing test lines were removed or weakened (the test diff has additions only). Stability rating: Stable - the tests use latches and await().atMost(...) rather than sleeps; the one risk is the shared server TaskExecutionService pool used by the bounded test, which is released in finally.
2.3 Docs
No user-facing documentation is needed (internal engine behavior).
3. Architectural Soundness
The change sits at the right lifecycle boundary (the tracker's terminal step), applies one ordering to all terminal states, and now has a bounded resource policy. Coalescing node-wide snapshots would be a further simplification but is not required.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Polluted history: 584 files / 45 commits in the PR | branch history | High |
| 2 | Un-timed report pins a pool thread during outage | updateMetricsContextInImap |
Low |
| 3 | Stale comments and PR description | TaskExecutionService.java, PR body |
Low |
| 4 | WARN with stack per rejected report | completeAfterFinalMetrics |
Low |
5. Merge Recommendation
CI state of head a257a6fb: the Build check is still in progress on the Apache side and the fork run is queued, so CI is pending (not failed). Given the 584-file diff, the matrix will also be larger than necessary.
Conclusion: Ready to merge after fixes
-
Blockers
- Issue 1: clean the branch so the PR contains only the two intended files.
- A green
Buildon the cleaned head.
-
Non-blocking
- Issues 2, 3 and 4.
The engine change itself looks good to me now. I did not run the code; this review is based on the full two-file diff, the call chain and the CI state. Thank you for the persistence!
a257a6f to
c065df7
Compare
Backport / clean rebase of PR apache#12795 fix onto current upstream/dev. - Use bounded 4-worker + 128-queue final-metrics executor (no more cached-thread pool exhaustion during master outages) - Add 15s fallback that publishes state before the fallback reports finish; the reports themselves are unbounded but queued - TaskExecutionServiceTest: interrupt isolation, CANCELED ordering, FAILED preservation, executor rejection, bounded-capacity coverage Refs: apache#12413, apache#12795 Signed-off-by: PR Maintainer <pr-maintainer@vllm.org>
|
@DanielLeens Clean rebuild onto upstream/dev tip — now confirms 2 changed files (down from the 584-file polluted history) and 1 single squashed commit. shows exactly TaskExecutionService.java + TaskExecutionServiceTest.java with the approved fix logic untouched. PTAL on the clean head; CI should now run the focused matrix. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the follow-up work on this. I re-read the full diff of the current head against the latest dev (not just the newest commit) and traced the new terminal-metrics path end to end. The core move — taking the final metrics report off the task worker, which can be interrupted — is the right fix for the problem you describe.
What Problem Does This PR Solve?
-
User pain point: when a task group ends as
CANCELEDorFAILED, the worker thread reporting that terminal state often has its interrupt flag set (cancel path, failover,shutdownNow). The old code calledupdateMetricsContextInImap()inline on that thread, and the first thing that method does is an un-timedinvoke.get()on a Hazelcast invocation. On an interrupted thread that either blows up immediately or, worse, leaves the terminalfuturewaiting on a master that may itself be failing over. Result: canceled/failed task groups can hang, and their metrics never land. -
Fix approach: move the report onto a dedicated bounded pool (
seatunnel.final-metrics-N) that never inherits a worker interrupt, guard the terminalfuture.completewith a 15 s fallback on a separate single-thread scheduler, and pin the context classloader so a recycled pool thread can't inherit a stale job classloader. -
In one sentence: terminal metrics are now reported from a clean thread with a hard time bound, so an interrupted or failing worker can no longer stall the job's terminal state.
-
Simple example: master failover cancels 200 task groups. Before: up to 200 workers each block on an un-timed metrics RPC while already interrupted, and their terminal futures may never resolve. After: at most 4 reports run at a time, the rest queue or are rejected, and every terminal future resolves within 15 s regardless.
1. Code Change Review
1.1 Core logic analysis
Changed files: TaskExecutionService.java (+204/-12) and TaskExecutionServiceTest.java (+367).
Key methods: TaskGroupContext.complete (the completionLatch.decrementAndGet() == 0 branch), the new private completeAfterFinalMetrics(...), updateMetricsContextInImap() (visibility widened to package-private + @VisibleForTesting), plus two new factories createFinalMetricsExecutor() / createFinalMetricsFallbackExecutor() and the shutdown path.
Before / after:
// before: report then complete, both on the (possibly interrupted) worker thread
finishExecution(taskGroupLocation);
try {
updateMetricsContextInImap();
} catch (Throwable t) {
logger.severe("update metrics context in imap failed", t);
}
if (ex == null) {
future.complete(new TaskExecutionState(taskGroupLocation, ExecutionState.FINISHED));
}// after: schedule off-thread, with a bounded fallback
finishExecution(taskGroupLocation);
if (ex == null) {
completeAfterFinalMetrics(taskGroupLocation, ExecutionState.FINISHED, null);
}
...
fallbackFutureRef.set(finalMetricsFallbackExecutorService.schedule(
() -> future.complete(terminalState), finalMetricsFallbackTimeoutMs, MILLISECONDS));
finalMetricsExecutorService.submit(() -> {
try { updateMetricsContextInImap(); }
catch (Throwable t) { logger.severe("update metrics context in imap failed", t); }
finally { future.complete(terminalState); /* cancel fallback */ }
});Full runtime chain on the new path:
TaskGroupContext.complete(...) (worker thread, may be interrupted)
-> finishExecution(taskGroupLocation) // unchanged, still first
-> completeAfterFinalMetrics(location, FINISHED|CANCELED|FAILED, ex) [TaskExecutionService.java:1785+]
-> new TaskExecutionState(...) // terminal payload built up front
-> finalMetricsFallbackExecutorService.schedule(future.complete(terminalState), 15s)
-> finalMetricsExecutorService.submit(lambda) // MDCTracer-wrapped, AbortPolicy
-> updateMetricsContextInImap() [TaskExecutionService.java:1065]
-> if node state != ACTIVE -> WARN + return (no invocation, report is a no-op)
-> collectLocalMetricsMap() // reads executionContexts + finishedExecutionContexts
-> ReportMetricsOperation invoke() (UN-TIMED) -> invoke.get()
-> success / interruption / failure counters
-> finally: future.complete(terminalState); cancel fallback
-> catch (Throwable): cancel fallback; future.complete(terminalState) directly
What I verified:
- Normal path is hit: every terminal task group now goes through
completeAfterFinalMetrics—FINISHED,CANCELEDandFAILEDare all routed there, so the ordering "metrics reported, then terminal state published" is preserved in the happy path exactly as before. - The
NodeState != ACTIVEearly return inupdateMetricsContextInImapstill applies, so the fallback isn't the only thing standing between a not-ready node and a stall — but it is now the only thing, and that's the improvement. collectLocalMetricsMap()readsexecutionContexts/finishedExecutionContexts, bothConcurrentMap(TaskExecutionService.java:221,:228), and theputAllinto a fresh localHashMapis safe. Running up to 4 of these concurrently introduces no new class of hazard over the pre-existing periodic backup.- The context-classloader fix is a genuine catch. A pooled thread that inherited a recycled
SeaTunnelChildFirstClassLoaderwould be a real leak/cross-job-contamination bug; pinning it toTaskExecutionService.class.getClassLoader()removes that. MDCTracer.tracing(pool)preserves the submitting worker's MDC, which is what theSEVEREmessages inupdateMetricsContextInImaprely on to stay attributable.
Key findings:
- The main path is correct and the interrupt hazard is genuinely removed.
- The new bounded pool introduces a silent metrics-loss path under exactly the conditions this PR targets (mass cancellation), and it is only visible as a
WARN. - The fallback can publish the terminal state before the metrics land, which inverts the pre-existing ordering guarantee.
- Concurrency-safety of the new pool is fine; the doc/code mismatch on
finalMetricsFallbackTimeoutMsis cosmetic.
1.2 Compatibility impact
Fully compatible for users and for the wire/config surface. No option, default, protocol or serialized format changes. The observable difference is internal: metrics for a terminal task group may now be reported from a different thread and, in saturation, not at all. Since this method was already best-effort (catch (Throwable) + SEVERE on dev), no user contract is broken — but see Problem 1, because "best-effort" got cheaper.
1.3 Performance / side effects
- CPU/memory: negligible. Two small pools (4 + 1 threads), created once per node.
- GC: no meaningful change; the pools are long-lived and the queue is bounded at 128.
- Network: up to 4 concurrent
ReportMetricsOperationinvocations instead of at most 1 per worker, each carrying a full metrics snapshot. In a mass-cancellation event that is a burst of overlapping full-state reports to the master, on top of the periodic backup. See Problem 2. - Locking: no new locks on the shared path.
executionContextsremains aConcurrentMap. - Concurrency:
future.completeis idempotent, so the fallback/report race is safe. Confirmed. - Idempotency / retry: unchanged — there is no retry, before or after.
- Resource release:
finalMetricsExecutorService.shutdownNow()+finalMetricsFallbackExecutorService.shutdownNow()in the service shutdown path, withsetRemoveOnCancelPolicy(true)on the fallback scheduler so cancelled fallbacks don't linger. Threads are daemon. This is correct and is a genuine improvement over an inline report that could hold shutdown. - Interrupt flag:
updateMetricsContextInImapre-sets the interrupt flag onInterruptedException(:1093). On a pooled threadThreadPoolExecutorclears interrupts between tasks, so this doesn't poison the next report — worth knowing, not worth changing.
1.4 Error handling and logging
Exception handling is thorough: report failures are logged at SEVERE with payloadTaskCount and invocationLatencyMs, never swallowed silently upward, and the terminal state always completes. Log levels are appropriate. No credentials or sensitive payloads are logged.
The gap is observability of dropped reports, which is Problem 1.
Problems
Problem 1 — Saturation silently drops final metrics with only a WARN
- Location:
TaskExecutionService.javacreateFinalMetricsExecutor()(FINAL_METRICS_MAX_CONCURRENT_REPORTS = 4,FINAL_METRICS_QUEUE_CAPACITY = 128,AbortPolicy) and thecatch (Throwable t)incompleteAfterFinalMetrics. - Description: the pool is bounded and uses
AbortPolicy, so once 4 reports are in flight and 128 are queued,submitthrows and the report is abandoned. That is a deliberate, tested design (testFinalMetricsExecutorRejectionStillCompletesTerminalState) and reasonable for a best-effort path — but the trigger condition is exactly the scenario this PR exists for. During master failover every task group cancels at once; if the master is the reason they're cancelling, each of those 4 in-flightinvoke.get()calls is un-timed and can sit for a long time. The 128-slot queue then drains into rejection, and metrics for the rest of the wave are lost with a singlelogger.warningline and no counter. - Risk: metrics loss precisely during the incident you most want metrics for. Not a correctness/data-loss issue — the terminal state is always published correctly — but it degrades observability exactly when it matters, and there is currently no way to tell "we dropped reports" from "reports succeeded" after the fact.
- Suggestion: add a counter in the same style as the existing
reportMetricsOperationSuccessCount/...Failure/...Interruptioncounters (areportMetricsOperationRejectedCount), and log it atWARNwith the saturation numbers. If you want to reduce the drop rate rather than just observe it, two options: (A) raise the queue and keepAbortPolicy; (B) coalesce instead of queueing — anAtomicBoolean"report in progress" so that a burst of terminal completions results in one in-flight report plus one pending re-run. Option B also fixes Problem 2 and is what I'd lean toward, since consecutive terminal completions reporting near-identical snapshots is wasted master-side work anyway. - Severity: Medium (has a workaround and does not affect correctness, but should not ship unobserved).
- Already raised by others: no.
Problem 2 — Up to 4 concurrent full-state metric reports, with no coalescing
- Location:
createFinalMetricsExecutor()(FINAL_METRICS_MAX_CONCURRENT_REPORTS = 4) combined withcollectLocalMetricsMap()→ReportMetricsOperation. - Description: each report snapshots all local task metrics and ships it to the master. Previously these ran one-per-worker on the thread that had just finished, in practice roughly serialized by the latch. Now four can be in flight simultaneously, plus the periodic
scheduledExecutorServicebackup. For a node with many task groups this is N concurrent full-state payloads for what is usually a near-identical snapshot. - Risk: extra load on the master during exactly the failover window where the master is already the bottleneck. Not incorrect — the master merges — but it's avoidable work at the worst possible time.
- Suggestion: the
AtomicBooleancoalescing in Problem 1's Option B solves this too: "if a report is already running, remember that another is needed and re-run once when the current one finishes" caps this at one in-flight report plus at most one queued re-run, regardless of how many task groups terminate at once. - Severity: Low.
- Already raised by others: no.
Problem 3 — The 15 s fallback can publish the terminal state before metrics land
- Location:
completeAfterFinalMetrics— the fallback() -> future.complete(terminalState)versus the report'sfinally { future.complete(terminalState); }. - Description: on the normal path the ordering is unchanged (report, then publish). But when the report hangs, the fallback publishes the terminal state at 15 s while
updateMetricsContextInImap()is still blocked ininvoke.get()and may yet succeed. So a consumer of the terminal state can observeFINISHEDbefore the final metrics are visible, which is the inverse of the pre-existing guarantee. - Risk: a dashboard or an automated decision reading "job finished" and then querying metrics can see a stale or empty final snapshot for up to the duration of the stuck invocation. Bounded and self-healing, and arguably the right trade (a stuck terminal future is worse), but it is a real behaviour change and currently undocumented.
- Suggestion: a Javadoc sentence on
DEFAULT_FINAL_METRICS_FALLBACK_TIMEOUT_MSnoting that on timeout the terminal state is published and the report may still complete afterwards would make the trade explicit. I would not block on changing the behaviour itself. - Severity: Low.
- Already raised by others: no.
Problem 4 — finalMetricsFallbackTimeoutMs Javadoc claims a constructor assignment that does not exist
- Location:
TaskExecutionService.java, the field Javadoc ("Defaults toDEFAULT_FINAL_METRICS_FALLBACK_TIMEOUT_MS; set in the constructor or directly in tests") versus the constructor, which only creates the two executors. - Description: small, but the next reader will look for constructor wiring that isn't there. It's also a mutable non-
finalfield read from a scheduler lambda; in practice it's only ever written by tests via reflection before use, so there's no real visibility hazard, butfinal(with the test override done by constructing with an explicit value, or by a protected factory) would be cleaner and self-documenting. - Severity: Low.
- Already raised by others: no.
2. Code Quality Assessment
2.1 Standards — Google Java Format / AOSP is satisfied, imports are explicit, no wildcard imports, and the Javadoc density here is well above the project norm (the two factory methods and the new field each explain why, which is exactly what the project asks for). One deliberate encapsulation trade-off: updateMetricsContextInImap goes from private to package-private @VisibleForTesting. Acceptable and conventional, but worth a conscious note since it's a production method opened up for tests rather than a package-private seam introduced for the purpose.
2.2 Test coverage and stability — seven new tests covering: report runs off the interrupted worker (testFinalMetricsRunOutsideInterruptedTaskWorker), canceled state preserved, failed state preserved, rejection path, fallback firing for both FINISHED and CANCELED, bounded concurrency (testFinalMetricsReportsRemainBoundedWhenInvocationHangs asserts the observed max concurrent reports equals the configured bound), and stale-generation cleanup.
Stability verdict: Stable. The new tests use CountDownLatch handshakes (releaseMetrics.await(), metricsStarted.await(5, SECONDS)) and Awaitility (await().atMost(...)) rather than fixed sleeps, so they don't depend on machine speed; the fallback tests shrink finalMetricsFallbackTimeoutMs to 200 ms via reflection instead of waiting out the production 15 s; the bounded-concurrency test asserts on a latched maximum rather than sampling timing. Nothing here is order-dependent or environment-sensitive. (The pre-existing Thread.sleep(5000) calls in older tests in this file are not from this PR.)
2.3 Documentation — no user-visible configuration or behavior change, so no docs/en / docs/zh update is required, and none is missing.
3. Architectural Soundness
3.1 Elegance — a targeted fix for a real defect, with the right instinct on the two things that usually go wrong here: a dedicated fallback scheduler (rather than reusing scheduledExecutorService, which can itself be blocked in an un-timed invoke — a genuinely sharp observation) and the context-classloader pin.
3.2 Maintainability — clear boundaries. The one thing I'd push on is the coupling between "don't stall the terminal future" and "how many metrics reports do we allow", which are currently expressed as one pool configuration with no coalescing; splitting those concerns (Problem 1/2) would make future tuning obvious.
3.3 Extensibility — the pattern (never inherit an interrupt for a terminal side-effect; bound it; always publish the state) generalizes to other terminal side-effects on the worker. If that comes up again, extracting a small runOffWorkerThread(...) helper would be worth it; for one call site today, keeping it inline is fine.
3.4 Historical compatibility — fully compatible, as covered in 1.2.
4. Summary
| # | Problem | Location | Severity |
|---|---|---|---|
| 1 | Saturation silently drops final metrics, only a WARN, under exactly the mass-cancellation conditions this PR targets | TaskExecutionService.java createFinalMetricsExecutor() / completeAfterFinalMetrics |
Medium |
| 2 | Up to 4 concurrent full-state metric reports with no coalescing | TaskExecutionService.java createFinalMetricsExecutor() |
Low |
| 3 | 15 s fallback can publish terminal state before metrics land | TaskExecutionService.java completeAfterFinalMetrics |
Low |
| 4 | Javadoc claims a constructor assignment of finalMetricsFallbackTimeoutMs that doesn't exist |
TaskExecutionService.java field Javadoc |
Low |
5. Merge Conclusion
Conclusion: merge after addressing Problem 1
Blocking:
- Problem 1 — not because the drop behaviour is wrong (best-effort was already the contract), but because it is currently invisible. Please add the rejection counter alongside the existing
reportMetricsOperation*counters so a drop is distinguishable from a success after the fact. If you also take the coalescing idea, Problem 2 closes at the same time.
Non-blocking (please consider, not required):
- Problem 2 (coalescing) — strongly recommended, cheap, and it reduces master load during failover.
- Problem 3 (document the fallback ordering) — one Javadoc sentence.
- Problem 4 (fix the field Javadoc / consider
final).
CI: Build is currently failing on this head and mergeStateStatus is BLOCKED pending review. I haven't attributed the failure to this change — please include the failing job link with your next push so we can tell whether it's this PR or upstream drift. If it's the new tests, the bounded-concurrency test in particular is the one I'd expect to be sensitive.
Overall: this is a good fix for a real production-shaped problem, the interrupt-classloader detail shows you've thought past the first-order bug, and the tests are unusually well-built — latch-based rather than sleep-based, with the timeout shrunk instead of waited out. My remaining items are observability and a small amount of duplicated master work, not correctness.
I don't have write-level review controls on this repository, so a maintainer with write access will need to take the final approval step. Happy to re-review as soon as there's a push.
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you for the new push (0fa72b98) and for adding the rejection counter, @Asthenia0412. I re-reviewed the whole diff against the current dev (two production files plus the telemetry classes, and the tests), not only the delta from my previous round. The counter closes my earlier "invisible drop" item, the field Javadoc now matches the code, and the fallback ordering is documented on completeAfterFinalMetrics. Now that the fork's Build has actually run on this head, it shows one problem that I should have caught earlier.
Sorry for missing this in the last review: the E2E harness thread-leak check (Issue 1 below) applies to the pools introduced in earlier heads as well. I looked at the unit-level behavior, and the earlier fork runs stopped at the code-style step before any integration job started, so I did not check SeaTunnelContainer. This is a carryover from my side, not something added in this push.
What Problem Does This PR Solve?
- User pain point: when a task group ends as
CANCELEDorFAILED, its last task callsupdateMetricsContextInImap()on a task worker whose interrupt flag may already be set. The synchronous Hazelcast call can close the worker's shared connection to the master and delay the terminal state (#12413). - Fix approach: run the final metrics report on a dedicated bounded daemon pool, publish the terminal
TaskExecutionStateafter the report finishes (or fails, or is rejected), and guard the terminal future with a 15 s fallback on its own scheduler. - One-sentence summary: report final metrics from a clean thread with a time bound so an interrupted worker cannot stall or break terminal completion.
1. Code Change Review
1.1 Core Logic Analysis
Before (TaskGroupExecutionTracker.taskDone): finishExecution then an inline updateMetricsContextInImap() then future.complete(state), all on the (possibly interrupted) worker.
After (TaskExecutionService.java:1759-1800, completeAfterFinalMetrics at :1797):
finishExecution(taskGroupLocation);
completeAfterFinalMetrics(taskGroupLocation, FINISHED | CANCELED | FAILED, ex);
// inside: schedule the 15 s fallback, then finalMetricsExecutorService.submit(report; finally complete + cancel fallback)
// RejectedExecutionException: count it, then complete the terminal state directlyRuntime path:
task worker (interrupt flag maybe set)
-> TaskGroupExecutionTracker.taskDone -> completionLatch == 0
-> finishExecution (context moves to finishedExecutionContexts)
-> completeAfterFinalMetrics
-> finalMetricsFallbackExecutorService.schedule(complete terminal, 15 s) [single thread]
-> finalMetricsExecutorService.submit(report) [4 threads, queue 128, AbortPolicy]
-> updateMetricsContextInImap (TaskExecutionService.java:1067)
-> collectLocalMetricsMap -> ReportMetricsOperation invoke.get() (line 1090, no explicit timeout)
-> finally: future.complete(terminalState); cancel fallback
-> RejectedExecutionException: reportMetricsOperationRejectedCount++ (line 1843), warn, complete directly
-> resultFuture.whenCompleteAsync(... notifyTaskStatusToMaster ...) on executorService (line ~765, async, so callbacks do not run on the pool or fallback thread)
What I verified on the head:
- Every terminal state goes through the new method, so the ordering "metrics first, terminal state second" is kept on the normal path.
- The terminal future's callbacks are registered with
whenCompleteAsync(..., MDCTracer.tracing(executorService)), so completing the future from the metrics pool or the single fallback thread never runs master notification on those threads. ReportMetricsOperationStatsgets a new field in the middle of an@AllArgsConstructor; the only constructor callers aregetReportMetricsOperationStats()andTelemetryCollectorCoordinatorGuardTest, both updated.- The pool is bounded (4 threads, 128 queue), which fixes the earlier unbounded-thread concern.
1.2 Compatibility Impact
Partially incompatible in observability only: a new result="rejected" label value is added to the existing report_metrics_operation_total counter (ReportMetricsOperationExports.java:~48-58). No configuration, wire or state change. See Issue 2 for the documentation gap.
1.3 Performance / Side-Effect Analysis
The worker no longer blocks on the metrics RPC, which is the intended gain. Under a mass cancellation, at most 4 reports run and 128 wait; later ones are dropped and counted, and their terminal states are published immediately, so the final metrics of those task groups can be stale until the periodic backup. That trade-off is documented and now visible through the counter.
1.4 Error Handling and Logging
Issue 1 (High, blocking; reproduced in CI)
- Location:
TaskExecutionService.java:302-331(createFinalMetricsExecutor),:338-358(createFinalMetricsFallbackExecutor); the check lives inSeaTunnelContainer.java(doExecuteJobthread-leak assertion andisSystemThread). - Problem: after each job the Zeta container E2E harness asserts that no new non-system thread is left in the server JVM, waiting up to 120 s. The core threads of the new pool (
seatunnel.final-metrics-1..4, core size 4, never timing out) and the fallback scheduler thread (seatunnel.final-metrics-fallback-1) are created by the first terminal task group and live forever, and none of these names is inisSystemThread. In the fork run for this head, the failure text isThere are still threads running in the container:followed by exactly these threads, for example inInfluxdbIT.testInfluxdbMultipleWrite(all-connectors-it-2) andTestFilterIT(transform-v2-it-part-1). The same message appears in the large majority of the 64 failing legs I counted in the run (I opened eight of them; seven contain the message). - Potential risk: every container-based IT on Zeta fails, so the change cannot be merged or even meaningfully validated; in production the pools also hold five idle daemon threads per worker for the process lifetime.
- Best improvement: let the threads go away when idle. For the metrics pool call
pool.allowCoreThreadTimeOut(true)with a short keep-alive (for example 30 s) instead of keep-alive0; for the scheduler callscheduler.setKeepAliveTime(30, TimeUnit.SECONDS)andallowCoreThreadTimeOut(true). Idle threads then exit inside the harness's 120 s window and nothing else changes (lazy start already happens on first submit). Whitelisting the two prefixes inSeaTunnelContainer.isSystemThreadis possible but weakens the leak detector, so I would not use it. - Severity: High. Raised by another reviewer: no.
Issue 2 (Medium, non-blocking)
- Location:
docs/en/engines/zeta/telemetry.md:163anddocs/zh/engines/zeta/telemetry.md:160,ReportMetricsOperationExports.java. - Problem: both docs still say
resultis one of"success" "failure" "interrupted"and that the counter is the number of invocations sent. The PR adds"rejected"(and changes the HELP text), and a rejected report is not an invocation at all, sosum(report_metrics_operation_total)now mixes attempts and dropped reports. - Potential risk: dashboards or alerts that sum all labels, or that enumerate label values, silently change meaning; users cannot learn about the new label.
- Best improvement: either expose the drop as its own counter (for example
report_metrics_operation_rejected_total) or update EN and ZH docs to listrejectedand state that it counts reports dropped before any invocation. - Severity: Medium. Raised by another reviewer: no.
Issue 3 (Low)
- Location:
TaskExecutionService.java:427-436(shutdown), PR description. - Problem: the description says "orderly executor shutdown drains reports already accepted", but
shutdown()callsshutdownNow()on both executors, which discards queued reports and the scheduled fallbacks, so those terminal futures are never completed; the nearby comment still talks about a "cached pool", which is no longer the case. - Potential risk: low, because the node is stopping and
executorServiceis alreadyshutdownNow(); but the description and the comment mislead future readers. - Best improvement: correct the description and the comment (or complete the futures of drained tasks if the intent was to drain).
- Severity: Low. Raised by another reviewer: no.
Issue 4 (Low)
- Location:
TaskExecutionService.java:~1843-1860(rejection handler). - Problem: a rejection is logged at WARN with the full stack trace per task group, and when the 15 s fallback wins over a slow report nothing is counted or logged at all.
- Potential risk: during a mass cancellation up to hundreds of identical stack traces, while the other degraded case (fallback fired first) stays invisible.
- Best improvement: log rejections without the stack trace (or rate-limit them), and add a single INFO/WARN line (or a second counter label) when the fallback publishes the terminal state before the report returns.
- Severity: Low. Raised by another reviewer: no.
Issue 5 (Low, carryover)
- Location:
TaskExecutionService.java:1090(invoke.get()),FINAL_METRICS_MAX_CONCURRENT_REPORTS(line 154). - Problem: the report invocation is still un-timed and each terminal task group sends its own full local metrics map; after the 15 s fallback the report keeps occupying one of the 4 threads until Hazelcast's own call timeout.
- Potential risk: during a long master outage the 4 threads can be tied up and later final reports are dropped (visible now through the counter); after recovery up to 128 queued, now stale, reports are sent one after another. I did not measure this.
- Best improvement:
invoke.get(timeout, unit)with a bound shorter than the fallback, and optionally coalesce queued final reports per node. Non-blocking. - Severity: Low. Raised by another reviewer: yes (earlier rounds, Problem 2).
2. Code Quality Assessment
2.1 Coding Standards
Good: Javadoc on the new constants, fields and methods, named daemon threads, a pinned context classloader, @VisibleForTesting on the widened method. The AtomicReference for the fallback handle is a little heavy but explained.
2.2 Test Coverage and Test Stability
Seven new TaskExecutionServiceTest cases cover the off-worker execution, canceled and failed terminal states, rejection plus counter, both fallback paths and the bounded pool; TelemetryCollectorCoordinatorGuardTest is updated for the new label. They use latches and Awaitility rather than fixed sleeps, and no existing assertion was weakened (additions plus one constructor-argument update). Stability: Risk present. Mockito.spy copies the field references of the live test server, so the spies share the server's real bounded executor; testFinalMetricsReportsRemainBoundedWhenInvocationHangs fills that shared pool (4 running plus 128 queued) and then asserts exact numbers (count of completed == 1, rejected == before + 1). Any final report that another test left in flight on the same server would shift those numbers. Please make the test wait for an empty pool and queue before it starts (or assert on deltas computed from the pool's own state), or give the spy its own executors via the existing reflection helper.
CI (head 0fa72b98): the apache Build check points to the fork run, which is red. (1) 64 jobs fail (17 succeeded), and the ones I opened fail on Issue 1. (2) The four unit-test legs fail in LLMBooleanOutputTest.readsLegacyFactoryWrapperWithValidationDisabled in transform-v2, which this PR does not touch; I could not confirm whether it is already fixed on dev. The unit-test run stopped before the seatunnel-engine-server module (I found no TaskExecutionService lines in the log), so the seven new unit tests have not been exercised by CI yet. The PR is 1 commit behind dev.
2.3 Documentation Updates
No user documentation covers the thread pool, but the telemetry label needs an update (Issue 2).
3. Architectural Soundness
3.1 Elegance
Long-term solution at the right lifecycle boundary: it fixes the cause (a blocking, interruptible RPC on a task worker) rather than the symptom.
3.2 Maintainability
Good separation: factories for the two executors, one method for the terminal ordering.
3.3 Extensibility
The pattern (never run a terminal side effect on an interruptible worker, bound it, always publish the state) can be reused for other terminal steps.
3.4 Historical-Version Compatibility
Fully compatible on the wire and in state; only the telemetry label set grows (Issue 2).
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | New pool and scheduler threads never exit, failing the E2E thread-leak check in most container ITs | TaskExecutionService.java:302-358, SeaTunnelContainer.isSystemThread |
High |
| 2 | New rejected label value is undocumented and mixes with invocation counts |
telemetry.md (EN/ZH), ReportMetricsOperationExports.java |
Medium |
| 3 | Shutdown description and comment do not match shutdownNow() |
TaskExecutionService.java:427-436 |
Low |
| 4 | Per-rejection stack trace; fallback win not observable | TaskExecutionService.java:~1843 |
Low |
| 5 | Un-timed invocation and no coalescing (carryover) | TaskExecutionService.java:1090 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
Blockers:
- Issue 1: allow idle timeout for both executors so no engine thread outlives the job, then confirm the container ITs pass.
- CI: after the fix, sync the latest
devand rerun the failed jobs so thatseatunnel-engine-servertests (including the seven new ones) are actually executed; theLLMBooleanOutputTestfailure is not caused by this diff.
Recommended fixes (non-blocking):
- Issue 2 (docs and metric semantics), Issue 3, Issue 4, Issue 5, and the test-isolation point in 2.2.
Overall assessment: the design is sound and has improved a lot over the rounds (bounded pool, separate fallback scheduler, rejection counter, classloader pin). The one remaining blocker is operational: the engine now owns long-lived threads that the E2E harness correctly flags.
Better alternative: none for the overall approach. If you want the smallest possible change for Issue 1, allowCoreThreadTimeOut(true) plus a 30 s keep-alive on both executors is a two-line fix per factory.
…fix shutdown docs and observability Address CHANGES_REQUESTED items from PR apache#12795: - Issue 1 (blocking): The new final-metrics pool (4 core threads) and the dedicated fallback scheduler (1 core thread) were created with keep-alive 0 and allowCoreThreadTimeOut=false, so their threads lived for the process lifetime. The E2E SeaTunnelContainer harness flags any new non-system thread left in the JVM after a job, and these threads caused every container-based IT on Zeta to fail with 'There are still threads running in the container'. Fix: set keep-alive to 30s and enable allowCoreThreadTimeOut on both executors so idle threads exit inside the harness's 120s wait window. - Issue 2 (non-blocking): docs/en and docs/zh telemetry.md did not mention the new 'rejected' label on report_metrics_operation_total, and the HELP text in ReportMetricsOperationExports did not distinguish between invocations actually sent and reports dropped before any invocation. Fix: update both docs and the HELP text. - Issue 3 (low): shutdown() comment still talked about a 'cached pool' and about draining reports; the pool has been bounded for several commits and shutdownNow is the intended behaviour. Fix: remove the now-misleading comment. - Issue 4 (low): the RejectedExecutionException catch path logged a full stack trace per saturated report, which is expected during mass cancellation; also, the 15s fallback path had no log at all, so when it fired the terminal future there was no observable signal. Fix: rejection path logs only a one-line WARN with the accumulated count; fallback logs an INFO when it publishes the terminal state before the metrics report returns.
Backport / clean rebase of PR apache#12795 fix onto current upstream/dev. - Use bounded 4-worker + 128-queue final-metrics executor (no more cached-thread pool exhaustion during master outages) - Add 15s fallback that publishes state before the fallback reports finish; the reports themselves are unbounded but queued - TaskExecutionServiceTest: interrupt isolation, CANCELED ordering, FAILED preservation, executor rejection, bounded-capacity coverage Refs: apache#12413, apache#12795 Signed-off-by: PR Maintainer <pr-maintainer@vllm.org>
…fix shutdown docs and observability Address CHANGES_REQUESTED items from PR apache#12795: - Issue 1 (blocking): The new final-metrics pool (4 core threads) and the dedicated fallback scheduler (1 core thread) were created with keep-alive 0 and allowCoreThreadTimeOut=false, so their threads lived for the process lifetime. The E2E SeaTunnelContainer harness flags any new non-system thread left in the JVM after a job, and these threads caused every container-based IT on Zeta to fail with 'There are still threads running in the container'. Fix: set keep-alive to 30s and enable allowCoreThreadTimeOut on both executors so idle threads exit inside the harness's 120s wait window. - Issue 2 (non-blocking): docs/en and docs/zh telemetry.md did not mention the new 'rejected' label on report_metrics_operation_total, and the HELP text in ReportMetricsOperationExports did not distinguish between invocations actually sent and reports dropped before any invocation. Fix: update both docs and the HELP text. - Issue 3 (low): shutdown() comment still talked about a 'cached pool' and about draining reports; the pool has been bounded for several commits and shutdownNow is the intended behaviour. Fix: remove the now-misleading comment. - Issue 4 (low): the RejectedExecutionException catch path logged a full stack trace per saturated report, which is expected during mass cancellation; also, the 15s fallback path had no log at all, so when it fired the terminal future there was no observable signal. Fix: rejection path logs only a one-line WARN with the accumulated count; fallback logs an INFO when it publishes the terminal state before the metrics report returns.
270094a to
515ab26
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you for the quick iteration and for rebasing onto the latest dev, @Asthenia0412. I re-reviewed the whole diff at head 515ab269 (7 files: TaskExecutionService, the telemetry stats and exports, the two telemetry docs, and two test classes), not only the delta from my last round at 0fa72b98. The previous blockers are addressed in code, but the latest push introduced a compile error, which is why CI cannot show anything useful for this head yet.
What Problem Does This PR Solve?
- User pain point: when a task group ends as
CANCELEDorFAILED, its last task callsupdateMetricsContextInImap()on a task worker whose interrupt flag may already be set. The synchronous Hazelcast call can close the worker's shared connection to the master and delay the terminal state (#12413). - Fix approach: run the final metrics report on a dedicated bounded daemon pool, publish the terminal
TaskExecutionStateafter the report finishes (or fails, or is rejected), and guard the terminal future with a 15 s fallback on its own scheduler. - One-sentence summary: report final metrics from a clean thread with a time bound so an interrupted worker cannot stall or break terminal completion.
1. Code Change Review
1.1 Core Logic Analysis
Before (TaskGroupExecutionTracker.taskDone): finishExecution, then an inline updateMetricsContextInImap() on the possibly interrupted worker, then future.complete(state).
After (completeAfterFinalMetrics, TaskExecutionService.java:1802-1890):
finishExecution(taskGroupLocation);
completeAfterFinalMetrics(taskGroupLocation, FINISHED | CANCELED | FAILED, ex);task worker (interrupt flag maybe set)
-> TaskGroupExecutionTracker.taskDone -> completionLatch == 0 -> finishExecution
-> completeAfterFinalMetrics
-> finalMetricsFallbackExecutorService.schedule(complete terminal state, 15 s) [1 daemon thread, idle timeout 30 s]
-> finalMetricsExecutorService.submit(report) [4 daemon threads, queue 128, AbortPolicy, idle timeout 30 s]
report: updateMetricsContextInImap() ; finally complete terminal state + cancel fallback
-> RejectedExecutionException: count it, cancel fallback, complete directly
-> terminal future callbacks run via whenCompleteAsync on executorService (not on the pool/fallback threads)
What I verified on this head: every terminal state goes through the new method; the pool is bounded; the terminal future is idempotent, so report and fallback can race safely; ReportMetricsOperationStats gets one new field and both constructor callers are updated; the content of TaskExecutionService is identical to the previous head 270094a1 (the only difference between the two heads is the dev rebase).
Status of my previous items:
- Thread-leak blocker: addressed in code. The metrics pool now has
allowCoreThreadTimeOut(true)with a 30 s keep-alive and the fallback scheduler usessetKeepAliveTime(30 s)plusallowCoreThreadTimeOut(true), so both can exit inside the E2E harness window. I could not confirm it in CI because of Issue 1. - Telemetry docs: addressed. EN and ZH
telemetry.mdnow listrejectedand explain that no invocation is sent. - Rejection log without stack trace and an INFO line when the fallback wins: addressed in code (but see Issue 1).
1.2 Compatibility Impact
Partially incompatible in observability only: a new result="rejected" value on report_metrics_operation_total, now documented in EN and ZH, with the HELP text updated. No configuration, wire or state change.
1.3 Performance / Side-Effect Analysis
The worker no longer blocks on the metrics RPC. Under a mass cancellation at most 4 reports run and 128 wait; later ones are dropped, counted, and their terminal state is published immediately. Idle threads now exit after 30 s, so there is no permanent thread cost per worker.
1.4 Error Handling and Logging
Issue 1 (High, blocking; reproduced in CI)
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:1827-1832and:1859 - Problem: the new log statements do not compile.
loggeris a HazelcastILogger(TaskExecutionService.java:192), which has onlyinfo(String),info(String, Throwable)andisInfoEnabled()/isWarningEnabled(). The code callslogger.info("... {} ... {} ... {}", taskGroupLocation, finalMetricsFallbackTimeoutMs, executionState)(slf4j style, four arguments) andlogger.isWarnEnabled()(not a method ofILogger). The fork run for the previous head270094a1(same content) fails inseatunnel-engine-serverwitherror: no suitable method found for info(String,TaskGroupLocation,long,ExecutionState)at[1828,46]anderror: cannot find symbolat[1859,30], and every downstream job (unit-test, engine ITs, Dependency licenses and so on) fails behind it. - Potential risk: nothing in this PR, including the seven new unit tests and the thread-leak fix, can be validated until it compiles.
- Best improvement: follow the style used elsewhere in this class:
if (logger.isInfoEnabled()) { logger.info(String.format("final metrics report for taskGroup %s timed out after %d ms; completing terminal state %s directly", taskGroupLocation, finalMetricsFallbackTimeoutMs, executionState)); }and replaceisWarnEnabled()withisWarningEnabled(). Please also build the module locally before pushing (seatunnel-engine-servercompile) so the next CI run reaches the tests. - Severity: High
- Raised by another reviewer: No
Issue 2 (Low)
- Location: PR description (and
TaskExecutionService.shutdown(),:435-445) - Problem: the description still says "orderly executor shutdown drains reports already accepted", but
shutdown()callsshutdownNow()on both executors, which discards queued reports and scheduled fallbacks. At node shutdown this is acceptable, but the sentence is wrong. - Best improvement: reword the description to say queued reports are dropped on shutdown.
- Severity: Low
- Raised by another reviewer: No
Issue 3 (Low, carryover)
- Location:
TaskExecutionService.java:~1090(invoke.get()insideupdateMetricsContextInImap),FINAL_METRICS_MAX_CONCURRENT_REPORTS - Problem: the report invocation is still un-timed. After the 15 s fallback the report keeps occupying one of the 4 threads until Hazelcast's own call timeout, and each terminal task group sends its own full metrics map.
- Potential risk: during a long master outage the 4 threads can be tied up and later reports are dropped (now visible through the counter); after recovery up to 128 stale reports are sent one after another. I did not measure this.
- Best improvement:
invoke.get(timeout, unit)with a bound shorter than the fallback; optionally coalesce queued reports per node. Non-blocking. - Severity: Low
- Raised by another reviewer: Yes (my earlier rounds)
2. Code Quality Assessment
2.1 Coding Standards
Javadoc on the new constants, fields and factories, named daemon threads, a pinned context classloader and @VisibleForTesting on the widened method. The AtomicReference holding the fallback handle is a bit heavy but explained.
2.2 Test Coverage and Test Stability
Seven new TaskExecutionServiceTest cases cover off-worker execution, the canceled and failed terminal states, rejection with the counter, both fallback paths and the bounded pool; TelemetryCollectorCoordinatorGuardTest is updated for the new label. They use latches and Awaitility instead of fixed sleeps, and no existing assertion is weakened. Stability: Risk present. Mockito.spy copies the field references of the live test server, so every spy shares the server's real bounded executor; testFinalMetricsReportsRemainBoundedWhenInvocationHangs (TaskExecutionServiceTest.java:~960-1030) fills that pool (4 running plus 128 queued) and asserts exact numbers (4 concurrent, exactly one immediate completion, rejected == before + 1). A final report left in flight by an earlier test on the same server would shift these numbers. Please make that test wait for an empty pool and queue before it starts, or give the spy its own executors with the existing reflection helper. This is non-blocking but should be done while the file is open.
CI: the fork Build for 515ab269 was queued when I checked. The known result for the identical content (270094a1) is a compile failure in seatunnel-engine-server (Issue 1), which cascades to all jobs, so those failures say nothing about unrelated flakiness. Separately, dev currently has a unit-test failure in LLMBooleanOutputTest (transform-v2) and one in JdbcOptionRuleCompletenessTest (#12874, fix #12875 open); please expect those to show up once the module compiles and do not attribute them to this PR.
2.3 Documentation Updates
EN and ZH telemetry docs now match the code.
3. Architectural Soundness
3.1 Elegance of the Solution
Long-term solution at the right lifecycle boundary: it removes a blocking, interruptible RPC from the task worker rather than masking the symptom.
3.2 Maintainability
Factories for the two executors and one method owning the terminal ordering.
3.3 Extensibility
The same pattern (no terminal side effect on an interruptible worker, bounded, always publish the state) can be reused.
3.4 Historical-Version Compatibility
Compatible on the wire and in state; only the telemetry label set grows, and it is documented.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | New log statements do not compile (ILogger has no slf4j-style info(...) or isWarnEnabled) | TaskExecutionService.java:1827-1832, 1859 | High |
| 2 | PR description says shutdown drains reports; code uses shutdownNow | PR description, TaskExecutionService.java shutdown() | Low |
| 3 | Un-timed report invocation and no coalescing (carryover) | TaskExecutionService.java:~1090 | Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- Issue 1: make the two log statements compile, then let CI run so the seven new unit tests and the thread-leak fix are actually exercised.
- CI must be green or only red from the unrelated
devfailures named above.
- Recommended non-blocking fixes
- Issues 2 and 3, and the shared-pool isolation in the bounded-pool test (see 2.2).
Overall assessment: the design is sound and has improved a lot over the rounds (bounded pool, separate fallback scheduler, rejection counter, idle thread timeout, documented label). The remaining blocker is a small, mechanical compile fix.
Better alternative: none for the overall approach.
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you for the quick follow-up, @Asthenia0412, and for fixing the logger compile error from my last round (and for the clear PR description update). I re-read the whole diff at the latest head (a41e38f6, 7 files, plus the merge of dev) from scratch, not only the increment since 515ab269. The blocker is cleared, the code now compiles in CI, and I found no new blocking issue in the code.
What Problem Does This PR Solve?
- User pain point: when a task group ends as
FINISHED,CANCELEDorFAILED, its last task callsupdateMetricsContextInImap()on a task worker whose interrupt flag may already be set. The synchronous Hazelcast call can then close the worker's shared connection to the master and delay or break terminal completion (#12413). - Fix approach: run the final metrics report on a dedicated bounded daemon pool, publish the terminal
TaskExecutionStateafter the report finishes, fails or is rejected, and guard the terminal future with a 15 s fallback on its own scheduler. - Summary: report final metrics from a clean thread with a time bound so an interrupted worker cannot stall the terminal state.
1. Code Change Review
1.1 Core Logic Analysis
Before (TaskGroupExecutionTracker.taskDone): finishExecution, then an inline updateMetricsContextInImap() on the possibly interrupted worker, then future.complete(state).
After (TaskExecutionService.java:1792-1894): finishExecution, then completeAfterFinalMetrics(taskGroupLocation, FINISHED | CANCELED | FAILED, ex).
task worker (interrupt flag maybe set)
-> TaskGroupExecutionTracker.taskDone -> completionLatch == 0 -> finishExecution
-> completeAfterFinalMetrics
-> finalMetricsFallbackExecutorService.schedule(complete terminal state, 15 s) [1 daemon thread, idle exit 30 s]
-> finalMetricsExecutorService.submit(report) [4 daemon threads, queue 128, AbortPolicy, idle exit 30 s]
report: updateMetricsContextInImap() ; finally complete terminal state + cancel fallback
-> RejectedExecutionException: count it, cancel fallback, complete directly
-> resultFuture.whenCompleteAsync(...) runs on executorService (not on the pool or fallback threads)
What I verified on this head: all three terminal states go through the new method; the terminal future is idempotent so report and fallback can race safely; the downstream callback is whenCompleteAsync (TaskExecutionService.java:770), so no heavy work runs on the metrics or fallback threads; ReportMetricsOperationStats is only built in-process (getReportMetricsOperationStats) and the one test constructor caller is updated, so the new field is not a serialization change; the imports and the ILogger calls (isInfoEnabled, isWarningEnabled, warning(String, Throwable)) now match the Hazelcast API.
Status of my previous items:
- Issue 1 (log statements did not compile): FIXED. The fork
Buildfor this head compiledseatunnel-engine-serverand ran the tests. - Issue 2 (description said shutdown drains reports): FIXED, the description now says node shutdown interrupts running reports and may discard queued ones.
- Shared-pool isolation in the bounded-pool test: FIXED, the test now installs its own
ThreadPoolExecutorthroughReflectionUtils.setFieldand waits for all futures beforeshutdownNow(). - Issue 3 (un-timed
invoke.get()atTaskExecutionService.java:1095): still open, Low, non-blocking (see below).
1.2 Compatibility Impact
Partially incompatible in observability only: a new result="rejected" value on report_metrics_operation_total, documented in EN and ZH telemetry.md, with the HELP text updated. No configuration, wire, state or checkpoint/savepoint change.
1.3 Performance / Side-Effect Analysis
The worker no longer blocks on the metrics RPC. Under a mass cancellation at most 4 reports run and 128 wait; later ones are dropped, counted, and their terminal state is published immediately, so memory and thread use stay bounded. Idle threads exit after 30 s, so there is no permanent thread cost.
1.4 Error Handling and Logging
No blocking issues found. Rejections log a one-line WARN with the running count, the fallback logs one INFO line, and the report failure keeps its stack trace. One remaining item:
Issue 1: The report invocation is still un-timed (carryover, non-blocking)
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:1095(invoke.get()inupdateMetricsContextInImap) - Problem description: after the 15 s fallback the report keeps occupying one of the 4 pool threads until Hazelcast's own call timeout, and each terminal task group sends a full metrics map.
- Potential risk: during a long master outage the 4 threads can all be tied up and later reports are dropped (now visible through the
rejectedcounter); the job's final metrics for those task groups are lost. This is documented as best-effort, and I did not measure it. - Best improvement:
invoke.get(timeout, unit)with a bound shorter than the fallback, optionally coalescing queued reports per node. Fine as a follow-up. - Severity: Low
- Raised by another reviewer: No (my earlier rounds)
2. Code Quality Assessment
2.1 Coding Standards
Javadoc on the new constants, fields and factories, named daemon threads, a pinned context classloader, @VisibleForTesting on the widened method, and spotless passes in the fork Code style job.
2.2 Test Coverage and Test Stability
Seven new TaskExecutionServiceTest cases cover off-worker execution (asserting the metrics thread is not the interrupted worker), CANCELED and FAILED ordering, rejection with the counter, both fallback paths (200 ms timeout injected by reflection) and the bounded pool; TelemetryCollectorCoordinatorGuardTest is updated for the new label. They use latches and Awaitility, there is no Thread.sleep, and no existing assertion is weakened. Stability rating: Stable.
CI for head a41e38f6 (fork Build run 39819530447): compile, code style and most jobs pass; 19 jobs failed. I read the logs of four of them and none points at this diff:
unit-test (17):SavePointTest.testSavePointButJobGoingToFail:87times out with the job stuck in RUNNING. This is the known engine cancel-hang ondev(the sink throws, one task group never completes); it does not involve final metrics and no final-metrics log line appears in that test.engine-v2-it: onlySplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAckfails, a worker-crash case where the worker is gone, so this PR's worker-side code is not on that path. Importantly the "There are still threads running in the container" check from the earlier round no longer fires.hbase-connector-it:PreconditionViolationfor all 22 tests, i.e. the container could not start (environmental).redis-connector-it:testRedisWithExpireexpected 100 but was 0, a Redis connector test.
The other 15 failed jobs (several connector ITs) I did not open, so I cannot rule them out individually.
2.3 Documentation Updates
EN and ZH telemetry docs match the code and each other.
3. Architectural Soundness
3.1 Elegance of the Solution
Long-term solution at the right lifecycle boundary: it moves a blocking, interruptible RPC off the task worker instead of masking the symptom.
3.2 Maintainability
Two small factories for the executors and one method that owns the terminal-state ordering.
3.3 Extensibility
The same pattern (no terminal side effect on an interruptible worker, bounded, always publish the state) can be reused.
3.4 Historical-Version Compatibility
Compatible on the wire and in state; only the telemetry label set grows, and it is documented.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Report invocation still un-timed, no coalescing (carryover) | TaskExecutionService.java:1095 | Low |
5. Merge Recommendation
Mergeability: not conflicting; the branch is 1 commit behind dev (metadata only, no sync needed for the CI findings above). The fork Build is red, but in the jobs I inspected the failures are unrelated to this diff. This review is static plus CI-log reading; I did not build or run anything locally.
Conclusion: Ready to merge after fixes
- Blockers - must be fixed
- No code blockers found. CI is the only gate: please retrigger only the failed jobs (no code change needed for the failures I traced) and, if any of the 15 jobs I did not open fails again, share the failing test name here so we can check whether it relates to the diff.
- Recommended non-blocking
- Issue 1 as a follow-up.
Overall assessment: the design is sound and the PR improved a lot over the rounds (bounded pool, separate fallback scheduler, rejection counter, idle thread exit, documented label, isolated bounded-pool test). Thank you for the patience through all of them!
Better alternative: none for the overall approach.
Backport / clean rebase of PR apache#12795 fix onto current upstream/dev. - Use bounded 4-worker + 128-queue final-metrics executor (no more cached-thread pool exhaustion during master outages) - Add 15s fallback that publishes state before the fallback reports finish; the reports themselves are unbounded but queued - TaskExecutionServiceTest: interrupt isolation, CANCELED ordering, FAILED preservation, executor rejection, bounded-capacity coverage Refs: apache#12413, apache#12795 Signed-off-by: PR Maintainer <pr-maintainer@vllm.org>
…fix shutdown docs and observability Address CHANGES_REQUESTED items from PR apache#12795: - Issue 1 (blocking): The new final-metrics pool (4 core threads) and the dedicated fallback scheduler (1 core thread) were created with keep-alive 0 and allowCoreThreadTimeOut=false, so their threads lived for the process lifetime. The E2E SeaTunnelContainer harness flags any new non-system thread left in the JVM after a job, and these threads caused every container-based IT on Zeta to fail with 'There are still threads running in the container'. Fix: set keep-alive to 30s and enable allowCoreThreadTimeOut on both executors so idle threads exit inside the harness's 120s wait window. - Issue 2 (non-blocking): docs/en and docs/zh telemetry.md did not mention the new 'rejected' label on report_metrics_operation_total, and the HELP text in ReportMetricsOperationExports did not distinguish between invocations actually sent and reports dropped before any invocation. Fix: update both docs and the HELP text. - Issue 3 (low): shutdown() comment still talked about a 'cached pool' and about draining reports; the pool has been bounded for several commits and shutdownNow is the intended behaviour. Fix: remove the now-misleading comment. - Issue 4 (low): the RejectedExecutionException catch path logged a full stack trace per saturated report, which is expected during mass cancellation; also, the 15s fallback path had no log at all, so when it fired the terminal future there was no observable signal. Fix: rejection path logs only a one-line WARN with the accumulated count; fallback logs an INFO when it publishes the terminal state before the metrics report returns.
a41e38f to
c9cc3c9
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the follow-up, @Asthenia0412. I re-read the full current diff at c9cc3c92c7, not just the rebuild/merge history. One clarification on the latest note: the actual comparison is seven focused files, including the rejection metric, exporter/test and EN/ZH telemetry notes, rather than two files. Those supporting changes belong to this fix; I am not asking you to remove them. Sorry for missing the integration-coverage and test-timing items in my last review. Issues 2 and 3 below are carryover omissions, not new regressions introduced by the cleaned-up history.
What Problem Does This PR Solve?
- User pain: The last task in a group reports metrics synchronously while its worker may already be interrupted. That interrupt can affect the Hazelcast invocation/connection and delay terminal-state reporting during cancellation or failure.
- Fix approach: Move terminal metrics to a bounded, dedicated daemon pool and complete the terminal future after reporting, rejection, failure or a separately scheduled fallback.
- One-sentence summary and example: Canceling a task can finish without making its interrupted worker perform the final metrics RPC; even a stuck report no longer indefinitely holds that task's terminal future.
1. Code Change Review
1.1 Core Logic Analysis
The main changes are executor factories/fields and TaskGroupExecutionTracker.completeAfterFinalMetrics in TaskExecutionService, plus the rejection statistics/export and tests. All FINISHED/CANCELED/FAILED branches use the same completion method.
Before:
finishExecution(taskGroupLocation);
try { updateMetricsContextInImap(); } catch (Throwable t) { /* log */ }
future.complete(terminalState);After:
finishExecution(taskGroupLocation);
completeAfterFinalMetrics(taskGroupLocation, terminalState, failure);
// Dedicated scheduler: complete future after configured 15 s fallback.
// Dedicated reporting pool: report; finally complete future and cancel fallback.
// Saturation/rejection: increment rejected counter and complete directly.Complete affected runtime chain:
Deploy local group -> deployLocalTask [762 onward]
-> resultFuture.whenCompleteAsync(..., executorService) [770-794]
-> start tasks / cancellation exceptional future -> cancelAllTask [1701-1736]
-> task worker finishes -> tracker.taskDone [1756-1787]
-> last completionLatch decrement -> finishExecution [1910-1953]
-> move this active generation to finished context, preserve newer generation
-> release this context's classloader/async/timer resources
-> completeAfterFinalMetrics [1803 onward]
-> schedule fallback on separate one-thread scheduler
-> submit report to bounded 4-worker / 128-queue executor
-> clean pool worker -> updateMetricsContextInImap [1072-1117]
-> collect local metrics -> ReportMetricsOperation -> invoke.get()
-> report success/failure finally completes original terminal state
and removes canceled fallback
-> rejected report: record rejected count; cancel fallback; complete immediately
-> scheduling failure: best-effort fallback cancellation; complete immediately
-> timeout wins: complete terminal state while report may continue
-> async terminal callback -> notifyTaskStatusToMaster
-> existing master task/pipeline terminal-state processing
Telemetry scrape -> getReportMetricsOperationStats [1149 onward]
-> in-process stats DTO -> ReportMetricsOperationExports
-> result=success/failure/interrupted/rejected counter samples
Key findings:
- Ordinary successful completion and interrupted cancellation/failure all reach the change. The task interrupt is not cleared to hide the problem; reporting moves to another thread.
- The terminal future is idempotent, so fallback/report races preserve the chosen FINISHED/CANCELED/FAILED result. Heavy downstream status notification is asynchronous on the existing executor, not inline on the fallback thread.
- The separate fallback scheduler avoids being blocked behind periodic metrics backup's un-timed invocation. Remove-on-cancel prevents normal reports retaining delayed fallback entries.
- Bounded report admission prevents unbounded reporting threads/work during a master outage; rejected metrics are explicitly best effort and observable.
- This is a focused lifecycle fix. The 15 s bound covers the terminal future under a running scheduler, not a hard real-time guarantee, delivery guarantee for final metrics, or a deadline on
notifyTaskStatusToMasteritself. Node shutdown can interrupt running reports/discard queued work; it is not a draining protocol.
The prior unsupported logger calls are corrected to Hazelcast ILogger methods. Generation-aware finishExecution remains intact; the new path does not remove a newer active context. The new stats field is used in process, with the constructor fixture updated; no operation/checkpoint serializer is changed.
1.2 Compatibility Impact
Partially incompatible in observability only: the Prometheus result label gains rejected, counting admission drops before an RPC. Existing metric names and labels remain, but consumers assuming exactly three result values should allow the fourth. EN/ZH telemetry and HELP text document this. API/configuration/default job semantics, wire protocols, checkpoint/savepoint formats and state assignment remain unchanged. Final metrics are best effort rather than a prerequisite for indefinite task completion.
1.3 Performance and Side Effects
At most four reports execute and 128 wait. The queue is bounded, and the fallback is independent. Scheduled fallback tasks can accumulate for the admitted in-flight groups until completed/canceled; rejected reports cancel theirs immediately. Idle pool/scheduler threads can exit after 30 s, with fixed engine classloader/named daemon threads. Reports still collect node-wide metrics and may hold a reporting worker until Hazelcast finishes (Issue 1). No per-record CPU, data-network change, checkpoint lock or sink idempotency change is added. Shutdown is best effort, not a metrics drain.
1.4 Error Handling, Logging and Formal Findings
Reporting exceptions cannot replace the original task failure. Rejection logs context/count without an unnecessary stack trace; fallback logs task/state/timeout; scheduling failure logs its cause. No new payload or credential logging appears.
Issue 2: Extend the existing engine IT for the real interrupted-worker completion path
- Location:
seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/TaskExecutionServiceTest.java:714and the existingseatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/ClusterFaultToleranceIT.java/SplitClusterFaultToleranceIT.javaarea (unchanged). - Description: The added service tests stub
updateMetricsContextInImap, so they establish thread/ordering behavior but bypass the actual Hazelcast invocation that motivated this fix. The repository already has engine lifecycle/cancellation IT coverage, and this PR changes no IT. This leaves the interrupted worker -> real final-report connection -> master terminal notification boundary unprotected by a focused regression. - Potential risk: The unit suite can remain green while the actual cancellation/report transport still closes a shared connection or fails to deliver a terminal state.
- Best improvement: Extend an existing engine cancellation/lifecycle IT to cancel a real running task group, await its terminal state, and verify continued cluster/job communication using the real metrics path. Use observable conditions and bounded waits, not sleep or a new unrelated fault harness. Keep the current unit tests for saturation/fallback internals.
- Severity: Medium; required integration coverage for this engine lifecycle change.
- Already raised by another reviewer: No; my previous review missed this delivery requirement. I am not claiming a demonstrated remaining production defect.
Issue 3: The bounded-pool assertion races the real 15-second fallback
- Location:
seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/TaskExecutionServiceTest.java:1021-1046. - Description: The test submits 133 groups, then expects exactly one terminal future to be done while reports remain blocked. Every accepted submission also schedules the production 15 s fallback. If the submission/assertion phase is delayed past a fallback deadline on a slow or paused runner, additional futures correctly complete and the exact-one assertion fails although admission bounds work.
- Potential risk: A timing-sensitive CI assertion; this is a possible slow-runner flake, not a demonstrated high-probability failure.
- Best improvement: Control/inject the fallback scheduler in this admission test, or assert bounded active/queued work plus the rejected counter without assuming all accepted futures remain incomplete before a wall-clock deadline. The separate fallback tests should continue to exercise expiration with condition waits.
- Severity: Medium; non-blocking stability improvement.
- Already raised by another reviewer: No; this existed in the previous head and was missed in my earlier Stable rating.
Issue 1: Reporting RPC remains un-timed (existing optional follow-up)
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:1095. - Description: After fallback completes a task,
invoke.get()can still occupy a reporting worker. Four stalled reports can saturate this best-effort pool, dropping later reports. - Potential risk: Lost final telemetry under a long master outage, without blocking the task future.
- Best improvement: Consider a bounded invocation wait/coalescing as a separate follow-up, preserving the independent fallback and interruption semantics.
- Severity: Low; non-blocking, as previously classified.
- Already raised by another reviewer: No; retained from Daniel's prior review, with its number preserved.
2. Code Quality Assessment
2.1 Coding Standards
The pool/scheduler factories and lifecycle method have focused contracts, named constants and thread names. Prefixing the added rejection counter is consistent with surrounding metrics fields; the stats DTO documents it. The implementation stays scoped to final metrics and its observability support.
2.2 Test Coverage and Stability
The service tests cover an interrupted worker, separate reports, canceled/failed state preservation, admission rejection/count, FINISHED/CANCELED fallbacks and bounded work. The metric exporter checks all four result samples. Latches/Awaitility are used instead of sleeps, producer resources are isolated in the bounded-pool test, and its finally block releases blocked reports and shuts down its test executor.
Stability rating: At risk (non-blocking). Issue 3 is the concrete assertion/deadline coupling. The 200 ms fallback cases use two-second Awaitility deadlines with scheduler headroom rather than asserting an exact duration; their latch gates are useful. They still do not replace the real transport coverage requested in Issue 2. The inherited real-server test fixture and ordinary CI must validate integration; I did not run them locally.
2.3 Documentation
Both telemetry pages correctly distinguish invocation results from reports rejected before dispatch, matching the exporter HELP text. No new user option or data-format migration guide is required. Shutdown/fallback should continue to be described as best effort rather than guaranteed metric delivery.
3. Architectural Assessment
3.1 Solution Quality
Focused long-term approach: isolate terminal side effects from interrupted task workers, bound admission, and always permit terminal publication. It fixes the lifecycle boundary rather than clearing interrupts around an RPC.
3.2 Maintainability
One method owns ordering and both racing completion paths. The independent scheduler and remove-on-cancel policy make the fallback easier to reason about. Avoid conflating terminal-state completion with transport/report completion.
3.3 Extensibility
The pattern is reusable for other best-effort terminal work, but should not be applied to durable sink commits that require stronger guarantees.
3.4 Historical Compatibility
No checkpoint/wire migration is introduced; monitoring consumers should accept the new result value. Static source compatibility is not an executed distributed shutdown/failover result.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 2 | Missing real engine cancellation/report IT regression | TaskExecutionServiceTest.java:714; existing engine IT area |
Medium |
| 3 | Admission assertion races fallback deadlines | TaskExecutionServiceTest.java:1021-1046 |
Medium, non-blocking |
| 1 | Un-timed metrics invocation | TaskExecutionService.java:1095 |
Low |
5. Merge Conclusion
Conclusion: Can merge after fixes
- Blockers (must fix): Issue 2: extend existing engine IT coverage for the real cancellation/report boundary; obtain current-head CI and effective maintainer approval. The earlier logger compile blocker is cleared in source, and no new functional defect was established by this review.
- Recommended improvements (non-blocking): Issue 3: decouple admission assertions from the fallback clock; Issue 1: bound/coalesce report work in a follow-up.
Overall assessment: The production design is coherent and preserves task state despite metrics failure. The additional coverage request and corrected stability rating are my previous omissions, explicitly acknowledged above. There are no independent non-Daniel formal reviews to duplicate or override in the collected discussion.
Alternatives: Retain the current bounded pool plus independent fallback and add the focused IT (preferred). Clearing the task worker's interrupt around synchronous reporting would obscure cancellation and retain coupling, so it is not a better solution. A timed RPC/coalescing layer can be evaluated separately.
Current CI: The exact-head rollup is empty and the queried contributor fork has no matching Build run. Thus the 19 failures/earlier compilation success discussed on a41e38f6 are old-head facts, not the state of c9cc3c92c7. No current failed workflow/job exists here to attribute to this diff or to a known upstream fix. This does not establish that the contributor disabled Actions. A maintainer/owner should check workflow discovery/approval and route the current head into Build; an unrelated source patch or drift-only sync is not justified by this evidence.
Daniel's technical conclusion is separate from the repository's effective review summary. READ-level COMMENT does not approve/dismiss a historical requested-changes entry; a write-capable maintainer owns that final gate.
Verification scope: Local fetch/isolated branch, full seven-file diff (+647/-17), caller/state/telemetry reads with Git, and live head/check/fork-run metadata. git diff --check returned 0. No local compilation, tests, E2E, containers or jobs were run by me.
Snapshot 2026-11-01T12:40:00.322908+00:00: head c9cc3c92c7a2dfca68e965febf4087dbd18c60ed, base dev; compare diverged, ahead 4 / behind 3; merge blocked / BLOCKED, review decision REVIEW_REQUIRED. Drift is recorded separately; it does not itself request synchronization.
Problem
When a task group is canceled, its last task can call
updateMetricsContextInImap()from an interrupted task worker. The synchronous Hazelcast socket write may then close the worker's shared connection to the master and delay terminal completion.Change
Run the final metrics attempt on a dedicated daemon executor so it does not inherit the task worker's interrupt status. Publish the task group's terminal state after the metrics attempt finishes, fails, is rejected, or reaches its timeout. This ordering applies to FINISHED, CANCELED, and FAILED task groups. The report is best-effort: node shutdown interrupts running reports and may discard queued reports. Queue rejections are exposed in telemetry.
Verification
TaskExecutionServiceTestandTelemetryCollectorCoordinatorGuardTestselection: 8 tests passed on JDK 21.spotless:checkforseatunnel-engine-server: passed on JDK 8.git diff --check: passed.Fixes #12413.