Skip to content

[Test][Zeta] Add E2E coverage for classloader release when deployLocalTask fails before context publication (apache/seatunnel#11808) - #12143

Merged
nzw921rx merged 1 commit into
apache:devfrom
DanielLeens:zeta-classloader-leak-deploylocaltask-siteb
Sep 7, 2026
Merged

nzw921rx merged 1 commit into
apache:devfrom
DanielLeens:zeta-classloader-leak-deploylocaltask-siteb

Conversation

@DanielLeens

Copy link
Copy Markdown
Contributor

Purpose of this pull request

Adds an engine E2E regression test for the second failure site closed by #11812 (issue #11808): a TaskGroup whose tasks all deserialize correctly but whose deployment then fails inside TaskExecutionService#deployLocalTask before the TaskGroupContext is published.

Background: two failure sites, one fix

TaskExecutionService#deployTask acquires one classloader reference per task while deserializing the group. Ownership is only transferred to the worker's regular bookkeeping when deployLocalTask publishes the TaskGroupContext into executionContexts. #11812 closed two distinct places where a failed deployment used to drop those references:

Site A Site B
Where deserialization inside deployTask's per-task loop, before the TaskGroup exists inside deployLocalTask, after the TaskGroup exists and before executionContexts.put(...)
deployTask result throws, returns TaskDeployState.failed(...) synchronously returns TaskDeployState.success() synchronously; the failure only surfaces asynchronously via notifyTaskStatusToMaster
Released by deployTask's outer catch (Throwable) the onFailureBeforeContextPublished callback wired by deployTask
Existing coverage TaskDeploymentClassLoaderLeakIT (#12028), end to end only TaskExecutionServiceTest#testDeployTaskHandlesFailureBeforeContextPublication, which stubs notifyTaskStatusToMaster with Mockito

Site B had no coverage through the real path: nothing ran the asynchronous FAILED report against a real master.

What the new test does

TaskDeploymentPrePublicationClassLoaderLeakIT sits next to TaskDeploymentClassLoaderLeakIT and uses the same SeaTunnelServerStarter master + worker harness, with classloader cache mode disabled so eviction is a second leak signal next to the reference count.

  1. Control deployment: a valid single-task group whose task blocks on a gate. While it runs, the published context owns the acquired classloader (reference count 1, live classloader count baseline + 1). Opening the gate lets the group finish through taskDone: reference count 0, classloader evicted, context moved to the finished contexts, and FINISHED reported to the master through the real NotifyTaskStatusOperation.
  2. Five Site B attempts: a two-task group where both tasks deserialize (two classloaders acquired) and the second task throws from Task#setTaskExecutionContext, the only per-task hook deployLocalTask invokes between TaskGroup construction and publication. Per attempt the test asserts:
    • deployTask returned success synchronously (the Site B signature);
    • no active or finished context was ever published for the location;
    • both references are already 0 and both classloaders evicted when deployTask returns, and the live classloader count is back to baseline (no accumulation across attempts);
    • asynchronously (bounded Awaitility, 60s): the worker completed the group with FAILED carrying the injected message, the master's CoordinatorService received FAILED for that exact location, and the worker's retry loop terminated on the master's JobNotFoundException (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 TaskExecutionService logger and the master's CoordinatorService logger (both nodes share the test JVM's Log4j2 context); nothing is mocked or stubbed.

Why setTaskExecutionContext and not init(): Task#init() is only called by BlockingWorker#run / CooperativeTaskWorker after publication, so an init() 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/main and no pom.xml changes.

How was this patch tested?

Test-only change. Verified locally on JDK 8 (jdk1.8.0_171) in a fresh worktree on apache/dev (10206bc7aa6), after a full dependency build:

./mvnw install -pl seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base -am -DskipTests -Dskip.ui=true -nsu -Dmaven.gitcommitid.skip=true -T 3C

(BUILD SUCCESS, 67 reactor modules, 8:57; seatunnel-engine-ui skipped via -Dskip.ui=true since this change does not touch it.)

Three consecutive runs of

./mvnw verify -pl seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base -DskipUT=true -DskipIT=false -Dit.test=TaskDeploymentPrePublicationClassLoaderLeakIT
Run Result Test time
1 Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 12.1 s
2 Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 11.6 s
3 Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 12.2 s

What the engine logged in run 1 (worker on :5803, master on :5802) for one of the five Site B attempts, in order:

TaskExecutionService - deploying TaskGroup TaskGroupLocation{jobId=1788670228489002, pipelineId=1, taskGroupId=1} init success
TaskExecutionService - Task TaskGroupLocation{jobId=1788670228489002, pipelineId=1, taskGroupId=1} complete with error java.lang.IllegalStateException: simulated failure before TaskGroupContext publication, attempt 0
TaskExecutionService - Task TaskGroupLocation{jobId=1788670228489002, pipelineId=1, taskGroupId=1} complete with state FAILED
CoordinatorService  - Received task end from execution TaskGroupLocation{jobId=1788670228489002, pipelineId=1, taskGroupId=1}, state FAILED
TaskExecutionService - send notify task status failed because can't find job ... JobNotFoundException: Job 1788670228489002 not running

All five attempts passed taskGroup.init() and failed at setTaskExecutionContext; only the control group logged the post-publication deploying TaskGroup ... success and was then reported as FINISHED at both ends. Six can't find job warnings (control + five attempts) and zero retry / restore-in-progress lines: every notifyTaskStatusToMaster loop terminated on the master's JobNotFoundException on its first round trip.

./mvnw spotless:apply was run on the module; no src/main or pom.xml files are touched.

Check list

  • Code changed are covered with tests, or it does not need tests for reason: test-only change
  • Change does not need documentation
  • Ran ./mvnw spotless:apply on the changed module

🤖 Generated with Claude Code

…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>
@github-actions github-actions Bot added the e2e label Sep 6, 2026

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 the TaskGroup exists) had end-to-end coverage, via TaskDeploymentClassLoaderLeakIT (#12028). "Site B" — every task deserializes fine, the TaskGroup is built, but deployLocalTask fails before the TaskGroupContext is published — was previously only covered by a unit test that stubs notifyTaskStatusToMaster with 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 (via TaskExecutionService#deployTask, exactly as the master's deploy operation invokes it) where the second task throws from setTaskExecutionContext — the only per-task hook invoked between TaskGroup construction 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 before deployTask returns, and an asynchronous FAILED report that travels through the real NotifyTaskStatusOperation RPC to a real master and terminates cleanly on JobNotFoundException. 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 exact acquiredClassLoaderJars bookkeeping, the outer catch (Throwable t) calling releaseClassLoadersAfterFailedDeployment (Site A), and the failure -> {...} callback wired into deployLocalTask that also calls releaseClassLoadersAfterFailedDeployment (Site B) — matches the test's premise precisely.
  • deployLocalTask (line 599 onward): confirmed task.setTaskExecutionContext(taskExecutionContext) is invoked inside the task-setup .peek() before executionContexts.put(...) publishes the context, and that the surrounding catch (Throwable t) only calls onFailureBeforeContextPublished.accept(t) when !contextPublished — exactly the Site B branch the test targets. The javadoc's claim that Task#init() only runs post-publication (so an init() failure would miss Site B) is architecturally consistent with this code: init() isn't called in this method at all, only setTaskExecutionContext is, so ContextInjectionFailureTask failing 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 in deployLocalTask's resultFuture.whenCompleteAsync handler.
    • "Task %s complete with state %s" → present verbatim, same handler.
    • "send notify task status failed because can't find job" → present verbatim in notifyTaskStatusToMaster (both the direct JobNotFoundException catch and the ExecutionException-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 in CoordinatorService.java:2061.
    • "Job %s not running" → present verbatim in CoordinatorService.java:2081, thrown as the JobNotFoundException the 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-JobRestoreInProgressException loop plus RPC round trips) — no raw Thread.sleep.
  • FAILED_DEPLOYMENT_ATTEMPTS = 5 repeated attempts with fresh job ids each time (JOB_ID_SEQUENCE seeded 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's CountDownLatch gate 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

  1. Blockers — None.
  2. 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.

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

+1

@nzw921rx
nzw921rx added this pull request to the merge queue Sep 7, 2026
Merged via the queue into apache:dev with commit e68e285 Sep 7, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants