Repository navigation
[Bug][Engine] Continue task lifecycle cleanup after unchecked failure - #12235
CryoThrust wants to merge 1 commit into
Conversation
Signed-off-by: Yohanes <CryoThrust@users.noreply.github.com>
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
SeaTunnelTask.close() iterates over every FlowLifeCycle in the task (source, transform, sink, intermediate queue) and closes each one so its resources (readers, writers, queues, executors) are released. The loop only caught IOException. If any single lifecycle's close() threw an unchecked exception (a RuntimeException bubbling out of a connector's SinkWriter#close() or SourceReader#close()), that exception escaped the loop immediately and every lifecycle after it in iteration order was never closed — a real resource leak on task teardown. This PR widens the per-lifecycle catch to IOException | RuntimeException so every lifecycle is still attempted, while preserving the first failure and attaching later ones as suppressed exceptions, exactly like the pre-existing IOException path already did.
Note for maintainers — this PR duplicates #12237. Both PRs fix the identical bug (SeaTunnelTask.close() in seatunnel-engine/.../task/SeaTunnelTask.java), both reference the same issue #12231, and both add a new test file at the exact same path (seatunnel-engine-server/src/test/java/.../task/SeaTunnelTaskCloseTest.java). They cannot both be merged as-is (the second to land will hit a straight file conflict on SeaTunnelTaskCloseTest.java). See the "Merge Recommendation" section below for a side-by-side comparison with #12237 and a concrete suggestion on how to resolve the duplication. I did not find any relationship between this pair and #12236 or #12238 — those touch CheckpointCoordinator and TaskExecutionService/TaskGroupContext respectively, disjoint files with no overlapping runtime state.
1. Code Change Review
1.1 Core Logic Analysis
File: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/SeaTunnelTask.java:448-473
Before:
public void close() throws IOException {
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.error("Close FlowLifeCycle error.", e);
if (closeException[0] == null) {
closeException[0] = e;
} else {
closeException[0].addSuppressed(e);
}
}
});
if (closeException[0] != null) {
throw closeException[0];
}
}After (this PR):
public void close() throws IOException {
Throwable[] closeException = {null};
try {
super.close();
} catch (IOException e) {
closeException[0] = e;
}
MDCTracer.tracing(allCycles.stream())
.forEach(flowLifeCycle -> {
try {
flowLifeCycle.close();
} catch (IOException | RuntimeException e) {
log.error("Close FlowLifeCycle error.", e);
if (closeException[0] == null) {
closeException[0] = e;
} else {
closeException[0].addSuppressed(e);
}
}
});
if (closeException[0] instanceof IOException) {
throw (IOException) closeException[0];
}
if (closeException[0] instanceof RuntimeException) {
throw (RuntimeException) closeException[0];
}
}Key findings:
-
I verified the bug is real by reading the connector-facing
FlowLifeCycleimplementations:SinkFlowLifeCycle.close()callswriter.close()— a connector-suppliedSinkWriter#close()(SinkFlowLifeCycle.java:277-283).SourceFlowLifeCycle.close()callsreader.close()— a connector-suppliedSourceReader#close()(SourceFlowLifeCycle.java:216-224).
Both are third-party code paths that are not contractually guaranteed to only throwIOException. A single misbehaving connector'sclose()throwingRuntimeException(NPE, an unwrapped driver exception, etc.) was enough to leak every downstream lifecycle in the same task before this fix (unclosed readers/writers/queues, and the leaked lifecycle'scompletableFutureinAbstractFlowLifeCyclenever completes).- The fix's per-lifecycle catch of
IOException | RuntimeExceptionis exhaustive for this call site:FlowLifeCycle#close()is declaredthrows IOException, so a conforming lambda body can only surface a checkedIOExceptionor an uncheckedRuntimeException— there is no third case being missed here (barring anError, discussed below). super.close()(AbstractTask.close(),AbstractTask.java:99-106) already wraps its body incatch (Exception ignore) {}and never itself throws, so leaving that call's catch asIOException-only (unlike #12237, which widens it toThrowable) is a difference without a practical effect today — it is not a functional gap in this PR.addSuppressedoncloseException[0](now typedThrowable) still compiles and behaves identically to before sinceaddSuppressedis defined onThrowable, notException.
-
Runtime-path diagram (why this is a hot path, not a rare corner case):
Task ends abnormally (cancel / error / group-level failure) -> TaskExecutionService.BlockingWorker.run() finally block (TaskExecutionService.java:1162-1170) -> if (result == null || !result.isDone()) tracker.task.close() -> SeaTunnelTask.close() -> flowLifeCycle.close() for each FlowLifeCycle in allCycles, in order -> SourceFlowLifeCycle / SinkFlowLifeCycle / IntermediateQueueFlowLifeCycle -> connector reader.close() / writer.close() <-- may throw RuntimeExceptionThis confirms the normal user path does reach the changed code:
task.close()from thisfinallyblock runs on every task cancellation and every task error across every job, not only on a recovery/restart boundary. A connector bug here is a routine occurrence at scale, so the blast radius of the pre-fix bug (silently skipping cleanup for every lifecycle after the first failing one) was real production exposure, not a theoretical edge case. -
One residual, out-of-scope observation: even after this fix, if the rethrown exception ends up being a
RuntimeException, it still escapesTaskExecutionService.BlockingWorker.run()'scatch (IOException e)atTaskExecutionService.java:1166-1169, so the "Close task error" log line and the trailingThread.currentThread().setContextClassLoader(oldClassLoader)(line 1172) would still be skipped for that thread. In practiceBlockingWorkerruns on a dedicated pooled thread and an escapingRuntimeExceptionsimply kills that worker thread (the pool replaces it), so this isn't a correctness blocker, but it does mean the operator-facing "Close task error" log is still lost on the exact failure mode this PR is trying to make visible. Not a blocker for this PR (out of the diff's scope,TaskExecutionService.javais untouched here), but worth a follow-up.
1.2 Compatibility
Fully compatible. No config option, serialization format, checkpoint/savepoint format, or public API is touched. SeaTunnelTask.close()'s signature (throws IOException) is unchanged. The observable behavior change is strictly additive: cleanup that used to stop early on an unchecked failure now runs to completion, and the first failure is still what's ultimately rethrown to the caller (same contract as before for the IOException-only case).
1.3 Performance / Side-Effect Analysis
No new locks, no additional I/O, no new allocations beyond an extra array covering the same single slot. MDCTracer.tracing(...).forEach(...) iteration is unchanged; only the catch clause width changed. No CPU/memory/GC-relevant regression.
1.4 Error Handling and Logging
No issues. log.error("Close FlowLifeCycle error.", e) still fires for every failing lifecycle (including now the ones that used to escape unlogged before crashing the loop), which is a genuine improvement in operator-facing diagnostics — previously an unchecked failure in the middle of the list meant later lifecycles' close failures (if any) were never even attempted, let alone logged.
2. Code Quality Assessment
2.1 Coding Standards
The updated Javadoc on close() (lines 439-446) correctly documents the new RuntimeException handling and adds a @throws RuntimeException tag. No missing comments on the touched method.
2.2 Test Coverage and Test Stability
New file: seatunnel-engine-server/src/test/java/.../task/SeaTunnelTaskCloseTest.java.
shouldCloseRemainingLifecyclesAfterUncheckedFailure(lines 94-115): three lifecycles, the middle one throwsIllegalStateExceptionon close; asserts all three still ran, the exception is rethrown, and — closing twice in a row — every lifecycle is attempted both times (allCyclesis re-iterated on eachclose()call, matching production semantics whereclose()can be invoked more than once, e.g. from both the normal completion path and a defensive cleanup path).shouldPreserveFirstFailureAndSuppressLaterFailures(lines 117-137): verifies the pre-existingaddSuppressedcontract still holds when a checkedIOExceptionis first and an uncheckedIllegalArgumentExceptionfollows — a good regression guard that the widened catch didn't disturb ordering semantics.- The test constructs a real
TestTask extends SeaTunnelTaskviasuper(1L, null, 0, null, Collections.emptyMap())and setsallCyclesdirectly rather than mocking. This exercises the realclose()implementation end-to-end rather than a partial mock, which I consider a slightly stronger isolation choice than reflection-based field injection, though it does mean the test relies onAbstractTask's constructor toleratingnullarguments — which it evidently does, since the PR author reports 3 passing tests when run in isolation. - No
Thread.sleep, no external state, no ordering dependency on other tests, no shared static/global state. Stability rating: Stable.
2.3 Documentation Updates
No docs/en / docs/zh change, and none is needed — this is a defect fix restoring the documented "close every lifecycle, propagate the first failure" contract, not a new user-facing config or behavior. I'd note as a minor, non-blocking observation that docs/en/introduction/concepts/incompatible-changes.md was also not touched; given the fix is strictly "cleanup that used to stop early now runs to completion," I don't think it rises to the level of an incompatible change requiring that doc, but the sibling PR #12237 self-declares "Does this PR introduce any user-facing change? Yes" in its own description for the identical underlying fix — worth the two authors/maintainers reconciling that inconsistency.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. The change is scoped exactly to the defect: widen the catch, keep the same suppressed-exception aggregation pattern that already existed for IOException, no unrelated refactor.
3.2 Maintainability
The instanceof-cast-and-rethrow pair (if (closeException[0] instanceof IOException) ... if (closeException[0] instanceof RuntimeException) ...) is a little more verbose than #12237's single-line sneakyThrow(closeException[0]), which reuses an existing utility (ExceptionUtil.sneakyThrow, already statically imported and used elsewhere in this very file at line 613 of the pre-PR source). That said, this PR's approach is arguably easier for a reader unfamiliar with the sneaky-throw idiom to follow at a glance, and it is exhaustive for the types it actually catches, so I would not call this a defect — just a stylistic trade-off worth weighing against #12237 (see Merge Recommendation).
3.3 Extensibility
Deliberately does not catch Error (e.g. OutOfMemoryError, StackOverflowError) — only IOException | RuntimeException. This is the more conservative and, in my view, the safer default: it matches common Java guidance against catching Error, and it mirrors this codebase's own ExceptionUtil.rethrow (seatunnel-engine-common/.../ExceptionUtil.java), which special-cases Error/OutOfMemoryError rather than treating it like any other Throwable. If a future lifecycle implementation needs Error handled too, that would be a conscious, separate follow-up rather than something silently inherited from this fix.
3.4 Historical-Version Compatibility
No checkpoint/savepoint state, serialized protocol field, or historical task JSON is touched. Purely an in-JVM control-flow fix confined to task teardown. Safe for rolling upgrade in either direction (old and new binaries produce the same close() contract for the previously-supported IOException case).
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Duplicate PR: identical fix for issue #12231 also submitted as #12237, touching the same production file and the same new test file path | SeaTunnelTask.java, SeaTunnelTaskCloseTest.java |
High (process-blocking, not a code defect) |
| 2 | super.close() catch stays IOException-only rather than widened to Throwable like #12237 — currently harmless since AbstractTask.close() swallows all Exceptions itself, but leaves an asymmetry between the two competing fixes |
SeaTunnelTask.java:451-455 |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
-
Blockers — must be fixed
- Issue 1 (duplication with #12237): Both PRs are technically sound fixes for the same real bug against the same issue (#12231). They cannot both land — the second to merge will conflict on
SeaTunnelTaskCloseTest.java. I'd suggest the maintainers (or the two authors) pick one:- This PR (#12235) is more conservative: it only widens the catch to
RuntimeException(notError), leavessuper.close()'s catch untouched, and uses an explicitinstanceofrethrow. Slightly more verbose, but very easy to audit line-by-line. - #12237 is more thorough: it also widens
super.close()'s catch toThrowable(defensive, currently a no-op givenAbstractTask.close()'s own swallowing) and reuses the file's existingsneakyThrowutility for the final rethrow, at the cost of also catchingErrorin the per-lifecycle loop (a debatable trade-off under OOM conditions — see my review on #12237 for detail).
Either is mergeable on technical merit; I lean marginally toward whichever the maintainers find easier to reconcile with #12237'sThrowable-wide handling, since that closes one more theoretical gap (thesuper.close()catch) even though it isn't observably triggered today. This is ultimately a judgment call for the project, not a code defect in this PR.
- This PR (#12235) is more conservative: it only widens the catch to
- Issue 1 (duplication with #12237): Both PRs are technically sound fixes for the same real bug against the same issue (#12231). They cannot both land — the second to merge will conflict on
-
Recommended fixes — non-blocking
- Consider reconciling the "user-facing change" framing between this PR and #12237 in whichever one is kept, so the merged changelog/PR description is consistent about whether this is a behavior change worth calling out.
Overall assessment: the underlying diagnosis and fix are correct, well-tested, and appropriately minimal — the only reason this isn't a straight "ready to merge" is the direct duplication with #12237 against the same issue, which the maintainers need to resolve before either can land cleanly.
|
Thanks for identifying the overlap. Since #12237 has been closed in favor of this PR, I am closing my duplicate as well. The implementation and tests are available for reference; no merged contribution should be attributed to this PR. |
Purpose
Fixes #12231.
SeaTunnelTask.close()previously caught onlyIOExceptionfrom eachFlowLifeCycle. An unchecked close failure could escape the iteration and leave later lifecycles open, leaking resources such as executors, connections, and buffers.Changes
Verification
mvn -s /Users/yohanes/.m2/settings-public-central.xml -pl seatunnel-engine/seatunnel-engine-server spotless:check -DskipTests✅mvn -s /Users/yohanes/.m2/settings-public-central.xml -pl seatunnel-engine/seatunnel-engine-server -DskipCheckstyleTests -Dlicense.skip=true -Dspotless.check.skip=true -Dtest=SeaTunnelTaskCloseTest -Dsurefire.failIfNoSpecifiedTests=false testJettyService.java: the resolvedHttpConfigdependency does not containgetUploadMaxFileSizeMb()andgetUploadMaxRequestSizeMb().