Skip to content

[Fix][Zeta] Close all flow lifecycles even when an earlier close fails - #12391

Open
SeaSand1024 wants to merge 9 commits into
apache:devfrom
SeaSand1024:dev-fix-12231-lifecycle-close
Open

SeaSand1024 wants to merge 9 commits into
apache:devfrom
SeaSand1024:dev-fix-12231-lifecycle-close

Conversation

@SeaSand1024

@SeaSand1024 SeaSand1024 commented Sep 19, 2026 •

Copy link
Copy Markdown

Purpose of this PR

Fixes #12231.

SeaTunnelTask.close() only caught IOException while iterating each flow
lifecycle's close(). An unchecked exception (e.g. RuntimeException) thrown by an
earlier 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:

  • Catch Throwable (checked IOException, unchecked RuntimeException, and Error)
    around each lifecycle's close() so a single failure never aborts the teardown loop.
  • Keep teardown order; preserve the first failure and attach subsequent failures as
    suppressed via Throwable#addSuppressed.
  • Skip addSuppressed when the same Throwable instance is thrown by more than one
    lifecycle, so self-suppression (SelfSuppressionNotPermittedException) cannot abort
    the loop.
  • Rethrow the first failure at the end: IOException stays declared as IOException;
    other checked/unchecked failures are rethrown via sneakyThrow.
  • Javadoc updated to reflect the new semantics.

seatunnel-engine/seatunnel-engine-server/.../TaskExecutionService.java (review follow-up):

Tests

Extended the existing SeaTunnelTaskStateTest (no new test class) with deterministic
coverage, including testCloseDoesNotSelfSuppressSameFailureInstance for the
addSuppressed same-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, IOException suppressed).
  • testCloseAttemptsEveryCycleWhenCycleThrowsError — an Error does not abort the loop.
  • testClosePreservesTeardownOrderAcrossLifecycles — InOrder assertion of teardown order.
  • testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTime — close() is repeatable.
  • testCloseDoesNotSelfSuppressSameFailureInstance — shared instance across lifecycles is
    not self-suppressed.

Fresh Maven/JUnit evidence (this branch):

mvn -B -ntp -Dskip.ui=true test -pl seatunnel-engine/seatunnel-engine-server -am -Dtest=SeaTunnelTaskStateTest
Tests run: 35, Failures: 0, Errors: 0, Skipped: 0
BUILD SUCCESS

Self-review checklist

  • Teardown order preserved; every initialized lifecycle is attempted.
  • First failure preserved; subsequent failures suppressed (incl. self-suppression guard).
  • Deterministic coverage for checked vs unchecked vs Error, failure positions,
    repeated close, and teardown order.
  • Change scoped to task cleanup + tests; no unrelated refactors.
  • User-facing change: none — internal cleanup only; no config or public API change.

How tested

  • Local: SeaTunnelTaskStateTest — 35 tests, 0 failures, 0 errors (Surefire, fresh).
  • CI: full unit-test suite running on this branch (Build workflow).

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>
@github-actions github-actions Bot added the Zeta label Sep 19, 2026
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 DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks 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 caught IOException around each FlowLifeCycle.close(). If an earlier lifecycle (for example a sink writer) threw an unchecked exception, the exception escaped the forEach and every later lifecycle was never closed, so their executors, connections and buffers outlived the task.
  • Fix approach: catch Throwable per lifecycle, keep the teardown order, remember the first failure, attach later failures with addSuppressed, and rethrow the first failure at the end (IOException as-is, everything else via sneakyThrow).
  • 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-mode is OFF (ServerConfigOptions.java:495-498, EngineConfig.java:63-65), so tasks run on BlockingWorker. When a task reaches CLOSED or CANCELLING, stateProcess() calls this.close() (SeaTunnelTask.java:292-301). If the task fails earlier, BlockingWorker.run() calls tracker.task.close() in its finally (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) and SourceFlowLifeCycle.close() (SourceFlowLifeCycle.java:216-224) delegate to connector-supplied SinkWriter#close() and SourceReader#close(), which are free to throw unchecked exceptions. On dev the 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.forEach delegates to the underlying sequential stream).
  • The sneakyThrow rethrow 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. IOException keeps its declared type, so the method signature and existing callers are unchanged.
  • Catching Throwable around super.close() is harmless. AbstractTask.close() (AbstractTask.java:98-106) already swallows Exception, 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 the IOException[] slot, and log.error is 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. Catching Throwable (including Error) 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 inside stateProcess(), call() throws, result stays null, and the finally block calls tracker.task.close() a second time (L1314). With this PR that second pass now attempts every lifecycle (good), but it then rethrows the failure through sneakyThrow, and the surrounding catch (IOException e) at L1315 does not match an unchecked exception or Error. The exception therefore escapes run(), the "Close task error" line at L1316 is skipped, and Thread.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() widen catch (IOException e) at L1315 to catch (Throwable e) (keeping the logger.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 the sneakyThrow branch with suppressed entries), and (d) an Error such as AssertionError/LinkageError, since the Javadoc explicitly promises Error handling. Also, the PR checklist says "teardown order preserved", but no test asserts the order; InOrder is 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 with verify(..., times(2)).close(); and an inOrder(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#addSuppressed throws IllegalArgumentException ("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

  1. 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).
  2. Recommended fixes — non-blocking

    • Issue 1 (Medium): widen the catch in BlockingWorker.run(), or track it as a follow-up under #12231. It is not introduced by this PR.
    • Issue 2 (Medium): a few more deterministic cases, so the coverage matches the acceptance list in #12231.
    • Issue 3 (Low): a one-line self-suppression guard.

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 davidzollo added the First-time contributor First-time contributor label Sep 19, 2026
davidzollo
davidzollo previously approved these changes Sep 19, 2026

@davidzollo davidzollo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

+1 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 😄

@SeaSand1024

Copy link
Copy Markdown
Author

@DanielLeens the non-blocking notes are in on 0fc63dc5:

  • BlockingWorker fallback close now catches Throwable, so an unchecked close failure still logs "Close task error" and restores the context classloader.
  • SeaTunnelTaskStateTest covers middle and last failure positions, a second close(), an unchecked primary with a checked suppressed exception, an Error, teardown order, and the shared-exception case.
  • addSuppressed skips the same Throwable instance, so that case cannot abort the close loop.

