Repository navigation
[Fix][Zeta] Close all flow lifecycles even when an earlier close fails - #12391
SeaSand1024 wants to merge 9 commits into
Conversation
SeaTunnelTask.close() only caught IOException while iterating the flow lifecycles. An unchecked exception (e.g. RuntimeException) from an earlier lifecycle escaped the teardown loop, so later lifecycles never closed, leaking executors/connections/buffers. Change the per-lifecycle close to catch Throwable, keep the first failure and attach subsequent failures as suppressed, rethrowing the original failure at the end while preserving teardown order. Extend SeaTunnelTaskStateTest with deterministic coverage for checked and unchecked close failures plus multi-failure suppression. Co-Authored-By: Claude <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai>
The three new close() lifecycle tests call doThrow without a static import, so testCompile failed before Surefire could run. Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: multica-agent <github@multica.ai>
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks so much for picking this up, @SeaSand1024, and for the clear PR description. I went through the full diff against the latest dev (the branch is 2 commits ahead and 0 behind), traced the close path end to end, and I did not find any code-side blocker. The approach is exactly what #12231 asked for, and I have a few small, non-blocking suggestions below. Nice work, and welcome to the project!
What Problem Does This PR Solve?
- User pain point:
SeaTunnelTask.close()only caughtIOExceptionaround eachFlowLifeCycle.close(). If an earlier lifecycle (for example a sink writer) threw an unchecked exception, the exception escaped theforEachand every later lifecycle was never closed, so their executors, connections and buffers outlived the task. - Fix approach: catch
Throwableper lifecycle, keep the teardown order, remember the first failure, attach later failures withaddSuppressed, and rethrow the first failure at the end (IOExceptionas-is, everything else viasneakyThrow). - In one sentence: one failing
close()can no longer stop the remaining lifecycles from being closed, and the original failure is still reported.
Simple example: a task has [source, transform, sink-A, sink-B] and sink-A.close() throws IllegalStateException. Before, sink-B was never closed and its thread pool stayed alive. Now sink-B is closed, the task still fails with the IllegalStateException, and any further close failure is attached as suppressed.
1. Code Change Review
1.1 Core Logic Analysis
Changed code: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:451-479 (close()), plus tests in SeaTunnelTaskStateTest.java:440-509.
Before:
IOException[] closeException = {null};
try { super.close(); } catch (IOException e) { closeException[0] = e; }
MDCTracer.tracing(allCycles.stream()).forEach(flowLifeCycle -> {
try { flowLifeCycle.close(); }
catch (IOException e) { /* log, keep first, suppress rest */ }
});
if (closeException[0] != null) { throw closeException[0]; }After (SeaTunnelTask.java:453-478):
Throwable[] closeException = {null};
try { super.close(); } catch (Throwable t) { closeException[0] = t; }
MDCTracer.tracing(allCycles.stream()).forEach(flowLifeCycle -> {
try { flowLifeCycle.close(); }
catch (Throwable t) { /* log, keep first, addSuppressed for the rest */ }
});
if (closeException[0] != null) {
if (closeException[0] instanceof IOException) { throw (IOException) closeException[0]; }
sneakyThrow(closeException[0]);
}Key findings
- The normal path reaches this code. The default
task-execution-thread-share-modeisOFF(ServerConfigOptions.java:495-498,EngineConfig.java:63-65), so tasks run onBlockingWorker. When a task reachesCLOSEDorCANCELLING,stateProcess()callsthis.close()(SeaTunnelTask.java:292-301). If the task fails earlier,BlockingWorker.run()callstracker.task.close()in itsfinally(TaskExecutionService.java:1310-1318). So this is a routine teardown path, not a rare corner. - The reported problem is real.
SinkFlowLifeCycle.close()(SinkFlowLifeCycle.java:277-283) andSourceFlowLifeCycle.close()(SourceFlowLifeCycle.java:216-224) delegate to connector-suppliedSinkWriter#close()andSourceReader#close(), which are free to throw unchecked exceptions. Ondevthe old catch clause really did skip later lifecycles. - It is a precise fix, scoped to the teardown loop. Teardown order is preserved because the stream is sequential and ordered (
MDCStream.forEachdelegates to the underlying sequential stream). - The
sneakyThrowrethrow compiles and behaves correctly.ExceptionUtil.sneakyThrow(Throwable)(ExceptionUtil.java:125-127) is already statically imported in this file (SeaTunnelTask.java:86) and used at line 619.IOExceptionkeeps its declared type, so the method signature and existing callers are unchanged. - Catching
Throwablearoundsuper.close()is harmless.AbstractTask.close()(AbstractTask.java:98-106) already swallowsException, so this is effectively defensive.
Runtime path (default blocking worker):
CLOSED / CANCELLING state (SeaTunnelTask.stateProcess, L292-301)
-> SeaTunnelTask.close() (L451-479)
-> super.close() // never throws today
-> for each FlowLifeCycle, in order:
close() ; on ANY Throwable: log + keep first + addSuppressed
-> rethrow first failure (IOException as-is, others via sneakyThrow)
-> exception leaves call() -> BlockingWorker.run() catch Throwable (L1303-1309)
-> finally: taskDone(t); result == null -> tracker.task.close() again (L1310-1318)
1.2 Compatibility Impact
Fully compatible. No config option, default value, protocol, serialization format, checkpoint/savepoint state or public API is touched. close() still declares throws IOException. The only behavioral change is that cleanup which used to stop early on an unchecked failure now runs to completion, and the first failure is still what the caller sees. No entry in incompatible-changes.md is needed.
1.3 Performance / Side-Effect Analysis
- CPU / memory / GC / network: no meaningful change; one extra
Throwable[]slot replaces theIOException[]slot, andlog.erroris now emitted for each failing lifecycle (bounded by the number of lifecycles in one task). - Locks / concurrency: none added.
close()runs on the task thread; the array is only touched from that thread, so the single-element holder pattern is safe. - Resource release: strictly improved, since every initialized lifecycle now gets its close attempt.
- Retries / idempotency: see Issue 1 and Issue 2 below about the second
close()that the blocking worker issues after a failed teardown.
1.4 Error Handling and Logging
- Every failure is logged with its stack trace (
SeaTunnelTask.java:465), the first failure is preserved and rethrown, and later ones are suppressed onto it, so failure is never converted into success. CatchingThrowable(includingError) for a best-effort cleanup loop is an acceptable trade-off here because everything is logged and the first failure is still propagated.
Issue 1: The blocking worker's fallback close still only handles IOException
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:1312-1320 - Problem description: On the default blocking path, if
close()fails insidestateProcess(),call()throws,resultstaysnull, and thefinallyblock callstracker.task.close()a second time (L1314). With this PR that second pass now attempts every lifecycle (good), but it then rethrows the failure throughsneakyThrow, and the surroundingcatch (IOException e)at L1315 does not match an unchecked exception orError. The exception therefore escapesrun(), the "Close task error" line at L1316 is skipped, andThread.currentThread().setContextClassLoader(oldClassLoader)at L1320 is never reached. Issue #12231 explicitly mentions this fallback close. This is not a regression from this PR (the same escape existed before), but it is the other half of the same teardown story. - Potential risk: as far as I can tell, the pooled worker thread keeps the job classloader as its context classloader until it is reused or retired, and the exception surfaces to the executor instead of being handled where the close is performed. The per-lifecycle failures are already logged at
SeaTunnelTask.java:465, so diagnostics are not lost. - Best improvement: Option A (smallest): in
BlockingWorker.run()widencatch (IOException e)at L1315 tocatch (Throwable e)(keeping thelogger.severe("Close task error", e)). Option B: leave it for a small follow-up PR that references #12231. Either is fine; I would lean to Option A because it is one line and completes the goal. - Severity: Medium (non-blocking)
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
The Javadoc on close() (SeaTunnelTask.java:439-450) was updated to describe the new semantics, which is exactly what I like to see. Formatting looks consistent (Code style passed in the fork run). A tiny nit, no action required: the new tests import assertThrows statically while the rest of the class uses Assertions.xxx.
2.2 Test Coverage and Test Stability
The three new tests in SeaTunnelTaskStateTest.java are a good start:
testCloseAttemptsEveryCycleWhenEarlierCycleThrowsUnchecked(L443)testCloseAttemptsEveryCycleWhenEarlierCycleThrowsIoException(L462)testClosePreservesFirstFailureAndAttachesOthersAsSuppressed(L481)
They extend the existing test class, use mocks, and exercise the real close() through doCallRealMethod() (L444, L463, L482 override the doNothing() stub from setUp() at L101).
Issue 2: The tests do not yet cover everything the issue asked for
- Location:
seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/SeaTunnelTaskStateTest.java:440-509 - Problem description: #12231 lists "first/middle/last failures, multiple failures, and repeated cleanup attempts" as the expected coverage. Today the tests cover the failing lifecycle in first position (two tests) and three failures in a row, but not: (a) a failure in the middle or last position, (b) calling
close()a second time and asserting every lifecycle is attempted again, which is exactly what the blocking worker does after a failed teardown (see Issue 1), (c) an unchecked failure being the first one with a checked failure attached as suppressed (this exercises thesneakyThrowbranch with suppressed entries), and (d) anErrorsuch asAssertionError/LinkageError, since the Javadoc explicitly promisesErrorhandling. Also, the PR checklist says "teardown order preserved", but no test asserts the order;InOrderis already imported at L32 and can be used with the same mocks. - Potential risk: a later refactor of the catch clause or the rethrow branch could silently regress one of these paths without a failing test.
- Best improvement: add two or three small cases in the same class (for example a parameterized-style helper that places the failing mock at index 0, 1 and last; a second
task.close()call withverify(..., times(2)).close(); and aninOrder(first, second, third)verification). - Severity: Medium (non-blocking)
- Raised by another reviewer: No
Test stability rating: Stable. Evidence: no Thread.sleep or timing dependence, no external resources or ports, no shared static state (the task mock is rebuilt in @BeforeEach, L61-102), identity-based exception comparisons (assertSame at L500, contains on the suppressed array at L503-504) are deterministic, and the interface stubs are valid because FlowLifeCycle.close() declares throws IOException (FlowLifeCycle.java:28).
Issue 3: Guard against self-suppression inside the catch block
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:466-470 - Problem description:
Throwable#addSuppressedthrowsIllegalArgumentException("Self-suppression not permitted") if the argument is the same instance as the receiver. If two lifecycles ever rethrow the same cached exception instance (for example a shared component that stores its first failure and rethrows it on every close),closeException[0].addSuppressed(t)would itself throw from inside the catch block, escape the lambda, and abort the loop, which is the exact failure class this PR removes. - Potential risk: very unlikely today (I did not find such a case in the lifecycles I read), but the guard is cheap and this is a teardown path where nothing should be able to abort the loop.
- Best improvement:
else if (t != closeException[0]) { closeException[0].addSuppressed(t); }. A one-line test with a shared exception instance would lock it in. - Severity: Low
- Raised by another reviewer: No
2.3 Documentation Updates
No docs/en or docs/zh change is needed; this restores the intended "close everything, report the first failure" behavior and adds no option or user-visible setting. One small housekeeping request: the self-review checklist in the PR description is still unchecked, and it would help reviewers if you could tick the boxes that apply and fill in the standard PR template sections (user-facing change: none; how it was tested).
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. It changes only the teardown loop, reuses the existing sneakyThrow idiom already used in the same file, and keeps the first-failure-plus-suppressed pattern that was already there.
3.2 Maintainability
Clear and small. The Javadoc explains the contract. Once Issue 3 is applied the loop is robust against its own bookkeeping.
3.3 Extensibility
The same "attempt everything, keep first, suppress rest" pattern can be reused for the other teardown loops in the engine if similar gaps show up; nothing here is hard-coded to a single connector.
3.4 Historical-Version Compatibility
Compatible. Nothing serialized or persisted is touched, so rolling upgrades and checkpoint/savepoint restore are unaffected. Earlier PRs for the same issue (#12235 and #12237) were closed by their authors, so there is no duplicate open PR and no file conflict to worry about.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Blocking worker's fallback close only catches IOException, so an unchecked failure from the second close skips the classloader restore |
TaskExecutionService.java:1312-1320 |
Medium |
| 2 | Tests miss middle/last failure, repeated close(), Error, unchecked-first-with-checked-suppressed, and order verification |
SeaTunnelTaskStateTest.java:440-509 |
Medium |
| 3 | addSuppressed can throw on the same exception instance and abort the loop |
SeaTunnelTask.java:466-470 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge
-
Blockers — must be fixed
- None on the code side. The change is correct, minimal, and compatible. The only gate I can see is CI (details below).
-
Recommended fixes — non-blocking
CI status (read live on head 0663920): the Apache-side Build check is still in progress and points to the run in your fork (SeaSand1024/seatunnel, run 35419125384). At the time I looked, Code style, License header, Dependency licenses and Sanity check results had passed, and several jobs were still running (including the Ubuntu unit-test jobs and engine-v2-it). One job had already failed: unit-test (11, windows-latest) stopped in connector-http-paypal at PayPalClientTest.closeWakesRetryWait:416 (expected: <true> but was: <false>), after which Maven skipped the Engine : Server module in that job. That test lives in a connector this PR does not touch and is a timing wait on a Windows runner (this looks like a known unrelated timing flake; the wider-wait change #12370 is already in dev and in this branch, so syncing will not change the outcome). Because Engine : Server was skipped in that job, it says nothing yet about the new tests, so please let the remaining jobs finish, and re-run only the failed job afterwards. Once the Ubuntu unit tests are green, I have no further concerns.
Overall assessment: a well-scoped, correct fix for a real teardown leak, with a clear Javadoc and sensible tests. There is no better alternative design for this issue; the three notes above are polish that would make the change even more robust. Thanks again for the contribution, and please ping me if anything above is unclear. Happy to take another look after your next push!
- TaskExecutionService BlockingWorker fallback close now catches Throwable instead of IOException, so an unchecked close failure still logs "Close task error" and restores the context classloader (never aborts teardown). - SeaTunnelTask.close() skips addSuppressed when the same Throwable instance is thrown by multiple lifecycles, avoiding SelfSuppressionNotPermittedException aborting the teardown loop. - Extend SeaTunnelTaskStateTest with cases for middle/last failure positions, repeated close(), unchecked-primary with checked-suppressed, an Error, InOrder teardown order, and same-instance self-suppression (TDD: RED then GREEN). Co-Authored-By: Claude <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai>
davidzollo
left a comment
There was a problem hiding this comment.
+1 if CI passes.
LGTM
Thanks for your first contribution! This is a solid addition to the project, and your attention to detail really shows. Contributors like you are what keep this community moving forward. Feel free to keep the PRs coming — we're always glad to have you here!
Please ignore the following message if you have joined in the Slack~
To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack
This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄
|
@DanielLeens the non-blocking notes are in on
No user-facing change. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you, @SeaSand1024, for turning the follow-ups around so quickly, and for the clear summary comment. I re-read the whole PR from scratch on the new head (0fc63dc), not only the delta since 0663920, and traced the close path again end to end. Short version: all three points from my previous review are resolved, and I found no new blocking issue. Nice work!
What changed since my last review (0663920 -> 0fc63dc, one commit):
TaskExecutionService.java:1314now catchesThrowablein theBlockingWorkerfallback close (previous Issue 1: resolved).SeaTunnelTaskStateTest.javagained the middle/last failure, repeatedclose(), unchecked-primary-with-checked-suppressed,Error, teardown-order and shared-instance cases (previous Issue 2: resolved).SeaTunnelTask.java:468now guardsaddSuppressedwitht != closeException[0](previous Issue 3: resolved).
I also want to +1 @davidzollo's approval: I agree with it, and the only remaining gate is CI (details at the end).
What Problem Does This PR Solve?
- User pain point:
SeaTunnelTask.close()only caughtIOExceptionaround eachFlowLifeCycle.close(). An unchecked exception from one lifecycle (for example a connectorSinkWriter#close()orSourceReader#close()) escaped the teardown loop, so every later lifecycle was never closed and its threads, connections and buffers leaked. - Fix approach: catch
Throwableper lifecycle, keep the teardown order, remember the first failure, attach later ones withaddSuppressed(skipping the same instance), and rethrow the first failure at the end. The blocking worker's fallback close now also tolerates unchecked failures. - Example: a task has
[source, transform, sink-A, sink-B]andsink-A.close()throwsIllegalStateException. Before:sink-Bwas never closed. Now:sink-Bis closed, the task still fails with theIllegalStateException, and any other close failure is attached to it as suppressed.
1. Code Change Review
1.1 Core Logic Analysis
Changed code (head 0fc63dc):
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:452-479(close())seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:1312-1316(BlockingWorker.run()finally block)- tests in
SeaTunnelTaskStateTest.java:440-654
Before (dev):
IOException[] closeException = {null};
try { super.close(); } catch (IOException e) { closeException[0] = e; }
... forEach(flowLifeCycle -> {
try { flowLifeCycle.close(); }
catch (IOException e) { log; keep first; else addSuppressed(e); }
});
if (closeException[0] != null) { throw closeException[0]; }After (SeaTunnelTask.java:453-478):
Throwable[] closeException = {null};
try { super.close(); } catch (Throwable t) { closeException[0] = t; }
... forEach(flowLifeCycle -> {
try { flowLifeCycle.close(); }
catch (Throwable t) {
log.error("Close FlowLifeCycle error.", t);
if (closeException[0] == null) { closeException[0] = t; }
else if (t != closeException[0]) { closeException[0].addSuppressed(t); }
}
});
if (closeException[0] != null) {
if (closeException[0] instanceof IOException) { throw (IOException) closeException[0]; }
sneakyThrow(closeException[0]);
}And in TaskExecutionService.java:1312-1316: catch (IOException e) became catch (Throwable e) (the now-unused java.io.IOException import was removed, which is correct).
Key findings
- The normal user path reaches this code. With the default thread-share mode (
OFF), every task runs onBlockingWorker. A task that finishes or is cancelled reachescase CLOSED/case CANCELLINGinSeaTunnelTask.stateProcess(), which callsthis.close()(SeaTunnelTask.java:292-298). A task that fails earlier reachestracker.task.close()in the worker'sfinally(TaskExecutionService.java:1310-1316). This is routine teardown, not a rare corner. - The reported leak is real.
SinkFlowLifeCycle.close()(SinkFlowLifeCycle.java:277-283) andSourceFlowLifeCycle.close()(SourceFlowLifeCycle.java:216-224) delegate to connector code (writer.close(),reader.close()) that may throw unchecked exceptions, andTransformFlowLifeCycle.close()andIntermediateQueueFlowLifeCycle.close()(IntermediateQueueFlowLifeCycle.java:65-68) are also part of the same loop. OndevtheIOException-only catch skipped everything after the first unchecked failure. - Teardown order is preserved. The stream in
allCycles.stream()is sequential, so the loop still closes lifecycles in list order. - The rethrow compiles and behaves correctly.
sneakyThrow(Throwable)(ExceptionUtil.java:125-127) is already statically imported in this file (SeaTunnelTask.java:86); anIOExceptionkeeps its declared type, so thethrows IOExceptionsignature and existing callers are unchanged. - The self-suppression guard is correct.
Throwable#addSuppressed(self)throwsIllegalArgumentException; thet != closeException[0]check (SeaTunnelTask.java:468) prevents that from escaping the lambda and aborting the loop.
Runtime path (default blocking worker):
task reaches CLOSED / CANCELLING state (SeaTunnelTask.stateProcess, L292-298)
-> SeaTunnelTask.close() (L452-479)
-> super.close() // AbstractTask.close() swallows Exception itself
-> for each FlowLifeCycle, in order:
close() ; on ANY Throwable: log + keep first + addSuppressed (skip same instance)
-> rethrow first failure (IOException as-is, others via sneakyThrow)
-> exception leaves call() -> BlockingWorker.run() catch Throwable (L1302-1309)
-> finally: taskDone(t); result == null -> tracker.task.close() again (L1310-1313)
-> any Throwable from that second close is now logged "Close task error" (L1314-1315)
-> Thread.currentThread().setContextClassLoader(oldClassLoader) (L1318) is now always reached
With thread-share mode ON, the cooperative worker already catches Throwable around task.call() (TaskExecutionService.java:1437), so that path needed no change.
1.2 Compatibility Impact
Fully compatible. No config option, default value, protocol, serialization format, checkpoint/savepoint state or public API is touched, and close() still declares throws IOException. The only behavior change is that cleanup which used to stop early on an unchecked failure now runs to completion, and the caller still sees the first failure. No entry in incompatible-changes.md is needed.
1.3 Performance / Side-Effect Analysis
- CPU / memory / GC / network: no meaningful change. One extra
log.errorper failing lifecycle, bounded by the number of lifecycles in a task. - Locks / concurrency: none added. The single-element array is only touched by the task thread that runs
close(). - Interrupt handling: no
InterruptedExceptioncan be thrown byFlowLifeCycle.close()(it declares onlyIOException), so nothing new swallows an interrupt. Continuing the loop when a close fails because of an interrupt-triggered unchecked exception is exactly the intent of this best-effort teardown. - Resource release: strictly improved. Every initialized lifecycle now gets its close attempt, and the worker thread's context classloader is restored even when the fallback close fails unexpectedly.
- Double close on failure (informational, not a new issue): when
close()fails insidestateProcess(), the blocking worker callstask.close()a second time (TaskExecutionService.java:1313). That second call already existed before this PR for the lifecycles that precede the failing one; it now covers all lifecycles. The lifecycles I read are tolerant of a repeat call (AbstractFlowLifeCycle.close()just completes a future,SourceFlowLifeCycle.closeFlushTimer()is null-guarded), and any repeat failure is only logged and suppressed, so I do not see a correctness risk. The new testtestCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTimedocuments this contract. - Checkpoint / restore: not touched. The close path only runs at task end, and no state serialization or barrier handling is involved.
1.4 Error Handling and Logging
No blocking issues found.
- Every failure is logged with its stack trace (
SeaTunnelTask.java:465), the first failure is preserved and rethrown, and later ones are attached as suppressed, so a failure is never converted into success. CatchingThrowable(includingError) around a best-effort cleanup loop is an acceptable trade-off here because everything is logged and the first failure is still propagated to the caller. - The log message and severity are unchanged for the
IOExceptioncase, so there is no hidden change in log volume for existing deployments.
Status of my previous review points
- Previous Issue 1 (fallback close only catches
IOException, so the classloader restore could be skipped): resolved atTaskExecutionService.java:1314. - Previous Issue 2 (missing middle/last/repeat/
Error/mixed-suppressed/order coverage): resolved, see 2.2. - Previous Issue 3 (
addSuppressedself-suppression guard): resolved atSeaTunnelTask.java:468, with a dedicated test.
2. Code Quality Assessment
2.1 Coding Standards
The Javadoc on close() (SeaTunnelTask.java:439-451) was updated to describe the new contract (checked, unchecked and Error; first failure preserved; later failures suppressed), which is exactly what a teardown method needs. Formatting is consistent and Code style passes in the fork run. No new non-trivial fields or methods were added, so there is nothing else that needs comments.
2.2 Test Coverage and Test Stability
The PR extends the existing SeaTunnelTaskStateTest (no new test class), which is the right place. The new tests at SeaTunnelTaskStateTest.java:443-654 cover:
- earlier failure, unchecked and
IOException(L443, L462); - three mixed failures with first preserved and the rest suppressed (L481);
- middle and last position failures (L512, L534);
- repeated
close()(L553); - unchecked primary with checked suppressed, i.e. the
sneakyThrowbranch (L571); - an
Error(L595); - teardown order via
InOrder(L615); - a shared exception instance (L635).
That matches the acceptance list in #12231, and the assertions are exact (assertSame on the propagated instance and on suppressed entries, verify(..., times(n))), so they would catch a regression in the catch clause or in the rethrow branch. Mock setup is valid because FlowLifeCycle.close() declares throws IOException (FlowLifeCycle.java:28), so doThrow(new IOException(...)) is legal, and the real close() runs via doCallRealMethod() over the CALLS_REAL_METHODS mock, with restoreComplete completed in setUp() (L86-88) so super.close() behaves normally. I did not find any weakening of existing tests: the diff only adds imports and new test methods.
Test stability rating: Stable. Evidence: pure Mockito, no Thread.sleep or timing dependence, no ports or external resources, no shared static state (the task mock and cycle list are rebuilt in @BeforeEach, L61-102), each test installs its own allCycles list, and there is no order dependence between tests.
2.3 Documentation Updates
Not required: this is an internal cleanup fix with no option, default or user-visible behavior change, so there is nothing to update in docs/en or docs/zh. The PR description checklist is now filled in, thank you.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. It only touches the teardown loop and the worker's fallback close, reuses the sneakyThrow idiom already present in this file, and keeps the existing first-failure-plus-suppressed pattern.
3.2 Maintainability
Small and clear, with an accurate Javadoc. The Throwable[] holder is the same pattern the method already used.
3.3 Extensibility
The same "attempt everything, keep first, suppress rest" pattern can be reused by other teardown loops in the engine if similar gaps show up; nothing here is connector-specific.
3.4 Historical-Version Compatibility
Compatible. Nothing serialized or persisted is touched, so rolling upgrades and checkpoint/savepoint restore are unaffected.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| - | No blocking or recommended issues found on head 0fc63dc |
- | - |
5. Merge Recommendation
Conclusion: Ready to merge
Blockers - must be fixed
- None on the code side.
Recommended fixes - non-blocking
- None. All three follow-ups from my previous review are done.
Overall assessment: a well-scoped, correct fix for a real teardown leak, now with the fallback close, the self-suppression guard and the full failure-position test matrix in place. I checked that the normal (default blocking worker) path reaches the changed logic, that teardown order and first-failure semantics are preserved, and that nothing serialized or persisted changes. There is no better alternative design for this issue. I agree with @davidzollo's approval; the merge gate is CI only.
CI (read live for head 0fc63dc): the Apache-side Build check is in_progress and points to the run in your fork (SeaSand1024/seatunnel, run 35424513689, currently queued/in_progress). At the time I looked, Code style, License header, Dependency licenses, Sanity check results, Dead links and both unit-test (8|11, windows-latest) jobs had passed, the Ubuntu unit-test (8|11) jobs and several integration jobs were still running, and no job had failed yet. I cannot call the PR verified until the Ubuntu unit-test jobs (which run SeaTunnelTaskStateTest) finish green. If one turns red on a connector module this PR does not touch, please re-run only that failed job rather than the whole workflow.
Thanks again for the contribution, and welcome to the project!
🤖 Generated with Claude Code
|
@DanielLeens thanks for confirming #12391 as the path for this issue and for the CI gate note. Following up on the Build failure on tip
I am re-running the failed Build jobs on the fork now. I will not broaden #12391 with the #12353/#12377 cancel-race fix so this PR stays scoped to the lifecycle-close contract. Happy to follow whatever you prefer if Build stays blocked on that known race after the re-run. |
|
@SeaSand1024 thanks for the quick turnaround on On the changes themselves: the On the Build failures, I agree with your read and with keeping #12391 scoped to the lifecycle-close contract rather than pulling in the #12353 / #12377 cancel-race fix. A couple of concrete asks so we can land this cleanly:
No need to push anything else unless the re-run surfaces something new. |
|
Thanks for the clear CI breakdown, @SeaSand1024, and for keeping this PR scoped. I would keep it exactly as it is: please do not fold the #12353 / #12377 cancel-race fix into #12391. That fix touches On my side, the source-level points from my last review on What I can see from the fork run for this head (run attempt 3): the failed jobs are
Suggested next step: use "Re-run failed jobs" only, and do not add unrelated changes to this branch. If the same two jobs stay red after a re-run, please paste the new failing job links here and I will take another look at that exact head. A committer can then decide whether to merge on the strength of the green unit-test matrix plus the known-flake attribution, or wait for #12311 / #12377 to land first. |
|
@SeaSand1024 thanks for the CI breakdown on Agreed on scope: please do not fold the #12353 / #12377 cancel-race fix into #12391. That touches On the code side, the three points from the earlier review (the Remaining asks, all CI-related:
Once the re-run result is posted, we can decide whether to merge on the green unit-test matrix plus the known-flake attribution, or wait for #12311 / #12377 to land first. |
|
@DanielLeens @SEZ9 the failed-jobs re-run on head Unit-test matrix stayed green. engine-v2-it
all-connectors-it-2
No further commits on this branch. Happy to wait for a committer decision: merge on the green unit-test matrix plus these attributions, or wait for #12311 / #12377. |
|
@SeaSand1024 @SEZ9 thanks for the detailed re-run breakdown — this is exactly the kind of evidence that lets us close this out without guessing. I re-checked first: head is still Good news first: The other three failures are pre-existing
So: sync No further code-side asks from me. Thanks again for staying on top of the CI noise instead of folding unrelated fixes in — that made this easy to untangle. |
|
@SeaSand1024 nothing new from me beyond my last comment, just to keep the next step clear:
Once the |
|
Synced latest
|
|
Thanks @SeaSand1024 for the sync and the direct job links. I checked this the same way as last time: On the CI picture: My conclusion is unchanged: the code side has been ready since my last review, and the one CI gap that was attributable to something fixable (the Opengauss job) is now closed. This is ready to merge on the green unit-test matrix plus the now-green |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks again for staying on this, @SeaSand1024. My last formal gh pr review submission was against 0fc63dc5 (COMMENTED); since then the branch picked up a dev sync (merge 57890813b) and my own follow-up comments confirmed that sync touched none of this PR's three files. Rather than leave the formal review state stuck on the old commit, I re-read the whole PR from scratch on the current head (57890813b) end to end, one more time, following the full checklist rather than relying on my earlier notes. Short version: nothing in the actual diff changed since 0fc63dc5, all three points from my very first review are still resolved, and I did not find a new blocking issue in the reviewed files. I did surface one out-of-scope, pre-existing observation in adjacent (unchanged) code that is worth a follow-up — details in Issue 1 below, not a blocker for this PR. I also want to +1 @davidzollo's approval and agree with @SEZ9's read of the CI picture.
What Problem Does This PR Solve?
- User pain point:
SeaTunnelTask.close()only caughtIOExceptionaround eachFlowLifeCycle.close(). An unchecked exception thrown by one lifecycle (for example a connectorSinkWriter#close()orSourceReader#close()) escaped the teardownforEach, so every lifecycle after the failing one was never closed, and its executors, connections and buffers leaked. - Fix approach: catch
Throwableper lifecycle instead of onlyIOException, keep the teardown order, remember the first failure, attach later failures to it viaaddSuppressed(skipping the case where the same instance is thrown twice), and re-throw the first failure at the end (IOExceptionas-is, everything else via the existingsneakyThrowidiom). The blocking worker's fallback close (TaskExecutionService.java) now also tolerates unchecked failures so the context classloader restore always runs. - Example: a task has
[source, transform, sink-A, sink-B]andsink-A.close()throwsIllegalStateException. Before:sink-Bis never closed. After:sink-Bis still closed, the task still fails with the originalIllegalStateException, and any other close failure is attached to it as suppressed.
1. Code Change Review
1.1 Core Logic Analysis
Changed code at head 57890813b (unchanged from 0fc63dc5):
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:452-479(close())seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:1312-1316(BlockingWorker.run()finally block)seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/SeaTunnelTaskStateTest.java:440-654(tests)
Before (dev):
IOException[] closeException = {null};
try { super.close(); } catch (IOException e) { closeException[0] = e; }
... forEach(flowLifeCycle -> {
try { flowLifeCycle.close(); }
catch (IOException e) { log; keep first; else addSuppressed(e); }
});
if (closeException[0] != null) { throw closeException[0]; }After (SeaTunnelTask.java:453-478):
Throwable[] closeException = {null};
try { super.close(); } catch (Throwable t) { closeException[0] = t; }
... forEach(flowLifeCycle -> {
try { flowLifeCycle.close(); }
catch (Throwable t) {
log.error("Close FlowLifeCycle error.", t);
if (closeException[0] == null) { closeException[0] = t; }
else if (t != closeException[0]) { closeException[0].addSuppressed(t); }
}
});
if (closeException[0] != null) {
if (closeException[0] instanceof IOException) { throw (IOException) closeException[0]; }
sneakyThrow(closeException[0]);
}And in TaskExecutionService.java:1312-1316, catch (IOException e) became catch (Throwable e) (the now-unused java.io.IOException import was correctly removed).
Key findings, independently re-verified this round:
- The normal path reaches this code. The default
task-execution-thread-share-modeisOFF, so every task runs onBlockingWorker. A task that finishes or is cancelled reachescase CLOSED/case CANCELLINGinSeaTunnelTask.stateProcess()(SeaTunnelTask.java:292-298), which callsthis.close(). A task that fails earlier reachestracker.task.close()in the worker'sfinally(TaskExecutionService.java:1310-1316). This is routine teardown, not a rare corner. - The leak is real.
SinkFlowLifeCycle.close()(SinkFlowLifeCycle.java:277-283) delegates towriter.close(),SourceFlowLifeCycle.close()(SourceFlowLifeCycle.java:216-224) delegates toreader.close(), andTransformFlowLifeCycle.close()/IntermediateQueueFlowLifeCycle.close()are also part of the same loop. Connector-suppliedwriter.close()/reader.close()are free to throw unchecked exceptions, and ondevtheIOException-only catch really did skip everything after the first unchecked failure. - Teardown order is preserved.
allCycles.stream()is a plain sequentialStreamfrom aList, andMDCTracer.tracing(Stream)(seatunnel-api/.../tracing/MDCTracer.java) just wraps it in anMDCStreamthat delegatesforEachto the same sequential stream, so the loop still closes lifecycles in list order. The newtestClosePreservesTeardownOrderAcrossLifecyclestest locks this in withInOrder. - The rethrow is correct.
ExceptionUtil.sneakyThrow(Throwable t)(seatunnel-engine-common/.../ExceptionUtil.java:125-127) is the classic unchecked-generics sneaky-throw and is already used elsewhere in this file (SeaTunnelTask.java:86,619,CheckpointCoordinator.java). There is a second, narrower overloadsneakyThrow(Exception t)in the same class, but sincecloseException[0]is statically typedThrowable, only theThrowableoverload is applicable — no ambiguity, no accidental narrowing. - The self-suppression guard is correct.
Throwable#addSuppressed(self)throwsIllegalArgumentException; thet != closeException[0]check atSeaTunnelTask.java:468prevents that from escaping the lambda and aborting the loop.testCloseDoesNotSelfSuppressSameFailureInstanceexercises exactly this. super.close()being widened to catchThrowableis defensive, not load-bearing.AbstractTask.close()(AbstractTask.java:98-105) already swallows everything it can throw (catch (Exception ignore)), so in practice this branch only matters ifrestoreComplete.cancel(true)ever threw anError, which is unrelated to this PR.
Runtime path (default blocking worker), re-traced against the current head:
task reaches CLOSED / CANCELLING state (SeaTunnelTask.stateProcess, L292-298)
-> SeaTunnelTask.close() (L452-479)
-> super.close() // AbstractTask.close() already swallows Exception itself
-> for each FlowLifeCycle, in order:
close() ; on ANY Throwable: log + keep first + addSuppressed (skip same instance)
-> rethrow first failure (IOException as-is, others via sneakyThrow)
-> exception leaves call() -> BlockingWorker.run() catch Throwable (L1302-1309)
-> finally: taskDone(t); result == null -> tracker.task.close() again (L1310-1313)
-> any Throwable from that second close is now logged "Close task error" (L1314-1315)
-> Thread.currentThread().setContextClassLoader(oldClassLoader) (L1318) is now always reached
With thread-share mode ON, the cooperative worker already catches Throwable around task.call() (TaskExecutionService.java:1437), so that path needed no change, as noted in the previous round.
1.2 Compatibility Impact
Fully compatible. No config option, default value, protocol, serialization format, checkpoint/savepoint state or public API is touched, and close() still declares throws IOException. The only behavior change is that cleanup which used to stop early on an unchecked failure now runs to completion, and the caller still sees the first failure. No entry in incompatible-changes.md is needed.
1.3 Performance / Side-Effect Analysis
- CPU / memory / GC / network: no meaningful change; one extra
log.errorper failing lifecycle, bounded by the number of lifecycles in a task. - Locks / concurrency: none added; the single-element
Throwable[]holder is only touched by the task thread runningclose(). - Resource release: strictly improved for the loop itself — every initialized lifecycle now gets a close attempt, and the worker thread's context classloader is restored even when the fallback close in
TaskExecutionServicefails unexpectedly. - Double close on failure (already discussed in the previous round, re-confirmed here): when
close()fails insidestateProcess(), the blocking worker callstask.close()a second time (TaskExecutionService.java:1313), which now re-attempts every lifecycle.testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTimedocuments that this is safe at theSeaTunnelTaskloop level.
Issue 1 (new, out of scope for this PR): per-lifecycle close() still doesn't guarantee its own state gets torn down if an earlier step inside that same lifecycle throws.
- Location:
SourceFlowLifeCycle.java:216-224,TransformFlowLifeCycle.java:352-373,IntermediateQueueFlowLifeCycle.java:64-67— none of these files are touched by this PR. - Problem description:
AbstractFlowLifeCycle.close()(AbstractFlowLifeCycle.java:44-46) completes a per-lifecyclecompletableFuture, andSeaTunnelTask.init()(SeaTunnelTask.java:189-190) aggregates all of these viaCompletableFuture.allOf(flowFutures).whenComplete((s, e) -> closeCalled = true), which in turn gates thePREPARE_CLOSE -> CLOSEDstate transition (SeaTunnelTask.java:283-289). Of the fourFlowLifeCycleimplementations in the loop this PR fixes, onlySinkFlowLifeCycle.close()(SinkFlowLifeCycle.java:276-279) callssuper.close()first, before its ownwriter.close().SourceFlowLifeCycle.close()callsreader.close()beforesuper.close();TransformFlowLifeCycle.close()callst.close()/errorHandler.close()beforesuper.close();IntermediateQueueFlowLifeCycle.close()callsqueue.close()beforesuper.close(). None of these three wrap the resource-specific step intry/finally, so if that step throws,super.close()— and therefore that lifecycle's owncompletableFuture.complete(null)— is skipped for that lifecycle instance. - Potential risk: in isolation this looks concerning (an unfinished
completableFuturecould in theory leavecloseCalledpermanentlyfalse), but I traced the actual production trigger forcloseCalledand it isAbstractTask.tryClose(long)→closeCall()(AbstractTask.java:122-127, called fromSeaTunnelTask.java:574,580,586on checkpoint-barrier completion), which setscloseCalled = truedirectly and does not depend onflowFutures. I could not find any call site that invokes an individualFlowLifeCycle#close()beforeSeaTunnelTask.close()itself runs, so in the code paths I traced, theflowFutures/allOfwiring never gets a chance to be the deciding factor in practice —closeCalledis alreadytruevia the checkpoint-barrier path by the timeSeaTunnelTask.close()(this PR's loop) runs. I want to be explicit that this is inference from reading the call graph, not something I ran; I'm flagging it as a real but low-confidence architectural gap rather than a proven hang. - Why it's out of scope here: all three files are untouched by this diff, and this PR's fix is precisely scoped to the outer
SeaTunnelTask.close()loop (consistent with the earlier scoping discussion in this thread about not folding in the unrelatedSubPlancancel-race fix). Fixing per-lifecycletry/finallyordering is a separate, larger change across four classes and deserves its own PR and its own tests. - Best improvement (for a follow-up, not this PR): wrap the resource-specific step of each lifecycle's
close()intry { ... } finally { super.close(); }, mirroring the "close everything, report first failure" contract this PR already establishes at the task level. - Severity: Low
- Raised by another reviewer: No
1.4 Error Handling and Logging
No blocking issues found.
- Every failure is logged with its stack trace (
SeaTunnelTask.java:465), the first failure is preserved and rethrown, and later ones are attached as suppressed, so a failure can never silently turn into success. - Catching
Throwable(includingError) around a best-effort cleanup loop is an acceptable trade-off here because everything is logged and the first failure is still propagated to the caller — this is not a case of an exception being swallowed without a trace. - No secrets or sensitive data appear in any of the new log statements.
Status of the three issues from my previous rounds (re-verified against the current head, not just trusted from memory):
- Previous Issue 1 (fallback close only caught
IOException, so the classloader restore could be skipped): still resolved,TaskExecutionService.java:1314catchesThrowable. - Previous Issue 2 (missing middle/last/repeat/
Error/mixed-suppressed/order coverage): still resolved, see 2.2. - Previous Issue 3 (
addSuppressedself-suppression guard): still resolved,SeaTunnelTask.java:468, with a dedicated test.
2. Code Quality Assessment
2.1 Coding Standards
The Javadoc on close() (SeaTunnelTask.java:420-431) describes the contract accurately (checked, unchecked and Error; first failure preserved; later failures suppressed). One small, non-blocking documentation nit I hadn't called out before: the @throws list only names IOException and RuntimeException, but the prose above it (and the testCloseAttemptsEveryCycleWhenCycleThrowsError test) also covers an Error being rethrown as the first failure. Error doesn't need to be declared, so this isn't incorrect, just slightly incomplete relative to the prose — feel free to add an @throws Error line or leave it, this is cosmetic. Formatting is consistent and Code style passes in the fork run.
2.2 Test Coverage and Test Stability
The PR extends the existing SeaTunnelTaskStateTest (correctly, no new test class). The tests at SeaTunnelTaskStateTest.java:443-654 cover: earlier failure unchecked/IOException (L443, L462), three mixed failures with first preserved and rest suppressed (L481), middle and last position failures (L512, L534), repeated close() (L553), unchecked-primary-with-checked-suppressed i.e. the sneakyThrow branch (L571), an Error (L595), teardown order via InOrder (L615), and a shared exception instance (L635). I re-read every one of these on the current head rather than assuming they matched my notes from 0fc63dc5, and they are byte-identical. The assertions are exact (assertSame on the propagated/suppressed instances, verify(..., times(n)), InOrder), so they would catch a regression in the catch clause or the rethrow branch. Mock setup is valid because FlowLifeCycle.close() declares throws IOException, and the real close() runs via doCallRealMethod() with restoreComplete pre-completed in setUp().
Test stability rating: Stable. Evidence: pure Mockito, no Thread.sleep or timing dependence, no ports or external resources, no shared static state (task and allCycles are rebuilt in @BeforeEach, L61-102), each test installs its own allCycles list, and there is no order dependence between tests.
2.3 Documentation Updates
Not required: this is an internal teardown-reliability fix with no option, default or user-visible behavior change, so docs/en/docs/zh need no update.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise, minimal fix that only touches the teardown loop and the worker's fallback close, reuses the sneakyThrow idiom already present in this file, and keeps the existing first-failure-plus-suppressed pattern.
3.2 Maintainability
Small and clear, with an accurate (if slightly incomplete, see 2.1) Javadoc. The Throwable[] holder is the same pattern the method already used for IOException[].
3.3 Extensibility
The "attempt everything, keep first, suppress rest" pattern is reusable by other teardown loops in the engine. As noted in Issue 1, the natural next step is applying the same discipline inside each individual FlowLifeCycle#close() implementation, but that is a separate, larger change.
3.4 Historical-Version Compatibility
Compatible. Nothing serialized or persisted is touched, so rolling upgrades and checkpoint/savepoint restore are unaffected.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Per-lifecycle close() in SourceFlowLifeCycle/TransformFlowLifeCycle/IntermediateQueueFlowLifeCycle doesn't guarantee super.close() (and its future) runs if the resource-specific step throws first — pre-existing, out of scope for this PR, worth a follow-up |
SourceFlowLifeCycle.java:216-224, TransformFlowLifeCycle.java:352-373, IntermediateQueueFlowLifeCycle.java:64-67 |
Low |
No blocking issues in the files this PR actually changes.
5. Merge Recommendation
Conclusion: Ready to merge
Blockers — must be fixed
- None on the code side.
Recommended fixes — non-blocking
- Issue 1 (Low): a follow-up PR to give each
FlowLifeCycle#close()implementation the same "close everything, guarantee the future completes" discipline this PR just gave the outer loop. Not required for this PR. - The
@throwsJavadoc nit in 2.1, purely cosmetic.
Overall assessment: I re-read the whole PR from scratch on the current head (57890813b) rather than relying on my earlier review of 0fc63dc5, and the diff for this PR's three files is byte-for-byte identical — the only thing that changed was picking up 28 unrelated dev commits via a sync merge. All three issues from my first review are still resolved, the fix is correct, minimal, and compatible, and the test matrix (failure position, repeat close, mixed exception types, Error, ordering, self-suppression) matches the acceptance criteria from #12231. I agree with @davidzollo's approval.
CI (read live for head 57890813b): The Apache-side Build check is currently FAILURE, pointing at the fork run SeaSand1024/seatunnel run 35870424836. I read the actual job list and logs for that run rather than trusting job names alone:
engine-v2-it (8, ubuntu-latest)fails onBackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressureandSplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck— these are exactly the two pre-existing, already-tracked flakes discussed earlier in this thread (open fixes #12316/#12313 and #12311, none merged todevyet), unrelated to the files this PR touches.- Two more jobs failed that weren't mentioned in the last CI update:
all-connectors-it-5 (8, ubuntu-latest)fails onOceanBaseCDCCompatibilityIT.testOceanBaseCdcWrapperRuntimeE2e(a Flink-runtime OceanBase CDC E2E failure), andtransform-v2-it-part-1 (11, ubuntu-latest)fails onTestFilterRowKindIT.testFilterRowKindMultiTable:53(expected: <0> but was: <1>). Neither test touchesseatunnel-engine-server, Zeta task lifecycle, or anything in this PR's diff, so I read these as unrelated to this change as well, though I have not root-caused either one and can't yet say whether they're flaky or a realdev-level regression from one of the 28 synced commits. all-connectors-it-2, which was the one confirmed-fixable failure (via #12346), is green on both JDKs as reported.
Given none of the four remaining red jobs touch the code this PR changes, and the source-level review is clean, a committer could reasonably merge on the strength of this review plus the attribution above. If you'd like tighter confidence on all-connectors-it-5 / transform-v2-it-part-1 specifically (since they're new to this thread), a "re-run failed jobs" on just those two would help confirm flakiness versus a real dev regression, but I wouldn't block this PR on that given they are outside the diff.
Thanks again for the thorough work here, and sorry for the extra round-trip on the formal review state — the technical conclusion hasn't changed since my first pass, but I wanted the recorded review to actually reflect the current head rather than 0fc63dc5.
|
@SeaSand1024 thanks for syncing Checked on my side:
No remaining asks from me on the previously raised point; the CI gap that was attributable to this branch being behind |
|
@SeaSand1024 @SEZ9 one correction to my last comment before we call this ready to merge. I went back through fork run
The second one I can close out the same way we closed the Opengauss job: it's a known, already-filed flake. #12116 describes exactly this test failing intermittently only on Flink legs, because The OceanBase one I can't close the same way yet. I didn't find a pre-filed issue for this exact test/symptom, and I only have this one occurrence to go on. Both failing tests run against the Flink translation layer rather than the Zeta engine For completeness: So: the code side is still ready, and most of the CI picture still stands, but I'd like to hold off on "ready to merge" specifically until the |
|
Quick follow-up on where this stands from my side. My last formal review submission was against The one thing still open before I'd refresh my formal review state on the current head is the CI picture from fork run
Concrete ask: please re-run just |
|
@SEZ9 agreed, and thanks for keeping this current -- we're asking for the same thing, so there's nothing new to add on my side. To be precise about where things stand as of this reply:
Once @SeaSand1024 posts the |
|
Re-ran |
|
@DanielLeens @SEZ9 follow-up on the Result: still failure — https://github.com/SeaSand1024/seatunnel/actions/runs/35870424836/job/110327089414 Same test as before: So the repeat failure is on the Flink translation legs only; the Zeta/ |
|
Triage on the repeat
|
|
@DanielLeens @SEZ9 follow-up on tip Closed out from last ask: Build still reports FAILURE on that run for three other jobs (none are close-path / OceanBase). Attribution from the logs:
Failed-jobs re-run for those three: https://github.com/SeaSand1024/seatunnel/actions/runs/36852053400 — will post results when finished. No new commits; close-path untouched. |
SEZ9
left a comment
There was a problem hiding this comment.
Thanks for working on this. I reviewed the latest head 2cc06fc4395f.
What this PR fixes
- User pain: On task teardown, a single
FlowLifeCycle.close()throwing an unchecked exception escapedSeaTunnelTask.close()(which only caughtIOException), so every later lifecycle inallCycleswas never closed, leaking executors, connections and buffers (#12231). - Fix approach:
SeaTunnelTask.close()now catchesThrowablearoundsuper.close()(SeaTunnelTask.java:456) and eachflowLifeCycle.close()(:464), keeps the first failure, attaches later distinct failures viaaddSuppressedguarded byt != closeException[0](:468), and rethrows anIOExceptionas-is (:474-475) or anything else viasneakyThrow(:477);BlockingWorker's fallbacktracker.task.close()now catchesThrowableinstead ofIOException(TaskExecutionService.java:1314) so an unchecked close failure is logged and the context classloader is still restored; ten new unit tests inSeaTunnelTaskStateTestcover the loop semantics. - One-line summary: The core leak is fixed and well-tested in isolation, but the widened
catch (Throwable)also traps JVM-fatal errors,close()is still not idempotent so a failing lifecycle on the CLOSED/CANCELLING path now triggers a second full teardown pass via theBlockingWorkerfallback, the@throwsJavadoc does not match the actual control flow (AbstractTask.close()swallows allExceptions, so only anErrorcan be collected at :456-457), and the end-to-endBlockingWorkerpath has no test.
Runtime chain I rechecked
TaskExecutionService.BlockingWorker.run() TaskExecutionService.java:1288-1318
-> t.init(); loop t.call() TaskExecutionService.java:1290-1295
-> SeaTunnelTask.stateProcess() case CLOSED/CANCELLING -> this.close() SeaTunnelTask.java:293 / :298
-> SeaTunnelTask.close() SeaTunnelTask.java:452
-> super.close() [AbstractTask.close(), swallows all Exception] AbstractTask.java:99-106; caught as Throwable at SeaTunnelTask.java:456
-> allCycles.stream().forEach(flowLifeCycle.close()) SeaTunnelTask.java:459-463
catch (Throwable t) -> first kept / addSuppressed if t != first SeaTunnelTask.java:464-470
-> rethrow: IOException as-is (:474-475) or sneakyThrow(:477)
-> if close() throws, progress.done() at :294/:300 is skipped, exception propagates out of call()
-> BlockingWorker catch (Throwable e) -> taskGroupExecutionTracker.exception(e) TaskExecutionService.java:1302-1308
-> finally: result == null || !result.isDone() -> tracker.task.close() [second full pass over allCycles] TaskExecutionService.java:1311-1313
catch (Throwable e) -> logger.severe("Close task error", e) TaskExecutionService.java:1314-1315
-> Thread.currentThread().setContextClassLoader(oldClassLoader) TaskExecutionService.java:1319
Findings
Issue 1: Because close() now always completes the full pass and then rethrows, any single lifecycle close failure on the normal CLOSED/CANCELLING path causes every lifecycle (including the ones that closed cleanly) to be closed a second time by the BlockingWorker fallback, and close() itself is not idempotent.
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:477 - Why it matters: - Root cause: the rethrow at
SeaTunnelTask.java:473-477is reached fromstateProcess()case CLOSED: this.close(); progress.done();(lines 293-294) and the equivalentCANCELLINGbranch (lines 298-300). When any lifecycle throws,progress.done()is skipped, the exception propagates toBlockingWorker.run()'scatch (Throwable e)(TaskExecutionService.java:1302), and thefinallyseesresult == null || !result.isDone()(:1311) and callstracker.task.close()again (:1313). With this PR the first pass is guaranteed to have already visited every lifecycle, so the second pass re-runsSinkFlowLifeCycle.close(),SourceFlowLifeCycle.close()andIntermediateQueueFlowLifeCycle.close()on already-closed objects. Before the PR an unchecked failure only double-closed lifecycles 0..k; now it is 0..n, and the new testtestCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTime(SeaTunnelTaskStateTest.java:553-568) codifies that every lifecycle is closed again on each call. - Impact: connector
SinkWriter.close()/SourceReader.close()implementations are not required to be idempotent; a second close can throw a fresh exception (e.g.IllegalStateException: already closed) that becomes theClose task errorlog entry and obscures the original cause, and listeners observe duplicate close events. The task group is also failed for a teardown-only error after the data path finished successfully. - Fix: make
SeaTunnelTask.close()idempotent with anAtomicBoolean closedguard (return early on the second call, which also makes theBlockingWorkerfallback harmless), and in theCLOSED/CANCELLINGbranches callprogress.done()in afinallyso a close failure does not re-enter the fallback path. UpdatetestCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTimeto assert single-close semantics instead. - Evidence:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:475 throw (IOException) closeException[0];;seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/SeaTunnelTaskStateTest.java:566 verify(first, times(2)).close();;seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:473 if (closeException[0] != null) { - Suggested fix: With the full pass now guaranteed, this rethrow has a side effect worth handling: from
stateProcess()case CLOSED/CANCELLINGit skipsprogress.done(), the exception lands inBlockingWorker.run()'scatch (Throwable), and thefinallysees!result.isDone()and callstracker.task.close()again — so every lifecycle (including the ones that closed cleanly) getswriter.close()/reader.close()a second time. Connector close methods aren't required to be idempotent, and a second-close exception becomes theClose task errorentry that hides the real cause. Could we add anAtomicBoolean closedguard here (return early on re-entry) and/or moveprogress.done()into afinallyin the CLOSED/CANCELLING branches?testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTimewould then assert single-close semantics. - Severity: Medium
Issue 2: Catching Throwable in both teardown loops also swallows fatal JVM errors (OutOfMemoryError, ThreadDeath, StackOverflowError): the lifecycle loop keeps invoking connector close() code after an OOM, and BlockingWorker now downgrades a fatal error during close to a severe log line instead of letting it propagate.
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:464 - Why it matters: - Root cause:
SeaTunnelTask.close()now wrapssuper.close()and everyflowLifeCycle.close()incatch (Throwable t)(SeaTunnelTask.java:456, :464) and the BlockingWorker fallback was widened fromcatch (IOException e)tocatch (Throwable e)(TaskExecutionService.java:1314). There is no carve-out forVirtualMachineError/ThreadDeath, so after anOutOfMemoryErrorfrom one lifecycle the loop continues callingSinkWriter.close()/SourceReader.close()and executor shutdowns in a heap-exhausted JVM, and whensneakyThrowfinally rethrows it,TaskExecutionService.java:1314-1315just logsClose task errorand returns normally. - Impact: before this PR an
Errorin the fallback close escapedrun()and surfaced through the executor thread's uncaught-exception path; now it is a log line. For Zeta operators this hides VM-level failures on the worker and leaves the task thread in an undefined state, which is exactly the class of failure that should not be absorbed. - The PR's own test
testCloseAttemptsEveryCycleWhenCycleThrowsError(SeaTunnelTaskStateTest.java:595-607) locks in the 'keep going after an Error' behaviour forAssertionError, and the Javadoc at SeaTunnelTask.java:444 promises it, so this is intentional for allErrortypes rather than an oversight. - Fix: in both catch blocks rethrow immediately when
t instanceof VirtualMachineError || t instanceof ThreadDeath || t instanceof LinkageError(or add a smallExceptionUtil.rethrowIfFatal(Throwable)helper in engine-common and use it in both places), and keep the collect-and-continue semantics forExceptionsubclasses only. Adjust the Javadoc at SeaTunnelTask.java:444 accordingly. - Evidence:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:464 } catch (Throwable t) {;seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:444 * ({@link RuntimeException}) or even an {@link Error} — is collected and does not prevent the;seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:1314 } catch (Throwable e) { - Suggested fix: Catching
Throwablehere (and in thesuper.close()block above, plus the widened catch inBlockingWorker) means anOutOfMemoryError/ThreadDeathfrom one lifecycle no longer stops teardown: we keep calling connectorclose()code in a heap-exhausted JVM, and the fallback atTaskExecutionService.java:1314then just logs it asClose task error. I'd keep collect-and-continue forExceptionbut rethrow fatal errors immediately, e.g.if (t instanceof VirtualMachineError || t instanceof ThreadDeath) throw t;(or a sharedrethrowIfFatalhelper inExceptionUtil) at the top of both catch blocks, and reword the Javadoc at line 444 so it no longer promises to absorbError. - Severity: Medium
Issue 3: The new tests cover the loop in isolation but not the two paths this PR actually changes end-to-end: the super.close() failure branch and the BlockingWorker fallback (TaskExecutionService.java:1314) that now absorbs unchecked close failures.
- Location:
seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/SeaTunnelTaskStateTest.java:566 - Why it matters: - All ten new tests set
allCyclesvia reflection and calltask.close()directly on a mock with the real method, so thecatch (Throwable t)aroundsuper.close()(SeaTunnelTask.java:456-457) is never exercised with a failure, and nothing asserts the first-failure-wins ordering whensuper.close()is the primary and a lifecycle failure is suppressed. - The production change in
TaskExecutionService.java:1314(catch (Throwable e)) has no test at all: nothing verifies that aRuntimeExceptionfromTask.close()inBlockingWorker.run()is logged and that the thread still restores the context classloader (:1319) and reachestaskDone(:1310). Since the PR description presents this as the piece that completes the teardown story, it should have coverage. testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTime(SeaTunnelTaskStateTest.java:566) assertstimes(2), which pins the non-idempotent double-close; if the idempotency fix in F1 is adopted this test must be inverted.- Fix: add one test that makes
AbstractTask.close()throw (e.g. via a smallSeaTunnelTasksubclass) and asserts a lifecycle failure is attached as suppressed; and extend an existingTaskExecutionServicetest to drive aTaskwhosecall()andclose()both throwRuntimeExceptionand assert the worker completes and the classloader is restored. - Evidence:
seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/SeaTunnelTaskStateTest.java:607 AssertionError ex = assertThrows(AssertionError.class, task::close);;seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:1314 } catch (Throwable e) { - Suggested fix: This asserts
times(2), i.e. it pins the fact that a secondclose()re-closes every lifecycle. GivenBlockingWorkerre-invokestask.close()whenever the first one throws, I'd rather we makeclose()idempotent and asserttimes(1)here. Separately, none of the new tests hit thesuper.close()failure branch (SeaTunnelTask.java:456-457) or the widenedcatch (Throwable)inTaskExecutionService.java:1314— a test wherecall()+close()both throwRuntimeExceptionand the worker still completes/restores the classloader would cover the second production change. - Severity: Low
Issue 4: Updated Javadoc @throws clauses do not match the new control flow, and the per-lifecycle error log carries no task/lifecycle context, so each failure is logged twice (here and in BlockingWorker) without a way to correlate them.
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:448 - Why it matters: -
@throws IOException if the parent AbstractTask#close() fails(SeaTunnelTask.java:448) is unreachable becauseAbstractTask.close()(AbstractTask.java:99-106) wraps its only statement incatch (Exception ignore); the realIOExceptionsource is a lifecycle close, which the clause no longer mentions.@throws RuntimeException(SeaTunnelTask.java:449) omits thatErroris also rethrown viasneakyThrow(SeaTunnelTask.java:477), which the paragraph at line 444 explicitly promises. log.error("Close FlowLifeCycle error.", t)(SeaTunnelTask.java:465) logs every failure with a full stack, then the first failure (with the others as suppressed) is rethrown and logged again byTaskExecutionService.java:1315asClose task error. On a task with several failing lifecycles an operator sees N+1 stack traces for one teardown with notaskLocationor lifecycle class name to tell them apart.- Fix: rewrite the
@throwstags to@throws IOException if the first failing lifecycle threw an IOException/@throws RuntimeException or Error (via sneakyThrow) otherwise, and includetaskLocationandflowLifeCycle.getClass().getSimpleName()in the log message (e.g.log.error("Task {} close FlowLifeCycle {} error.", taskLocation, flowLifeCycle.getClass().getSimpleName(), t)), which also follows the project rule that exceptions and logs carry task context. - Evidence:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:449 * @throws RuntimeException if an unchecked lifecycle close failure is the first failure;seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:465 log.error("Close FlowLifeCycle error.", t);;seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:448 * @throws IOException if the parent {@link AbstractTask#close()} fails - Suggested fix: Two small doc/log nits on the new semantics: (1)
AbstractTask.close()already swallowsException, so this@throws IOExceptionpath cannot happen — the realIOExceptionsource is a lifecycle close; and@throws RuntimeExceptionon the next line should mention thatErroris rethrown viasneakyThrowtoo, as the paragraph above promises. (2) Thelog.error("Close FlowLifeCycle error.", t)at line 465 has no task/lifecycle context and the same throwable is logged again asClose task errorbyBlockingWorker; includingtaskLocationandflowLifeCycle.getClass().getSimpleName()would make the N+1 stack traces on a failing teardown correlatable. - Severity: Low
Issue 5: The widened catch (Throwable) around super.close() cannot collect anything but an Error in practice, and allCycles is still dereferenced unguarded right after it, so an init() failure before allCycles is assigned still NPEs in the fallback close path.
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:456 } catch (Throwable t) { - Why it matters: - Root cause:
AbstractTask.close()(AbstractTask.java:99-106) wraps its only statement incatch (Exception ignore), so the newcatch (Throwable t)at SeaTunnelTask.java:456 can only ever observe anError. MeanwhileallCyclesis assigned insideinit()(SeaTunnelTask.java:185) aftersuper.init()and the metrics/observability setup that precede it; if any of those throw,BlockingWorkerstill callstracker.task.close()(TaskExecutionService.java:1313) andallCycles.stream()at SeaTunnelTask.java:459 throwsNullPointerException. - Impact: this is pre-existing, but the PR's stated goal is a complete teardown story; with the widened fallback catch in
TaskExecutionService.java:1314the NPE is now logged asClose task errorrather than escapingrun(), which hides the realinit()failure's cleanup problem behind an unrelated NPE stack. - Fix: guard the loop with
if (allCycles != null)(or initialiseallCycles = new ArrayList<>()at the field declaration andclear()it ininit()), and reduce thecatch (Throwable)aroundsuper.close()to a plain call orcatch (IOException)since the base already swallowsException, so the Javadoc@throws IOException if the parent AbstractTask#close() fails(SeaTunnelTask.java:448) describes a path that exists. - Evidence:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:457 closeException[0] = t;;seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:448 * @throws IOException if the parent {@link AbstractTask#close()} fails;seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:1315 logger.severe("Close task error", e); - Severity: Low
Review conclusion
Conclusion: final approval remains pending on the previous comments
2. Remaining follow-ups
- Issue 1: Because
close()now always completes the full pass and then rethrows, any single lifecycle close failure on the normal CLOSED/CANCELLING path causes every lifecycle (including the ones that closed cleanly) to be closed a second time by theBlockingWorkerfallback, andclose()itself is not idempotent. - Issue 2: Catching
Throwablein both teardown loops also swallows fatal JVM errors (OutOfMemoryError, ThreadDeath, StackOverflowError): the lifecycle loop keeps invoking connectorclose()code after an OOM, and BlockingWorker now downgrades a fatal error during close to aseverelog line instead of letting it propagate. - Issue 3: The new tests cover the loop in isolation but not the two paths this PR actually changes end-to-end: the
super.close()failure branch and theBlockingWorkerfallback (TaskExecutionService.java:1314) that now absorbs unchecked close failures. - Issue 4: Updated Javadoc
@throwsclauses do not match the new control flow, and the per-lifecycle error log carries no task/lifecycle context, so each failure is logged twice (here and inBlockingWorker) without a way to correlate them. - Issue 5: The widened
catch (Throwable)aroundsuper.close()cannot collect anything but anErrorin practice, andallCyclesis still dereferenced unguarded right after it, so aninit()failure beforeallCyclesis assigned still NPEs in the fallback close path.
Thanks for the updates so far. Happy to discuss the remaining points.
|
Failed-jobs re-run on tip Build: https://github.com/SeaSand1024/seatunnel/actions/runs/36852053400
|
|
@SeaSand1024 thanks for the CI breakdown on tip Since the sync contained no close-path edits, the earlier review points are still open. What's still needed in
On the test side (F3, Once those land I'm happy to take another look. No need to re-run the full CI matrix before then — a green |
Address SEZ9 F1–F5 on apache#12391: AtomicBoolean close guard + progress.done() in finally, catch Exception (not Throwable) in teardown/BlockingWorker, null-guard allCycles, improve Javadoc/log context, and add coverage for super.close() failure and BlockingWorker fallback. Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: multica-agent <github@multica.ai>
|
@SEZ9 @DanielLeens F1–F5 addressed on tip F1 idempotency: F2 catch narrowing: lifecycle teardown and BlockingWorker fallback close catch F5 F4 Javadoc + log: F3 tests: Local: |
|
@SEZ9 @DanielLeens one deliberate consequence of F2 ( |
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you again, @SeaSand1024, for turning around the F1-F5 follow-ups so quickly and for being upfront in your last comment about the classloader-restore consequence of the narrowed catch. I re-read the whole PR at head 877056bf1 from scratch (not just the delta), traced the close path again, and verified each earlier point in source. Most of it is fixed. I do have one real blocker that is a consequence of the combination of two of the new changes, and I own part of it: in my earlier rounds I accepted the catch (Throwable) shape without checking what happens when an Error escapes the loop once teardown can no longer be retried. That interaction only exists at this head, so it is new, not a carryover, but I should have asked about the retry path earlier.
+1 to @SEZ9's F1 (idempotency) and F5 (super.close() / null allCycles guard): both are correctly addressed at this head. I partially disagree with F2 (narrowing to Exception); details are in Issue 1 below.
What Problem Does This PR Solve?
- User pain point:
SeaTunnelTask.close()used to catch onlyIOExceptionperFlowLifeCycle.close(). An unchecked exception from one lifecycle escaped the loop, so every later lifecycle (executors, connections, buffers) was never closed (#12231). - Fix approach: per-lifecycle try/catch, keep teardown order, keep the first failure, attach the rest as suppressed, rethrow the first (
IOExceptionas is, others viasneakyThrow). At this head it also adds a close-once latch (AtomicBoolean closed),try/finallyaroundclose()in the CLOSED and CANCELLING states, and narrows the catches toException. - One sentence: a single failing lifecycle close must not stop the remaining lifecycles from being closed, and the original failure must still surface.
Simple example: a task has [source, transform, sink-A, sink-B] and sink-A.close() throws IllegalStateException. Before the PR sink-B was never closed. Now sink-B is closed and the task still fails with the IllegalStateException. The problem case for this review: sink-A.close() throws NoClassDefFoundError. Now sink-B is never closed, and nothing can close it later.
1. Code Change Review
1.1 Core Logic Analysis
Files: SeaTunnelTask.java (close() at about lines 462-500, closeSuper() right after, state machine at stateProcess() CLOSED/CANCELLING around lines 296-312, field closed at about line 145), TaskExecutionService.java:1311-1316 (BlockingWorker fallback), plus tests in SeaTunnelTaskStateTest, TaskExecutionServiceTest and the new CallAndCloseThrowRuntimeExceptionTask.
Real call chain (normal path, verified):
BlockingWorker.run() (TaskExecutionService.java ~1285)
-> t.init(); do { result = t.call(); } while (!result.isDone() ...)
-> SeaTunnelTask.call() -> stateProcess()
PREPARE_CLOSE -> CLOSED -> this.close() (SeaTunnelTask.java ~296)
closed.compareAndSet(false,true) -> first caller wins
closeSuper() (AbstractTask.close only cancels restoreComplete)
for each FlowLifeCycle in allCycles: close() (catch Exception -> collect)
rethrow first failure
finally progress.done()
-> finally: taskDone(t); if result==null || !result.isDone() -> tracker.task.close() (fallback)
The normal success path (no close failure) reaches the changed code on every task teardown, so this is a main-path change in cleanup, not only a recovery path. The failure path (a lifecycle throws on close) is what the PR targets. Before/after for the loop is as described in the PR and is correct for Exception subclasses.
Verification of the earlier review points at this head:
| Earlier point | Status | Evidence |
|---|---|---|
Fallback close only caught IOException (my Issue 1) |
Fixed, now catch (Exception e) |
TaskExecutionService.java:1314 (see Issue 2 for the Error side effect) |
Same-instance addSuppressed guard (my Issue 3) |
Fixed | SeaTunnelTask.java loop, e != closeException[0] |
| Test gaps (my Issue 2) | Fixed and extended | SeaTunnelTaskStateTest now has middle/last, repeated close, Error, order, shared instance, parent-failure and null allCycles cases |
| @SEZ9 F1 double close via fallback | Fixed | closed.compareAndSet at the top of close(); progress.done() in finally |
| @SEZ9 F4 Javadoc and log context | Fixed | @throws lines updated; log includes taskLocation and lifecycle simple name |
@SEZ9 F5 super.close() and null allCycles |
Fixed | closeSuper() plus if (allCycles != null) |
@SEZ9 F2 narrow Throwable |
Applied, but see Issue 1 | catch (Exception e) in loop and fallback |
Runtime path for the problem I found (non-fatal Error from a connector close):
stateProcess() CLOSED
-> close(): closed=true (latch set BEFORE any lifecycle is closed)
-> cycle[0].close() OK
-> cycle[1].close() throws NoClassDefFoundError / LinkageError / AssertionError
-> not an Exception -> escapes forEach, escapes close()
-> cycle[2..n] never closed
-> finally: progress.done()
-> call() throws -> BlockingWorker catch (Throwable) -> task group marked failed
-> BlockingWorker finally: result == null -> tracker.task.close()
-> closed.compareAndSet(false,true) fails -> returns immediately
=> cycle[2..n] are never closed by anyone (executors, connections, buffers leak)
Before the latch existed, the fallback close would at least have re-attempted the remaining lifecycles. With the latch, an escaping Error is now unrecoverable by design. The test testCloseAttemptsEveryCycleWhenCycleThrowsError asserts verify(later, never()).close(), i.e. it encodes exactly this leak as the expected behavior.
1.2 Compatibility Impact
Fully compatible. No config option, public API, serialized checkpoint/savepoint format or default changed. Notes:
SeaTunnelTaskisSerializablethroughTask, so the newprivate final AtomicBoolean closedis part of the Java-serialized task. It must stay non-transient (a transient final would be null after deserialization), and it is:AtomicBooleanis serializable and starts false on deploy. Tasks are serialized before they run, so no old-version task ever carries atruevalue. Please keep it that way.- The only other direct caller of
SeaTunnelTask.close()besides the state machine and the BlockingWorker fallback isCloseRequestOperation.runInternal(); I could not find any code that constructs that operation inmain(only the serializer hook creates an empty instance), so the changed idempotency does not alter any live behavior there. - Mixed-version clusters: no wire change.
1.3 Performance / Side-Effect Analysis
Negligible: one CAS per close, a small string format only on failure. No new queues, threads, locks or retries. The log line is emitted once per failed lifecycle with the stack trace, which is bounded by the number of lifecycles in one task. Not a concern at very high data volumes since this runs once per task, not per record.
1.4 Error Handling and Logging
Issue 1: An Error from one lifecycle close now permanently skips all remaining lifecycles (close-once latch plus catch (Exception))
- Location:
SeaTunnelTask.javaclose()(latch at the top,catch (Exception e)in the loop), and the testSeaTunnelTaskStateTest#testCloseAttemptsEveryCycleWhenCycleThrowsError(assertsnever()). - Problem:
closedis flipped before any lifecycle is closed, and onlyExceptionis caught per lifecycle. AnyErrorthrown by a connectorclose()aborts the loop, and the BlockingWorker fallback can no longer finish the job becauseclose()now returns immediately. This is the same class of leak #12231 is meant to remove, just triggered by anErrorinstead of aRuntimeException. Non-fatalErrors are realistic here:NoClassDefFoundError,ExceptionInInitializerError, otherLinkageErrors (a closed or unloaded plugin classloader during teardown) andAssertionErrorall derive fromErrorand are not JVM-fatal. - Potential risk: executors, JDBC/HTTP connections and buffers of every lifecycle after the failing one leak for the lifetime of the worker JVM; repeated across jobs this exhausts threads or connections on a long-running cluster. The task still reports failure, so the leak is silent.
- Best improvement: keep the "do not keep calling connector code after the JVM is broken" intent of F2, but scope it to genuinely fatal errors. Catch
Throwableper lifecycle, collect it as first or suppressed as today, and stop the loop early only forVirtualMachineError(OutOfMemoryError, StackOverflowError, InternalError) andThreadDeath, rethrowing it after recording. Rethrow the first failure at the end (add anErrorbranch next to theIOExceptionbranch;sneakyThrowalready handles it). Update the test to assert that later lifecycles are closed for anAssertionErrororNoClassDefFoundError, and add one case showing aVirtualMachineErrorstops the loop. The alternative, if you prefer to keepExceptiononly, is to set the latch only after the loop completes and clear it if anErrorescapes so the fallback can retry, but that reintroduces the double-close window F1 removed, so I recommend the first option. - Severity: High
- Raised by another reviewer: Partially, @SEZ9 F2 asked for the narrowing; this issue is the consequence of applying it together with the latch, and I disagree with narrowing to
Exceptionalone.
Issue 2: BlockingWorker fallback leaves the pooled thread's context classloader unrestored when close throws an Error
- Location:
TaskExecutionService.java:1305-1319(fallbackcatch (Exception e)followed byThread.currentThread().setContextClassLoader(oldClassLoader)at the end ofrun()). - Problem: The restore is not in a
finally. Iftracker.task.close()throws anError, the exception escapesrun()before the restore. The author's last comment acknowledges this and calls it optional polish. - Potential risk: BlockingWorker runs on a shared, reused executor thread (
BlockingTaskThreadFactorythreads), so a stale plugin classloader stays referenced from the thread and pins the whole plugin classloader and its classes. This is a classloader leak that also contradicts the PR's stated goal (the earlier head withcatch (Throwable)did restore it). - Best improvement: put the
setContextClassLoader(oldClassLoader)call in an outerfinallyofrun()(or a nestedtry/finallyaround the fallback close). It is a two-line change and removes the dependence on what close can throw. With Issue 1 fixed this matters less but it is still worth doing. - Severity: Medium
- Raised by another reviewer: No (author noted it in a comment)
Issue 3: engine-v2-it (8, ubuntu-latest) is red on this head and not attributed
- Location: fork run 37097098821, job
Run / engine-v2-it (8, ubuntu-latest). The JDK 11engine-v2-itleg and every other job are green. - Problem: The only public annotations are repeated "SeaTunnel job executed failed" messages, and the author's last CI update stops at the previous head. It is not clear which test failed. Because this head changes the close path, we cannot treat this as a known flake without the test name.
- Best improvement: please post the failing test name and a short stack snippet. If it is one of the already tracked flakes (for example the cancel-vs-worker-loss test tracked in #12353), say so. If it is a different test that exercises task teardown or cancel, please check it against Issue 1.
- Severity: Medium (CI attribution)
- Raised by another reviewer: No
Issue 4: Minor cleanups
- Location:
SeaTunnelTask.javacloseSuper()and itscatch (Exception e); fieldclosed;TaskExecutionServiceTest#testBlockingWorkerFallbackCloseWhenCallAndCloseThrowRuntimeException. - Problem: (a)
AbstractTask.close()swallows everyExceptionitself, socloseSuper()plus its catch can never see anExceptionin production; it exists only as a test seam. A one-line comment saying so would help the next reader. (b) The field Javadoc should state that it must stay non-transient becauseTaskisSerializable. (c) The new TaskExecutionService test asserts onlyFAILEDandcloseCalled; it cannot tell whether the classloader was restored, which is what its comment claims. - Best improvement: add the two comments, and either assert the thread context classloader after the worker finishes or soften the comment.
- Severity: Low
- Raised by another reviewer: Partially, F5 touched
closeSuper().
2. Code Quality Assessment
2.1 Coding Standards
Good overall. Javadoc on close() explains the contract, the license header is present on the new test task class, no wildcard imports. The new field and helper need the short comments mentioned in Issue 4.
2.2 Test Coverage and Test Stability
Coverage is broad and deterministic: SeaTunnelTaskStateTest uses Mockito mocks, no Thread.sleep, no static state, and InOrder for ordering. The new BlockingWorker test uses an Awaitility wait of 10 seconds on a task that fails immediately, which is stable. Stability rating: Stable.
Quality concern: the Error test asserts the leak (never() for the later lifecycle), so it will fail once Issue 1 is fixed correctly. That is expected and the assertion should flip. A test that would catch Issue 2 is also missing.
2.3 Documentation Updates
No user-facing change; no docs/en or docs/zh updates needed. The internal Javadoc is updated.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix for the unchecked-exception case. The latch-plus-narrow-catch design is the part that needs one more iteration.
3.2 Maintainability
Small and readable. Keeping all teardown rules in one place (collect first, suppress the rest, special handling for fatal errors) is easy to reason about once Issue 1 is applied.
3.3 Extensibility
The "attempt everything, keep the first failure, suppress the rest" pattern is reusable for other teardown loops in the engine.
3.4 Historical-Version Compatibility
Compatible. Nothing persisted or sent between nodes changes; the Java-serialized task gains a boolean latch that deserializes to its initial value, so rolling upgrades and checkpoint or savepoint restore are unaffected.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Non-fatal Error from one close permanently skips remaining lifecycles (latch set first, catch (Exception) only); test asserts the leak |
SeaTunnelTask.java close(); SeaTunnelTaskStateTest#testCloseAttemptsEveryCycleWhenCycleThrowsError |
High |
| 2 | Fallback close Error skips context classloader restore on a pooled thread |
TaskExecutionService.java:1305-1319 |
Medium |
| 3 | engine-v2-it (8) red on this head, no failing test named |
fork run 37097098821 | Medium |
| 4 | Missing comments on closeSuper() and closed; BlockingWorker test cannot prove classloader restore |
SeaTunnelTask.java, TaskExecutionServiceTest |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
-
Blockers - must be fixed
- Issue 1: do not let a non-fatal
Errorstop the teardown loop once the close-once latch has been set. CatchThrowableper lifecycle, stop early only onVirtualMachineErrororThreadDeath, rethrow the first failure, and flip the Error test. - Issue 3: name the failing
engine-v2-it (8)test and confirm it is unrelated, or fix it.
- Issue 1: do not let a non-fatal
-
Recommended fixes - non-blocking
- Issue 2: move the context classloader restore into a
finally. - Issue 4: add the comments and strengthen the BlockingWorker test.
- Issue 2: move the context classloader restore into a
Overall assessment: F1, F3, F4 and F5 are properly fixed and the tests are good. The remaining blocker is a small, local change in the same method, and the rest of the design (order preserved, first failure kept, suppressed attached, IOException type preserved) is sound and compatible.
Better alternative: none needed beyond Issue 1's scoped catch.
Response to existing reviews: I agree with @SEZ9 and @davidzollo that the lifecycle-close contract is the right scope and that the cancel-race fix (#12353 / #12377) should stay out of this PR. Their approval or +1 was given before the latch and the narrowed catch landed (the +1 was dismissed after the earlier sync), so it does not cover the Issue 1 interaction.
CI / sync: Build is red on this head only because of engine-v2-it (8, ubuntu-latest); every other job, including the unit-test matrix, is green. Please post the failing test name (Issue 3). The branch is 14 commits behind dev with no conflicts, so no sync is required for this review; if you push the Issue 1 fix, a sync at the same time is harmless but optional.
|
Thanks @SeaSand1024 for calling out the classloader-restore consequence explicitly. On F2: agreed that an What I want to resolve before merge is how the narrowed
If so, F1 (idempotency) and F2 (not swallowing fatal errors) are individually right, but combined they lose the full-pass guarantee for exactly the unchecked-failure class this PR exists to handle. Two options, either is fine:
I lean to option 1 as the smaller behavioral surface. F3: please add one test that drives the F1 / F5: could you point me to the relevant hunks at |
Catch Throwable per lifecycle so NoClassDefFoundError/AssertionError no longer abort teardown under the close-once latch; early-stop only for VirtualMachineError/ThreadDeath; prefer Error over Exception when rethrowing. Restore BlockingWorker context classloader in nested finally. Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: multica-agent <github@multica.ai>
|
@DanielLeens @SEZ9 addressed on tip Issue 1 (Error + close-once latch): per-lifecycle Issue 2 / polish (BlockingWorker classloader): F3 / comments / Javadoc: end-to-end NCDFE coverage + existing engine-v2-it (8) on Local: |
|
@DanielLeens @SEZ9 one non-blocking follow-up on item 5: the BlockingWorker classloader assert in |
|
Thanks for the heads-up on the classloader assert — agreed. Since the Awaitility Rather than dropping the assert outright, my preference would be to have the test capture the worker thread's context classloader from inside the close path and assert on it after the worker has finished. If that is awkward with the current test seam, dropping it with a short comment explaining why is fine too. Either way, a follow-up is acceptable — just link it from this thread so it doesn't get lost. On the rest of your Remaining asks from my side: (1) the classloader assert fix or removal as above (this PR or a linked follow-up), and (2) a quick confirmation that the BlockingWorker fallback test still exercises the unchecked-close-failure branch after the Error-policy change, since that was the gap in F3. |
Awaitility runs on the test thread, so comparing context classloaders there never observes the worker's nested-finally restore. Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: multica-agent <github@multica.ai>
|
@SEZ9 @DanielLeens follow-up on tip 1. Classloader assert: dropped the tautological Awaitility assert in 2. F3 / BlockingWorker RuntimeException path: still covers unchecked close after the Error-policy change. 3. CI on Build 37460272377 (tip
Local: BlockingWorker fallback test 1/0/0 after the assert drop. |
|
@SeaSand1024 thanks for the follow-ups on F3: dropping the test-thread classloader assert and documenting why in the comment sounds right. I'll verify the end-to-end NCDFE coverage ( Remaining points I'll check against the diff; pointers are welcome but I'll resolve each based on the code and tests rather than on the comment thread:
I'll follow up once I've gone through the diff. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you, @SeaSand1024, for the fast and careful turnaround on every point from my last round, and for being so transparent about CI attribution along the way. I re-read the whole PR at the new head (6ad74f1fb9f5) from scratch rather than only the delta since 877056bf19, traced the close path again, and checked each item of my previous review against the source. Short version: all three Highs/Mediums from my last review are fixed, and I do not see a source-level blocker at this head. One correction to my own last review is in the Compatibility section (Issue 3), so I want to open with an apology for that.
Existing reviews and comments. @SEZ9's open asks from the last comment are all answerable from the diff, so I verified them: F1 (double close) is closed by the latch at SeaTunnelTask.java:476 and testCloseIsIdempotentAndClosesEachLifecycleOnlyOnce; F4 (log context) by the Task {} close FlowLifeCycle {} error. log at SeaTunnelTask.java:496; F5 by the null guard at SeaTunnelTask.java:487 plus testCloseSkipsLifecycleLoopWhenAllCyclesNull; the super.close() failure test @SEZ9 asked for by name is testClosePreservesSuperCloseFailureAndAttachesLifecycleFailuresAsSuppressed. On F2, the two readings only conflict at the older head: at this head the per-lifecycle loop catches Throwable and stops early only for fatal errors (SeaTunnelTask.java:495,511), and the BlockingWorker fallback catches Exception only (TaskExecutionService.java:1315), so a fatal Error is no longer downgraded to a severe log line there. +1 to @SEZ9's request to confirm that the fallback test discriminates; I traced it and have a concrete finding in Issue 1.
What Problem Does This PR Solve?
- User pain point:
SeaTunnelTask.close()only caughtIOExceptionper lifecycle, so one unchecked exception from a connectorclose()skipped every later lifecycle (executors, connections, buffers), as reported in #12231. - Fix approach: a per-lifecycle try/catch that keeps teardown order, keeps the first failure and attaches the rest as suppressed, a close-once latch so the BlockingWorker fallback cannot re-close,
try/finallyaroundclose()in the CLOSED and CANCELLING states, and a nestedfinallythat always restores the worker thread's context classloader. - One-sentence summary: a failing lifecycle close can no longer stop the remaining lifecycles from being closed, and the original failure still surfaces.
1. Code Change Review
1.1 Core Logic Analysis
Changed methods: SeaTunnelTask.close() (:475), new closeSuper() (:532), the CLOSED and CANCELLING branches of stateProcess() (:303-316), and BlockingWorker.run() (TaskExecutionService.java:1310-1321).
Runtime path (default teardown of every task, so this is a main-path change in cleanup):
SeaTunnelTask.call() -> stateProcess()
CLOSED / CANCELLING
try { close() } finally { progress.done() (and currState = CANCELED) } SeaTunnelTask.java:303-316
close(): closed.compareAndSet(false,true) else return :476
closeSuper() :481 (AbstractTask.close, does not throw in prod)
for each FlowLifeCycle (iterator): :487-515
catch Throwable -> log, keep first failure (Error beats Exception, rest suppressed)
stop early only for VirtualMachineError / ThreadDeath :511
rethrow first failure (IOException as-is, others sneakyThrow) :517-521
BlockingWorker.run() finally: TaskExecutionService.java:1310-1321
try { taskDone(t); if (result == null || !done) { try { task.close() } catch (Exception) -> severe log } }
finally { setContextClassLoader(oldClassLoader) }
Key findings:
- The three issues from my last review are resolved in the code. The Error plus latch leak is gone: a non-fatal
Error(NoClassDefFoundError,LinkageError,AssertionError) from one lifecycle no longer skips the rest, covered bytestCloseAttemptsEveryCycleWhenCycleThrowsNoClassDefFoundErrorand...AssertionError;testCloseStopsLoopOnVirtualMachineErrorcovers the fatal early stop. The classloader restore is now in a nestedfinally.closeSuper()and the non-transient field both carry explanatory comments. MDCTracer.tracing(allCycles.stream()).iterator()(:490) delegates straight to the underlying stream (MDCStream.iterator()), so the per-element MDC wrapper thatforEachused to apply is not used any more. I checked that it was a functional no-op here: the context is captured on the same thread that runs the loop, so the job and task MDC values are the same as before.- The latch is only consulted for repeated
close()calls. The fallback close after acall()that threw from insideclose()now returns immediately, which is exactly what removes the double close. - A side observation from the fork's
engine-v2-it (11)log:SinkFlowLifeCycle.close()throwsNullPointerExceptionatSinkFlowLifeCycle.java:279(writer.close()) when the fallback closes a task that never finished init, and this PR now logs it per lifecycle instead of letting it escape unseen. That null-safety gap exists ondevand is not caused by this PR, so I only mention it as a possible follow-up.
1.2 Compatibility Impact
Fully compatible for same-version clusters: no option, public API, checkpoint or savepoint format changes. One correction to my previous round, see Issue 3.
1.3 Performance / Side-Effect Analysis
One CAS per close and a log line only on failure; runs once per task, not per record. No new thread, lock, queue or retry. The loop is bounded by the number of lifecycles in a task. The logged stack traces can be large when many sinks fail during a cancel (the fork run shows hundreds of SinkFlowLifeCycle entries caused by interrupts), but this is bounded per task and is an observability trade-off, not a risk.
1.4 Error Handling and Logging
Exceptions are no longer swallowed: the first failure is rethrown with the others suppressed, and the task still ends FAILED. Log context now carries the task location and lifecycle name.
Issue 1 (Medium, non-blocking): the new BlockingWorker test cannot go red for the production change it is meant to guard
- Location:
TaskExecutionServiceTest#testBlockingWorkerFallbackCloseWhenCallAndCloseThrowRuntimeException, coveringTaskExecutionService.java:1310-1321. - Problem:
taskDone(t)completes the future before the fallbackclose()runs. If the fallback catch were reverted tocatch (IOException e)(the original bug), theRuntimeExceptionwould escaperun()after the future is already complete, and the test would still seeFAILEDandcloseCalled == true. The same holds if the nestedfinallywere removed, because the classloader is not observed. So both production edits in this file are effectively untested. This answers @SEZ9's last question: the test runs the branch but does not discriminate. - Best improvement: make
close()of the test task throw anAssertionError(it escapes the fallbackcatch (Exception), so only the nestedfinallycan restore the classloader), recordThread.currentThread()insideclose(), and after the future completes assert with Awaitility thatthread.getContextClassLoader()is no longer the task classloader. That can be read from the test thread because it is a property of the recordedThread. TheRuntimeExceptioncase can stay as is. - Severity: Medium (does not block merge; the production code itself is correct as written)
- Raised by another reviewer: Partially, @SEZ9 asked whether this test still covers the unchecked-close branch.
Issue 2 (Low, non-blocking): a fatal error can be hidden as a suppressed exception
- Location:
SeaTunnelTask.java:503-509. - Problem: when a non-fatal
Erroris already the primary failure and a later lifecycle throws aVirtualMachineError, the code attaches the fatal error as suppressed under the earlierErrorand then stops the loop. The thrown exception is then the earlier non-fatal one. - Best improvement: when
t instanceof VirtualMachineErrorand the current primary is not one, promotetto primary (same swap you already do forErroroverException), plus a one-line test. This is a rare combination, so it is fine as a follow-up. - Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Good. The close() Javadoc matches the control flow, closeSuper() and the field explain why they exist, the new test task class has the ASF header, and there are no wildcard imports.
2.2 Test Coverage and Test Stability
SeaTunnelTaskStateTest now covers first, middle and last failures, unchecked and checked, repeated close, Error and fatal-error policy, ordering, shared instance, parent failure, null allCycles and progress.done() on a throwing close. These are deterministic Mockito tests with no sleeps. Stability rating: Stable. The only coverage gap is Issue 1. Earlier tests were only extended, none weakened.
2.3 Documentation Updates
Not needed; there is no user-facing behavior or option change.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix at the right layer (the task's own teardown), with the policy for fatal errors made explicit.
3.2 Maintainability
Good. The Javadoc states the policy, and the helper closeSuper() is documented as a test seam.
3.3 Extensibility
Fine for the current scope.
3.4 Historical-Version Compatibility
Issue 3 (Low, non-blocking, a carryover from my last review): Sorry for missing this in the last review. I wrote that no old-version task could carry a closed value, but I did not consider the reverse. SeaTunnelTask is Serializable with an explicit serialVersionUID (SeaTunnelTask.java:118) that this PR does not change. If a task serialized by a build without the new closed field is ever deserialized by a build that has it, Java serialization leaves the field null (field initializers do not run on deserialization), and closed.compareAndSet at :476 would throw a NullPointerException on the first close(). I could not find any documented rolling-upgrade guarantee for Zeta (tasks are normally deployed by a master of the same build), so I treat this as a note and not a blocker. If you want to remove the question entirely, a null-tolerant guard or a short comment stating that master and worker must run the same build would be enough.
- Severity: Low
- Raised by another reviewer: No
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | New BlockingWorker test cannot fail for the catch or finally it guards |
TaskExecutionServiceTest#testBlockingWorkerFallbackCloseWhenCallAndCloseThrowRuntimeException, TaskExecutionService.java:1310-1321 |
Medium (non-blocking) |
| 2 | Fatal VirtualMachineError can end up only as a suppressed exception |
SeaTunnelTask.java:503-509 |
Low |
| 3 | Old-format serialized task would leave closed null |
SeaTunnelTask.java:151,476 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers: none at the source level. Every High and Medium from my previous review, and the F1-F5 points from @SEZ9, are closed with code and test evidence at this head.
- Recommended fixes, non-blocking: Issues 1 to 3. They improve test strength and robustness but do not change the correctness of the fix.
CI state (checked on the fork run for this head, SeaSand1024/seatunnel run 37581382366). All four unit-test jobs pass (JDK 8 and 11, Linux and Windows). Three jobs are red, and none of them is caused by this PR: engine-v2-it (11) failed only SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck (a member-loss cancel race that #12311 is meant to fix, still open); engine-v2-it (8) failed only BackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressure (the checkpoint-lock starvation tracked in #12316, also still open); all-connectors-it-6 (8) failed at dependency resolution (Maven Central transfer of flink-core) before running any test. Because those two engine fixes are not on dev yet, syncing with dev will not clear them, so I am not asking for a sync. Re-running only the failed jobs should be enough. mergeStateStatus is BLOCKED with REVIEW_REQUIRED, and the branch is diverged from dev (ahead_by=8, behind_by=80); I record that without requesting a sync. I only have read-level permissions here, so my earlier changes requested entry will stay visible in GitHub's review summary even though the source blockers are cleared, and a maintainer with write access would need to do the final approval or dismissal.
Overall assessment: the fix is now in good shape and the design decisions (full pass for non-fatal errors, early stop only for fatal ones, idempotent close, always-restored classloader) are the right ones. Thanks again for the patience through these rounds, @SeaSand1024; this is a solid contribution.
|
Pushed merge commit |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks again for the patient work on this, @SeaSand1024. This is a fresh full read of the PR diff against dev on the current head (2a5e21f), plus the close path in the engine. One transparency note: 2a5e21f is a merge of current dev that I pushed to your branch to clear a conflict in the import block of SeaTunnelTask.java; the rest of the PR diff is the same as the head I reviewed last (6ad74f1). I re-checked that the merge did not change the interplay with the close path (details in 1.1).
What Problem Does This PR Solve?
User pain point: SeaTunnelTask.close() only caught IOException per lifecycle, so one unchecked exception from a connector close() skipped every later lifecycle (executors, connections, buffers), as reported in #12231. The BlockingWorker fallback close also only caught IOException.
Fix approach: a per-lifecycle try/catch that keeps teardown order, keeps the first failure and attaches the rest as suppressed (an Error takes priority over an Exception; early stop only for VirtualMachineError and ThreadDeath); a close-once latch (AtomicBoolean closed) so the BlockingWorker fallback cannot close twice; try/finally around close() in the CLOSED and CANCELLING states; and a nested finally that always restores the worker thread's context classloader.
One-sentence summary: a failing lifecycle close can no longer stop the remaining lifecycles from being closed, and the original failure still surfaces.
1. Code Change Review
1.1 Core Logic Analysis
Changed code: SeaTunnelTask.close(), new closeSuper(), the CLOSED and CANCELLING branches of stateProcess(), and BlockingWorker.run() in TaskExecutionService.
Runtime path (default teardown of every task, so this is a main-path change in cleanup):
SeaTunnelTask.call() -> stateProcess()
CLOSED / CANCELLING: try { close() } finally { (currState = CANCELED;) progress.done() }
close(): closed.compareAndSet(false, true) else return (idempotent)
closeSuper() (AbstractTask.close, does not throw in production)
for each FlowLifeCycle (iterator over allCycles):
catch Throwable -> log with task location + lifecycle name; keep first failure
(Error beats Exception; others suppressed; same instance skipped)
stop early only for VirtualMachineError / ThreadDeath
rethrow first failure (IOException as is, others via sneakyThrow)
BlockingWorker.run() finally:
try { taskDone(t); if (result == null || !done) { try { task.close() } catch (Exception) -> severe log } }
finally { setContextClassLoader(oldClassLoader) }
Before / after, in one line: before, catch (IOException) inside forEach, so any RuntimeException or Error aborted the loop; after, catch (Throwable) inside an iterator loop with an explicit fatal-error policy.
Checks I did on this head:
- Merge interplay:
devnow declaresallCyclesasvolatileand aCopyOnWriteArrayList, and addscancel()/cancelRequested. The PR readsallCyclesonce for a null guard and then iterates a stream snapshot, which is compatible with a copy-on-write list; the PR'sclose()anddev'scancel()do not share state. - The fallback close after a
call()that threw from insideclose()now returns immediately through the latch, which removes the double close. The latch is only consulted on repeatedclose(). - Error handling: an
Errorrethrown fromclose()reachesBlockingWorker'scatch (Throwable)and is recorded on the tracker like any task failure; this is not a regression forIOException, which already propagated. CANCELLINGnow setscurrState = CANCELEDandprogress.done()even whenclose()throws; the exception still propagates, so the task group still ends as failed exactly as before for a failing close. This does not alter the terminal state of the happy path.sneakyThrowis the existing static import fromExceptionUtil; theThrowable[]holder withIOExceptionspecial-casing keeps the declared signaturethrows IOException.
Key finding: the normal path hits the change, and the fix is at the right layer (the task's own teardown). The three open points are the same as in my previous round (below), none of which the contributor has had a chance to change yet.
1.2 Compatibility Impact
Compatible for same-version clusters: no option, public API, checkpoint or savepoint format change. One serialization note (Issue 3 below).
1.3 Performance / Side-Effect Analysis
One CAS per close and a log line only on failure; runs once per task, not per record. No new thread, lock, queue or retry; the loop is bounded by the number of lifecycles. Logging many stack traces when many sinks fail during a cancel is an observability trade-off, bounded per task. At the stated production scale this teardown path is not on any hot path.
1.4 Error Handling and Logging
Exceptions are no longer swallowed: the first failure is rethrown with the others suppressed. Log context carries the task location and the lifecycle class. Issues:
Issue 1: The new BlockingWorker test cannot go red for the production change it is meant to guard
- Location:
TaskExecutionServiceTest#testBlockingWorkerFallbackCloseWhenCallAndCloseThrowRuntimeException, guardingTaskExecutionService.javaBlockingWorker.run()finally block - Problem:
taskDone(t)completes the future before the fallbackclose()runs. If the fallback catch were reverted tocatch (IOException e)(the original bug), theRuntimeExceptionwould escaperun()after the future is already complete, and the test would still seeFAILEDandcloseCalled == true. Removing the nestedfinallywould not be observed either, because the classloader is never checked. So both production edits in this file are effectively untested by this test. - Potential risk: a regression of the fallback catch or the classloader restore would pass CI.
- Best improvement: make the test task's
close()throw anAssertionError(it escapescatch (Exception), so only the nestedfinallycan restore the classloader), recordThread.currentThread()insideclose(), and after the future completes assert (with Awaitility) thatthread.getContextClassLoader()is no longer the task classloader; this is readable from the test thread because it is a property of the recordedThread. Alternatively drop the test and rely on the unit tests ofSeaTunnelTask, which do discriminate. - Severity: Medium (the production code is correct as written; I would still like this resolved before a committer merges)
- Raised by another reviewer: Partially (SEZ9 asked whether the test still covers the unchecked-close branch)
Issue 2: A fatal VirtualMachineError can end up only as a suppressed exception
- Location:
SeaTunnelTask.javaclose()catch block (thet instanceof Error && !(closeException[0] instanceof Error)swap) - Problem: when a non-fatal
Erroris already the primary failure and a later lifecycle throws aVirtualMachineError, the fatal one is attached as suppressed under the earlierError, then the loop stops; the thrown exception is the earlier non-fatal one. - Best improvement: when
tis aVirtualMachineErrorand the current primary is not, promotetto primary, plus a one-line test. Rare; fine as a follow-up. - Severity: Low
- Raised by another reviewer: No
Issue 3: An old-format serialized task would leave closed null
- Location:
SeaTunnelTask.javafieldclosedandclose() - Problem:
SeaTunnelTaskisSerializablewith an unchangedserialVersionUID. A task serialized by a build without this field and deserialized by a build with it getsclosed == null(initializers do not run on deserialization), andclosed.compareAndSetwould throw aNullPointerExceptionon the firstclose(). I found no documented rolling-upgrade guarantee for Zeta (tasks are deployed by a master of the same build), so this is a note. - Best improvement: a short comment that master and worker must run the same build, or a null-tolerant guard.
- Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Good. The close() Javadoc matches the control flow, closeSuper() and the field explain why they exist (the catch (Exception) around closeSuper() is documented as a test seam), the new test task class has the ASF header, no wildcard imports.
2.2 Test Coverage and Test Stability
SeaTunnelTaskStateTest covers first, middle and last failures (checked and unchecked), repeated close, NoClassDefFoundError, AssertionError, the fatal-error early stop, error-over-exception priority, teardown order, shared exception instance, parent-close failure, null allCycles, and progress.done() on a throwing close. They are deterministic Mockito tests with real outcome assertions (thrown type and suppressed count, not only call counts) and no sleeps. Stability rating: Stable. Earlier tests were only extended, none weakened. The one gap is Issue 1.
2.3 Documentation Updates
Not needed; no user-facing behavior or option change.
3. Architectural Soundness
3.1 Elegance
Precise fix at the right layer, with an explicit policy for fatal errors.
3.2 Maintainability
Good; the policy is in the Javadoc.
3.3 Extensibility
Fine for the current scope.
3.4 Historical-Version Compatibility
Same-version clusters: no impact. See Issue 3 for mixed builds.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | BlockingWorker test cannot fail for the catch or finally it guards |
TaskExecutionServiceTest#testBlockingWorkerFallbackCloseWhenCallAndCloseThrowRuntimeException |
Medium |
| 2 | Fatal VirtualMachineError can end up only as a suppressed exception |
SeaTunnelTask.java close() |
Low |
| 3 | Old-format serialized task would leave closed null |
SeaTunnelTask.java field closed |
Low |
5. Merge Recommendation
Conclusion: Ready to merge
Blockers
- Source: none at the source level; the production change is correct and the
SeaTunnelTasktests discriminate. Issue 1 should be fixed or the test dropped before a committer merges. - CI: the apache-side
Buildcheck for this head isaction_required("noBuildworkflow run was found there for the PR head commit"), and your forkSeaSand1024/seatunnelhas no workflow run for 2a5e21f, so this exact head has not been tested. Please start theBuildworkflow on this branch in your fork (or push an empty commit). For the previous head (6ad74f1) the fork run showed all fourunit-testjobs green; the red jobs wereengine-v2-it(SplitClusterFaultToleranceITcancel race andBackpressureSlowSinkIT) and a Maven Central transfer failure inall-connectors-it-6. The two engine failures belong to open fixes (#12311 and #12316) that are not indevyet, so syncing will not clear them; the branch is 0 commits behinddevnow. After the run, re-running only the failed jobs should be enough.
Recommended fixes (non-blocking): Issue 2 and Issue 3.
Overall assessment: the design decisions (full pass for non-fatal errors, early stop only for fatal ones, idempotent close, always-restored classloader) are the right ones, and the closing contract is well covered by unit tests. A committer approval is still needed. Thank you!
|
Thanks for the follow-up work here. Looking at the current head (2a5e21f, a merge of
Once items 2–5 are confirmed or addressed, I think this is good to go. |
|
Thanks @SEZ9 for going through the current head. I re-read the diff at 2. Does the BlockingWorker fallback rethrow an 3a. 3b. Fallback hitting the already-closed latch. Here I agree with the gap, and it is the same point as Issue 1 in my last review, which is still open. The latch itself is covered at the 4. Javadoc. The 5. CI. Unchanged: the apache-side My remaining open items from the last review are Issue 1 (Medium, the BlockingWorker test) and the two Low notes (a |
Purpose of this PR
Fixes #12231.
SeaTunnelTask.close()only caughtIOExceptionwhile iterating each flowlifecycle's
close(). An unchecked exception (e.g.RuntimeException) thrown by anearlier lifecycle escaped the teardown loop, so every later lifecycle was never
closed — leaking executors, connections and buffers on task teardown.
Changes
seatunnel-engine/seatunnel-engine-server/.../task/SeaTunnelTask.java:Throwable(checkedIOException, uncheckedRuntimeException, andError)around each lifecycle's
close()so a single failure never aborts the teardown loop.suppressed via
Throwable#addSuppressed.addSuppressedwhen the sameThrowableinstance is thrown by more than onelifecycle, so self-suppression (
SelfSuppressionNotPermittedException) cannot abortthe loop.
IOExceptionstays declared asIOException;other checked/unchecked failures are rethrown via
sneakyThrow.seatunnel-engine/seatunnel-engine-server/.../TaskExecutionService.java(review follow-up):Throwableinstead ofIOException, so anunchecked close failure still logs "Close task error" and restores the context
classloader — completes the teardown story from [Bug][Zeta] Unchecked lifecycle close failure skips remaining task resource cleanup #12231.
Tests
Extended the existing
SeaTunnelTaskStateTest(no new test class) with deterministiccoverage, including
testCloseDoesNotSelfSuppressSameFailureInstancefor theaddSuppressedsame-instance guard:testCloseAttemptsEveryCycleWhenEarlierCycleThrowsUnchecked/...ThrowsIoException— an earlier close failure no longer skips later lifecycles (checked and unchecked).
testClosePreservesFirstFailureAndAttachesOthersAsSuppressed— first preserved,subsequent suppressed (3-cycle mixed).
testCloseAttemptsEveryCycleWhenMiddleCycleThrowsUnchecked/...LastCycleThrowsUnchecked— failure in the middle / last position still tears down every lifecycle.
testClosePreservesUncheckedPrimaryWithCheckedSuppressed— sneakyThrow path(unchecked primary,
IOExceptionsuppressed).testCloseAttemptsEveryCycleWhenCycleThrowsError— anErrordoes not abort the loop.testClosePreservesTeardownOrderAcrossLifecycles—InOrderassertion of teardown order.testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTime—close()is repeatable.testCloseDoesNotSelfSuppressSameFailureInstance— shared instance across lifecycles isnot self-suppressed.
Fresh Maven/JUnit evidence (this branch):
Self-review checklist
repeated close, and teardown order.
How tested
SeaTunnelTaskStateTest— 35 tests, 0 failures, 0 errors (Surefire, fresh).Buildworkflow).