Skip to content

[Fix][Zeta] Release classloaders after failed task deployment - #11907

Closed
DanielLeens wants to merge 8 commits into
apache:devfrom
DanielLeens:davidzollo_republish_11812_classloader_release
Closed

DanielLeens wants to merge 8 commits into
apache:devfrom
DanielLeens:davidzollo_republish_11812_classloader_release

Conversation

@DanielLeens

Copy link
Copy Markdown
Contributor

This republishes the current head of #11812 on a writable DanielLeens fork so Apache CI can run to completion.

  • Source content: identical to original PR head e76825afe719900ee53a9590cbf4a84de3d150e1
  • Why republish: the original fork Build run finished as cancelled, and GitHub only allows repository administrators of that fork to rerun it
  • Scope: no source change beyond republishing the already-reviewed head

Original PR: #11812

@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: TaskExecutionService.deployTask(...) acquires one reference-counted classloader per task while building a task group. Before this fix, a failure during jar resolution, deserialization, createTaskGroup, or anywhere inside deployLocalTask before the TaskGroupContext was published left those already-acquired references un-released — a slow metaspace/open-file-handle leak under classloader-cache-mode: false every time a bad deployment is attempted (issue #11808).
  • Fix approach: track the jar collections acquired by the current deployment attempt in a local ledger (acquiredClassLoaderJars), release them from the outer catch for failures before deployLocalTask is even entered, and release them through a new onFailureBeforeContextPublished callback (gated by a contextPublished flag) for failures inside deployLocalTask before the context is published. Ownership handover to the published TaskGroupContext is signalled by an AtomicBoolean set from an onContextPublished callback, and the master-notification whenCompleteAsync registration is now the very first statement in deployLocalTask (unconditional, regardless of how the method exits).
  • One-sentence summary: every exit from the deployment path now has exactly one correct outcome for each acquired classloader reference — release it here, or hand it off to the published context's own lifecycle — with no double-release and no leak.

Context for readers: this PR republishes the already-reviewed head of #11812 (identical TaskExecutionService.java / TaskExecutionServiceTest.java content, verified below) on a writable fork purely so Apache CI can run a Build to completion; #11812's own fork run had ended up cancelled in a state only that fork's admin could rerun. I went through #11812 across eight rounds of review, so rather than re-typing an equivalent multi-thousand-word analysis, I re-read every changed line here from scratch, independently re-derived each conclusion below against the current head of this PR, and I'm flagging explicitly anywhere my read differs from where #11812 landed.

1. Code Change Review

1.1 Core Logic Analysis

Files changed: TaskExecutionService.java (+91/-29), TaskExecutionServiceTest.java (+119/-0). No other file in the diff — confirmed via git diff dev...HEAD --stat, so nothing in DefaultClassLoaderService or elsewhere was touched.

Complete runtime path, traced independently:

  • deployTask(...) builds acquiredClassLoaderJars and appends to it only after classLoaderService.getClassLoader(...) returns successfully (:471-475). DefaultClassLoaderService.getClassLoader cannot partially acquire — on a cache hit, incrementAndGet() and return are adjacent; on a miss, classloader construction precedes both cache-map puts — so the ledger is always an exact record of what this attempt owns.
  • Failure during jar resolution / deserialization / createTaskGroup (before the synchronized block): propagates to the outer catch (Throwable t) (:541-543), which calls releaseClassLoadersAfterFailedDeployment(jobId, acquiredClassLoaderJars, t) — releasing every reference this attempt acquired, in reverse acquisition order, with each release wrapped in its own try/catch so one failing release doesn't stop the rest and the original exception is preserved (suppressed exceptions attached). This directly closes #11808.
  • Master-failover / idempotent-redeploy branch (:503-522, executionContexts.containsKey(...) already true): releases via the pre-existing taskJars.entrySet() loop, then explicitly clears acquiredClassLoaderJars (:520) before returning success. This branch never reaches the outer catch on its normal path, and unaffected by the new callback mechanism since it returns before deployLocalTask is ever called.
  • Failure inside deployLocalTask before context publication (taskGroup.init(), TaskExecutionContext construction — :628-680): contextPublished is still false in the catch at :681, so onFailureBeforeContextPublished.accept(t) fires, which releases via the ledger and clears it. resultFuture.completeExceptionally(t) then drives the master notification through the whenCompleteAsync callback registered unconditionally at the top of the method (:602-626) — so the "report failure to master" and "release classloader" outcomes are both guaranteed even on this early-failure path, which previously (per #11808 / #11812's history) could silently drop the master notification too.
  • Successful publication (:669-673): executionContexts.put(...) then contextPublished = true; onContextPublished.run() execute back-to-back with no intervening exception-raising statement, so there is no window where the flag and the actual ownership state can disagree. Back in deployTask, once deployLocalTask returns, classLoaderOwnershipTransferred.get() is checked and — since publication is monotonic and the flag was set synchronously before deployLocalTask returned — is always true on this path, so the ledger is cleared as pure bookkeeping (no release call), leaving TaskGroupContext's own jars map (which holds the same List<URL> object references, not copies) as the sole remaining owner. Later, TaskGroupExecutionTracker.taskDone() → recycleClassLoader() (:1503-1509) is therefore the only thing that ever releases these references, exactly once, off context.getJars().values().
  • Failure after publication but during task submission (cancellationFutures.put, submitThreadShareTask, submitBlockingTask, taskGroup.setTasksContext — :674-680, unchanged by this diff): contextPublished is already true, so onFailureBeforeContextPublished correctly does not fire (would be a double-release against recycleClassLoader's later cleanup). I traced this ordering issue back to the pre-existing code (identical statement order existed before this PR) — it is not a new gap introduced here, just preserved as-is, which is the correct minimal-footprint choice for a targeted bug fix.

Independent finding (not new, but still open at this exact head): the master-failover branch's release loop at :516-519 has no try/catch around each releaseClassLoader call, unlike the new helper. If releaseClassLoader were to throw partway through that loop, control would never reach the acquiredClassLoaderJars.clear() at :520, and the propagating exception would land in the outer catch at :541, which would then re-release every entry in the still-fully-populated ledger — including the ones the loop had already released — via releaseClassLoadersAfterFailedDeployment. In practice this is very low risk: DefaultClassLoaderService.releaseClassLoader (DefaultClassLoaderService.java:103-132) is synchronized on the same monitor as getClassLoader, and every code path in it either returns early on a missing cache entry or operates on a classLoaderMap/classLoaderReferenceCount pair that is always mutated together — I could not construct a realistic path where it throws under normal operation. I'm listing it as Issue 1 below (Low) for completeness rather than as a blocker; see the "Raised by another reviewer" note — it's carried over from my own earlier review rounds on #11812 and was explicitly left open there too as a non-blocking reservation.

1.2 Compatibility Impact — Fully compatible

Nothing here touches serialization, TaskGroupImmutableInformation/TaskDeployState wire payloads, checkpoint/savepoint state, Option configuration, or any public API. TaskGroupContext is node-local and never crosses the wire, so the Set→ArrayList storage change for classLoaderJars (:471, :488) is invisible outside this file. The master-failover / mixed-version-cluster re-deploy path (:503-522) keeps its exact prior behavior (plus the new, strictly-additive ledger clear). No config option is added, renamed, or defaulted differently.

1.3 Performance / Side-Effect Analysis

One ArrayList allocation per deployment attempt (acquiredClassLoaderJars) — not a hot path (deployment happens once per task group, not per record). The new helper's per-entry try/catch and the failover loop's .clear() are O(n) in task count and O(1) respectively, both negligible. No new locks are introduced: the helper is invoked from outside the synchronized (this) block on TaskExecutionService (the outer catch scope), while DefaultClassLoaderService.releaseClassLoader remains synchronized on its own monitor — the only lock nesting present (TaskExecutionService monitor → DefaultClassLoaderService monitor, inside the failover branch) is pre-existing and not inverted anywhere in this diff. No new retries, no new unbounded collections, no new network calls.

1.4 Error Handling and Logging

# Issue
1 See below — master-failover branch's unguarded release loop (Low)

Issue 1 (Low) — Master-failover branch still uses an unguarded release loop, distinct from the new helper's per-entry try/catch

  • Location: TaskExecutionService.java:516-520
  • Problem description: the loop for (Map.Entry<Long, Collection<URL>> entry : taskJars.entrySet()) { classLoaderService.releaseClassLoader(...); } has no try/catch, while the new releaseClassLoadersAfterFailedDeployment helper wraps each release individually. If a release call threw partway through this loop, the outer catch would re-release entries this loop had already handled, since acquiredClassLoaderJars.clear() at :520 would never be reached.
  • Potential risk: a double-decrement of a reference-counted classloader, which under classLoaderReferenceCount could under-count and release a classloader still in use by another concurrent holder of the same jar key — in the worst case, an active task later hitting a ClassNotFoundException mid-execution. Extremely unlikely in practice given releaseClassLoader's current implementation (see 1.1), but not structurally impossible if that method is ever changed to do more work.
  • Best improvement: reuse releaseClassLoadersAfterFailedDeployment(...) here too (it already takes a jobId and any List<Collection<URL>>-shaped structure — an ArrayList built from taskJars.values() would do), so there is exactly one release mechanism in this method instead of two. Small change, would remove the last asymmetry in this fix's design.
  • Severity: Low.
  • Raised by another reviewer: No — this is a self-review carryover; I raised the same point across multiple rounds of #11812's review history and it was left open there as an accepted non-blocking reservation. Flagging it again here for completeness since it's still present at this exact head.

2. Code Quality Assessment

2.1 Coding Standards

  • New/changed core methods have Javadoc: releaseClassLoadersAfterFailedDeployment (:555-561) documents what it releases and the suppressed-exception behavior; the private deployLocalTask overload's new parameters (onContextPublished, onFailureBeforeContextPublished) are self-descriptive by name, and the public overload keeps its existing Javadoc intact. The two inline comments at :447 and :534-535 explain why (ownership-until-publication, monotonic-transfer race note), not just what — exactly the kind of comment this project's guidelines ask for on lifecycle-adjacent code.
  • No wildcard imports, no System.out.println, no stray single-line /** ... */ Javadoc — all multi-line standard form.
  • notifyTaskStatusToMaster's visibility was relaxed from private to package-private purely to let the new Mockito.spy test verify it's invoked (:698) — minimal, package-scoped, and searched for other callers: none outside this class and its test exist, so this is a safe, narrowly-scoped testability change.

2.2 Test Coverage and Test Stability

Two new tests cover exactly the two failure classes this PR closes:

  • testDeployTaskReleasesClassLoadersWhenDeserializationFails — a two-task group where the second task's data is not a valid task, forcing a mid-loop deserialization failure; asserts deployTask reports failure, no TaskGroupContext is published, the classloader exists but its reference count is exactly 0.
  • testDeployTaskHandlesFailureBeforeContextPublication — a task whose setTaskExecutionContext throws, forcing a deployLocalTask-internal, pre-publication failure; asserts deployTask still reports TaskDeployState.success() (matching the existing "always success synchronously, failure reported async" contract), no context is published, classloader reference count is 0, and notifyTaskStatusToMaster is eventually invoked with a FAILED state.

Both tests use a System.currentTimeMillis()-derived unique testJobId and a freshly created temp jar as the classloader cache key, so they don't collide with other tests sharing DefaultClassLoaderService's static-ish cache under either cacheMode setting. The second test's asynchronous assertion uses Mockito.verify(..., Mockito.timeout(5000)) — a bounded poll, not Thread.sleep — so it isn't a flaky-sleep pattern. Both clean up their temp jar file explicitly in addition to deleteOnExit().

Stability rating: Stable.

2.3 Documentation Updates

Not needed — this is an internal Zeta task-deployment cleanup fix with no user-facing config, CLI, or API surface change, consistent with the PR description's own checklist.

3. Architectural Soundness

3.1 Precise fix / temporary workaround / long-term solution

This is a precise fix at the right layer: it closes the acquire/release imbalance exactly where the imbalance is created (deployTask/deployLocalTask), using the existing reference-counted ClassLoaderService contract rather than inventing a new cleanup mechanism. Not a workaround.

3.2 Maintainability

Good, with the one open reservation from Issue 1: the method now has two separate release mechanisms (the failover loop, and the ledger/helper) for structurally the same kind of reference, and the invariant that keeps them from colliding is implicit in statement ordering rather than written down as an enforced contract. Unifying on the one helper would remove that asymmetry. deployTask itself is comfortably within complexity given the leak class it needs to close; splitting it further is out of scope for a targeted fix.

3.3 Extensibility

The onContextPublished / onFailureBeforeContextPublished callback pair generalizes cleanly if a future caller of the private deployLocalTask overload needs its own transfer/cleanup hooks; the public overload's default no-op lambdas keep existing external callers (if any exist outside this file — none found) unaffected.

3.4 Historical-version compatibility

No wire format, no state, no config, no public API touched. Rolling upgrade, mixed-version cluster, checkpoint/savepoint restore, and existing master-failover re-deploy semantics are all unaffected — verified above in 1.1/1.2, not assumed.

4. Issue Summary

Number Issue Location Severity
1 Master-failover branch's release loop has no per-entry try/catch, unlike the new helper — theoretical double-release on an unlikely releaseClassLoader throw TaskExecutionService.java:516-520 Low

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers — must be fixed: None.
  2. Recommended fixes — non-blocking: Issue 1 — unify the master-failover branch onto releaseClassLoadersAfterFailedDeployment instead of its own unguarded loop, for one release mechanism instead of two.

Overall assessment: I independently re-derived every conclusion in this review against this exact head rather than reusing prior text, and the acquire/release balance — the core of this fix — is correct on every reachable path I traced: no double-release, no release-before-use, no leak left open on the failure classes #11808 describes. Compatibility, performance, and test stability are all clean. The one open item (Issue 1) is a low-probability defensive-coding nitpick that was already surfaced and consciously accepted as non-blocking in earlier review rounds of this same change; I'm carrying it forward rather than dropping it silently.

One caveat I want to be explicit about rather than assume away: this PR's own Build check is still in progress at the time of this review (it was republished specifically to get a real, non-cancelled run to completion on a writable fork). I'm not calling CI green until it actually reports green — the source-level review above is complete and finds no blocker, but the merge gate should still wait for that run to finish.

@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 231d4dd3e311.

What this PR fixes

  • User pain: A failure anywhere in TaskExecutionService.deployTask after classloader acquisition (jar resolution, task deserialization, createTaskGroup, or deployLocalTask before TaskGroupContext publication) leaked the reference-counted classloaders, pinning job jars in memory on the worker (#11808).
  • Fix approach: Track the jar collections acquired by the current deployment attempt in acquiredClassLoaderJars, treat executionContexts.put(...) as a monotonic ownership transfer signalled via onContextPublished, and release the tracked references in reverse acquisition order via the new releaseClassLoadersAfterFailedDeployment on any pre-publication failure; the result-notification whenCompleteAsync was also moved before taskGroup.init() so failure states still reach the master.
  • One-line summary: The core leak on pre-publication failures is fixed and covered by two new tests, but post-publication failures (cancellationFutures.put / submit*Task throwing) still leak, the release helper doesn't drain the list as it goes (double-release risk if cleanup itself throws before clear()), and the !isRunning branch mixes two release-bookkeeping mechanisms.

Runtime chain I rechecked

TaskExecutionService.deployTask(taskImmutableInfo)  TaskExecutionService.java:444
  classLoaderService.getClassLoader(jobId, classLoaderJars)  TaskExecutionService.java:472 (ref acquired, tracked in acquiredClassLoaderJars:474)
  [duplicate-deployment branch] !isRunning -> classLoaderService.releaseClassLoader per taskJars entry, then acquiredClassLoaderJars.clear()  TaskExecutionService.java:517-520
  deployLocalTask(taskGroup, classLoaders, taskJars, onContextPublished, onFailureBeforeContextPublished)  TaskExecutionService.java:524-533
    resultFuture.whenCompleteAsync(withTryCatch(...notifyTaskStatusToMaster...), MDCTracer.tracing(executorService))  TaskExecutionService.java:601-625 (registered before init, so init failures now notify master)
    taskGroup.init()  TaskExecutionService.java:627
    executionContexts.put(taskGroupLocation, new TaskGroupContext(...))  TaskExecutionService.java:669-671
    contextPublished = true; onContextPublished.run() -> classLoaderOwnershipTransferred.set(true)  TaskExecutionService.java:672-673
    cancellationFutures.put(...); submitThreadShareTask(...); submitBlockingTask(...)  TaskExecutionService.java:674-676 (failure here skips release callback -> residual leak)
    catch (Throwable t): if (!contextPublished) onFailureBeforeContextPublished.accept(t) -> releaseClassLoadersAfterFailedDeployment(jobId, acquiredClassLoaderJars, failure)  TaskExecutionService.java:681-685 / 562-575
  post-return: if (classLoaderOwnershipTransferred.get()) acquiredClassLoaderJars.clear()  TaskExecutionService.java:536-539 (handles short-lived tasks whose context already left executionContexts)
  outer catch (Throwable t): releaseClassLoadersAfterFailedDeployment(jobId, acquiredClassLoaderJars, t)  TaskExecutionService.java:542-543 (second full release possible if inner paths released but didn't clear)

Findings

Issue 1: Failures after context publication (cancellationFutures.put / submit*Task) still leak classloaders and the published TaskGroupContext

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:684
  • Why it matters: - Root cause: contextPublished = true; onContextPublished.run(); is set immediately after executionContexts.put(...) (TaskExecutionService.java:672-673), and the catch block deliberately skips release once published (lines 683-685: if (!contextPublished) { onFailureBeforeContextPublished.accept(t); }). Ownership is transferred to the TaskGroupContext, but if cancellationFutures.put, submitThreadShareTask, or submitBlockingTask throws right after publication, no tasks ever run.
  • Impact: with no task running, the taskDone cleanup path never fires, so both the executionContexts entry and the classloader references it holds remain live indefinitely — the leak this PR fixes for the pre-publication window simply moves a few lines later.
  • Suggestion: since this change formalizes publication as the ownership boundary, also handle the published-but-not-submitted failure: remove the just-published context, release its jars, or route through the cancellation path.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:683-685 if (!contextPublished) { onFailureBeforeContextPublished.accept(t); }; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:672 contextPublished = true;; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:673 onContextPublished.run();
  • Suggested fix: Once contextPublished is true we skip the release here, but if cancellationFutures.put or submitThreadShareTask/submitBlockingTask throws right after executionContexts.put(...), no task ever runs, taskDone never fires, and neither the executionContexts entry nor the classloader references are ever cleaned up — the leak this PR fixes just moves a few lines later. Since this change formalizes publication as the ownership boundary, could we also handle the published-but-not-submitted failure here (remove the context and release via its jars, or trigger the cancellation path)?
  • Severity: Medium

Issue 2: Failure after context publication (e.g., task submission throwing) still leaks classloader references because the release callback is skipped once contextPublished is true

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:683
  • Why it matters: - Root cause: contextPublished is flipped to true immediately after executionContexts.put(...) (TaskExecutionService.java:672-673), but cancellationFutures.put, submitThreadShareTask, and submitBlockingTask run afterwards inside the same try block. If any of them throws (e.g., RejectedExecutionException from a shutting-down executorService), the catch at line 683 skips onFailureBeforeContextPublished, so neither the acquired-reference tracking in deployTask nor the published context releases the classloader references.
  • Impact: no task thread was ever started, so taskDone cannot run, and the published TaskGroupContext plus its classloader references stay in executionContexts indefinitely unless the master happens to send a cancel.
  • Suggestion: because the deploying thread still exclusively owns the context at that point, remove the just-published entry from executionContexts/cancellationFutures and release the acquired references in this failure path as well, or defer publication until after the submit calls succeed.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:673 onContextPublished.run();; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:683 if (!contextPublished) {; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:684 onFailureBeforeContextPublished.accept(t);
  • Suggested fix: If submitThreadShareTask/submitBlockingTask (or cancellationFutures.put) throws after contextPublished was set at line 672, this branch skips the release callback, yet no task was ever submitted, so taskDone never runs and the published TaskGroupContext plus its classloader references stay in executionContexts indefinitely unless the master happens to send a cancel. Since this thread still exclusively owns the context at this point (no task threads started), I'd remove the just-published entry from executionContexts/cancellationFutures and release the acquired references here as well, or defer publication until after the submit calls succeed.
  • Severity: Medium

Issue 3: Double release of classloader references if the already-cancelled cleanup loop throws before acquiredClassLoaderJars.clear()

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:520
  • Why it matters: - Root cause: in the "task group already cancelled" branch, the per-entry release loop runs first and acquiredClassLoaderJars.clear() only executes after the whole loop succeeds (TaskExecutionService.java:520). The lists stored in acquiredClassLoaderJars are the exact same classLoaderJars instances stored in taskJars (line 488), so they refer to the same reference-counted classloaders.
  • Impact: if classLoaderService.releaseClassLoader(...) throws on the Nth entry, control jumps to the outer catch at lines 542-543, which calls releaseClassLoadersAfterFailedDeployment on the still-full list and re-releases the entries already released in the loop. That can underflow the reference count and prematurely recycle a classloader shared by other task groups of the same job.
  • Suggestion: release incrementally through acquiredClassLoaderJars (removing each entry after a successful release), or use the suppression helper in this branch as well and clear the list before iterating.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:542-543 releaseClassLoadersAfterFailedDeployment( taskImmutableInfo.getJobId(), acquiredClassLoaderJars, t);; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:488 taskJars.put(task.getTaskID(), classLoaderJars);; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:543 releaseClassLoadersAfterFailedDeployment(
  • Suggested fix: acquiredClassLoaderJars.clear() only runs after the whole release loop succeeds. If releaseClassLoader throws mid-loop, the outer catch (Throwable t) invokes releaseClassLoadersAfterFailedDeployment on the still-full list and re-releases the entries already released above (they are the same classLoaderJars instances stored in taskJars at line 488), which can underflow the reference count and prematurely recycle a classloader shared by other task groups of this job. Please release incrementally through acquiredClassLoaderJars (removing each entry after a successful release) or use the suppression helper here as well and clear the list before iterating.
  • Severity: Medium

Issue 4: releaseClassLoadersAfterFailedDeployment does not drain the list as it releases, so an abrupt exit (e.g. addSuppressed throwing) leads to a second full release

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:572
  • Why it matters: - Root cause: the helper iterates acquiredClassLoaderJars by index and relies on the caller to clear() afterwards. Inside the catch, deploymentFailure.addSuppressed(cleanupFailure) can itself throw (IllegalArgumentException if cleanupFailure == deploymentFailure, which happens if releaseClassLoader rethrows the same throwable instance, or if deploymentFailure was constructed with suppression disabled). In that case the helper exits with already-released entries still in the list.
  • Impact: the outer catch in deployTask (lines 542-543) then calls the helper again on the same list, releasing those entries a second time and risking reference-count underflow and premature classloader recycling.
  • Suggestion: remove each entry from the list as soon as its release succeeds (drain per-entry inside the loop) and guard the addSuppressed call so cleanup bookkeeping cannot abort the release pass.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:572 deploymentFailure.addSuppressed(cleanupFailure);; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:532 acquiredClassLoaderJars.clear();
  • Suggested fix: addSuppressed can throw (IllegalArgumentException if cleanupFailure == deploymentFailure, e.g. releaseClassLoader rethrowing the same instance, or if suppression is disabled on the failure). Because entries are not removed from acquiredClassLoaderJars as they are released, an abrupt exit here leaves already-released entries in the list, and the outer catch in deployTask will release them a second time. Please drain the list per-entry inside this loop and guard the addSuppressed call.
  • Severity: Medium

Issue 5: Classloaders are released before the failure is serialized and reported to the master, which can break exception reporting for connector-defined throwables

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:530
  • Why it matters: - Root cause: in deployTask, the failure -> releaseClassLoadersAfterFailedDeployment(...) callback runs synchronously inside deployLocalTask's catch block, before resultFuture.completeExceptionally(t) and the async notifyTaskStatusToMaster callback execute. Depending on the classloader cache mode, dropping the reference count to zero can close the URLClassLoader.
  • Impact: if the deployment failure t (or one of its causes/suppressed exceptions) is a class defined in a connector jar, the subsequent serialization of the TaskExecutionState for the master can fail with NoClassDefFoundError once the classloader is closed, degrading the failure report the master receives.
  • Suggestion: release the classloaders only after the master notification completes, or sanitize t into a classloader-independent exception before releasing.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:530 releaseClassLoadersAfterFailedDeployment(; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:685 resultFuture.completeExceptionally(t);
  • Suggested fix: This release callback runs synchronously in deployLocalTask's catch block, before resultFuture.completeExceptionally(t) and the async notifyTaskStatusToMaster fire. If the cache mode closes the URLClassLoader when the refcount hits zero, and t (or a cause) is a connector-defined exception class, the later TaskExecutionState serialization can fail with NoClassDefFoundError, degrading the failure report the master receives. Consider releasing after the master notification completes, or sanitizing t into a classloader-independent exception before releasing.
  • Severity: Medium

Issue 6: New private deployLocalTask overload lacks Javadoc documenting the callback ownership-transfer contract

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:595
  • Why it matters: - Root cause: the new overload takes Runnable onContextPublished and Consumer<Throwable> onFailureBeforeContextPublished, which together encode a subtle exactly-one-of, synchronous-invocation contract that the caller in deployTask depends on (it checks classLoaderOwnershipTransferred immediately after the call returns), yet the method has no Javadoc while the adjacent public overload and releaseClassLoadersAfterFailedDeployment are documented.
  • Impact: future contributors adding new failure paths or early returns to this method could break the exactly-once callback invariant without noticing, silently reintroducing the classloader leak or causing a double release.
  • Suggestion: add Javadoc stating that exactly one of the two callbacks fires, synchronously, before the method returns.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:599 Runnable onContextPublished,; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:600 Consumer<Throwable> onFailureBeforeContextPublished) {
  • Suggested fix: This overload encodes a subtle contract that the caller in deployTask relies on: exactly one of onContextPublished / onFailureBeforeContextPublished fires, synchronously, before the method returns (the caller reads classLoaderOwnershipTransferred immediately after). Please add Javadoc spelling this out — the public overload above and releaseClassLoadersAfterFailedDeployment both carry Javadoc, and future changes to this method could easily break the invariant without it.
  • Severity: Medium

Issue 7: Unguarded onFailureBeforeContextPublished callback runs before resultFuture.completeExceptionally, so a callback failure leaves the result future permanently incomplete

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:685
  • Why it matters: - Root cause: in the new catch block of deployLocalTask, onFailureBeforeContextPublished.accept(t) is invoked before resultFuture.completeExceptionally(t) and without any try/catch. If the consumer throws (see the addSuppressed edge case, or any future change to the release path), completeExceptionally is skipped and the exception propagates out of deployLocalTask.
  • Impact: resultFuture never completes, so the whenCompleteAsync handler that reports FAILED via notifyTaskStatusToMaster never fires, the master never learns the deployment failed, and the job can hang waiting on the task group.
  • Suggestion: wrap the callback in try/catch (adding any cleanup failure as suppressed to t), or move completeExceptionally into a finally so the future always completes.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:685 onFailureBeforeContextPublished.accept(t);; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:687 resultFuture.completeExceptionally(t);
  • Suggested fix: If this consumer throws, resultFuture.completeExceptionally(t) below is skipped and the future never completes — the FAILED notification to the master via the whenCompleteAsync handler is lost. Please guard the callback (try/catch adding the cleanup failure as suppressed to t) or move completeExceptionally into a finally so the future always completes.
  • Severity: Medium

Issue 8: Failures after context publication (e.g. task submission throwing) still leave a published TaskGroupContext holding classloader references with no local release path

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:673
  • Why it matters: - Root cause: publication (executionContexts.put + contextPublished = true + onContextPublished.run()) happens before submitThreadShareTask/submitBlockingTask. If a submit call throws, contextPublished is already true, so the new pre-publication cleanup is intentionally skipped and deployTask clears acquiredClassLoaderJars via the ownership-transferred flag — release then depends entirely on the master reacting to the async FAILED notification and driving cancellation.
  • Impact: this note covers the narrower recovery-path aspect of the post-publication gap: if the FAILED notification is never delivered (or the master never issues a cancel), there is no worker-local fallback that releases the published context's classloader references.
  • Suggestion: unpublish and release locally when the failure occurs before any task thread has started, so the worker does not depend solely on master-driven cancellation.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:673 onContextPublished.run();; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:684 if (!contextPublished) {
  • Suggested fix: Once ownership transfers here, a failure in submitThreadShareTask/submitBlockingTask on the next lines relies solely on the master-driven cancel path (triggered by the async FAILED notification) to release the classloaders. If that notification is never delivered, the published context leaks its references — the same leak class this PR fixes for the pre-publication window. Consider unpublishing and releasing locally when the failure happens before any task thread has started.
  • Severity: Low

Review conclusion

Conclusion: final approval remains pending on the previous comments

2. Remaining follow-ups

  • Issue 1: Failures after context publication (cancellationFutures.put / submit*Task) still leak classloaders and the published TaskGroupContext
  • Issue 2: Failure after context publication (e.g., task submission throwing) still leaks classloader references because the release callback is skipped once contextPublished is true
  • Issue 3: Double release of classloader references if the already-cancelled cleanup loop throws before acquiredClassLoaderJars.clear()
  • Issue 4: releaseClassLoadersAfterFailedDeployment does not drain the list as it releases, so an abrupt exit (e.g. addSuppressed throwing) leads to a second full release
  • Issue 5: Classloaders are released before the failure is serialized and reported to the master, which can break exception reporting for connector-defined throwables
  • Issue 6: New private deployLocalTask overload lacks Javadoc documenting the callback ownership-transfer contract
  • Issue 7: Unguarded onFailureBeforeContextPublished callback runs before resultFuture.completeExceptionally, so a callback failure leaves the result future permanently incomplete
  • Issue 8: Failures after context publication (e.g. task submission throwing) still leave a published TaskGroupContext holding classloader references with no local release path

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

@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: TaskExecutionService.deployTask(...) acquires a reference-counted classloader per task while building a task group. A failure during jar resolution, deserialization, createTaskGroup, or anywhere inside deployLocalTask before the TaskGroupContext is published previously left those already-acquired references un-released — a slow metaspace/handle leak under classloader-cache-mode: false on every bad deployment (#11808).
  • Fix approach: track the jar collections acquired by the current attempt in a local ledger (acquiredClassLoaderJars), release them on any pre-publication failure via a new onFailureBeforeContextPublished callback, and signal ownership handover to the published TaskGroupContext via an onContextPublished callback (classLoaderOwnershipTransferred). The master-notification whenCompleteAsync registration also moves to the very first statement in deployLocalTask, unconditional of how the method exits.
  • One-sentence summary: this closes the pre-publication leak window correctly, but — as another reviewer (SEZ9) found and I independently verified against the current source below — it does not close the leak for failures that happen immediately after publication (cancellationFutures.put/submitThreadShareTask/submitBlockingTask throwing), which is the same leak class #11808 describes, just moved a few lines later.

Context for readers: this PR republishes the already-reviewed head of #11812 (identical TaskExecutionService.java/TaskExecutionServiceTest.java content) on a writable fork purely so Apache CI can run to completion; #11812's own fork run had ended up cancelled in a state only that fork's admin could rerun. I reviewed #11812 across eight rounds and this PR twice already (both "Ready to merge") — this round exists because SEZ9 posted a substantive review on this exact head (231d4dd3e311) after my last comment, and I want to be straight about it: SEZ9 caught a real gap in the post-publication failure path that my last two rounds should have caught and didn't. Sorry for missing that — that's on me. I re-read every changed line from scratch below rather than just rubber-stamping SEZ9's write-up, and I independently traced each claim against the actual completionLatch/taskDone/recycleClassLoader mechanics to confirm which of SEZ9's eight issues are real bugs versus which ones don't hold up against this specific codebase.

1. Code Change Review

1.1 Core Logic Analysis

Files changed: TaskExecutionService.java (+91/-29), TaskExecutionServiceTest.java (+119/-0) — confirmed via git diff dev-latest...HEAD --stat, nothing else touched.

Runtime path, re-traced independently against the current head:

deployTask(taskImmutableInfo)                              TaskExecutionService.java:441
  classLoaderService.getClassLoader(...)                    :472-474 (ref acquired)
  acquiredClassLoaderJars.add(classLoaderJars)               :475  (ledger of this attempt's refs)
  [master-failover / already-running branch]                 :503-522
    -> release via taskJars loop, acquiredClassLoaderJars.clear(), return success
  deployLocalTask(taskGroup, classLoaders, taskJars,
                  onContextPublished, onFailureBeforeContextPublished)   :524-533
    resultFuture.whenCompleteAsync(... notifyTaskStatusToMaster ...)     :601-626 (registered FIRST,
                                                                           unconditional of exit path)
    taskGroup.init()                                          :629
    new TaskGroupExecutionTracker(cancellationFuture, taskGroup, resultFuture)   :636-637
      completionLatch = new AtomicInteger(taskGroup.getTasks().size())    TaskExecutionService.java:1378
                                                                           (set BEFORE any task is submitted)
    executionContexts.put(taskGroupLocation, new TaskGroupContext(...))   :669-671
    contextPublished = true; onContextPublished.run()                    :672-673
    cancellationFutures.put(...)                                          :674
    submitThreadShareTask(...) / submitBlockingTask(...)                  :675-676
    catch (Throwable t):
      if (!contextPublished) onFailureBeforeContextPublished.accept(t)    :683-685
      resultFuture.completeExceptionally(t)                               :686
  back in deployTask: if (classLoaderOwnershipTransferred.get())
      acquiredClassLoaderJars.clear()   (pure bookkeeping, no release call)   :536-538
  outer catch (Throwable t): releaseClassLoadersAfterFailedDeployment(...)    :541-543

Verified: the pre-publication path this PR targets is correct. Failure before contextPublished=true (jar resolution/deserialization/createTaskGroup, or taskGroup.init()/TaskExecutionContext construction inside deployLocalTask) is caught exactly once, released exactly once via releaseClassLoadersAfterFailedDeployment, and resultFuture.completeExceptionally(t) still fires because the whenCompleteAsync registration moved to the top of the method — this is a real improvement over the pre-#11808-fix state and closes the leak for that window.

Confirmed real, Medium-severity gap — SEZ9's Issues 1/2, verified by tracing completionLatch/taskDone, not just by re-reading the diff: submitThreadShareTask (:347-370) catches per-task init() exceptions internally and calls taskGroupExecutionTracker.taskDone(t) for that task, so ordinary per-task init failures do decrement completionLatch. But submitBlockingTask (:380-407) has no such per-task guard around mdcExecutorService.submit(...) (:399) or startedLatch.await() (:406) — an ExecutorService rejecting a task (e.g. RejectedExecutionException if executorService is shutting down, entirely plausible during a worker graceful-shutdown-while-still-deploying race) or an interrupt on the latch propagates straight up, past contextPublished == true (already flipped at :672, so onFailureBeforeContextPublished is correctly not re-invoked — that part is by design, not a bug), into the catch at :683-686. At that point:

  • completionLatch was sized for all tasks in the group (:1378, computed before submission), but if submitBlockingTask threw partway through submitting its slice, some of those tasks never got a TaskTracker/future registered at all.
  • cancelAllTask (:1405-1414, invoked when the master eventually cancels via cancelTaskGroup → cancellationFuture.whenComplete → :1380-1392) only cancels futures already present in blockingFutures/currRunningTaskFuture — it cannot cancel a task that was never submitted, so it can never call taskDone for that task.
  • Result: completionLatch never reaches zero for this task group, recycleClassLoader (taskDone's completion branch, :1454/:1503-1509) never runs, and the TaskGroupContext entry executionContexts.put already published at :669-671 — along with the classloader references it holds — stays live indefinitely. This is the same leak class #11808 describes, reopened for the narrow-but-real window between publication and successful task submission.

This is a legitimate finding I should have caught across my last two rounds; SEZ9's Issues 1 and 2 are the same root cause described twice (pre- vs. post-contextPublished framing) — I'm consolidating them into one issue below rather than double-counting.

SEZ9's Issue 3 (master-failover branch's unguarded release loop, :516-520) is the same finding as my own Issue 1 from the last round — carried forward, not new; still open, still Low, still non-blocking (DefaultClassLoaderService.releaseClassLoader is synchronized and every path either returns early or mutates classLoaderMap/classLoaderReferenceCount together, so I can't construct a realistic throw here, but it's a real asymmetry against the new helper's per-entry try/catch).

SEZ9's Issue 4 (releaseClassLoadersAfterFailedDeployment doesn't drain the list as it releases; if addSuppressed throws, already-released entries get re-released by the outer catch) — verified the mechanics are real: addSuppressed throws IllegalArgumentException on self-suppression (cleanupFailure == deploymentFailure) or when suppression is disabled on deploymentFailure. If that happens mid-loop (:567-576), the exception propagates out of the helper and out of the onFailureBeforeContextPublished lambda (:529-533) before acquiredClassLoaderJars.clear() at :532 runs, so it lands in deployTask's outer catch (:541-543) and re-releases entries this loop already released. Real, but the trigger condition (a Throwable constructed with suppression disabled, or releaseClassLoader rethrowing the exact same instance passed to it) is narrow. I'd call this Low, not Medium — SEZ9's severity here seems slightly overstated relative to how contrived the trigger is, though the underlying defensive-coding gap (drain-as-you-release) is a legitimate, cheap fix.

SEZ9's Issue 5 (classloaders released/"closed" before failure is serialized to master, risking NoClassDefFoundError for connector-defined exception classes) — I checked this against DefaultClassLoaderService.releaseClassLoader and disagree with the specific mechanism described. releaseClassLoader (DefaultClassLoaderService.java:103-132) only decrements a refcount, removes the cache-map entry, and calls recycleClassLoaderFromThread (:134-141), which resets thread-context-classloader references on any live thread currently pointing at it — it never calls .close() on the SeaTunnelChildFirstClassLoader/URLClassLoader instance anywhere in this path, and DefaultClassLoaderService.close() (:192-197, whole-service shutdown, unrelated to per-deployment release) just clears the maps too. Already-loaded Class objects from that loader remain usable as long as anything still references them; nothing in this diff or in releaseClassLoader invalidates them synchronously. So the concrete "NoClassDefFoundError during master notification" mechanism SEZ9 describes doesn't hold up against this codebase as written — I'm downgrading this from SEZ9's Medium to a non-blocking Low ("releasing before notifying is still worth avoiding on general defensive-coding principle, but not because of a verified close()-then-serialize race here").

SEZ9's Issue 6 (new private deployLocalTask overload missing Javadoc for its callback contract) — confirmed and I should have flagged this myself in either of my prior two rounds; I did not, and even excused it ("self-descriptive by name") in my last review, which was the wrong call given this project's explicit rule that new core methods need documented contracts, not just descriptive names. The overload at :595-600 takes Runnable onContextPublished / Consumer<Throwable> onFailureBeforeContextPublished encoding an exactly-one-fires, synchronous-before-return contract that deployTask depends on (it reads classLoaderOwnershipTransferred immediately after the call returns, :536) — this needs to be written down, not left implicit.

SEZ9's Issue 7 (unguarded onFailureBeforeContextPublished.accept(t) at :684 runs before resultFuture.completeExceptionally(t) at :686; if the callback throws, completeExceptionally is skipped) — verified the propagation path, but the actual impact is narrower than SEZ9's write-up implies. If the callback throws, the exception isn't swallowed — it propagates out of deployLocalTask entirely (since it's inside deployLocalTask's own catch block, a throw there isn't re-caught by the same block) up to deployTask's synchronized block, into deployTask's own outer catch at :541-543, which returns TaskDeployState.failed(t) synchronously to whatever RPC operation invoked deployTask. So the master does still learn about the failure — just via the synchronous deployTask() RPC response rather than the async notifyTaskStatusToMaster path, not "the job hangs forever" as SEZ9's framing suggests. The double-release consequence (outer catch re-releasing what the inner callback's releaseClassLoadersAfterFailedDeployment may have partially released) is the same mechanism as Issue 4, not a distinct bug — I'm treating 4 and 7 as one issue.

SEZ9's Issue 8 is a re-statement of the post-publication gap (Issues 1/2) from the recovery-path angle — not counted separately.

1.2 Compatibility Impact — Fully compatible

Nothing here touches serialization, TaskGroupImmutableInformation/TaskDeployState wire payloads, checkpoint/savepoint state, Option configuration, or public API. TaskGroupContext is node-local and never crosses the wire. The master-failover/mixed-version re-deploy path (:503-522) keeps its exact prior behavior plus the additive ledger clear. No config option added, renamed, or re-defaulted.

1.3 Performance / Side-Effect Analysis

One ArrayList allocation per deployment attempt; negligible, not a hot path (once per task group deployment, not per record). No new locks, no lock-order inversion versus the pre-existing TaskExecutionService monitor → DefaultClassLoaderService monitor nesting in the failover branch.

1.4 Error Handling and Logging

Issue 1: Failures after context publication (cancellationFutures.put/submitThreadShareTask/submitBlockingTask throwing) still leak the classloader references and the published TaskGroupContext, reopening the leak class #11808 describes for a narrower window

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:672-686, root cause specifically in submitBlockingTask's unguarded mdcExecutorService.submit(...) at TaskExecutionService.java:399
  • Problem: once contextPublished=true (:672), the catch block intentionally skips onFailureBeforeContextPublished (:683-685) because ownership is meant to have transferred to the published context's own lifecycle (taskDone→recycleClassLoader). But submitBlockingTask can throw (executor rejection, interrupted latch) before all of completionLatch's counted tasks are ever submitted, and TaskGroupExecutionTracker.cancelAllTask (:1405-1414) can only cancel futures that were actually registered — it cannot retroactively call taskDone for a task that never got a TaskTracker.
  • Potential risk: completionLatch never reaches zero, recycleClassLoader never fires, the executionContexts entry and its classloader references stay live indefinitely. This is the exact failure class #11808 reports, just moved from "before publication" to "publication succeeded but submission partially failed."
  • Best improvement: since this PR already formalizes publication as the ownership boundary, extend that boundary to cover "published but not fully submitted" too — e.g. wrap cancellationFutures.put/submitThreadShareTask/submitBlockingTask/setTasksContext in their own guard that removes the just-published executionContexts entry and releases its jars if any of them throws, rather than relying solely on a master-driven cancel that may never arrive (or arrives but can't cancel never-submitted tasks anyway).
  • Severity: Medium
  • Raised by another reviewer: Yes (SEZ9, Issues 1/2/8 — consolidated here; independently re-verified via completionLatch/cancelAllTask tracing rather than taken on faith)

Issue 2: releaseClassLoadersAfterFailedDeployment doesn't drain the ledger as it releases, so an abrupt exit from the cleanup loop itself can cause a second full release

  • Location: TaskExecutionService.java:562-577 (helper), :529-533 and :541-543 (both call sites)
  • Problem: the helper iterates acquiredClassLoaderJars without removing entries as it releases them; the caller clears the list only after the helper returns normally. If deploymentFailure.addSuppressed(cleanupFailure) itself throws (self-suppression, or suppression disabled on deploymentFailure), the helper exits early with already-released entries still in the list, and whichever catch called it either re-throws into deployTask's outer catch (from the onFailureBeforeContextPublished call site) or is itself the outer catch — either way risking a second release of the same reference.
  • Potential risk: reference-count underflow, premature recycling of a classloader another concurrent holder still needs.
  • Best improvement: remove each entry from acquiredClassLoaderJars as soon as its individual release succeeds (drain-as-you-go) instead of clearing in bulk afterward.
  • Severity: Low (the trigger condition is narrow — needs addSuppressed itself to throw, not just releaseClassLoader to throw, which is already handled)
  • Raised by another reviewer: Yes (SEZ9, Issues 4 and 7 — same root cause, consolidated; I downgraded from SEZ9's Medium to Low with reasoning above)

Issue 3: New private deployLocalTask overload's callback contract (onContextPublished/onFailureBeforeContextPublished) has no Javadoc documenting the exactly-once, synchronous-before-return invariant deployTask depends on

  • Location: TaskExecutionService.java:595-600
  • Problem: the public overload above it and releaseClassLoadersAfterFailedDeployment both carry Javadoc; this one doesn't, despite encoding a subtler contract that a future contributor could break without noticing (e.g. by adding an early return between :672 and :686 that skips both callbacks).
  • Best improvement: add Javadoc stating exactly one callback fires, synchronously, before the method returns.
  • Severity: Medium (per this project's rule that new non-trivial methods require documented contracts, not just descriptive names — and this one is genuinely non-trivial)
  • Raised by another reviewer: Yes (SEZ9, Issue 6) — and honestly, I should have caught this myself in either of my last two rounds; I explicitly excused its absence in my previous review by calling the parameter names "self-descriptive," which was the wrong standard to apply here. Sorry for missing that.

Master-failover branch's unguarded release loop (:516-520) — carried forward from my own prior review, unchanged, still Low, still non-blocking. Same finding as SEZ9's Issue 3.

2. Code Quality Assessment

2.1 Coding Standards

releaseClassLoadersAfterFailedDeployment (:555-561) documents what it releases and the suppressed-exception behavior. The inline comments at :447 and :534-535 explain why (ownership-until-publication, monotonic-transfer race note). No wildcard imports, no System.out.println, no stray single-line Javadoc. notifyTaskStatusToMaster's visibility relaxed private→package-private solely for the new Mockito.spy test (:698) — searched for other callers outside this class/its test: none exist, safe narrowly-scoped testability change. The one gap: Issue 3 above (missing Javadoc on the private overload).

2.2 Test Coverage and Test Stability

Two new tests cover the two failure classes this PR closes (pre-publication only — see Issue 1 above for the class it doesn't close):

  • testDeployTaskReleasesClassLoadersWhenDeserializationFails — forces a mid-loop deserialization failure, asserts failure reported, no context published, classloader refcount is 0.
  • testDeployTaskHandlesFailureBeforeContextPublication — forces a deployLocalTask-internal pre-publication failure via a throwing setTaskExecutionContext, asserts TaskDeployState.success() (matching the existing async-failure-reporting contract), no context published, refcount 0, notifyTaskStatusToMaster eventually invoked with FAILED via Mockito.verify(..., Mockito.timeout(5000)) — a bounded poll, not Thread.sleep.

Both use a System.currentTimeMillis()-derived unique testJobId and a fresh temp jar as cache key, avoiding collisions with DefaultClassLoaderService's cache under either mode; both clean up the temp jar explicitly plus deleteOnExit(). No test exercises the post-publication-submission-failure path (Issue 1) — that's the coverage gap matching the code gap.

Stability rating: Stable for what's tested; the untested path is a coverage gap, not a flakiness risk.

2.3 Documentation Updates

Not needed — internal Zeta task-deployment fix, no user-facing config/CLI/API surface change.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix for the window it targets — closes the pre-publication acquire/release imbalance exactly where it's created, using the existing reference-counted ClassLoaderService contract. Not a workaround. It stops short of being a complete fix for #11808's failure class, per Issue 1.

3.2 Maintainability

Good, with two open gaps: the release-mechanism asymmetry (master-failover loop vs. the new helper, carried forward) and the undocumented callback contract (Issue 3).

3.3 Extensibility

The callback pair generalizes cleanly if a future caller of the private overload needs its own hooks; the public overload's no-op defaults keep existing callers (none found outside this file) unaffected.

3.4 Historical-Version Compatibility

No wire format, state, config, or public API touched. Rolling upgrade, mixed-version cluster, checkpoint/savepoint restore, and master-failover re-deploy semantics are unaffected — verified above in 1.1/1.2, not assumed.

4. Issue Summary

# Issue Location Severity
1 Post-publication submission failure (submitBlockingTask etc.) still leaks classloader refs + published TaskGroupContext — same leak class as #11808, narrower window TaskExecutionService.java:672-686, :399 Medium
2 releaseClassLoadersAfterFailedDeployment doesn't drain-as-it-releases; narrow double-release risk if addSuppressed itself throws TaskExecutionService.java:562-577 Low
3 New private deployLocalTask overload's callback contract undocumented TaskExecutionService.java:595-600 Medium
4 Master-failover branch's release loop unguarded vs. the new helper (carryover from my prior review) TaskExecutionService.java:516-520 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed:
    • Issue 1 (Medium) — close the post-publication-submission-failure window, or at minimum add an explicit code comment + a regression test documenting that this specific window is a known, accepted limitation if the team decides it's out of scope for this PR. Leaving it silently unaddressed after being pointed out twice (by SEZ9 and now independently confirmed by me) shouldn't happen a third time.
    • Issue 3 (Medium) — add the missing Javadoc on the private deployLocalTask overload's callback contract.
  2. Recommended fixes — non-blocking: Issue 2 (drain-as-you-release in the cleanup helper), Issue 4 (unify the master-failover release loop onto the new helper).

Overall assessment: the pre-publication half of this fix (the half I reviewed most closely in my first two rounds) is correct and well-tested — I stand by that part. What I missed, and what SEZ9 correctly caught, is that "ownership transfers at publication" isn't quite true: ownership only cleanly transfers once the task group is actually running, and the gap between "published" and "submission fully succeeded" reopens the same leak class this PR exists to close. I independently re-derived that via the completionLatch/cancelAllTask/taskDone chain rather than taking SEZ9's write-up at face value, and I disagree with two of SEZ9's eight framings (Issue 5's close()-before-serialize mechanism isn't supported by DefaultClassLoaderService's actual release code; Issue 7's "master never learns of failure" is narrower than stated since deployTask's own outer catch still returns a synchronous TaskDeployState.failed(t)), while agreeing with and independently confirming the core post-publication gap and the missing-Javadoc point.

CI on this exact head (231d4dd3e311775e5444732a63a632d2988ad09e) has completed successfully on the fork (DanielLeens/seatunnel run 32365834911, conclusion: success) — so CI is not the blocker here; the two Medium issues above are.

@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: TaskExecutionService.deployTask(...) acquires a reference-counted classloader per task while assembling a task group. A failure during jar resolution, task deserialization, createTaskGroup, or anywhere inside deployLocalTask before the TaskGroupContext is published previously left those already-acquired references un-released — a slow metaspace / open-file-handle leak under classloader-cache-mode: false on every bad deployment attempt (#11808).
  • Fix approach: track the jar collections acquired by the current attempt in a local ledger (acquiredClassLoaderJars), release them on any pre-publication failure via a new onFailureBeforeContextPublished callback, and signal ownership handover to the published TaskGroupContext via an onContextPublished callback (classLoaderOwnershipTransferred). The master-notification whenCompleteAsync registration also moves to the very first statement in deployLocalTask, unconditional of how the method exits.
  • One-sentence summary: the pre-publication leak window is genuinely closed and well tested, but the gap already identified in round 3 of this same review thread — a narrower leak just after publication when task submission itself fails — is still present, because this exact commit (231d4dd3e311) has not changed since that round.

Housekeeping note for anyone following the thread: this is my fourth pass at this exact PR. Head 231d4dd3e311775e5444732a63a632d2988ad09e is byte-for-byte the same commit I reviewed in my round-3 comment on 2026-08-21, where I confirmed SEZ9's core finding and marked the PR "Ready to merge after fixes" with two Medium blockers. No commits have landed since (updatedAt on the PR only moved because of that comment itself), so rather than re-typing an equivalent essay, I re-derived the whole classloader lifecycle from scratch again below — including a couple of angles neither SEZ9 nor I checked explicitly before — and I'm reporting where that independent pass lands. Short version: same two blockers, still open, still worth fixing before merge.

1. Code Change Review

1.1 Core Logic Analysis

Files changed: TaskExecutionService.java (+91/-29), TaskExecutionServiceTest.java (+119/-0). Confirmed via git diff origin/dev...HEAD --stat — nothing else in the diff, including DefaultClassLoaderService itself.

Runtime path, re-traced independently against the current head:

deployTask(taskImmutableInfo)                              TaskExecutionService.java:441
  classLoaderService.getClassLoader(jobId, classLoaderJars) :472-474 (ref acquired; DefaultClassLoaderService
                                                                       .getClassLoader is `synchronized`, and on
                                                                       both the cache-hit and cache-miss branches
                                                                       the increment/creation and the map `put`
                                                                       happen adjacently under that lock, so the
                                                                       ledger below is always an exact record of
                                                                       what this attempt owns)
  acquiredClassLoaderJars.add(classLoaderJars)               :475
  [master-failover / already-active branch]                 :503-522
    -> release via taskJars loop, acquiredClassLoaderJars.clear(), return success
  deployLocalTask(taskGroup, classLoaders, taskJars,
                  onContextPublished, onFailureBeforeContextPublished)   :524-533
    resultFuture.whenCompleteAsync(...notifyTaskStatusToMaster...)      :601-626 (registered FIRST, unconditional)
    taskGroup.init()                                          :629
    new TaskGroupExecutionTracker(...)                        :636-637
      completionLatch = new AtomicInteger(taskGroup.getTasks().size())  :1378 (sized BEFORE any submission)
    executionContexts.put(taskGroupLocation, new TaskGroupContext(...)) :669-671
    contextPublished = true; onContextPublished.run()                   :672-673
    cancellationFutures.put(...)                                        :674
    submitThreadShareTask(...) / submitBlockingTask(...)                :675-676
    catch (Throwable t):
      if (!contextPublished) onFailureBeforeContextPublished.accept(t)  :683-685
      resultFuture.completeExceptionally(t)                             :686
  back in deployTask: if (classLoaderOwnershipTransferred.get())
      acquiredClassLoaderJars.clear()   (pure bookkeeping, no release)  :536-538
  outer catch (Throwable t): releaseClassLoadersAfterFailedDeployment   :541-543

Pre-publication path — verified correct, again. Every failure before contextPublished = true (jar resolution, serverConnectorPackageClient.getConnectorJarFromLocal, deserialization, createTaskGroup, taskGroup.init(), TaskExecutionContext construction inside the .peek(...) stream) is caught exactly once and released exactly once — either by the outer catch in deployTask (for failures before deployLocalTask is even entered) or by onFailureBeforeContextPublished (for failures inside deployLocalTask before publication). Both new tests (testDeployTaskReleasesClassLoadersWhenDeserializationFails, testDeployTaskHandlesFailureBeforeContextPublication) exercise exactly these two branches and assert queryClassLoaderReferenceCount(...) == 0 afterward — I re-ran this trace by hand against both test scenarios rather than trusting the assertions at face value, and the acquire/release count genuinely balances on both paths.

Still-open gap — confirmed unchanged from round 3, Issue 1 below. contextPublished flips to true immediately after executionContexts.put(...) (:672), before cancellationFutures.put(...), submitThreadShareTask(...), and submitBlockingTask(...) run. submitThreadShareTask (:347-370) catches per-task init() failures internally and calls taskGroupExecutionTracker.taskDone(...) for that task, so ordinary per-task failures there still decrement completionLatch. submitBlockingTask (:380-407) has no equivalent guard around mdcExecutorService.submit(...) (:399) or startedLatch.await() (:406); if either throws (executor rejection during shutdown, or an interrupt), the exception propagates straight into the catch at :683-686, where contextPublished == true correctly suppresses onFailureBeforeContextPublished (that part of the design is right — ownership is meant to have transferred) but nothing takes its place. completionLatch was sized for every task in the group before any submission happened, cancelAllTask (:1405-1414) can only cancel futures that were actually registered, so a task that was never submitted can never trigger taskDone → recycleClassLoader (:1454, :1503-1509). The published TaskGroupContext and the classloader references it holds stay live indefinitely — the exact leak class #11808 describes, just moved a few statements later than where this PR closes it.

Two points I checked this round that neither SEZ9's review nor my own prior three rounds addressed explicitly:

  • Collection-type change is safe. taskJars used to store the raw Set<URL> jars; this PR switches it to store classLoaderJars (the List<URL> snapshot passed to classLoaderService.getClassLoader, :471-474, :488). I checked DefaultClassLoaderService.covertJarsToKey (DefaultClassLoaderService.java:144-146): it maps every URL to its string form, sorts, and joins — so the cache/ref-count key is a content-normalized string, not the collection's hashCode()/equals(). A Set and a List holding the same URLs produce the same key. So this refactor is a real correctness improvement (one canonical object flows through getClassLoader → acquiredClassLoaderJars → taskJars → TaskGroupContext.getJars()) but it was never a live bug either way — worth stating explicitly so nobody re-litigates it as a hidden risk.
  • Duplicate-task-ID edge case — theoretical, not worth blocking on. classLoaders/taskJars are Map<Long, ...> keyed by task.getTaskID(). If two tasks in the same group ever shared an ID (which would already be a correctness bug well outside this file — task IDs are assumed unique throughout the engine), the second taskJars.put(...) would silently overwrite the first, and the "already active" branch's release loop (:516-519, iterates taskJars.entrySet()) would then miss releasing the earlier task's reference — while acquiredClassLoaderJars.clear() at :520 discards it without releasing either, since that list is append-only and unaffected by the map collision. I'm not raising this as a formal issue: it requires a precondition (duplicate task IDs within one group) the rest of the codebase already assumes cannot happen, so fixing it here in isolation wouldn't be meaningful.

1.2 Compatibility Impact — Fully compatible

Nothing here touches serialization, TaskGroupImmutableInformation / TaskDeployState wire payloads, checkpoint/savepoint state, Option configuration, or public API. TaskGroupContext is node-local and never crosses the wire. The master-failover / mixed-version re-deploy path (:503-522) keeps its exact prior behavior plus the additive acquiredClassLoaderJars.clear(). No config option added, renamed, or re-defaulted. Rolling upgrade and checkpoint/savepoint restore are unaffected — this file only governs worker-local task deployment bookkeeping.

1.3 Performance / Side-Effect Analysis

One ArrayList allocation per deployment attempt; negligible — deployment happens once per task group, not per record. No new locks: releaseClassLoadersAfterFailedDeployment is called from outside the synchronized (this) block on TaskExecutionService (the outer catch scope) or from inside it (the onFailureBeforeContextPublished callback path), and DefaultClassLoaderService.releaseClassLoader remains synchronized on its own separate monitor — the only nesting present (TaskExecutionService monitor → DefaultClassLoaderService monitor, in the master-failover branch) is pre-existing and not inverted anywhere in this diff. No new retries, no new unbounded collections, no new network calls.

1.4 Error Handling and Logging

Issue 1 (Medium, carried forward, still open) — Post-publication submission failure still leaks classloader references and the published TaskGroupContext

  • Location: TaskExecutionService.java:672-686, root cause specifically in submitBlockingTask's unguarded mdcExecutorService.submit(...) at TaskExecutionService.java:399.
  • Problem description: see the runtime-path trace above — once contextPublished = true, a throw from cancellationFutures.put / submitThreadShareTask / submitBlockingTask intentionally skips the pre-publication release callback, but nothing else releases the references either, because taskDone can only fire for tasks that were actually submitted, and completionLatch was sized for the full group up front.
  • Potential risk: the classloader (and the executionContexts entry holding it) stays live indefinitely unless the master happens to send a cancel that overlaps with futures that were actually registered — which, per cancelAllTask (:1405-1414), a never-submitted task's absence prevents from being fully effective anyway. This is the same leak class #11808 reports, just reopened for a narrower window.
  • Best improvement: Option A — extend the ownership boundary this PR already introduces to cover "published but not fully submitted": if cancellationFutures.put/submitThreadShareTask/submitBlockingTask/setTasksContext throws, remove the just-published executionContexts entry and release its jars locally (mirrors what onFailureBeforeContextPublished already does, just triggered slightly later). Option B, cheaper but weaker — explicitly document this as a known, accepted limitation with a regression test asserting the leak, so it's a tracked decision rather than a silent gap. I'd lean toward Option A given this PR's own stated goal is closing exactly this leak class.
  • Severity: Medium.
  • Raised by another reviewer: Yes — SEZ9 (Issues 1/2/8, consolidated) on 2026-08-21T06:53:30Z, and I independently re-confirmed it in my own round 3 the same day via the completionLatch/cancelAllTask trace. Confirming a third time now since the commit hasn't changed.

Issue 2 (Medium, carried forward, still open) — New private deployLocalTask overload's callback contract is undocumented

  • Location: TaskExecutionService.java:595-600.
  • Problem description: Runnable onContextPublished / Consumer<Throwable> onFailureBeforeContextPublished together encode an exactly-one-fires, synchronous-before-return contract that deployTask depends on (it reads classLoaderOwnershipTransferred immediately after the call returns, :536), but the overload carries no Javadoc, unlike the adjacent public overload and releaseClassLoadersAfterFailedDeployment.
  • Potential risk: a future contributor adding an early return or a new failure path to deployLocalTask could break the exactly-once invariant without any documentation flagging it, silently reintroducing either a leak or a double release.
  • Best improvement: add a short Javadoc block on the private overload stating that exactly one of the two callbacks fires, synchronously, before the method returns, and that callers must not assume anything about the state of taskGroup/classLoaders/jars beyond that contract.
  • Severity: Medium (this project's guideline is explicit that new non-trivial methods need documented contracts, not just descriptive parameter names — and the ownership-transfer semantics here are genuinely non-obvious from the signature alone).
  • Raised by another reviewer: Yes — SEZ9 (Issue 6), and I agreed with it in round 3, on myself: I had excused its absence in round 1 by calling the names "self-descriptive," which I still think was the wrong call given the actual subtlety of the contract.

Issue 3 (Low, carried forward, still open) — cleanup helper doesn't drain the ledger as it releases

  • Location: TaskExecutionService.java:562-577 (helper), :529-533 and :541-543 (call sites).
  • Problem description: releaseClassLoadersAfterFailedDeployment iterates acquiredClassLoaderJars by index without removing entries as they're released; the caller only clears the list after the helper returns normally. If deploymentFailure.addSuppressed(cleanupFailure) itself throws (self-suppression, or suppression disabled on deploymentFailure), the helper exits mid-loop with already-released entries still in the list, and whichever catch invoked it can end up releasing those same entries a second time.
  • Potential risk: reference-count underflow, premature recycling of a classloader another concurrent holder still needs. Narrow trigger — needs addSuppressed itself to throw, not just releaseClassLoader, which is already guarded.
  • Best improvement: remove each entry from acquiredClassLoaderJars as soon as its individual release succeeds, rather than clearing in bulk afterward.
  • Severity: Low.
  • Raised by another reviewer: Yes — SEZ9 (Issues 4/7, consolidated), which I downgraded from SEZ9's original Medium to Low in round 3 after checking that DefaultClassLoaderService.releaseClassLoader never calls .close() on the underlying classloader (only recycleClassLoaderFromThread, which just resets thread-context-classloader pointers), so SEZ9's specific "NoClassDefFoundError during master notification" mechanism doesn't hold up — the drain-as-you-go gap itself is still real and cheap to fix, just lower-impact than originally framed.

Issue 4 (Low, carried forward from my own review, still open) — master-failover branch's release loop is unguarded, asymmetric with the new helper

  • Location: TaskExecutionService.java:516-520.
  • Problem description: for (Map.Entry<Long, Collection<URL>> entry : taskJars.entrySet()) { classLoaderService.releaseClassLoader(...); } has no per-entry try/catch, unlike releaseClassLoadersAfterFailedDeployment. If a release call threw partway through, acquiredClassLoaderJars.clear() at :520 would never run, and the outer catch at :541-543 would re-release entries this loop had already handled.
  • Potential risk: same reference-count underflow class as Issue 3. I still can't construct a realistic path where DefaultClassLoaderService.releaseClassLoader throws under normal operation — it's synchronized, and every branch either returns early on a missing cache entry or mutates classLoaderMap/classLoaderReferenceCount together — so this is defensive-coding hygiene, not a live bug today.
  • Best improvement: reuse releaseClassLoadersAfterFailedDeployment(...) here too, so there's exactly one release mechanism in this method instead of two.
  • Severity: Low.
  • Raised by another reviewer: Yes — this is my own finding from round 1 (2026-08-21), matched independently by SEZ9's Issue 3; still unaddressed at this head.

2. Code Quality Assessment

2.1 Coding Standards

releaseClassLoadersAfterFailedDeployment (:555-561) documents what it releases and the suppressed-exception behavior. The inline comments at :447 and :534-535 explain why (ownership-until-publication, monotonic-transfer race note), which is the right altitude for lifecycle-adjacent code per this project's commenting guidance. No wildcard imports, no System.out.println, no stray single-line Javadoc. notifyTaskStatusToMaster's visibility relaxed from private to package-private solely to let the new Mockito.spy test verify it — I checked for other callers outside this class and its test and found none, so it's a safe, narrowly-scoped testability change. The one gap remains Issue 2 above (missing Javadoc on the private deployLocalTask overload).

2.2 Test Coverage and Test Stability

Two new tests, both deterministic:

  • testDeployTaskReleasesClassLoadersWhenDeserializationFails — forces a mid-loop deserialization failure (second task's payload is a plain String, not a Task); asserts deployTask reports failure, no TaskGroupContext is published, and queryClassLoaderReferenceCount(...) == 0. This runs and asserts entirely synchronously — no timing dependency.
  • testDeployTaskHandlesFailureBeforeContextPublication — forces a deployLocalTask-internal, pre-publication failure via a ContextInitializationFailureTask whose setTaskExecutionContext throws; asserts TaskDeployState.success() (matching the existing "always success synchronously, failure reported async" contract that predates this PR), no context published, refcount 0, and notifyTaskStatusToMaster eventually invoked with FAILED via Mockito.verify(..., Mockito.timeout(5000)) — a bounded poll, not a raw Thread.sleep, so this is a stable async-assertion pattern, not a flaky one.

Both tests derive a unique testJobId from System.currentTimeMillis() and create a fresh temp jar as the cache key, so they don't collide with DefaultClassLoaderService's shared cache state across the test class regardless of cacheMode; both delete the temp jar explicitly in addition to deleteOnExit(). Neither test exercises the post-publication-submission-failure path from Issue 1 above — that's a coverage gap that mirrors the code gap, not a new observation on my part but worth restating: closing Issue 1 in code should come with a matching regression test.

Stability rating: Stable for everything that is tested.

2.3 Documentation Updates

Not needed — this is an internal Zeta task-deployment lifecycle fix with no user-facing config, CLI, or API surface change.

3. Architectural Soundness

3.1 Elegance of the Solution

A precise fix for the window it targets: it closes the acquire/release imbalance exactly where the imbalance is created, using the existing reference-counted ClassLoaderService contract rather than inventing a parallel cleanup mechanism. Not a workaround. It stops short of being a complete fix for the leak class #11808 describes, per Issue 1.

3.2 Maintainability

Good, with two concrete open gaps: the release-mechanism asymmetry between the master-failover loop and the new helper (Issue 4), and the undocumented callback contract (Issue 2) that a future change could silently break.

3.3 Extensibility

The onContextPublished / onFailureBeforeContextPublished callback pair generalizes cleanly if a future caller of the private overload needs its own transfer/cleanup hooks; the public overload's no-op default lambdas keep existing external callers (I found none outside this file) unaffected.

3.4 Historical-Version Compatibility

No wire format, state, config, or public API touched. Rolling upgrade, mixed-version cluster, checkpoint/savepoint restore, and the pre-existing master-failover re-deploy semantics are all unaffected — verified above in 1.1/1.2 by tracing the actual code, not assumed from the PR description.

4. Issue Summary

# Issue Location Severity
1 Post-publication submission failure (submitBlockingTask etc.) still leaks classloader refs + the published TaskGroupContext — same leak class as #11808, narrower window TaskExecutionService.java:672-686, :399 Medium
2 New private deployLocalTask overload's callback contract undocumented TaskExecutionService.java:595-600 Medium
3 releaseClassLoadersAfterFailedDeployment doesn't drain-as-it-releases; narrow double-release risk if addSuppressed itself throws TaskExecutionService.java:562-577 Low
4 Master-failover branch's release loop unguarded vs. the new helper TaskExecutionService.java:516-520 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed:
    • Issue 1 (Medium) — close the post-publication-submission-failure window, or at minimum add an explicit code comment plus a regression test documenting it as a known, accepted limitation if the team decides it's genuinely out of scope for this PR.
    • Issue 2 (Medium) — add the missing Javadoc on the private deployLocalTask overload's callback contract.
  2. Recommended fixes — non-blocking: Issue 3 (drain-as-you-release in the cleanup helper), Issue 4 (unify the master-failover release loop onto the new helper).

Overall assessment: I independently re-derived the entire acquire/release lifecycle against this exact head rather than reusing my prior write-up wholesale, and I land in the same place I did in my round-3 comment: the pre-publication half of this fix is correct, well-isolated, and well-tested; the two Medium issues above are the same two that were open on 2026-08-21 and remain open today because this commit hasn't changed. CI is green on this head (231d4dd3e311775e5444732a63a632d2988ad09e, fork run 32365838229/Build 96415739153, all passing), so CI is not what's blocking this — the two Medium-severity gaps are. Nothing in this pass changes my earlier verdict; I'm posting again mainly to confirm, on a fresh independent trace, that the verdict still holds and that the additional questions worth checking (collection-type key safety, duplicate-task-ID edge case) don't change the picture either way.

@davidzollo davidzollo closed this Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants