Repository navigation
[Test][Zeta] Add E2E coverage for classloader release when deployLocalTask fails before context publication (apache/seatunnel#11808) - #12143
Conversation
…ask init failure (apache#11808) PR apache#11812 (issue apache#11808) closed two failure sites in TaskExecutionService where a failed deployment used to leak the classloader references that deployTask had already acquired: - Site A: deserialization fails inside deployTask's per-task loop, before the TaskGroup exists. deployTask returns TaskDeployState.failed(...) synchronously and releases from its outer catch. Covered end to end by TaskDeploymentClassLoaderLeakIT (apache#12028). - Site B: every task deserializes, the TaskGroup is built, and deployLocalTask then fails before executionContexts.put(...) publishes the TaskGroupContext. deployTask still returns TaskDeployState.success() synchronously; the failure only surfaces asynchronously through notifyTaskStatusToMaster, and the release happens in the onFailureBeforeContextPublished callback. Until now only the mocked unit test testDeployTaskHandlesFailureBeforeContextPublication exercised it, with notifyTaskStatusToMaster stubbed out. TaskDeploymentPrePublicationClassLoaderLeakIT covers Site B through the real worker-side path on a clustered master + worker pair. A control group first proves acquire -> publish -> release on the same worker. Five two-task groups whose second task throws from Task#setTaskExecutionContext (the only per-task hook deployLocalTask invokes between TaskGroup construction and publication; Task#init() only runs after publication) then assert: synchronous success from deployTask, no published or finished context, both references released and both classloaders evicted before deployTask returns, no accumulation across attempts, and an asynchronous FAILED report that reaches the master's CoordinatorService through the real NotifyTaskStatusOperation and terminates on the master's JobNotFoundException. The asynchronous report is observed at both ends with a Log4j2 appender on the two engine loggers; nothing is mocked. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point: #11808 reported that a worker leaks classloader references when task deployment fails. #11812 fixed this at two distinct failure sites, but only "Site A" (a task failing to deserialize inside
deployTask's own loop, before theTaskGroupexists) had end-to-end coverage, viaTaskDeploymentClassLoaderLeakIT(#12028). "Site B" — every task deserializes fine, theTaskGroupis built, butdeployLocalTaskfails before theTaskGroupContextis published — was previously only covered by a unit test that stubsnotifyTaskStatusToMasterwith Mockito, so the real asynchronous master-notification path was never exercised. - Fix approach: this PR adds
TaskDeploymentPrePublicationClassLoaderLeakIT, which deploys a real two-task group on a real worker (viaTaskExecutionService#deployTask, exactly as the master's deploy operation invokes it) where the second task throws fromsetTaskExecutionContext— the only per-task hook invoked betweenTaskGroupconstruction and context publication in every thread-share mode — and asserts the full Site B contract: synchronous success returned to the caller, no published/finished context, both classloader references released beforedeployTaskreturns, and an asynchronousFAILEDreport that travels through the realNotifyTaskStatusOperationRPC to a real master and terminates cleanly onJobNotFoundException. A control deployment of a valid group runs first to prove the same counters and log lines move the expected way on a healthy deployment. - One-sentence summary: a rigorous, real worker-to-master end-to-end test that closes the one part of #11812's fix that was previously only unit-tested with a mocked master.
1. Code Change Review
1.1 Core Logic Analysis
Test-only addition (one new *IT class, no production code touched). I cross-checked every structural claim in the javadoc against current dev (f0c459055706) source rather than accepting the PR's framing:
TaskExecutionService#deployTask(seatunnel-engine-server/.../TaskExecutionService.java:445): confirmed the exactacquiredClassLoaderJarsbookkeeping, the outercatch (Throwable t)callingreleaseClassLoadersAfterFailedDeployment(Site A), and thefailure -> {...}callback wired intodeployLocalTaskthat also callsreleaseClassLoadersAfterFailedDeployment(Site B) — matches the test's premise precisely.deployLocalTask(line 599 onward): confirmedtask.setTaskExecutionContext(taskExecutionContext)is invoked inside the task-setup.peek()beforeexecutionContexts.put(...)publishes the context, and that the surroundingcatch (Throwable t)only callsonFailureBeforeContextPublished.accept(t)when!contextPublished— exactly the Site B branch the test targets. The javadoc's claim thatTask#init()only runs post-publication (so aninit()failure would miss Site B) is architecturally consistent with this code:init()isn't called in this method at all, onlysetTaskExecutionContextis, soContextInjectionFailureTaskfailing there is the only way to hit this branch.- Log message assertions — I verified these character-for-character against the real source rather than assuming they'd match:
"Task %s complete with error %s"→ present verbatim indeployLocalTask'sresultFuture.whenCompleteAsynchandler."Task %s complete with state %s"→ present verbatim, same handler."send notify task status failed because can't find job"→ present verbatim innotifyTaskStatusToMaster(both the directJobNotFoundExceptioncatch and theExecutionException-wrapping catch), which is what makes the worker's retry loop terminate cleanly instead of looping forever."Received task end from execution %s, state %s"→ present verbatim inCoordinatorService.java:2061."Job %s not running"→ present verbatim inCoordinatorService.java:2081, thrown as theJobNotFoundExceptionthe worker's retry loop treats as terminal.
DefaultClassLoaderService.queryClassLoaderCount(),queryClassLoaderById(long, Collection<URL>),queryClassLoaderReferenceCount(long, Collection<URL>)all exist with the exact signatures used.
Runtime path exercised:
Test -> TaskExecutionService#deployTask (worker, real invocation path)
-> deployLocalTask: TaskGroup built, PassiveTask + ContextInjectionFailureTask
deserialize successfully (2 classloader refs acquired)
-> setTaskExecutionContext(ContextInjectionFailureTask) throws IllegalStateException
-> caught in deployLocalTask's catch (contextPublished == false)
-> onFailureBeforeContextPublished.accept(t)
-> releaseClassLoadersAfterFailedDeployment releases both refs
-> resultFuture completed exceptionally
-> whenCompleteAsync handler logs "Task ... complete with error ..."
logs "Task ... complete with state FAILED"
-> notifyTaskStatusToMaster: real NotifyTaskStatusOperation RPC to master
-> CoordinatorService: "Received task end from execution ..., state FAILED"
-> no job registered for synthetic job id -> JobNotFoundException("Job X not running")
-> worker's retry loop logs "can't find job" and stops retrying
This is a genuine cross-node, cross-thread trace (worker deploy thread -> worker async executor -> real Hazelcast RPC -> master operation thread), not a same-thread simulation. The control-deployment run beforehand is a nice touch: it independently proves the same counters/log lines move correctly on the healthy path before the failure-path assertions rely on the same instrumentation.
I confirmed via the real CI runs (fork run 34012686456) that this test executed and passed on both JDK matrix legs: engine-v2-it (8, ubuntu-latest) — Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 7.126s — and engine-v2-it (11, ubuntu-latest) — same result, 7.129s.
1.2 Compatibility Impact
Fully compatible. No production code, config, protocol, or serialization format changed.
1.3 Performance / Side-Effect Analysis
No production hot path affected. EngineLogCapture registers two dedicated, additive LoggerConfig entries (for TaskExecutionService and CoordinatorService) at INFO level for the duration of the test method only, and removes them in close() (used as try (EngineLogCapture engineLog = EngineLogCapture.install())), so regular console logging is unaffected and no configuration leaks past the test. The GatedTask static GATES registry is properly scoped per-test via registerGate/unregisterGate in a finally block, so no state survives across attempts or test classes. Temp jar files use both deleteOnExit() and explicit delete() in finally — good hygiene, no leak.
1.4 Error Handling and Logging
No issues. The design deliberately relies on production log output as the only observable signal for the asynchronous master-notification path, which is architecturally necessary here (there's no other public API surface for "did the master receive this FAILED report and stop the worker's retries") — this is called out honestly in the class javadoc rather than hidden.
2. Code Quality Assessment
2.1 Coding Standards
Comments are excellent throughout — the class javadoc distinguishes Site A vs. Site B precisely and explains exactly why setTaskExecutionContext (not init()) is the correct failure-injection point. PassiveTask, ContextInjectionFailureTask, and GatedTask each carry a short javadoc explaining their role. License header present, no wildcard imports.
One small, non-blocking observation worth surfacing for the record (Low, not blocking): the test's stability depends on exact log message wording in TaskExecutionService/CoordinatorService (e.g. "can't find job", "Job %s not running"). This is the only viable signal for this specific regression and is already acknowledged in the javadoc, but a future unrelated log-message rewording would break this test even though the underlying fix remains intact. I'm noting this for awareness, not as something to fix now.
2.2 Test Coverage and Test Stability
Stability rating: Stable.
- Entirely
Awaitility-based (ASYNC_REPORT_TIMEOUT_SECONDS = 60, generous and justified by the javadoc's accounting of the worker's 1s retry-on-JobRestoreInProgressExceptionloop plus RPC round trips) — no rawThread.sleep. FAILED_DEPLOYMENT_ATTEMPTS = 5repeated attempts with fresh job ids each time (JOB_ID_SEQUENCEseeded from wall clock) specifically to catch a leak that "never returns to zero" rather than trusting a single-shot assertion — a real defense against a subtle cumulative leak passing a naive single-attempt test.GatedTask'sCountDownLatchgate makes the control deployment's "still running" assertions deterministic rather than timing-dependent — no race window relies on luck.- Verified against a real, currently-green CI run on both JDK 8 and JDK 11.
This closes a genuine, previously unit-test-only gap for a real production fix.
2.3 Documentation Updates
Not applicable — test-only, no user-visible behavior changed.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix for a real coverage gap, tightly scoped to exactly the failure hook (setTaskExecutionContext) that reaches Site B, with an explicit explanation of why init() would not.
3.2 Maintainability
High — the Site A/Site B distinction and the exact hook semantics are spelled out clearly enough that a future contributor modifying deployLocalTask's failure handling would immediately understand what this test protects against.
3.3 Extensibility
EngineLogCapture is a reusable, self-contained utility that other engine E2E tests needing to observe cross-node log-driven behavior could adopt directly.
3.4 Historical-Version Compatibility
Not applicable — no serialization/checkpoint/protocol change.
4. Issue Summary
No blocking issues found.
| Number | Issue | Location | Severity |
|---|---|---|---|
| — | None found (see 2.1 for one non-blocking observation about log-message coupling) | — | — |
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers — None.
- Recommended fixes — non-blocking: none required; the log-message-coupling note in 2.1 is for awareness only.
Overall assessment: this is a careful, well-verified regression test for the harder-to-reach half of #11812's fix. I independently confirmed the exact log strings, method signatures, and control-flow branches referenced in the javadoc against current dev source, and confirmed the test actually executed and passed on both JDK 8 and JDK 11 in the fork's CI, not merely that it compiles. No concerns. Approving.
Purpose of this pull request
Adds an engine E2E regression test for the second failure site closed by #11812 (issue #11808): a
TaskGroupwhose tasks all deserialize correctly but whose deployment then fails insideTaskExecutionService#deployLocalTaskbefore theTaskGroupContextis published.Background: two failure sites, one fix
TaskExecutionService#deployTaskacquires one classloader reference per task while deserializing the group. Ownership is only transferred to the worker's regular bookkeeping whendeployLocalTaskpublishes theTaskGroupContextintoexecutionContexts. #11812 closed two distinct places where a failed deployment used to drop those references:deployTask's per-task loop, before theTaskGroupexistsdeployLocalTask, after theTaskGroupexists and beforeexecutionContexts.put(...)deployTaskresultTaskDeployState.failed(...)synchronouslyTaskDeployState.success()synchronously; the failure only surfaces asynchronously vianotifyTaskStatusToMasterdeployTask's outercatch (Throwable)onFailureBeforeContextPublishedcallback wired bydeployTaskTaskDeploymentClassLoaderLeakIT(#12028), end to endTaskExecutionServiceTest#testDeployTaskHandlesFailureBeforeContextPublication, which stubsnotifyTaskStatusToMasterwith MockitoSite B had no coverage through the real path: nothing ran the asynchronous
FAILEDreport against a real master.What the new test does
TaskDeploymentPrePublicationClassLoaderLeakITsits next toTaskDeploymentClassLoaderLeakITand uses the sameSeaTunnelServerStartermaster + worker harness, with classloader cache mode disabled so eviction is a second leak signal next to the reference count.taskDone: reference count 0, classloader evicted, context moved to the finished contexts, andFINISHEDreported to the master through the realNotifyTaskStatusOperation.Task#setTaskExecutionContext, the only per-task hookdeployLocalTaskinvokes betweenTaskGroupconstruction and publication. Per attempt the test asserts:deployTaskreturned success synchronously (the Site B signature);deployTaskreturns, and the live classloader count is back to baseline (no accumulation across attempts);FAILEDcarrying the injected message, the master'sCoordinatorServicereceivedFAILEDfor that exact location, and the worker's retry loop terminated on the master'sJobNotFoundException(the production branch for a task group whose job the master does not track).The asynchronous report is observed at both ends by a Log4j2 appender attached to the worker's
TaskExecutionServicelogger and the master'sCoordinatorServicelogger (both nodes share the test JVM's Log4j2 context); nothing is mocked or stubbed.Why
setTaskExecutionContextand notinit():Task#init()is only called byBlockingWorker#run/CooperativeTaskWorkerafter publication, so aninit()failure takes the ordinary post-publication path and never reaches Site B. It is the same hook #11812's own unit test used.Does this PR introduce any user-facing change?
No. Test-only change: no
src/mainand nopom.xmlchanges.How was this patch tested?
Test-only change. Verified locally on JDK 8 (
jdk1.8.0_171) in a fresh worktree onapache/dev(10206bc7aa6), after a full dependency build:(BUILD SUCCESS, 67 reactor modules, 8:57;
seatunnel-engine-uiskipped via-Dskip.ui=truesince this change does not touch it.)Three consecutive runs of
What the engine logged in run 1 (worker on
:5803, master on:5802) for one of the five Site B attempts, in order:All five attempts passed
taskGroup.init()and failed atsetTaskExecutionContext; only the control group logged the post-publicationdeploying TaskGroup ... successand was then reported asFINISHEDat both ends. Sixcan't find jobwarnings (control + five attempts) and zero retry / restore-in-progress lines: everynotifyTaskStatusToMasterloop terminated on the master'sJobNotFoundExceptionon its first round trip../mvnw spotless:applywas run on the module; nosrc/mainorpom.xmlfiles are touched.Check list
./mvnw spotless:applyon the changed module🤖 Generated with Claude Code