No user-facing change.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you, @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:1314 now catches Throwable in the BlockingWorker fallback close (previous Issue 1: resolved).
  • SeaTunnelTaskStateTest.java gained the middle/last failure, repeated close(), unchecked-primary-with-checked-suppressed, Error, teardown-order and shared-instance cases (previous Issue 2: resolved).
  • SeaTunnelTask.java:468 now guards addSuppressed with t != 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 caught IOException around each FlowLifeCycle.close(). An unchecked exception from one lifecycle (for example a connector SinkWriter#close() or SourceReader#close()) escaped the teardown loop, so every later lifecycle was never closed and its threads, connections and buffers leaked.
  • Fix approach: catch Throwable per lifecycle, keep the teardown order, remember the first failure, attach later ones with addSuppressed (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] and sink-A.close() throws IllegalStateException. Before: sink-B was never closed. Now: sink-B is closed, the task still fails with the IllegalStateException, 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 on BlockingWorker. A task that finishes or is cancelled reaches case CLOSED / case CANCELLING in SeaTunnelTask.stateProcess(), which calls this.close() (SeaTunnelTask.java:292-298). A task that fails earlier reaches tracker.task.close() in the worker's finally (TaskExecutionService.java:1310-1316). This is routine teardown, not a rare corner.
  • The reported leak is real. SinkFlowLifeCycle.close() (SinkFlowLifeCycle.java:277-283) and SourceFlowLifeCycle.close() (SourceFlowLifeCycle.java:216-224) delegate to connector code (writer.close(), reader.close()) that may throw unchecked exceptions, and TransformFlowLifeCycle.close() and IntermediateQueueFlowLifeCycle.close() (IntermediateQueueFlowLifeCycle.java:65-68) are also part of the same loop. On dev the IOException-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); an IOException keeps its declared type, so the throws IOException signature and existing callers are unchanged.
  • The self-suppression guard is correct. Throwable#addSuppressed(self) throws IllegalArgumentException; the t != 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.error per 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 InterruptedException can be thrown by FlowLifeCycle.close() (it declares only IOException), 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 inside stateProcess(), the blocking worker calls task.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 test testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTime documents 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. Catching Throwable (including Error) 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 IOException case, 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 at TaskExecutionService.java:1314.
  • Previous Issue 2 (missing middle/last/repeat/Error/mixed-suppressed/order coverage): resolved, see 2.2.
  • Previous Issue 3 (addSuppressed self-suppression guard): resolved at SeaTunnelTask.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 sneakyThrow branch (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

@SeaSand1024

Copy link
Copy Markdown
Author

@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 0fc63dc5:

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.

@SEZ9

SEZ9 commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator

@SeaSand1024 thanks for the quick turnaround on 0fc63dc5 and for the clear CI breakdown.

On the changes themselves: the Throwable catch in the BlockingWorker fallback close, the same-instance guard around addSuppressed, and the extra SeaTunnelTaskStateTest cases (middle/last failure position, repeated close(), unchecked primary with checked suppressed, Error, teardown order, shared instance) cover exactly the gaps I'd want closed here. Nothing further from me on the code, and I agree with @davidzollo's +1.

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:

  1. Once the re-run finishes, please drop a short note here with the result for engine-v2-it and all-connectors-it-2.
  2. If SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck fails again on 0fc63dc5, please paste the assertion/stack snippet from that run so we can confirm it is the same CANCELED vs FAILED symptom as [Bug][Zeta] Worker crash during cancellation resolves job as FAILED #12353 and not something new from this PR. If it matches, I'm fine treating it as a known flaky race; we can either wait for [Fix][Zeta] Preserve cancellation after worker failure #12377 to land and rebase, or merge on the green unit-test matrix plus a clean re-run of the other IT jobs.
  3. If OpengaussCDCIT is still red after the re-run, please confirm it's the testcontainers startup issue (e.g. image pull / container start failure) rather than a test assertion, since that job is unrelated to the engine code touched here.

No need to push anything else unless the re-run surfaces something new.

@DanielLeens

Copy link
Copy Markdown
Contributor

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 SubPlan terminal-state selection, which is a different contract from the close-all-flow-lifecycles change here, and mixing the two would make both harder to review and to revert.

On my side, the source-level points from my last review on 0fc63dc5 are closed, so I do not see a new code-side blocker in this PR. The remaining gate is CI on the fork run.

What I can see from the fork run for this head (run attempt 3): the failed jobs are engine-v2-it and all-connectors-it-2 on both JDK 8 and JDK 11, and the unit-test matrix is not among them. That matches your description. I have not independently re-read each individual assertion line in those job logs, so please treat the attribution below as a reading of the job names plus your notes rather than a log-level proof:

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.

@SEZ9

SEZ9 commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

@SeaSand1024 thanks for the CI breakdown on 0fc63dc5 and for keeping this PR scoped to the lifecycle-close contract.

Agreed on scope: please do not fold the #12353 / #12377 cancel-race fix into #12391. That touches SubPlan terminal-state selection, which is a separate contract from the close-all-flow-lifecycles change here, and mixing them would make both harder to review and revert.

On the code side, the three points from the earlier review (the Throwable catch in the BlockingWorker fallback close, the added SeaTunnelTaskStateTest cases, and the t != closeException[0] guard around addSuppressed) are resolved between 0663920 and 0fc63dc, so I don't see a remaining code blocker.

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.

@SeaSand1024

Copy link
Copy Markdown
Author

@DanielLeens @SEZ9 the failed-jobs re-run on head 0fc63dc5 is finished (fork run attempt 3, no new commits): https://github.com/SeaSand1024/seatunnel/actions/runs/35424513689

Unit-test matrix stayed green. engine-v2-it and all-connectors-it-2 are still red on both JDKs.

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.

@DanielLeens

Copy link
Copy Markdown
Contributor

@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 0fc63dc5, and the diff against my last review is unchanged (same three files), so nothing below required a fresh code review, just triage of the four red jobs.

Good news first: OpengaussCDCIT.testAddFieldWithRestore (all-connectors-it-2, both JDKs) should clear with a dev sync. That failure's real root cause was found and fixed in #12346 ("Preserve disabled CDC schema behavior"), which merged into dev on 2026-09-20 — it's the fix for the exact issue you both were tracking as #12344. This branch is currently 24 commits behind dev (per the compare view), so it predates that fix, which is why your fork re-run still hits it. Unlike the other three jobs below, this one is not "wait for an open PR" — the fix is already on dev. @SeaSand1024, could you sync/merge latest dev into this branch (no need for a full rebase, just picking up dev HEAD is enough) and re-run all-connectors-it-2? I'd expect it to go green.

The other three failures are pre-existing dev-level flakes, none of them touching the code this PR changes, and none of them fixed yet:

  • SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck (engine-v2-it, JDK 8) — this is the known CANCELED-vs-FAILED race tracked in #12353. The fix (#12311) is still open, not merged, so syncing dev won't clear this one — same conclusion as my last comment, just re-confirmed live.
  • CheckpointCoordinatorFailoverIT.testStreamJobFailsAfterCheckpointTriggerDispatchFailure (engine-v2-it, JDK 11) — this is a new one for this thread, but it's a known racy fault-injection timing issue in the test itself (the readiness gate it uses can fire before the checkpoint it's supposed to target has actually completed, so the injected fault can land on either checkpoint and surface as different symptoms, including the taskGroupLocation lookup failure you saw). A fix for the test's fault-injection ordering is open in #12288, not yet merged. Nothing in this PR's diff touches CheckpointCoordinator or barrier/notify dispatch, so I don't read this as caused by this change.
  • BackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressure (engine-v2-it, JDK 11) — known checkpoint-lock-starvation flake under sustained backpressure. Fixes are open in #12316 (engine fix) and #12313 (test-only, complementary), neither merged yet.

So: sync dev and re-run all-connectors-it-2 — that should turn green. The two engine-v2-it (JDK 11 leg gets both CheckpointCoordinatorFailoverIT and BackpressureSlowSinkIT; JDK 8 gets SplitClusterFaultToleranceIT) failures will very likely stay red until #12311, #12288, and #12316/#12313 land, since none of those are in dev yet. That's a judgment call for whoever merges this: the code side has been ready since my last review, and all four red jobs are now attributed to specific, tracked, pre-existing issues rather than anything in this diff — a committer could reasonably merge on the green unit-test matrix plus this attribution once the Opengauss job is confirmed green post-sync, without waiting for the other three upstream fixes.

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.

@SEZ9

SEZ9 commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

@SeaSand1024 nothing new from me beyond my last comment, just to keep the next step clear:

  • Please sync latest dev into this branch and re-run all-connectors-it-2. If OpengaussCDCIT.testAddFieldWithRestore still fails after the sync, post the job link and we'll triage it fresh rather than assume it's pre-existing.
  • The engine-v2-it failures on 0fc63dc5 (jobs 106082736268 / 106082736247) stay out of scope here, and as before, please keep the cancel-race fix out of this PR.

Once the all-connectors-it-2 re-run is in, I'll make the merge call.

@SeaSand1024

Copy link
Copy Markdown
Author

Synced latest dev into this branch (merge 57890813b). all-connectors-it-2 is green on both JDKs:

OpengaussCDCIT.testAddFieldWithRestore is not failing on this run. engine-v2-it left out of scope.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SeaSand1024 for the sync and the direct job links. I checked this the same way as last time: git compare between the previously-reviewed head (0fc63dc) and the new one (5789081) shows 28 commits and 177 changed files, none of which are this PR's own three files (TaskExecutionService.java, SeaTunnelTask.java, SeaTunnelTaskStateTest.java). So this is confirmed a pure dev-sync -- zero overlap with the diff I already reviewed -- and doesn't reopen the code review.

On the CI picture: OpengaussCDCIT.testAddFieldWithRestore going green on both JDKs in your linked runs matches the expected outcome now that #12346 (merged to dev on 2026-09-20) is picked up by the sync. engine-v2-it staying out of scope is still correct -- SplitClusterFaultToleranceIT depends on #12311, which hasn't merged yet, so that failure mode is unrelated to this PR's diff and untouched by the sync.

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 all-connectors-it-2, without waiting on the separately-tracked engine-v2-it flakes.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks again for 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 caught IOException around each FlowLifeCycle.close(). An unchecked exception thrown by one lifecycle (for example a connector SinkWriter#close() or SourceReader#close()) escaped the teardown forEach, so every lifecycle after the failing one was never closed, and its executors, connections and buffers leaked.
  • Fix approach: catch Throwable per lifecycle instead of only IOException, keep the teardown order, remember the first failure, attach later failures to it via addSuppressed (skipping the case where the same instance is thrown twice), and re-throw the first failure at the end (IOException as-is, everything else via the existing sneakyThrow idiom). 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] and sink-A.close() throws IllegalStateException. Before: sink-B is never closed. After: sink-B is still closed, the task still fails with the original IllegalStateException, 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-mode is OFF, so every task runs on BlockingWorker. A task that finishes or is cancelled reaches case CLOSED / case CANCELLING in SeaTunnelTask.stateProcess() (SeaTunnelTask.java:292-298), which calls this.close(). A task that fails earlier reaches tracker.task.close() in the worker's finally (TaskExecutionService.java:1310-1316). This is routine teardown, not a rare corner.
  • The leak is real. SinkFlowLifeCycle.close() (SinkFlowLifeCycle.java:277-283) delegates to writer.close(), SourceFlowLifeCycle.close() (SourceFlowLifeCycle.java:216-224) delegates to reader.close(), and TransformFlowLifeCycle.close() / IntermediateQueueFlowLifeCycle.close() are also part of the same loop. Connector-supplied writer.close()/reader.close() are free to throw unchecked exceptions, and on dev the IOException-only catch really did skip everything after the first unchecked failure.
  • Teardown order is preserved. allCycles.stream() is a plain sequential Stream from a List, and MDCTracer.tracing(Stream) (seatunnel-api/.../tracing/MDCTracer.java) just wraps it in an MDCStream that delegates forEach to the same sequential stream, so the loop still closes lifecycles in list order. The new testClosePreservesTeardownOrderAcrossLifecycles test locks this in with InOrder.
  • 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 overload sneakyThrow(Exception t) in the same class, but since closeException[0] is statically typed Throwable, only the Throwable overload is applicable — no ambiguity, no accidental narrowing.
  • The self-suppression guard is correct. Throwable#addSuppressed(self) throws IllegalArgumentException; the t != closeException[0] check at SeaTunnelTask.java:468 prevents that from escaping the lambda and aborting the loop. testCloseDoesNotSelfSuppressSameFailureInstance exercises exactly this.
  • super.close() being widened to catch Throwable is 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 if restoreComplete.cancel(true) ever threw an Error, 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.error per 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 running close().
  • 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 TaskExecutionService fails unexpectedly.
  • Double close on failure (already discussed in the previous round, re-confirmed here): when close() fails inside stateProcess(), the blocking worker calls task.close() a second time (TaskExecutionService.java:1313), which now re-attempts every lifecycle. testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTime documents that this is safe at the SeaTunnelTask loop 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-lifecycle completableFuture, and SeaTunnelTask.init() (SeaTunnelTask.java:189-190) aggregates all of these via CompletableFuture.allOf(flowFutures).whenComplete((s, e) -> closeCalled = true), which in turn gates the PREPARE_CLOSE -> CLOSED state transition (SeaTunnelTask.java:283-289). Of the four FlowLifeCycle implementations in the loop this PR fixes, only SinkFlowLifeCycle.close() (SinkFlowLifeCycle.java:276-279) calls super.close() first, before its own writer.close(). SourceFlowLifeCycle.close() calls reader.close() before super.close(); TransformFlowLifeCycle.close() calls t.close() / errorHandler.close() before super.close(); IntermediateQueueFlowLifeCycle.close() calls queue.close() before super.close(). None of these three wrap the resource-specific step in try/finally, so if that step throws, super.close() — and therefore that lifecycle's own completableFuture.complete(null) — is skipped for that lifecycle instance.
  • Potential risk: in isolation this looks concerning (an unfinished completableFuture could in theory leave closeCalled permanently false), but I traced the actual production trigger for closeCalled and it is AbstractTask.tryClose(long) → closeCall() (AbstractTask.java:122-127, called from SeaTunnelTask.java:574,580,586 on checkpoint-barrier completion), which sets closeCalled = true directly and does not depend on flowFutures. I could not find any call site that invokes an individual FlowLifeCycle#close() before SeaTunnelTask.close() itself runs, so in the code paths I traced, the flowFutures/allOf wiring never gets a chance to be the deciding factor in practice — closeCalled is already true via the checkpoint-barrier path by the time SeaTunnelTask.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 unrelated SubPlan cancel-race fix). Fixing per-lifecycle try/finally ordering 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() in try { ... } 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 (including Error) 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:1314 catches Throwable.
  • Previous Issue 2 (missing middle/last/repeat/Error/mixed-suppressed/order coverage): still resolved, see 2.2.
  • Previous Issue 3 (addSuppressed self-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 @throws Javadoc 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 on BackpressureSlowSinkIT.testCheckpointsKeepCompletingUnderSustainedBackpressure and SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck — these are exactly the two pre-existing, already-tracked flakes discussed earlier in this thread (open fixes #12316/#12313 and #12311, none merged to dev yet), 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 on OceanBaseCDCCompatibilityIT.testOceanBaseCdcWrapperRuntimeE2e (a Flink-runtime OceanBase CDC E2E failure), and transform-v2-it-part-1 (11, ubuntu-latest) fails on TestFilterRowKindIT.testFilterRowKindMultiTable:53 (expected: <0> but was: <1>). Neither test touches seatunnel-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 real dev-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.

@SEZ9

SEZ9 commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

@SeaSand1024 thanks for syncing dev and posting the direct job links — that's exactly the evidence needed here.

Checked on my side:

  • The PR diff at 57890813b is identical to what was reviewed at 0fc63dc5; the sync (merge 57890813b) brought in only upstream dev commits and touched none of the files this PR changes, so the earlier code review still stands and nothing needs to be re-opened.
  • all-connectors-it-2 in run 35870424836 is green on both 107213895744 (JDK 8) and 107213896064 (JDK 11), and OpengaussCDCIT.testAddFieldWithRestore no longer fails there, which is the outcome we expected once the branch picked up the current dev.
  • Agreed that engine-v2-it stays out of scope for this PR — that failure mode is unrelated to your diff and unaffected by the sync.

No remaining asks from me on the previously raised point; the CI gap that was attributable to this branch being behind dev is closed. I'll proceed on the green unit-test matrix plus the now-green all-connectors-it-2. If anything in CI changes before merge, please drop the run link here as you did this time.

@DanielLeens

Copy link
Copy Markdown
Contributor

@SeaSand1024 @SEZ9 one correction to my last comment before we call this ready to merge.

I went back through fork run 35870424836 job by job instead of relying on job names alone (it's the same run that confirmed all-connectors-it-2 green), and the apache-side Build check is still reporting FAILURE on this head for a reason beyond what we've covered so far. Two more jobs in that same run are red and neither of us had flagged them yet:

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 AssertSinkWriter evaluates static JVM-wide row counters per subtask close(); it's already reproduced the same wrong-row-count symptom on two unrelated PRs (#11458, #11077). Nothing in this PR's diff or in the Zeta engine touches AssertSinkWriter, so I read this as the same category of pre-existing noise.

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 SeaTunnelTask.close() path this PR touches, so mechanically I don't see how this diff could cause either — but "mechanically unrelated" isn't the same as "confirmed pre-existing," so I'd rather not wave it away without another data point. @SeaSand1024, could you re-run just all-connectors-it-5 (8, ubuntu-latest) and post the result? Green on a re-run would put it in the same bucket as the other testcontainers-level flakes we already tracked down; a repeat failure with the same error would mean we should look at it properly before merging.

For completeness: engine-v2-it (8, ubuntu-latest) in this same run is still SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck, the same #12353/#12311 symptom we've already attributed — nothing new there, just re-confirmed on this exact head.

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 all-connectors-it-5 re-run is in — one more real data point is worth the short wait.
=== END REPLY ===

@SEZ9

SEZ9 commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

Quick follow-up on where this stands from my side.

My last formal review submission was against 0fc63dc5, and the branch has since picked up the dev sync (merge 57890813b). Based on the re-read posted above, the actual diff on 57890813b is unchanged from 0fc63dc5 and the earlier review points remain resolved, so I have nothing new to raise on the code itself.

The one thing still open before I'd refresh my formal review state on the current head is the CI picture from fork run 35870424836:

  • transform-v2-it-part-1 (11, ubuntu-latest) (job 107213895413): the TestFilterRowKindIT.testFilterRowKindMultiTable failure matches the already-filed flake in [Bug][Connector-V2][Assert] Multi-table row-count rules flaky on Flink: AssertSinkWriter uses static JVM-wide counters evaluated per-subtask close() #12116, and nothing in this diff touches AssertSinkWriter. I'm fine treating that as pre-existing noise.
  • all-connectors-it-5 (8, ubuntu-latest) (job 107213895383): OceanBaseCDCCompatibilityIT.testOceanBaseCdcWrapperRuntimeE2e failing with Flink job executed failed. This runs against the Flink translation layer rather than the Zeta SeaTunnelTask.close() path this PR changes, so I don't see a mechanism for the diff to cause it, but there is only one occurrence and no pre-filed issue for this exact symptom yet.

Concrete ask: please re-run just all-connectors-it-5 (8, ubuntu-latest) on 57890813b and post the result here. If it comes back green, I'll bucket it with the other testcontainers-level flakes and submit a fresh review against the current head. If it fails again with the same error, let's look at it properly before merging.

@DanielLeens

Copy link
Copy Markdown
Contributor

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

  • Code side: unchanged since the diff I reviewed on 0fc63dc5; the dev sync that produced 57890813b is byte-identical for this PR's three files, so there is no new code-side blocker.
  • transform-v2-it-part-1 -> TestFilterRowKindIT.testFilterRowKindMultiTable: I'm treating this the same way you are, as the already-filed [Bug][Connector-V2][Assert] Multi-table row-count rules flaky on Flink: AssertSinkWriter uses static JVM-wide counters evaluated per-subtask close() #12116 AssertSinkWriter static-counter flake on Flink legs. Nothing in this PR's diff touches AssertSinkWriter.
  • all-connectors-it-5 -> OceanBaseCDCCompatibilityIT.testOceanBaseCdcWrapperRuntimeE2e: still only one occurrence and I could not find a pre-filed issue for this exact symptom, so I'd rather have a second data point than assume it's noise. Mechanically it runs against the Flink translation layer, not the Zeta SeaTunnelTask.close() path this PR touches, so I don't see a plausible causal path from this diff, but "mechanically unrelated" isn't the same as "confirmed pre-existing."

Once @SeaSand1024 posts the all-connectors-it-5 re-run result, I'll fold it into a fresh review comment against 57890813b: green closes it out as another testcontainers/E2E flake unrelated to this PR, a repeat failure with the same error means we look at it properly before merging. No action needed from either of you beyond that re-run; I'll pick this back up as soon as the result is posted.

@SeaSand1024

Copy link
Copy Markdown
Author

Re-ran all-connectors-it-5 (8, ubuntu-latest) on 57890813b (attempt 2): failure — https://github.com/SeaSand1024/seatunnel/actions/runs/35870424836/job/110327089414
Public annotations only show exit code 1; I cannot download job logs from this environment. Prior attempt on the same tip failed in OceanBaseCDCCompatibilityIT.testOceanBaseCdcWrapperRuntimeE2e (ProgramInvocationException: The main method caused an error: Flink job executed failed). Someone with fork Actions access should paste the OceanBase/Surefire snippet from attempt 2 so we can confirm it matches before merge.

@SeaSand1024

Copy link
Copy Markdown
Author

@DanielLeens @SEZ9 follow-up on the all-connectors-it-5 (8) re-run (attempt 2) with the Surefire snippet:

Result: still failure — https://github.com/SeaSand1024/seatunnel/actions/runs/35870424836/job/110327089414

Same test as before: OceanBaseCDCCompatibilityIT.testOceanBaseCdcWrapperRuntimeE2e — 2 errors / 3 runs.

[ERROR] testOceanBaseCdcWrapperRuntimeE2e{TestContainer}[1]  <<< ERROR!
org.apache.flink.client.program.ProgramInvocationException: The main method caused an error: Flink job executed failed
Caused by: ... CommandExecuteException: Flink job executed failed
Caused by: ... TaskExecuteException: Execute Flink job error
Caused by: org.apache.flink.util.FlinkRuntimeException: Error in serialization.

[ERROR] testOceanBaseCdcWrapperRuntimeE2e{TestContainer}[2]  <<< ERROR!
(same ProgramInvocationException / Flink job executed failed)

Test ...testOceanBaseCdcWrapperRuntimeE2e successfully run.   # seatunnel-engine / Zeta leg

So the repeat failure is on the Flink translation legs only; the Zeta/seatunnel-engine parameterized leg on this tip is green. That matches the earlier read that this is outside the SeaTunnelTask.close() path this PR changes. No new commits. Happy to dig further if you want a tracked issue / comparison against plain dev, or to wait for a committer call on merge vs hold.

@SeaSand1024

Copy link
Copy Markdown
Author

Triage on the repeat OceanBaseCDCCompatibilityIT Flink failure (attempt 2 job https://github.com/SeaSand1024/seatunnel/actions/runs/35870424836/job/110327089414):

@SeaSand1024

Copy link
Copy Markdown
Author

@DanielLeens @SEZ9 follow-up on tip 2cc06fc43 (dev sync picking up #12477).

Closed out from last ask: all-connectors-it-5 is green on both JDKs after the sync — OceanBase Flink serializedUDF no longer fails (as expected with #12477).

Build still reports FAILURE on that run for three other jobs (none are close-path / OceanBase). Attribution from the logs:

  1. unit-test (11, ubuntu-latest) https://github.com/SeaSand1024/seatunnel/actions/runs/36852053400/job/110336780523
    SavePointTest.testSavePointButJobGoingToFail — expected: <RUNNING> but was: <FAILED> within 2 minutes. Checkpoint/savepoint path; not the three files in this PR. Possibly adjacent to open [Bug][Zeta] startSavepoint holds the coordinator lock across its sleep-poll, blocking concurrent checkpoint triggers #12441 (startSavepoint lock). Re-running this job now.

  2. all-connectors-it-2 (8, ubuntu-latest) https://github.com/SeaSand1024/seatunnel/actions/runs/36852053400/job/110336781393
    Not a test assertion — Maven DependencyResolutionException transferring hadoop-annotations:3.3.4 from Central while resolving connector-cdc-mongodb-e2e. Re-running.

  3. oracle-cdc-connector-it (8, ubuntu-latest) https://github.com/SeaSand1024/seatunnel/actions/runs/36852053400/job/110336781621
    Maven wrapper download 404 (infra; no Surefire reports). Re-running.

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 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 escaped SeaTunnelTask.close() (which only caught IOException), so every later lifecycle in allCycles was never closed, leaking executors, connections and buffers (#12231).
  • Fix approach: SeaTunnelTask.close() now catches Throwable around super.close() (SeaTunnelTask.java:456) and each flowLifeCycle.close() (:464), keeps the first failure, attaches later distinct failures via addSuppressed guarded by t != closeException[0] (:468), and rethrows an IOException as-is (:474-475) or anything else via sneakyThrow (:477); BlockingWorker's fallback tracker.task.close() now catches Throwable instead of IOException (TaskExecutionService.java:1314) so an unchecked close failure is logged and the context classloader is still restored; ten new unit tests in SeaTunnelTaskStateTest cover 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 the BlockingWorker fallback, the @throws Javadoc does not match the actual control flow (AbstractTask.close() swallows all Exceptions, so only an Error can be collected at :456-457), and the end-to-end BlockingWorker path 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-477 is reached from stateProcess() case CLOSED: this.close(); progress.done(); (lines 293-294) and the equivalent CANCELLING branch (lines 298-300). When any lifecycle throws, progress.done() is skipped, the exception propagates to BlockingWorker.run()'s catch (Throwable e) (TaskExecutionService.java:1302), and the finally sees result == null || !result.isDone() (:1311) and calls tracker.task.close() again (:1313). With this PR the first pass is guaranteed to have already visited every lifecycle, so the second pass re-runs SinkFlowLifeCycle.close(), SourceFlowLifeCycle.close() and IntermediateQueueFlowLifeCycle.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 test testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTime (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 the Close task error log 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 an AtomicBoolean closed guard (return early on the second call, which also makes the BlockingWorker fallback harmless), and in the CLOSED/CANCELLING branches call progress.done() in a finally so a close failure does not re-enter the fallback path. Update testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTime to 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/CANCELLING it skips progress.done(), the exception lands in BlockingWorker.run()'s catch (Throwable), and the finally sees !result.isDone() and calls tracker.task.close() again — so every lifecycle (including the ones that closed cleanly) gets writer.close()/reader.close() a second time. Connector close methods aren't required to be idempotent, and a second-close exception becomes the Close task error entry that hides the real cause. Could we add an AtomicBoolean closed guard here (return early on re-entry) and/or move progress.done() into a finally in the CLOSED/CANCELLING branches? testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTime would 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 wraps super.close() and every flowLifeCycle.close() in catch (Throwable t) (SeaTunnelTask.java:456, :464) and the BlockingWorker fallback was widened from catch (IOException e) to catch (Throwable e) (TaskExecutionService.java:1314). There is no carve-out for VirtualMachineError/ThreadDeath, so after an OutOfMemoryError from one lifecycle the loop continues calling SinkWriter.close()/SourceReader.close() and executor shutdowns in a heap-exhausted JVM, and when sneakyThrow finally rethrows it, TaskExecutionService.java:1314-1315 just logs Close task error and returns normally.
  • Impact: before this PR an Error in the fallback close escaped run() 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 for AssertionError, and the Javadoc at SeaTunnelTask.java:444 promises it, so this is intentional for all Error types rather than an oversight.
  • Fix: in both catch blocks rethrow immediately when t instanceof VirtualMachineError || t instanceof ThreadDeath || t instanceof LinkageError (or add a small ExceptionUtil.rethrowIfFatal(Throwable) helper in engine-common and use it in both places), and keep the collect-and-continue semantics for Exception subclasses 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 Throwable here (and in the super.close() block above, plus the widened catch in BlockingWorker) means an OutOfMemoryError/ThreadDeath from one lifecycle no longer stops teardown: we keep calling connector close() code in a heap-exhausted JVM, and the fallback at TaskExecutionService.java:1314 then just logs it as Close task error. I'd keep collect-and-continue for Exception but rethrow fatal errors immediately, e.g. if (t instanceof VirtualMachineError || t instanceof ThreadDeath) throw t; (or a shared rethrowIfFatal helper in ExceptionUtil) at the top of both catch blocks, and reword the Javadoc at line 444 so it no longer promises to absorb Error.
  • 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 allCycles via reflection and call task.close() directly on a mock with the real method, so the catch (Throwable t) around super.close() (SeaTunnelTask.java:456-457) is never exercised with a failure, and nothing asserts the first-failure-wins ordering when super.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 a RuntimeException from Task.close() in BlockingWorker.run() is logged and that the thread still restores the context classloader (:1319) and reaches taskDone (:1310). Since the PR description presents this as the piece that completes the teardown story, it should have coverage.
  • testCloseCanBeCalledRepeatedlyClosingEachLifecycleEachTime (SeaTunnelTaskStateTest.java:566) asserts times(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 small SeaTunnelTask subclass) and asserts a lifecycle failure is attached as suppressed; and extend an existing TaskExecutionService test to drive a Task whose call() and close() both throw RuntimeException and 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 second close() re-closes every lifecycle. Given BlockingWorker re-invokes task.close() whenever the first one throws, I'd rather we make close() idempotent and assert times(1) here. Separately, none of the new tests hit the super.close() failure branch (SeaTunnelTask.java:456-457) or the widened catch (Throwable) in TaskExecutionService.java:1314 — a test where call()+close() both throw RuntimeException and 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 because AbstractTask.close() (AbstractTask.java:99-106) wraps its only statement in catch (Exception ignore); the real IOException source is a lifecycle close, which the clause no longer mentions. @throws RuntimeException (SeaTunnelTask.java:449) omits that Error is also rethrown via sneakyThrow (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 by TaskExecutionService.java:1315 as Close task error. On a task with several failing lifecycles an operator sees N+1 stack traces for one teardown with no taskLocation or lifecycle class name to tell them apart.
  • Fix: rewrite the @throws tags to @throws IOException if the first failing lifecycle threw an IOException / @throws RuntimeException or Error (via sneakyThrow) otherwise, and include taskLocation and flowLifeCycle.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 swallows Exception, so this @throws IOException path cannot happen — the real IOException source is a lifecycle close; and @throws RuntimeException on the next line should mention that Error is rethrown via sneakyThrow too, as the paragraph above promises. (2) The log.error("Close FlowLifeCycle error.", t) at line 465 has no task/lifecycle context and the same throwable is logged again as Close task error by BlockingWorker; including taskLocation and flowLifeCycle.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 in catch (Exception ignore), so the new catch (Throwable t) at SeaTunnelTask.java:456 can only ever observe an Error. Meanwhile allCycles is assigned inside init() (SeaTunnelTask.java:185) after super.init() and the metrics/observability setup that precede it; if any of those throw, BlockingWorker still calls tracker.task.close() (TaskExecutionService.java:1313) and allCycles.stream() at SeaTunnelTask.java:459 throws NullPointerException.
  • Impact: this is pre-existing, but the PR's stated goal is a complete teardown story; with the widened fallback catch in TaskExecutionService.java:1314 the NPE is now logged as Close task error rather than escaping run(), which hides the real init() failure's cleanup problem behind an unrelated NPE stack.
  • Fix: guard the loop with if (allCycles != null) (or initialise allCycles = new ArrayList<>() at the field declaration and clear() it in init()), and reduce the catch (Throwable) around super.close() to a plain call or catch (IOException) since the base already swallows Exception, 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 the BlockingWorker fallback, and close() itself is not idempotent.
  • 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.
  • 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.
  • 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.
  • 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.

Thanks for the updates so far. Happy to discuss the remaining points.

@SeaSand1024

Copy link
Copy Markdown
Author

@SEZ9

SEZ9 commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

@SeaSand1024 thanks for the CI breakdown on tip 2cc06fc43. Good to see all-connectors-it-5 green on both JDKs after the dev sync, and the attempt-2 re-run clearing unit-test (11, ubuntu-latest), all-connectors-it-2 (8, ubuntu-latest) and oracle-cdc-connector-it (8, ubuntu-latest) — the attribution to the savepoint test, Maven dependency resolution and the wrapper download 404 looks like unrelated flakiness, so nothing there blocks this PR.

Since the sync contained no close-path edits, the earlier review points are still open. What's still needed in SeaTunnelTask.java:

  1. F1 – double-close / idempotency: when a single lifecycle close() fails on the normal CLOSED/CANCELLING path, the method still completes the pass and rethrows, so the BlockingWorker fallback closes every lifecycle (including the clean ones) again. Please make close() idempotent (or track which lifecycles already closed) so the fallback doesn't re-close them.
  2. F2 – catch (Throwable) in both teardown loops: this swallows fatal JVM errors (OOM, ThreadDeath, StackOverflowError) and keeps calling connector close() after an OOM, while BlockingWorker downgrades the error to a severe log. Please narrow to Exception (or rethrow Errors immediately).
  3. F5 – super.close() catch + allCycles guard: the widened catch (Throwable) around super.close() can only collect an Error in practice, and allCycles is still dereferenced unguarded right after, so an init() failure before allCycles is assigned still NPEs on the fallback close path. A null check there would be enough.
  4. F4 – Javadoc + log context: the Javadoc throws clauses no longer reflect the actual control flow, and the per-lifecycle error log lacks task/lifecycle identifiers, so each failure is logged twice (here and in BlockingWorker) with no way to correlate them. Please update the Javadoc and add task id + lifecycle name to the log line.

On the test side (F3, SeaTunnelTaskStateTest.java): the new tests exercise 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 that now absorbs unchecked close failures. A test for each would let us verify F1/F5 behave as intended.

Once those land I'm happy to take another look. No need to re-run the full CI matrix before then — a green unit-test on the follow-up commit is sufficient.

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

Copy link
Copy Markdown
Author

@SEZ9 @DanielLeens F1–F5 addressed on tip 877056bf1 (close-path + tests only).

F1 idempotency: AtomicBoolean closed makes close() a no-op on re-entry; progress.done() is in finally on CLOSED/CANCELLING. Repeated-close test now asserts times(1).

F2 catch narrowing: lifecycle teardown and BlockingWorker fallback close catch Exception only so fatal JVM Errors propagate (Error test expects later cycles not closed).

F5 super.close() + allCycles: closeSuper() + catch (Exception); loop guarded with if (allCycles != null).

F4 Javadoc + log: @throws updated; per-lifecycle log includes taskLocation and lifecycle simple name.

F3 tests: testClosePreservesSuperCloseFailureAndAttachesLifecycleFailuresAsSuppressed, null-allCycles, CLOSED progress.done() on close failure; testBlockingWorkerFallbackCloseWhenCallAndCloseThrowRuntimeException for call()+close() both throwing RuntimeException.

Local: SeaTunnelTaskStateTest — Tests run: 38, Failures: 0, Errors: 0, Skipped: 0.

@SeaSand1024

Copy link
Copy Markdown
Author

@SEZ9 @DanielLeens one deliberate consequence of F2 (catch (Exception) only in the BlockingWorker fallback finally): if fallback close() throws a fatal JVM Error (OOM / ThreadDeath / StackOverflowError), that exception escapes before setContextClassLoader(oldClassLoader), so the worker thread’s context classloader stays unrestored. Only relevant when the JVM is already unrecoverable; not treated as a merge blocker. Nested-finally restore would be optional polish.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you 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 only IOException per FlowLifeCycle.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 (IOException as is, others via sneakyThrow). At this head it also adds a close-once latch (AtomicBoolean closed), try/finally around close() in the CLOSED and CANCELLING states, and narrows the catches to Exception.
  • 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:

  • SeaTunnelTask is Serializable through Task, so the new private final AtomicBoolean closed is part of the Java-serialized task. It must stay non-transient (a transient final would be null after deserialization), and it is: AtomicBoolean is serializable and starts false on deploy. Tasks are serialized before they run, so no old-version task ever carries a true value. Please keep it that way.
  • The only other direct caller of SeaTunnelTask.close() besides the state machine and the BlockingWorker fallback is CloseRequestOperation.runInternal(); I could not find any code that constructs that operation in main (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.java close() (latch at the top, catch (Exception e) in the loop), and the test SeaTunnelTaskStateTest#testCloseAttemptsEveryCycleWhenCycleThrowsError (asserts never()).
  • Problem: closed is flipped before any lifecycle is closed, and only Exception is caught per lifecycle. Any Error thrown by a connector close() aborts the loop, and the BlockingWorker fallback can no longer finish the job because close() now returns immediately. This is the same class of leak #12231 is meant to remove, just triggered by an Error instead of a RuntimeException. Non-fatal Errors are realistic here: NoClassDefFoundError, ExceptionInInitializerError, other LinkageErrors (a closed or unloaded plugin classloader during teardown) and AssertionError all derive from Error and 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 Throwable per lifecycle, collect it as first or suppressed as today, and stop the loop early only for VirtualMachineError (OutOfMemoryError, StackOverflowError, InternalError) and ThreadDeath, rethrowing it after recording. Rethrow the first failure at the end (add an Error branch next to the IOException branch; sneakyThrow already handles it). Update the test to assert that later lifecycles are closed for an AssertionError or NoClassDefFoundError, and add one case showing a VirtualMachineError stops the loop. The alternative, if you prefer to keep Exception only, is to set the latch only after the loop completes and clear it if an Error escapes 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 Exception alone.

Issue 2: BlockingWorker fallback leaves the pooled thread's context classloader unrestored when close throws an Error

  • Location: TaskExecutionService.java:1305-1319 (fallback catch (Exception e) followed by Thread.currentThread().setContextClassLoader(oldClassLoader) at the end of run()).
  • Problem: The restore is not in a finally. If tracker.task.close() throws an Error, the exception escapes run() 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 (BlockingTaskThreadFactory threads), 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 with catch (Throwable) did restore it).
  • Best improvement: put the setContextClassLoader(oldClassLoader) call in an outer finally of run() (or a nested try/finally around 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 11 engine-v2-it leg 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.java closeSuper() and its catch (Exception e); field closed; TaskExecutionServiceTest#testBlockingWorkerFallbackCloseWhenCallAndCloseThrowRuntimeException.
  • Problem: (a) AbstractTask.close() swallows every Exception itself, so closeSuper() plus its catch can never see an Exception in 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 because Task is Serializable. (c) The new TaskExecutionService test asserts only FAILED and closeCalled; 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

  1. Blockers - must be fixed

    • Issue 1: do not let a non-fatal Error stop the teardown loop once the close-once latch has been set. Catch Throwable per lifecycle, stop early only on VirtualMachineError or ThreadDeath, 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.
  2. Recommended fixes - non-blocking

    • Issue 2: move the context classloader restore into a finally.
    • Issue 4: add the comments and strengthen the BlockingWorker test.

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.

@SEZ9

SEZ9 commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator

Thanks @SeaSand1024 for calling out the classloader-restore consequence explicitly.

On F2: agreed that an Error escaping the BlockingWorker fallback before setContextClassLoader(oldClassLoader) is not a merge blocker on its own; if the JVM is already in an OOM / StackOverflowError state, an unrestored context classloader is the least of the problems. A nested try/finally so the restore runs unconditionally is small and I would take it as polish, but if you would rather leave it, just say so.

What I want to resolve before merge is how the narrowed catch (Exception) interacts with the close-once latch at 877056bf1:

  • A lifecycle close() that throws an Error (realistically NoClassDefFoundError from a connector classloader, not OOM) now escapes the per-lifecycle loop, so every lifecycle after it is skipped.
  • Could you confirm when the closed latch is set relative to that loop? If it is already set when the Error escapes, the fallback's second close() becomes a no-op and nothing ever closes the remaining lifecycles.

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:

  1. In the per-lifecycle loop, catch Throwable, keep iterating so the full pass completes, then rethrow the first failure, with an Error taking priority over any Exception so a fatal error is never downgraded to a log line.
  2. Keep catch (Exception) in the loop but only set closed after the loop has completed the full pass, so an escaping Error leaves the latch unset and the fallback can still finish teardown.

I lean to option 1 as the smaller behavioral surface.

F3: please add one test that drives the Error-from-a-lifecycle case end to end (lifecycle A throws NoClassDefFoundError, assert lifecycle B still gets close() and the Error is what surfaces), plus one for the super.close() failure branch.

F1 / F5: could you point me to the relevant hunks at 877056bf1 (the close-once latch and the null allCycles guard) so I can close them out? F4 is fine once the Javadoc throws clauses match whichever option you pick above.

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

Copy link
Copy Markdown
Author

@DanielLeens @SEZ9 addressed on tip 563fd4e8a (close-path + tests only; no #12353/#12311).

Issue 1 (Error + close-once latch): per-lifecycle catch (Throwable); full pass continues for non-fatal Errors (NoClassDefFoundError / AssertionError / LinkageError); early-stop only for VirtualMachineError / ThreadDeath; rethrow prefers Error over earlier Exception. Tests flipped/added accordingly (testCloseAttemptsEveryCycleWhenCycleThrowsNoClassDefFoundError, AssertionError case, testCloseStopsLoopOnVirtualMachineError, testClosePrefersErrorOverEarlierException).

Issue 2 / polish (BlockingWorker classloader): setContextClassLoader(oldClassLoader) moved into nested finally so restore always runs.

F3 / comments / Javadoc: end-to-end NCDFE coverage + existing super.close() failure test kept; comments on closeSuper() (prod Exception unreachable / test seam) and non-transient closed; @throws updated for the Error policy.

engine-v2-it (8) on 877056bf1 run 37097098821: failsafe shows one error — SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck — expected: <CANCELED> but was: <FAILED> (ConditionTimeoutException at assertEventuallyCanceled). Same cancel-vs-FAILED class as #12353; not close-path / lifecycle teardown. Not folded into this tip.

Local: SeaTunnelTaskStateTest 41/0/0 + BlockingWorker fallback test green.

@SeaSand1024

Copy link
Copy Markdown
Author

@DanielLeens @SEZ9 one non-blocking follow-up on item 5: the BlockingWorker classloader assert in TaskExecutionServiceTest runs on the test thread (Awaitility untilAsserted), so it does not observe the worker thread’s context classloader. Production restore in nested finally is still correct. Happy to drop/soften that assert in a follow-up; not treated as a merge blocker.

@SEZ9

SEZ9 commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the heads-up on the classloader assert — agreed. Since the Awaitility untilAsserted block runs on the test thread, it cannot observe the worker thread's context classloader, so it does not actually verify the nested-finally restore in BlockingWorker. I also agree the production restore is correct as written on 563fd4e8a, so this is not a merge blocker.

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 563fd4e8a summary: the Error-policy split (full pass for non-fatal Errors, early-stop only for VirtualMachineError / ThreadDeath, prefer Error over earlier Exception), the nested finally restore, the end-to-end NCDFE coverage plus the retained super.close() failure test, and the Javadoc updates all line up with what was asked. The SplitClusterFaultToleranceIT cancel-vs-FAILED failure you described on 877056bf1 / run 37097098821 reads as outside the close-path changes here, so I'm fine not folding it into this tip.

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

Copy link
Copy Markdown
Author

@SEZ9 @DanielLeens follow-up on tip 6ad74f1fb (close-path/tests only).

1. Classloader assert: dropped the tautological Awaitility assert in testBlockingWorkerFallbackCloseWhenCallAndCloseThrowRuntimeException — it compared classloaders on the test thread and could not observe the worker's nested-finally restore. Comment now states that. Production restore unchanged.

2. F3 / BlockingWorker RuntimeException path: still covers unchecked close after the Error-policy change. CallAndCloseThrowRuntimeExceptionTask.close() throws RuntimeException("close-fail"); BlockingWorker fallback still catch (Exception) and logs Close task error. Error-policy only widened the lifecycle loop in SeaTunnelTask.close(); the fallback Exception catch is unchanged.

3. CI on Build 37460272377 (tip 563fd4e8a):

Local: BlockingWorker fallback test 1/0/0 after the assert drop.

@SEZ9

SEZ9 commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

@SeaSand1024 thanks for the follow-ups on 563fd4e8a and 6ad74f1fb.

F3: dropping the test-thread classloader assert and documenting why in the comment sounds right. I'll verify the end-to-end NCDFE coverage (testCloseAttemptsEveryCycleWhenCycleThrowsNoClassDefFoundError), the kept super.close() failure test, and testBlockingWorkerFallbackCloseWhenCallAndCloseThrowRuntimeException in the diff before resolving. If you can share the name of the super.close() failure test, that will speed it up.

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:

  • F1 (double close / idempotency): since close() completes the full pass and then rethrows, lifecycles that closed cleanly can be closed again by the BlockingWorker fallback. Does the non-transient closed latch short-circuit that second pass, and which test exercises it? If it does not, please explain why the second pass is safe.
  • F2: the VirtualMachineError / ThreadDeath early-stop addresses the lifecycle loop. For the fallback, your note says BlockingWorker is an unchanged catch (Exception), whereas F2 was raised because the fallback catches Throwable and downgrades a fatal error to a severe log line. Those two readings conflict, so I'll re-read the fallback catch in the diff before marking that half resolved; if you believe F2 misread it, point me to the relevant lines.
  • F4: does the per-lifecycle error log now carry task/lifecycle context so it can be correlated with the Close task error line from BlockingWorker?
  • F5: is allCycles still dereferenced unguarded after the super.close() catch? If an init() failure before allCycles is assigned still NPEs in the fallback close path, a null guard plus a small test would close this out.

I'll follow up once I've gone through the diff.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you, @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 caught IOException per lifecycle, so one unchecked exception from a connector close() 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/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 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:

  1. 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 by testCloseAttemptsEveryCycleWhenCycleThrowsNoClassDefFoundError and ...AssertionError; testCloseStopsLoopOnVirtualMachineError covers the fatal early stop. The classloader restore is now in a nested finally. closeSuper() and the non-transient field both carry explanatory comments.
  2. MDCTracer.tracing(allCycles.stream()).iterator() (:490) delegates straight to the underlying stream (MDCStream.iterator()), so the per-element MDC wrapper that forEach used 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.
  3. The latch is only consulted for repeated close() calls. The fallback close after a call() that threw from inside close() now returns immediately, which is exactly what removes the double close.
  4. A side observation from the fork's engine-v2-it (11) log: SinkFlowLifeCycle.close() throws NullPointerException at SinkFlowLifeCycle.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 on dev and 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, covering TaskExecutionService.java:1310-1321.
  • Problem: taskDone(t) completes the future before the fallback close() runs. If the fallback catch were reverted to catch (IOException e) (the original bug), the RuntimeException would escape run() after the future is already complete, and the test would still see FAILED and closeCalled == true. The same holds if the nested finally were 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 an AssertionError (it escapes the fallback catch (Exception), so only the nested finally can restore the classloader), record Thread.currentThread() inside close(), and after the future completes assert with Awaitility that thread.getContextClassLoader() is no longer the task classloader. That can be read from the test thread because it is a property of the recorded Thread. The RuntimeException case 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 Error is already the primary failure and a later lifecycle throws a VirtualMachineError, the code attaches the fatal error as suppressed under the earlier Error and then stops the loop. The thrown exception is then the earlier non-fatal one.
  • Best improvement: when t instanceof VirtualMachineError and the current primary is not one, promote t to primary (same swap you already do for Error over Exception), 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

  1. 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.
  2. 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.

@DanielLeens

Copy link
Copy Markdown
Contributor

Pushed merge commit 2a5e21feb7d (current dev into your branch), @SeaSand1024, to clear the merge conflict. The only conflict was in the import block of SeaTunnelTask.java (AtomicBoolean from this PR vs CopyOnWriteArrayList from dev); both imports are kept and no logic line changed. The PR diff against dev is otherwise the same as the head I reviewed last (6ad74f1fb). The fork CI run on the new head is the verification.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks again for 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: dev now declares allCycles as volatile and a CopyOnWriteArrayList, and adds cancel()/cancelRequested. The PR reads allCycles once for a null guard and then iterates a stream snapshot, which is compatible with a copy-on-write list; the PR's close() and dev's cancel() do not share state.
  • The fallback close after a call() that threw from inside close() now returns immediately through the latch, which removes the double close. The latch is only consulted on repeated close().
  • Error handling: an Error rethrown from close() reaches BlockingWorker's catch (Throwable) and is recorded on the tracker like any task failure; this is not a regression for IOException, which already propagated.
  • CANCELLING now sets currState = CANCELED and progress.done() even when close() 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.
  • sneakyThrow is the existing static import from ExceptionUtil; the Throwable[] holder with IOException special-casing keeps the declared signature throws 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, guarding TaskExecutionService.java BlockingWorker.run() finally block
  • Problem: taskDone(t) completes the future before the fallback close() runs. If the fallback catch were reverted to catch (IOException e) (the original bug), the RuntimeException would escape run() after the future is already complete, and the test would still see FAILED and closeCalled == true. Removing the nested finally would 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 an AssertionError (it escapes catch (Exception), so only the nested finally can restore the classloader), record Thread.currentThread() inside close(), and after the future completes assert (with Awaitility) that thread.getContextClassLoader() is no longer the task classloader; this is readable from the test thread because it is a property of the recorded Thread. Alternatively drop the test and rely on the unit tests of SeaTunnelTask, 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.java close() catch block (the t instanceof Error && !(closeException[0] instanceof Error) swap)
  • Problem: when a non-fatal Error is already the primary failure and a later lifecycle throws a VirtualMachineError, the fatal one is attached as suppressed under the earlier Error, then the loop stops; the thrown exception is the earlier non-fatal one.
  • Best improvement: when t is a VirtualMachineError and the current primary is not, promote t to 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.java field closed and close()
  • Problem: SeaTunnelTask is Serializable with an unchanged serialVersionUID. A task serialized by a build without this field and deserialized by a build with it gets closed == null (initializers do not run on deserialization), and closed.compareAndSet would throw a NullPointerException on the first close(). 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 SeaTunnelTask tests discriminate. Issue 1 should be fixed or the test dropped before a committer merges.
  • CI: the apache-side Build check for this head is action_required ("no Build workflow run was found there for the PR head commit"), and your fork SeaSand1024/seatunnel has no workflow run for 2a5e21f, so this exact head has not been tested. Please start the Build workflow on this branch in your fork (or push an empty commit). For the previous head (6ad74f1) the fork run showed all four unit-test jobs green; the red jobs were engine-v2-it (SplitClusterFaultToleranceIT cancel race and BackpressureSlowSinkIT) and a Maven Central transfer failure in all-connectors-it-6. The two engine failures belong to open fixes (#12311 and #12316) that are not in dev yet, so syncing will not clear them; the branch is 0 commits behind dev now. 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!

@SEZ9

SEZ9 commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the follow-up work here. Looking at the current head (2a5e21f, a merge of dev; the rest of the diff matches 6ad74f1), here is where I stand on my earlier points:

  1. Double close / idempotency – The AtomicBoolean closed latch with compareAndSet(false, true) plus the try/finally around close() in the CLOSED and CANCELLING branches addresses this. Resolved from my side.

  2. catch (Throwable) swallowing fatal errors – Stopping the loop early for VirtualMachineError / ThreadDeath and letting an Error take priority over an Exception covers the concern in SeaTunnelTask. One remaining question: does the BlockingWorker fallback rethrow (rather than only log) when the propagated failure is an Error, so a fatal error during close is not downgraded to a log line?

  3. Test coverage – With closeSuper() extracted, could you point me to (or add) tests that exercise (a) closeSuper() throwing while the lifecycle loop still runs, and (b) the BlockingWorker fallback path hitting the already-closed latch and absorbing an unchecked close failure?

  4. Javadoc / log context – Logging with task location + lifecycle name resolves the correlation half. Please double-check that the throws documentation on close() and closeSuper() matches the new flow (first failure rethrown, IOException as is, other throwables rethrown unwrapped, remaining failures attached as suppressed).

  5. allCycles null guard – Is allCycles now guarded before the iteration for the case where init() failed before it was assigned? If not, a simple null check (or treating it as an empty list) in close() would close this one out.

Once items 2–5 are confirmed or addressed, I think this is good to go.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SEZ9 for going through the current head. I re-read the diff at 2a5e21fe for each of your questions, so here is what the code shows (this is a merge-only head, the PR content is the same as 6ad74f1f).

2. Does the BlockingWorker fallback rethrow an Error? It does not downgrade it to a log line. In TaskExecutionService.BlockingWorker.run() the fallback is now try { tracker.task.close(); } catch (Exception e) { logger.severe("Close task error", e); } inside an outer try { ... } finally { setContextClassLoader(oldClassLoader); }. An Error thrown by close() is not an Exception, so it skips the inner catch, the outer finally restores the classloader, and the Error then propagates out of run() (to the thread's uncaught-exception handling). Only Exception subtypes are logged and absorbed. One nuance for the record: because taskDone(t) has already been called at that point, such an Error is not recorded on the execution tracker, which matches the pre-PR behaviour for the fallback path.

3a. closeSuper() throwing while the lifecycle loop still runs. SeaTunnelTaskStateTest#testClosePreservesSuperCloseFailureAndAttachesLifecycleFailuresAsSuppressed stubs the parent close to fail, then asserts that the parent failure is the primary one and the lifecycle failures are attached as suppressed. testCloseSkipsLifecycleLoopWhenAllCyclesNull covers the null case.

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 SeaTunnelTask level by testCloseIsIdempotentAndClosesEachLifecycleOnlyOnce. But TaskExecutionServiceTest#testBlockingWorkerFallbackCloseWhenCallAndCloseThrowRuntimeException uses CallAndCloseThrowRuntimeExceptionTask, which is not a SeaTunnelTask and has no latch. The test also asserts only FAILED and closeCalled, which would still hold if the fallback catch went back to catch (IOException) (the RuntimeException would escape run() after the future has already completed). So it does not currently guard either production edit in BlockingWorker. @SeaSand1024, the concrete way to make it discriminate is in my last review: have the test task's close() throw an AssertionError, record the worker thread, and assert after completion that its context classloader was restored.

4. Javadoc. The close() Javadoc matches the flow: @throws IOException when the primary failure is an IOException, unchecked exceptions and Errors rethrown unwrapped via sneakyThrow, later failures attached as suppressed, Error preferred over Exception, early stop only for VirtualMachineError and ThreadDeath. closeSuper() has no @throws IOException tag even though it declares it, which is a tiny nit.

5. allCycles null guard. Yes: close() now wraps the loop in if (allCycles != null), so a failure in init() before allCycles is assigned no longer NPEs in the fallback close. It is exercised by testCloseSkipsLifecycleLoopWhenAllCyclesNull.

CI. Unchanged: the apache-side Build for 2a5e21fe is action_required and the fork has no run for this SHA, so this head has not been tested. A fork Build run (or a fresh push) is still needed, after which re-running only failed jobs should suffice.

My remaining open items from the last review are Issue 1 (Medium, the BlockingWorker test) and the two Low notes (a VirtualMachineError ending up only as suppressed, and closed being null for an old-format serialized task). None of them are production correctness problems in the common path.

This branch has not been deployed

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

Labels

First-time contributor First-time contributor Zeta

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug][Zeta] Unchecked lifecycle close failure skips remaining task resource cleanup

5 participants