Repository navigation
[Fix][Zeta] Release classloaders after failed task deployment - #11812
Conversation
Signed-off-by: Goutam Adwant <workwithgoutam@gmail.com>
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point:
TaskExecutionService.deployTask(...)acquires one classloader reference per task in a task group, one at a time, inside a loop. If any task after the first one fails during jar resolution, classloader creation, or deserialization, the outercatch (Throwable t)returnedTaskDeployState.failed(t)without ever callingclassLoaderService.releaseClassLoader(...)for the references already acquired in that same attempt. BecauseDefaultClassLoaderServiceis reference-counted, those orphaned references pin theSeaTunnelChildFirstClassLoader(and its open JAR file handles) for the lifetime of the node. Repeated bad submissions, broken/missing jars, or incompatible task payloads therefore accumulate metaspace pressure and file handles — the classic slow production leak that is essentially undiagnosable after the fact. This is the gap reported in issue #11808. - Fix approach: Track the exact jar collections acquired by the current deployment attempt in a local
List<Collection<URL>> acquiredClassLoaderJars(TaskExecutionService.java:446), append to it immediately after each successfulgetClassLoader(...)(:473), clear it once ownership has been handed over to the publishedTaskGroupContext(:521), and release every still-owned reference in the outercatch(:525-526, helper at:538-552). Cleanup failures are attached to the original deployment exception viaaddSuppressedso the deployment failure remains the primary error and cleanup continues for the remaining entries. - One-sentence summary: A tightly scoped, correct compensation for a real reference-count leak on the Zeta task-deployment failure path, with a targeted regression test — the production logic is sound, but the new test is not isolated from a process-wide classloader cache and will be order-dependent, and the fix stops short of the failure window inside
deployLocalTask(...).
1. Code Change Review
1.1 Core Logic Analysis
Scope: 2 files, +67/-2. One production file (seatunnel-engine-server/.../TaskExecutionService.java, +24/-2) and one test file (TaskExecutionServiceTest.java, +43/-0). No API, config, serialization, packaging, or documentation surface is touched.
Before / after
Before (acquisition, per task):
ClassLoader classLoader =
classLoaderService.getClassLoader(
taskImmutableInfo.getJobId(), Lists.newArrayList(jars));
...
taskJars.put(task.getTaskID(), jars);After (TaskExecutionService.java:469-473, :486):
List<URL> classLoaderJars = Lists.newArrayList(jars);
ClassLoader classLoader =
classLoaderService.getClassLoader(
taskImmutableInfo.getJobId(), classLoaderJars);
acquiredClassLoaderJars.add(classLoaderJars);
...
taskJars.put(task.getTaskID(), classLoaderJars);Plus ownership handover (:520-522) and compensation (:524-526, :538-552):
deployLocalTask(taskGroup, classLoaders, taskJars);
acquiredClassLoaderJars.clear();
return TaskDeployState.success();
}
} catch (Throwable t) {
releaseClassLoadersAfterFailedDeployment(
taskImmutableInfo.getJobId(), acquiredClassLoaderJars, t);Question 1 — Does the NORMAL (successful) deployment path reach the changed code?
Answer: partially yes. Three of the five changed statements execute on every single successful deployment; only the behavioural change (the release) is confined to the exception path. This distinction matters for risk assessment, so here is the traced chain.
Zeta task deployment — traced call chain (head 520454e3c)
─────────────────────────────────────────────────────────────────────────────
[master] PhysicalVertex.deployOnLocal(SlotProfile)
PhysicalVertex.java:262-271
-> SeaTunnelServer.getSlotService().getSlotContext(slotProfile)
.getTaskExecutionService().deployTask(taskGroupImmutableInformation)
PhysicalVertex.deployOnRemote(SlotProfile)
PhysicalVertex.java:273-285
-> NodeEngineUtil.sendOperationToMemberNode(new DeployTaskOperation(...))
[Hazelcast operation thread on the target worker]
-> DeployTaskOperation.run() DeployTaskOperation.java:55
-> TaskExecutionService.deployTask(Data) TaskExecutionService.java:414-418
-> nodeEngine.getSerializationService().toObject(...) :416
-> TaskExecutionService.deployTask(TaskGroupImmutableInformation)
TaskExecutionService.java:440
[worker] deployTask(TaskGroupImmutableInformation) :440
446 List<Collection<URL>> acquiredClassLoaderJars = new ArrayList<>(); <-- NEW, normal path
454 for (i = 0 .. taskData.size()-1)
463 jars = serverConnectorPackageClient.getConnectorJarFromLocal(...) [may throw]
469 List<URL> classLoaderJars = Lists.newArrayList(jars); <-- NEW, normal path
470 classLoader = classLoaderService.getClassLoader(jobId, classLoaderJars)
-> DefaultClassLoaderService.getClassLoader() DefaultClassLoaderService.java:58
:60-63 cacheMode -> jobId := 1L
:70-72 cache hit -> refCount.incrementAndGet()
:74-98 cache miss -> jar existence check [may throw
ClassLoaderException NOT_FOUND_JAR], then
new SeaTunnelChildFirstClassLoader(jars), refCount = 1
473 acquiredClassLoaderJars.add(classLoaderJars); <-- NEW, normal path
475-483 deserialize task (plain or CustomClassLoadedObject) [may throw]
486 taskJars.put(task.getTaskID(), classLoaderJars); <-- CHANGED value
488 TaskGroupUtils.createTaskGroup(...) [may throw]
500 synchronized (this)
501 if executionContexts.containsKey(location) -> failover branch :508-518
releases via taskJars, returns success (acquired list NOT cleared)
520 deployLocalTask(taskGroup, classLoaders, taskJars)
:569 taskGroup.init()
:609 executionContexts.put(location, new TaskGroupContext(taskGroup,
classLoaders, taskJars)) <-- OWNERSHIP HANDOVER
:613 submitThreadShareTask(...) :346-369
:614 submitBlockingTask(...) :379-406
:619-622 catch (Throwable) { log; resultFuture.completeExceptionally } <-- SWALLOWS
:623 resultFuture.whenCompleteAsync(..., MDCTracer.tracing(executorService))
521 acquiredClassLoaderJars.clear(); <-- NEW, normal path
522 return TaskDeployState.success();
524 catch (Throwable t)
525 releaseClassLoadersAfterFailedDeployment(jobId, acquired, t) <-- NEW, FAILURE PATH ONLY
:542 reverse iteration
:545 classLoaderService.releaseClassLoader(jobId, jars)
-> DefaultClassLoaderService.releaseClassLoader() :103
:119-121 cacheMode -> decrement then RETURN (no close)
:122-127 refCount==0 -> remove from cache +
recycleClassLoaderFromThread(cl) :134-142
[Thread.getAllStackTraces() — expensive]
[eventual normal release, unchanged]
TaskGroupExecutionTracker.taskDone(Task) :1406
:1413 if (completionLatch.decrementAndGet() == 0)
:1414 recycleClassLoader(taskGroupLocation) :1463-1469
for (Collection<URL> jars : context.getJars().values())
classLoaderService.releaseClassLoader(jobId, jars) :1467
So:
:446,:469,:473,:486,:521— executed on every normal deployment. These are allocation and bookkeeping only;:486changes the concrete type of the value stored inTaskGroupContext.jarsfrom theSet<URL>obtained at:455/:467to theArrayList<URL>copy.:525-526and the wholereleaseClassLoadersAfterFailedDeploymenthelper — exception path only.
The normal-path portion is therefore what needs the compatibility scrutiny (see 1.2), and the failure-path portion is what needs the lifecycle scrutiny (Question 2).
Question 2 — Classloader lifecycle correctness (double-release / release-before-use)
I enumerated every exit of deployTask(...) and checked the acquire/release balance against DefaultClassLoaderService's reference counter.
| # | Path | Acquired | Released | Balanced? |
|---|---|---|---|---|
| A | Full success (:520-522) |
N | N later, via recycleClassLoader at :1463-1469 reading TaskGroupContext.getJars() |
Yes |
| B | Failure inside the loop, e.g. missing jar (DefaultClassLoaderService.java:82-88) or deserialization (:475-483) |
K (1..N) | K in catch (:525) |
Yes — this is the fix |
| C | Failure at TaskGroupUtils.createTaskGroup (:488-493) |
N | N in catch |
Yes |
| D | Master-failover "already exists" branch (:501-518) |
N | N via taskJars loop at :514-517; acquiredClassLoaderJars is not cleared, but the branch returns, so the catch is not reached |
Yes (see Issue 4 for the latent edge) |
| E | Failure inside deployLocalTask (:568-622) |
N | Depends — see below | No, in some sub-cases |
| F | Throw escaping deployLocalTask after executionContexts.put (:609) |
N | Potentially twice | Theoretically no (see Issue 5) |
No double-release exists on any path I can construct that is reachable in normal operation. The reason is structural and worth stating explicitly for the record: acquiredClassLoaderJars is cleared at :521 after deployLocalTask(...) returns, i.e. after executionContexts.put(...) at :609-611 has transferred ownership to the TaskGroupContext. Between :520 and :521 there is no statement that can throw (clear() on an ArrayList cannot throw, and returning from a synchronized block cannot throw), so there is no window in which both recycleClassLoader and the new catch handler own the same reference. That is the right place for the handover and I want to credit the author for getting it right — this is exactly the subtle part.
No release-before-use race exists either, because DefaultClassLoaderService is reference-counted per (jobId, jarKey) and the compensation releases exactly the count this attempt acquired, never more. If a concurrently running task group of the same job holds a reference to the same key, the counter stays above zero, the classloader is not removed from the cache (DefaultClassLoaderService.java:122-127), and recycleClassLoaderFromThread (:134-142) is not invoked. I verified there is no path where the new code releases a key it did not acquire.
Path E is the real remaining gap. deployLocalTask swallows Throwable at TaskExecutionService.java:619-622 — it logs, completes resultFuture exceptionally, and returns normally. Control therefore returns to :521, acquiredClassLoaderJars.clear() runs, and deployTask returns TaskDeployState.success(). If the failure occurred before executionContexts.put(...) at :609 (e.g. taskGroup.init() at :569, or new TaskExecutionContext(...) inside the peek at :584-586), then no TaskGroupContext was ever published, recycleClassLoader (:1463) can never find it, and the N references leak permanently — the same class of leak issue #11808 describes.
There is also a concrete reachable sub-case after publication: submitThreadShareTask at :346-369. When a task's init() throws (:357), the catch at :359-362 calls taskGroupExecutionTracker.taskDone(t) for that task only; every subsequent task in the stream then hits the executionCompletedExceptionally() guard at :352 and the mapper returns null, which threadShareTaskQueue::add at :367 rejects with a NullPointerException (LinkedBlockingDeque forbids null). Those later tasks never call taskDone, so completionLatch at :1413 never reaches zero, recycleClassLoader is never invoked — and the NPE is swallowed by :619-622 so deployTask still reports success. This is pre-existing and not caused by this PR, but it means the headline claim "classloaders are released after failed task deployment" is only true for failures that occur before deployLocalTask is entered. See Issue 3.
Question 3 — Interaction with existing classloader caching/reuse
I grepped every getClassLoader( / releaseClassLoader( call site in the whole seatunnel-engine tree. The production call sites are:
| Site | Acquire | Release | Interaction with this PR |
|---|---|---|---|
TaskExecutionService.java:471 / :515 / :545 / :1467 |
per task, per deployment attempt | failover branch, new compensation helper, and recycleClassLoader |
The three release sites now cover mutually exclusive outcomes; verified no overlap (table above) |
JobMaster.java:254 / :311 |
job-level, master side | job cleanup | Different acquisition, own balanced pair. The new code releases only what deployTask acquired, so it cannot decrement JobMaster's reference |
PhysicalPlanGenerator.java:273 / :283 |
plan generation, master side | immediately after use | Same key space as deployTask when master and worker are colocated and classloader-cache-mode: false; safe because of reference counting |
DAGUtils.java:86 / :92 |
DAG info, master side | immediately after use | Same as above |
MultipleTableJobConfigParser.java:319 / :302-304 |
config parse, client/master side | after parse | Same as above |
The single shared cache is DefaultClassLoaderService.classLoaderCache / classLoaderReferenceCount (DefaultClassLoaderService.java:43-44), keyed by jobId plus covertJarsToKey(jars) (:144-146, a sorted concatenation of URL.toString()). Because the key is derived from URL strings — not from collection identity or type — changing the stored value at :486 from a HashSet<URL> to an ArrayList<URL> copy of the same elements produces an identical key, so recycleClassLoader at :1467 still resolves to the same cache entry. I checked this specifically; it is correct.
One important production-impact nuance that the PR description does not mention: classloader-cache-mode defaults to true (ServerConfigOptions.java:31-36, wired at EngineConfig.java:80-81 and SeaTunnelServer.java:157-159). In cache mode, releaseClassLoader decrements the counter and then returns at DefaultClassLoaderService.java:119-121 without ever removing the classloader or closing anything. So under the default configuration the pre-existing bug leaks only a counter value, with no metaspace or file-handle consequence — the classloader is intentionally retained anyway. The leak this PR fixes has real teeth only when operators set classloader-cache-mode: false to get per-job classloader isolation and reclamation. That does not make the fix less correct or less worth merging; it means the severity framing in issue #11808 ("metaspace pressure, JAR handle usage") applies to the non-default configuration. Worth a sentence in the PR description so future readers calibrate correctly.
Question 4 — Does early release break legitimate reuse of a cached classloader (e.g. on retry)?
No. Three independent reasons, all verified in source:
- Release is exactly counter-balanced. The classloader is only evicted when the count reaches zero (
DefaultClassLoaderService.java:122-127), i.e. when nobody else holds it. A concurrent task group,JobMasterreference, orPhysicalPlanGeneratorreference keeps it alive. - On the failure path there is by definition no surviving
TaskGroupContextfor this attempt, so nothing on this node needs the classloader afterwards. - On retry,
PhysicalVertexre-invokesdeployTask, which callsgetClassLoader(...)again at:470. If the entry was evicted,DefaultClassLoaderService.java:94-98simply constructs a freshSeaTunnelChildFirstClassLoader— which is the desired semantics after a failed attempt, since the previous attempt may have failed precisely because of a bad jar. Retaining a stale classloader across a retry would be the worse behaviour.
The only thing to be aware of is that eviction also triggers recycleClassLoaderFromThread (:134-142), which nulls the context classloader of any thread still pointing at it. Since eviction requires a zero count, no live task can be affected. Under the default cacheMode = true, this branch is unreachable entirely (:119-121).
1.2 Compatibility Impact
Fully compatible.
- No public API, SPI, or
Optionis added, removed, renamed, or given a new default.ClassLoaderService(ClassLoaderService.java:24-45) is untouched. - No serialization format changes.
TaskGroupImmutableInformation,TaskDeployState, and every Hazelcast operation payload are untouched.TaskGroupContext(TaskGroupContext.java:29-42) is node-local and does not implementSerializable, so theSet→ArrayListchange at:486never crosses the wire and cannot break a rolling upgrade or a mixed-version cluster. - No checkpoint/savepoint state, no restore path, no state-machine transition is touched. Nothing in the change is persisted.
- Behaviour on the success path is byte-for-byte identical except for the concrete collection type held in
TaskGroupContext.jars. The only consumer isrecycleClassLoader(:1466), which iterates values and feeds them tocovertJarsToKey— order- and type-insensitive. The existing testtestClassloaderSplitasserts withassertIterableEquals(TaskExecutionServiceTest.java:215-220), which compares element-by-element and is unaffected bySetvsList; I checked this explicitly because anassertEqualsthere would have broken. - Behaviour on the failure path changes from "leak silently" to "release" — strictly an improvement, and observable only as extra
Release classloader for job ...log lines atDefaultClassLoaderService.java:124in non-cache mode. - Old jobs, restored jobs, savepoint resumes, and master-failover re-deploys (
:501-518) all behave exactly as before.
1.3 Performance / Side-Effect Analysis
Normal path — negligible. One ArrayList per deployment (:446) and one ArrayList copy per task (:469). Note the Lists.newArrayList(jars) copy already existed before the PR — it was previously created inline as the getClassLoader argument and thrown away. The change hoists it into a variable and reuses it, so the net allocation delta is one ArrayList per deployTask call, and the taskJars map now retains the copy instead of retaining a reference into taskImmutableInfo, which is marginally better for GC. Deployment happens once per task group per job start; this is not a hot path.
Failure path — a new expensive JVM call appears, but only in non-cache mode. When a released reference drops the count to zero, DefaultClassLoaderService.java:126 calls recycleClassLoaderFromThread, which executes Thread.getAllStackTraces() (:135). That captures stack traces for every live thread in the JVM and is a genuinely costly operation. Before this PR these releases never happened on the failure path, so this cost is newly introduced there — up to N times per failed deployment. In practice: failures are rare, cacheMode = true (the default) short-circuits before reaching it at :119-121, and the alternative is leaking a classloader, so the trade-off is clearly correct. I am recording it as an observation rather than an objection (Issue 7).
Locking / threading. deployTask runs on a Hazelcast operation thread (via DeployTaskOperation.java:55). getClassLoader and releaseClassLoader are both synchronized on the DefaultClassLoaderService instance (:58, :103). The new helper is invoked from the catch block outside the synchronized (this) block on TaskExecutionService at :500-523 (the failover branch's releases at :514-517 are inside it) — this is fine and in fact preferable, since it avoids extending the TaskExecutionService monitor hold across a second lock acquisition. No new deadlock ordering is introduced: the only lock nesting in the changed code (TaskExecutionService monitor → DefaultClassLoaderService monitor at :515) is pre-existing and is not inverted anywhere I could find.
Exception mutation. deploymentFailure.addSuppressed(cleanupFailure) at :547 mutates the throwable that is about to be converted by TaskDeployState.failed(t) → ExceptionUtils.getMessage(e) (TaskDeployState.java:34-36). The suppressed exception will therefore appear in the message sent back to the master. That is the intended and desirable behaviour. Self-suppression (addSuppressed(this)) would throw IllegalArgumentException, but cleanupFailure originates inside the helper and can never be the same object as deploymentFailure, so this is not reachable.
1.4 Error Handling and Logging
The failure handling design here is good: the deployment exception stays primary, cleanup is best-effort, one cleanup failure does not abort the remaining releases (the try is inside the loop at :544-550), and the cleanup failure is both logged and attached as suppressed. logger.severe(String, Throwable) is a valid Hazelcast ILogger overload. No sensitive data is logged. This is the pattern I would want to see.
Issues found across all sections follow.
Issue 1 — New test is not isolated from the process-wide classloader cache and is order-dependent
- Location:
seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/TaskExecutionServiceTest.java:249,:261-262,:274-277 - Problem description: The test derives a "unique"
testJobIdfromSystem.currentTimeMillis()(:249) and assertsclassLoaderService.queryClassLoaderReferenceCount(testJobId, Collections.emptySet()) == 0(:274-277). That isolation is illusory.classloader-cache-modedefaults totrue(ServerConfigOptions.java:31-36,EngineConfig.java:80-81), and the server under test builds its service with that default (SeaTunnelServer.java:157-159); the test resourceseatunnel-engine/seatunnel-engine-server/src/test/resources/seatunnel.yamldoes not override it. In cache mode,DefaultClassLoaderServicerewritesjobIdto1Lin bothgetClassLoader(DefaultClassLoaderService.java:60-63) andqueryClassLoaderReferenceCount(:169-172). The assertion therefore reads a JVM-global counter for the empty-jars key"", shared by every test in the class.testDeployTaskIdempotentWhenAlreadyRunning(TaskExecutionServiceTest.java:462-502) deploys two tasks with the same empty jar sets (:482-483), leaving a net count of 2 on that exact key, and it returns at:500-501immediately aftercancelTaskGroup(...)without awaiting termination — while the matching release happens asynchronously inTaskGroupExecutionTracker.taskDone→recycleClassLoader(TaskExecutionService.java:1413-1414), gated behindTestTasksleeps of 500 ms. Additionally, in cache modereleaseClassLoaderreturns atDefaultClassLoaderService.java:119-121before removing the entry, so the counter is never reset and can even be observed negative. - Potential risk: JUnit 5 applies no
MethodOrdererby default; execution order is deterministic for a given build but derives from a method-name hash and can shift when a test is added, renamed, or the JDK changes. IftestDeployTaskIdempotentWhenAlreadyRunningis scheduled before the new test, the assertion reads 2 instead of 0 and the build fails for reasons unrelated to the code under test. This is a latent CI flake seeded into a module whose unit tests already have known intermittent failures. - Best improvement: Two clean options, either is sufficient. (a) Give the test its own private cache key — create a temp jar file the way
testClassloaderSplitdoes at:176-179and passCollections.singleton(new URL(tmpFile))for both tasks, so the key cannot collide with any other test regardless ofcacheMode. (b) Make the assertion a delta rather than an absolute: captureint before = classLoaderService.queryClassLoaderReferenceCount(testJobId, Collections.emptySet());beforedeployTaskand assert the count returns tobeforeafterwards. Option (a) is stronger because it also removes the dependency oncacheMode. Separately, consider asserting the count is non-zero mid-flight is impossible here, so it is also worth noting in a comment that a zero result cannot distinguish "released" from "never acquired" — a future refactor that stops acquiring classloaders would keep this test green. - Severity: Medium
- Raised by another reviewer: No
Issue 2 — New private method and new ownership variable have no explanatory comment
- Location:
TaskExecutionService.java:538-541(methodreleaseClassLoadersAfterFailedDeployment),:446(acquiredClassLoaderJars),:521(acquiredClassLoaderJars.clear()) - Problem description:
releaseClassLoadersAfterFailedDeploymentcarries no Javadoc, in a class where every neighbouring method has one (deployTaskat:433-439,deployLocalTaskat:554-562,taskDoneat:1389-1405). More importantly, the two most subtle lines in the patch are undocumented::446does not say that the list holds references owned by this attempt only, and:521does not say thatclear()means "ownership has been transferred to the publishedTaskGroupContext; from here onrecycleClassLoaderat:1463is responsible". That single invariant is the entire reason there is no double-release, and it is invisible to the next reader. - Potential risk: A future refactor that moves
deployLocalTask(...)or inserts a statement between:520and:521— or that adds an earlyreturninside thesynchronizedblock — reintroduces either a leak or a double-release, with no comment to warn them. Given that eviction triggersrecycleClassLoaderFromThread(DefaultClassLoaderService.java:134-142), which nulls thread context classloaders, a future double-release would corrupt running tasks rather than fail loudly. - Best improvement: Add a Javadoc block to
releaseClassLoadersAfterFailedDeploymentstating that it releases only references acquired by the current attempt, that failures are suppressed onto the primary exception so cleanup continues, and that it must not be called once theTaskGroupContexthas been published. Add a one-line comment at:446("references acquired by this deployment attempt; ownership moves to TaskGroupContext once deployLocalTask publishes it") and at:521("ownership handed to TaskGroupContext — released later by recycleClassLoader()"). - Severity: Medium
- Raised by another reviewer: No
Issue 3 — Fix does not cover failures that occur inside deployLocalTask, so the leak class is only partially closed
- Location:
TaskExecutionService.java:520-522in combination with:619-622; leaking sub-paths at:569,:584-586,:352-368 - Problem description:
deployLocalTaskcatchesThrowableat:619-622, logs it, completesresultFutureexceptionally, and returns normally — it never rethrows. Control therefore reachesacquiredClassLoaderJars.clear()at:521anddeployTaskreturnsTaskDeployState.success()even though deployment failed. If the failure happened beforeexecutionContexts.put(...)at:609-611(for exampletaskGroup.init()at:569, ornew TaskExecutionContext(...)at:584-586), noTaskGroupContextwas ever published, sorecycleClassLoaderat:1463-1469can never locate it and the N references leak permanently. A concretely reachable variant exists even after publication: insubmitThreadShareTask(:346-369), when a task'sinit()throws at:357the handler at:359-362callstaskDoneonly for that task; subsequent tasks fail the guard at:352, the mapper returnsnull, andthreadShareTaskQueue::addat:367throwsNullPointerExceptionon the null element. Those tasks never calltaskDone,completionLatchat:1413never reaches zero, andrecycleClassLoadernever runs. - Potential risk: A connector whose
init()throws (bad credentials, unreachable endpoint, malformed schema) is a far more common production failure than the deserialization failure this PR reproduces in its test. In that scenario the classloader references still leak, anddeployTaskstill reports success to the master, so the job appears deployed. Anyone reading the PR title will reasonably believe the classloader leak on failed deployment is now closed; it is closed only for failures raised beforedeployLocalTaskis entered. To be explicit: this is a pre-existing defect that the PR does not make worse. - Best improvement: Keep this PR's scope as-is (it matches issue #11808 precisely) but (a) add a sentence to the PR description delimiting the covered window — "failures up to and including
createTaskGroup; failures insidedeployLocalTaskare tracked separately" — and (b) file a follow-up issue for thedeployLocalTaskwindow. The natural fix there is fordeployLocalTask's owncatchat:619to release the classloaders it was handed when it fails before publishing the context, and forsubmitThreadShareTaskto calltaskDonefor the tasks it skips at:352-364instead of enqueuingnull. - Severity: Medium
- Raised by another reviewer: No
Issue 4 — Master-failover branch uses a second, divergent release mechanism and leaves acquiredClassLoaderJars populated
- Location:
TaskExecutionService.java:513-518 - Problem description: After this PR the method has two different ways of releasing the same references: the pre-existing loop over
taskJars.entrySet()at:514-517in the failover branch, and the newacquiredClassLoaderJars-based helper at:538-552. The failover branch does not clearacquiredClassLoaderJarsbefore returning at:518. Today the counts happen to match (task IDs within a group are unique, sotaskJarsholds one entry per acquisition), and because the branch returns normally thecatchis never reached — so behaviour is correct. But ifclassLoaderService.releaseClassLoaderwere to throw partway through the loop at:515— the loop has notry, unlike the new helper — the exception would propagate to thecatchat:524, which would then release all N references a second time viaacquiredClassLoaderJars, over-releasing every entry that the loop had already handled. - Potential risk: Over-release drives the counter below the true value; in non-cache mode this can evict a classloader that is still referenced elsewhere and trigger
recycleClassLoaderFromThread(DefaultClassLoaderService.java:134-142) against live threads. I could not construct a realistic trigger forreleaseClassLoaderthrowing — it is fullysynchronizedand null-guarded at:109-116— so I am rating this as a latent robustness/consistency defect rather than an active bug. - Best improvement: Have the failover branch reuse the same helper — replace
:513-517withreleaseClassLoadersAfterFailedDeployment(...)-style handling, or at minimum addacquiredClassLoaderJars.clear();immediately after the loop at:517. One release mechanism instead of two also removes a maintenance trap. - Severity: Low
- Raised by another reviewer: No
Issue 5 — Theoretical premature-release window if a throwable escapes deployLocalTask after the context is published
- Location:
TaskExecutionService.java:520-526in combination with:609-611and:623-647 - Problem description:
deployLocalTask'stry/catchends at:622; theresultFuture.whenCompleteAsync(..., MDCTracer.tracing(executorService))call at:623-647sits outside it. If that call were to throw (e.g.RejectedExecutionExceptionfrom a shut-down executor), the exception would escapedeployLocalTaskafterexecutionContexts.put(...)at:609had already published theTaskGroupContextand aftersubmitThreadShareTask/submitBlockingTaskat:613-614had started tasks.deployTask'scatchat:524would then release N references that the liveTaskGroupContextstill owns, andrecycleClassLoaderat:1467would later release them again. - Potential risk: In non-cache mode, premature eviction plus
recycleClassLoaderFromThreadnulling the context classloader of running task threads, followed by a double decrement into negative counts. I want to be explicit about my confidence here: I could not construct a realistic trigger.executorServiceis an unboundednewCachedThreadPool(:172-173), and if it were shut down,submitBlockingTask'smdcExecutorService::submitat:398would fail first — inside thetry, hence caught at:619. So this window requires the submits to succeed and onlywhenCompleteAsyncto be rejected, which I believe is unreachable in the current code. I am recording it because the invariant "nothing may throw out ofdeployLocalTaskafter:609" is currently undocumented and unenforced, and this PR is what makes violating it harmful. - Best improvement: Move
resultFuture.whenCompleteAsync(...)insidedeployLocalTask'stry, or moveacquiredClassLoaderJars.clear()so it executes immediately after the ownership handover rather than afterdeployLocalTaskreturns. Either makes the invariant structural rather than incidental. A comment stating the invariant (see Issue 2) is the minimum. - Severity: Low
- Raised by another reviewer: No
Issue 6 — Test assertion depends on an exception's message text
- Location:
TaskExecutionServiceTest.java:268 - Problem description:
Assertions.assertTrue(taskDeployState.getThrowableMsg().contains("ClassCastException"))asserts on a formatted string produced byExceptionUtils.getMessage(e)(TaskDeployState.java:34-36). TheClassCastExceptionarises from the implicit checked cast when the inferred return ofnodeEngine.getSerializationService().toObject(...)at:476is assigned toTask. That is stable today, but any change in how Hazelcast surfaces a type mismatch (e.g. wrapping inHazelcastSerializationException), or any change toExceptionUtils.getMessage, breaks the test without any behavioural regression. - Potential risk: Low-value maintenance failure. It also does not strengthen the test — the classloader-count assertion at
:274-277is what proves the fix. - Best improvement: Assert only
assertFalse(taskDeployState.isSuccess())andassertNotNull(taskDeployState.getThrowableMsg()), or keep the message check but scope it to something the engine controls rather than the JVM's exception naming. - Severity: Low
- Raised by another reviewer: No
Issue 7 — Failure path now performs Thread.getAllStackTraces() (non-cache mode only)
- Location:
TaskExecutionService.java:545reachingDefaultClassLoaderService.java:126→:134-142 - Problem description: When a released reference drops the count to zero,
recycleClassLoaderFromThreadcallsThread.getAllStackTraces(), which captures stack traces for every live thread. Prior to this PR the failure path never released, so this cost is new there — up to N invocations per failed deployment, and a high-parallelism job failing to deploy across many task groups multiplies it. Under the defaultclassloader-cache-mode: truethe early return atDefaultClassLoaderService.java:119-121makes this unreachable. - Potential risk: Brief pauses on Hazelcast operation threads during a deployment-failure storm in non-cache mode. Bounded and strictly preferable to leaking; recorded for completeness, not as an objection.
- Best improvement: No change requested in this PR. If it ever matters,
recycleClassLoaderFromThreaditself is the right place to optimise (it is a pre-existing implementation detail ofDefaultClassLoaderService). - Severity: Low
- Raised by another reviewer: No
Issue 8 — Reverse-order release is unnecessary and unexplained
- Location:
TaskExecutionService.java:542-543 - Problem description: The helper iterates
acquiredClassLoaderJarsfrom the tail. For an independent, reference-counted release there is no ordering requirement — eachreleaseClassLoader(jobId, jars)call touches a key derived solely from its own argument (DefaultClassLoaderService.java:144-146). The PR description calls this out as deliberate ("released in reverse order"), but the code carries no comment saying why, which invites a future reader to assume an ordering constraint exists that does not. - Potential risk: Purely readability. Behaviour is correct either way.
- Best improvement: Either simplify to an enhanced
forloop, or add a one-line comment ("reverse order mirrors acquisition; not required for correctness since releases are independent"). - Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
- Google Java Format (AOSP) style is respected throughout; the formatting matches what Spotless produces, and I found no wildcard imports or unshaded-dependency usage.
Listsis already the shadedorg.apache.seatunnel.shade.com.google.common.collect.Listsin this file. - No new imports were needed in
TaskExecutionService.java—ArrayList,Collection,List,URL, andListswere all already in use (:452,:453,:469). The two new test imports (DefaultClassLoaderService,TaskGroupContextNotFoundExceptionatTaskExecutionServiceTest.java:24-25) are both used. No unused imports. - No new files, so no ASF header question arises.
- The new method is
privateand placed directly after its single caller — correct visibility and reasonable placement. logger.severe(String, Throwable)at:548-549matches the HazelcastILoggercontract and the surrounding logging style. NoSystem.out.println, no emoji or special symbols in messages, no sensitive data logged.- Comment completeness — this is where the patch falls short. The new private method
releaseClassLoadersAfterFailedDeployment(:538) has no Javadoc, and the two most invariant-bearing lines in the change (:446,:521) are bare. In a class where the surrounding methods are all documented and where the correctness argument hinges on an implicit ownership-transfer contract, this is a real gap, not a style nit. Recorded as Issue 2 (Medium). - The new test method does carry a Javadoc block (
TaskExecutionServiceTest.java:239-242) stating what production behaviour it protects, and correctly avoids@DisplayName. Good.
2.2 Test Coverage and Test Stability
Stability rating: Risk present.
What the test does well: it reproduces the exact scenario from issue #11808 (one valid task followed by an unusable payload), it asserts the negative outcome three ways — deployment failed (:267), no TaskGroupContext was published (:269-273), and the reference count returned to zero (:274-277) — and the third assertion is genuinely discriminating: without the fix, two references remain and the count reads 2. It introduces no Thread.sleep, no new shared static mutable state, no unclosed resources, and no floating-point comparison. The TestTask created at :250 is never executed because deployment fails, so it leaves no background thread behind. It also does not weaken, relax, disable, or narrow any existing test — I diffed the test file against the merge base and the change is purely additive (+43/-0).
Why it is nonetheless Risk present rather than Stable:
- Order-dependent shared state (Issue 1).
queryClassLoaderReferenceCount(testJobId, emptySet())at:274-277resolves to a JVM-global counter becausecacheModedefaults totrueand rewritesjobIdto1L(DefaultClassLoaderService.java:60-63,:169-172).testDeployTaskIdempotentWhenAlreadyRunningat:462-502writes to that same key and does not await async release (:500-501vs.TaskExecutionService.java:1413-1414). This is the classic order-dependent / shared-state flake anti-pattern and is the reason for the rating. Evidence is fully cited in Issue 1. - Message-text assertion (Issue 6) at
:268— brittle to third-party exception-naming changes. - Minor:
System.currentTimeMillis()as a job identifier (:249) is a pattern the file already uses (:189,:469), so it is consistent, but it provides no real uniqueness guarantee. In cache mode it provides none at all.
Both items are straightforward to fix; giving the test its own temp-jar-derived cache key resolves item 1 completely and takes only a few lines, modelled directly on testClassloaderSplit at :176-179.
Coverage gaps worth noting: there is no test for the failure-inside-deployLocalTask window (Issue 3), and no test for the multi-task case where the first task's jar resolution fails (K=0 acquired). Neither is required for this PR, but the second would be a cheap addition proving the helper is a no-op on an empty list.
2.3 Documentation Updates
None required and none provided — correct. This is internal engine cleanup with no user-facing configuration, no Option, no connector behaviour, and no incompatible change, so neither docs/en nor docs/zh nor docs/en/introduction/concepts/incompatible-changes.md needs to move. The PR checklist reflects this accurately.
The one documentation item I would ask for is in the PR description rather than the docs tree: it should state (a) that the covered failure window ends at createTaskGroup and does not include deployLocalTask (Issue 3), and (b) that under the default classloader-cache-mode: true the pre-existing leak is a counter-only leak, with the metaspace/file-handle impact applying to classloader-cache-mode: false (section 1.1, Question 3). Both keep future readers from over- or under-estimating what changed.
3. Architectural Soundness
3.1 Elegance of the Solution
Classification: Precise fix.
This is compensation logic placed exactly where the resource is acquired, scoped exactly to the attempt that acquired it, released exactly at the boundary where ownership has not yet transferred. It is the textbook shape for this problem: an acquisition ledger local to the attempt, cleared at the handover point, drained in the failure handler. It is not a workaround — nothing is being papered over, no symptom is being suppressed, and no sentinel or retry is introduced.
On the "is this the best repair site?" question that a maintainer owes the project: I considered the alternative of pushing the ownership tracking down into DefaultClassLoaderService (e.g. a scoped/try-with-resources handle that releases on close). That would be architecturally cleaner and would fix every caller at once — JobMaster, PhysicalPlanGenerator, DAGUtils, and MultipleTableJobConfigParser all hand-balance their own acquire/release pairs today and are all one early-return away from the same bug. But it changes a public SPI (ClassLoaderService) used across three modules, and the minimal-blast-radius principle clearly favours the local fix for a bug fix on dev. The author chose correctly. The broader "scoped classloader handle" refactor is worth an issue, not a demand on this PR.
3.2 Maintainability
Good, with one reservation. The helper is small, single-purpose, side-effect-local, and reads clearly. The reservation is that the method now contains two release mechanisms for the same references — the failover loop at :514-517 and the new helper at :538-552 (Issue 4) — and the invariant that keeps them from colliding is implicit in statement ordering rather than stated anywhere (Issue 2). Unifying on one mechanism and writing down the ownership contract would take about five lines and would make the next reader's job much easier. deployTask is now ~96 lines with three exit points and nested try/synchronized; it is at the edge of comfortable, though splitting it is out of scope here.
3.3 Extensibility
Neutral, which is the right answer for a bug fix. No new abstraction, interface, or extension point is introduced, and none is needed. The List<Collection<URL>> ledger is a local implementation detail that a future refactor can replace freely. If the project later adopts a scoped classloader handle (3.1), this code is the natural first migration site and will delete cleanly.
3.4 Historical-Version Compatibility
No historical-compatibility concerns, verified rather than assumed:
- Rolling upgrade / mixed-version cluster: the only cross-node payloads on this path are
TaskGroupImmutableInformation(in) andTaskDeployState(out); neither is modified.DeployTaskOperationis unchanged. A new-version worker and an old-version master interoperate exactly as before. - Checkpoint / savepoint: nothing in the change is written to or read from checkpoint state. Restore paths (
NotifyTaskRestoreOperation,RestoredSplitOperation) consumeTaskGroupContext.getClassLoader(taskId)(TaskGroupContext.java:35-41), which is untouched. - Master failover: the pre-existing idempotency branch at
:501-518— the path a restoring master exercises when it re-deploys a still-running task group — retains its behaviour precisely, including its own classloader release.testDeployTaskIdempotentWhenAlreadyRunningcontinues to cover it and was not modified. - Existing job semantics: a job that deployed successfully before this change deploys identically after it. A job that failed to deploy before still fails, with the same
TaskDeployState.failedresult and the same reported message (plus any suppressed cleanup exception, which in practice will not occur). - Configuration: no option added, removed, renamed, or re-defaulted.
classloader-cache-modesemantics are unchanged in both settings.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | New test is not isolated from the process-wide classloader cache (cacheMode rewrites jobId to 1L); shares the empty-jars key with testDeployTaskIdempotentWhenAlreadyRunning, which releases asynchronously — order-dependent flake |
TaskExecutionServiceTest.java:249, :274-277; DefaultClassLoaderService.java:60-63, :169-172; ServerConfigOptions.java:31-36 |
Medium |
| 2 | New private method has no Javadoc; the ownership-transfer invariant behind acquiredClassLoaderJars / .clear() is undocumented |
TaskExecutionService.java:538-541, :446, :521 |
Medium |
| 3 | Fix does not cover failures inside deployLocalTask (swallowed at :619-622), so classloaders still leak when taskGroup.init() or task init() fails — pre-existing, not worsened, but the PR's claim needs bounding |
TaskExecutionService.java:520-522, :619-622, :569, :352-368, :1413-1414 |
Medium |
| 4 | Failover branch uses a second, un-guarded release mechanism and does not clear acquiredClassLoaderJars; latent over-release if releaseClassLoader throws mid-loop |
TaskExecutionService.java:513-518 |
Low |
| 5 | Theoretical premature/double release if a throwable escapes deployLocalTask after executionContexts.put; no realistic trigger found, invariant is undocumented |
TaskExecutionService.java:520-526, :609-611, :623 |
Low |
| 6 | Test asserts on exception message text (contains("ClassCastException")) |
TaskExecutionServiceTest.java:268 |
Low |
| 7 | Failure path newly triggers Thread.getAllStackTraces() in non-cache mode; acceptable trade-off, recorded for completeness |
TaskExecutionService.java:545 → DefaultClassLoaderService.java:126, :134-142 |
Low |
| 8 | Reverse-order release is unnecessary for a reference-counted release and unexplained in code | TaskExecutionService.java:542-543 |
Low |
Totals: 0 High, 3 Medium, 5 Low.
5. Merge Recommendation
Conclusion: Ready to merge after fixes
-
Blockers — must be fixed
- Issue 1 (Medium) — test isolation. The new regression test reads a JVM-global reference counter and shares its cache key with another test in the same class that releases asynchronously. It will pass or fail depending on method execution order. A regression test that can fail for reasons unrelated to the code it guards is worse than no test, and this module's unit tests already carry known intermittent failures. The fix is small: give the test its own temp-jar-derived cache key (mirroring
testClassloaderSplitatTaskExecutionServiceTest.java:176-179), or assert a before/after delta instead of an absolute zero. - Issue 2 (Medium) — missing comments on the invariant-bearing code. Add Javadoc to
releaseClassLoadersAfterFailedDeployment(TaskExecutionService.java:538) and one-line comments at:446and:521recording that clearing the list means ownership has passed to the publishedTaskGroupContext. The absence of a double-release today rests entirely on that implicit contract; leaving it unwritten in engine code whose failure mode is a silent production memory leak is not acceptable for this codebase.
Note explicitly: no High-severity issue was found. I found no double-release, no release-before-use race, and no leak newly introduced by this PR on any path reachable in normal operation. The acquire/release balance was verified exhaustively across all six exit paths of
deployTask(section 1.1, Question 2), and the reference-counting inDefaultClassLoaderServicecorrectly protects concurrent holders of the same key (Question 4). Both blockers above are quality-of-change items, not correctness defects in the fix itself. - Issue 1 (Medium) — test isolation. The new regression test reads a JVM-global reference counter and shares its cache key with another test in the same class that releases asynchronously. It will pass or fail depending on method execution order. A regression test that can fail for reasons unrelated to the code it guards is worse than no test, and this module's unit tests already carry known intermittent failures. The fix is small: give the test its own temp-jar-derived cache key (mirroring
-
Recommended fixes — non-blocking
- Issue 3 (Medium): bound the claim in the PR description ("failures up to
createTaskGroup; failures insidedeployLocalTaskare a separate window") and open a follow-up issue for thedeployLocalTask/submitThreadShareTaskleak path. Also worth adding one sentence noting that under the defaultclassloader-cache-mode: truethe original bug leaks a counter only, and that the metaspace/file-handle impact described in issue #11808 applies toclassloader-cache-mode: false. - Issue 4 (Low): unify on a single release mechanism, or add
acquiredClassLoaderJars.clear();after the failover loop at:517. - Issue 5 (Low): move
resultFuture.whenCompleteAsync(...)insidedeployLocalTask'stry, so "nothing throws out ofdeployLocalTaskafter the context is published" becomes structural rather than incidental. - Issue 6 (Low): drop or loosen the
ClassCastExceptionmessage assertion atTaskExecutionServiceTest.java:268. - Issue 8 (Low): simplify the reverse loop at
:542-543or comment why it is reversed. - Issue 7 needs no action.
- Optional: consider filing an issue for a scoped/auto-closing classloader handle in
ClassLoaderService. Four other call sites (JobMaster.java:254/:311,PhysicalPlanGenerator.java:273/:283,DAGUtils.java:86/:92,MultipleTableJobConfigParser.java:319/:302-304) hand-balance the same pair and are structurally exposed to the identical bug. Out of scope here, but this PR is good evidence the pattern is worth having.
- Issue 3 (Medium): bound the claim in the PR description ("failures up to
-
CI status
At the time of review the apache-side
Buildcheck is pending and the corresponding run in the contributor's fork (goutamadwant/seatunnel, run31856511698, head520454e3c524f3561069f555a875b05546dc9774) is queued — no results yet.Notify test workflowandlabelerhave passed.mergeStateStatusisBLOCKED(awaiting review),mergeableisMERGEABLE, with no conflict againstdev. Green CI on the current head remains a gate; this review does not substitute for it. Given Issue 1 concerns test ordering, a green run is meaningful evidence for the current build but does not by itself retire that finding, since the ordering can shift on any subsequent change to the class.
Overall assessment: This is a well-targeted, well-reasoned fix by a contributor who clearly read the surrounding lifecycle code before touching it. The hardest part of this change — knowing that ownership transfers at executionContexts.put(...) and that the ledger must be cleared after deployLocalTask returns rather than before — was gotten right, and that is precisely where a less careful patch would have introduced a double-release or a release-before-use into a running task group. The error handling (primary exception preserved, cleanup best-effort, suppressed exceptions attached, loop continues past a failure) is the pattern I would want to see. Compatibility is clean in every dimension I checked: no wire format, no state, no config, no API, and existing failover behaviour untouched.
What holds it back is not the production logic but the test around it: the reference-count assertion reads a shared, cache-mode-normalised global counter and will be order-dependent against a sibling test. Fix that, add the two or three comments recording the ownership invariant, and bound the claim in the description so the remaining deployLocalTask window is not mistaken for solved — then this is a clean merge. Nice work, and thank you for filing the issue with a full source-level analysis before writing the patch; that made this review considerably easier.
Signed-off-by: goutamadwant <workwithgoutam@gmail.com>
|
@DanielLeens Addressed the deployment cleanup review The regression test now uses a unique jar key instead of the process-wide empty-jar cache and no longer depends on the exception message. I also documented the classloader ownership transfer and reverse cleanup order and clarified the pre-deployLocalTask scope in the PR description TaskExecutionServiceTest passes locally with 14 tests on JDK 11 |
DanielLeens
left a comment
There was a problem hiding this comment.
First, an apology. In my previous round I raised the "throwable escaping deployLocalTask after the context is published" window as a Low-severity, theoretical concern and wrote that I "could not construct a realistic trigger." That conclusion was wrong, and it was wrong on code that was already in front of me — this is a carryover miss, not something the new commit introduced. My reasoning was that if executorService were unable to accept work, submitBlockingTask's submit would fail first inside deployLocalTask's try and therefore be caught. That step is correct but the inference from it is not: being caught at :629 is precisely what arms the escape, because the handler completes resultFuture exceptionally at :631, and the resultFuture.whenCompleteAsync(..., MDCTracer.tracing(executorService)) at :633 then dispatches its action immediately and synchronously on that same unavailable executor. I treated this as requiring two independent failures when it is really one root cause with two consequences. Details and the corrected analysis are in Issue 1 below, which I am now raising as High and as a blocker. I am sorry for the extra round this costs you — you fixed everything I actually asked for last time, and cleanly.
Everything below is a complete re-review of head c6a7ac1f323196c268d22649ac84831508ac46ff, re-derived from source rather than carried over from my previous notes.
Disclosure: I am the reporter of the linked issue #11808. I have tried to keep this review anchored to source evidence rather than to my own framing of the bug; please push back anywhere it reads as the reporter grading his own bug report.
What Problem Does This PR Solve?
- User pain point:
TaskExecutionService.deployTask(...)acquires one reference-counted classloader per task, one at a time, inside a loop (TaskExecutionService.java:455-488). If any task after the first one fails during jar resolution, classloader creation, or deserialization, the outercatch (Throwable t)returnedTaskDeployState.failed(t)without ever callingclassLoaderService.releaseClassLoader(...)for the references already acquired in that same attempt. BecauseDefaultClassLoaderServiceis reference-counted (DefaultClassLoaderService.java:44,:117,:122-127), those orphaned references pin theSeaTunnelChildFirstClassLoaderand its open JAR handles for the lifetime of the node. Repeated bad submissions, missing jars, or incompatible task payloads accumulate the counter and — underclassloader-cache-mode: false— metaspace and file handles. That is issue #11808. - Fix approach: Track the jar collections acquired by the current attempt in a local ledger
List<Collection<URL>> acquiredClassLoaderJars(:447), append immediately after each successfulgetClassLoader(...)(:474), clear it once ownership is believed to have transferred to a publishedTaskGroupContext(:523), and drain it in the outercatchvia the newreleaseClassLoadersAfterFailedDeployment(...)helper (:527-528,:547-562). Cleanup failures are attached to the deployment exception withaddSuppressedso the original error stays primary and cleanup continues for the remaining entries. - One-sentence summary: A correct and well-scoped compensation for a real reference-count leak on the Zeta deployment-failure path — but the ledger is cleared after
deployLocalTask(...)returns rather than at the moment ownership actually transfers, which leaves a narrow but genuinely reachable window in which the newcatchreleases classloaders that a published, already-executingTaskGroupContextstill owns.
Simple example. A job has a task group with three tasks that all use connector-jdbc.jar. Task 0 and task 1 deserialize fine; task 2's payload references a class that is not on the node.
before this PR: getClassLoader x3 -> refCount = 3
task 2 throws -> catch -> failed(t)
refCount stays 3 forever <-- the leak in #11808
after this PR: getClassLoader x3 -> refCount = 3
task 2 throws -> catch -> releaseClassLoadersAfterFailedDeployment
-> releaseClassLoader x3 -> refCount = 0
classloader evicted (non-cache mode), handles closed <-- fixed
That part is right. The problem is the other direction, described in Issue 1.
1. Code Change Review
1.1 Core Logic Analysis
Scope: 2 files, +79/-2. One production file (seatunnel-engine-server/.../TaskExecutionService.java, +34/-2) and one test file (TaskExecutionServiceTest.java, +45/-0). No API, SPI, config, serialization, packaging, or documentation surface is touched.
Changes since my previous review (head 520454e3c -> c6a7ac1f3)
The new commit [Fix][Zeta] Strengthen failed deployment cleanup coverage addresses four of my previous findings. I re-verified each independently:
| Prior issue | Status at this head | Evidence |
|---|---|---|
| 1 (Medium) — test not isolated from the process-wide classloader cache | Resolved | The test now creates its own temp jar (TaskExecutionServiceTest.java:250-253) and passes testJars for both tasks (:266). covertJarsToKey (DefaultClassLoaderService.java:144-146) derives the cache key from the URL strings, so the key is unique per run and cannot collide with testDeployTaskIdempotentWhenAlreadyRunning (:464) or any other test regardless of cacheMode. Confirmed correct. |
| 2 (Medium) — no Javadoc, invariant undocumented | Resolved in form, but see Issue 1 | Javadoc added at TaskExecutionService.java:540-546; ownership comments added at :446 and :522. Wording is clear and accurate about intent. Unfortunately the Javadoc now states an invariant that the code does not actually enforce. |
| 6 (Low) — assertion on exception message text | Resolved | contains("ClassCastException") removed. This was also necessary for correctness: with non-empty jars the deserialization now goes through CustomClassLoadedObject.deserializeWithCustomClassLoader (:479-483) instead of the plain toObject branch at :477, so the previous assertion was on a path the test no longer takes. Good catch by the author. |
| 8 (Low) — reverse-order release unexplained | Resolved | Comment added at :551. |
3 (Medium) — deployLocalTask window |
Partially addressed — PR description now bounds the claim, but the bounding sentence is itself inaccurate. See Issue 2. | |
| 4 (Low) — failover branch second release mechanism | Unaddressed — still open, see Issue 3. | |
| 5 (Low) — escape after publication | Unaddressed, and my previous severity was wrong. See Issue 1. |
Classloader lifecycle — full traced path at this head
CLASSLOADER LIFECYCLE ON THE ZETA TASK-DEPLOYMENT PATH (head c6a7ac1f3)
════════════════════════════════════════════════════════════════════════
[master] PhysicalVertex.deployOnLocal / deployOnRemote
-> DeployTaskOperation.run() [Hazelcast operation thread, worker node]
-> TaskExecutionService.deployTask(Data) :414-418
-> TaskExecutionService.deployTask(TaskGroupImmutableInformation) :440
[worker] deployTask(...) :440
447 ┌─ LEDGER CREATED: List<Collection<URL>> acquiredClassLoaderJars
│
455 ├─ for (i = 0 .. taskData.size()-1) ── ACQUISITION LOOP ──
464 │ jars = serverConnectorPackageClient.getConnectorJarFromLocal(...) [may throw]
470 │ List<URL> classLoaderJars = Lists.newArrayList(jars);
471 │ classLoader = classLoaderService.getClassLoader(jobId, classLoaderJars)
│ └─> DefaultClassLoaderService.getClassLoader() :58
│ :60-63 cacheMode -> jobId := 1L
│ :70-72 cache HIT -> refCount.incrementAndGet(); return
│ :74-90 jar existence check [may throw NOT_FOUND_JAR]
│ :94 new SeaTunnelChildFirstClassLoader(jars) [may throw]
│ :96-97 cache PUT + refCount = 1
474 │ acquiredClassLoaderJars.add(classLoaderJars); <── LEDGER +1 (after success only)
476 │ task = toObject(...) | deserializeWithCustomClassLoader(...) [may throw CCE]
487 │ taskJars.put(task.getTaskID(), classLoaderJars);
│
489 ├─ TaskGroupUtils.createTaskGroup(...) [may throw]
501 ├─ synchronized (this) {
502 │ if (executionContexts.containsKey(location)) ── FAILOVER BRANCH ──
515 │ for (entry : taskJars.entrySet())
516 │ classLoaderService.releaseClassLoader(jobId, entry.getValue())
519 │ return success; [ledger NOT cleared — see Issue 3]
│
521 │ deployLocalTask(taskGroup, classLoaders, taskJars); ─────────────┐
523 │ acquiredClassLoaderJars.clear(); <── LEDGER DROPPED │
524 │ return success; │
525 ├─ } │
526 └─ catch (Throwable t) │
527 releaseClassLoadersAfterFailedDeployment(jobId, ledger, t) │
│ :552 reverse iteration │
│ :555 classLoaderService.releaseClassLoader(jobId, jars) │
│ -> :119-121 cacheMode -> decrement, RETURN (no evict) │
│ -> :122-127 refCount==0 -> remove from cache │
│ + recycleClassLoaderFromThread(cl) :134 │
│ └─ NULLS ContextClassLoader OF EVERY │
│ LIVE THREAD POINTING AT IT │
536 return TaskDeployState.failed(t); │
│
┌───────────────────────────────────────────┘
▼
deployLocalTask(taskGroup, classLoaders, jars) :573
578 try {
579 taskGroup.init(); [may throw]
592-600 peek: new TaskExecutionContext(...) per task [may throw]
619 ══ executionContexts.put(location, ══════════════
new TaskGroupContext(taskGroup, classLoaders, jars))
══ OWNERSHIP TRANSFERS HERE — NOT AT :523 ══
622 cancellationFutures.put(...)
623 submitThreadShareTask(tracker, byCooperation.get(true))
-> threadShareTaskQueue::add :367
-> CooperativeTaskWorker picks it up, sets TCCL :1237-1241
and runs task.call() :1242
624 submitBlockingTask(tracker, byCooperation.get(false))
-> mdcExecutorService::submit :398 [may REJECT]
-> BlockingWorker.run(): sets TCCL :1103-1104
t.init(); t.call() :1109-1111
625 taskGroup.setTasksContext(...)
629 } catch (Throwable t) {
630 logger.severe(...);
631 resultFuture.completeExceptionally(t); <── SWALLOWS, does NOT rethrow
632 }
633 resultFuture.whenCompleteAsync(action, MDCTracer.tracing(executorService));
▲ OUTSIDE the try. Future is ALREADY COMPLETE if :631 ran, so this
dispatches SYNCHRONOUSLY via executor.execute() -> can throw
RejectedExecutionException / OutOfMemoryError -> ESCAPES to :526
658 return new PassiveCompletableFuture<>(resultFuture);
[normal release, unchanged]
TaskGroupExecutionTracker.taskDone(Task) :1416
1423 if (completionLatch.decrementAndGet() == 0)
1424 recycleClassLoader(taskGroupLocation) :1473
for (Collection<URL> jars : context.getJars().values())
classLoaderService.releaseClassLoader(jobId, jars) :1477
Does the normal (successful) deployment path reach the new code?
Partially — and the distinction matters. Five of the changed statements execute on every successful deployment: :446-447 (ledger allocation), :470 (hoisted ArrayList copy), :474 (ledger append), :487 (changed value stored in taskJars), :523 (ledger clear). All of those are bookkeeping only; none changes observable behaviour. The behavioural change — the actual releaseClassLoader calls in releaseClassLoadersAfterFailedDeployment — runs only from the catch at :526.
So the answer to "does the normal deploy-failure path actually reach the new release code, or only some race/recovery path?" is: yes, the ordinary failure path reaches it. Any throw from getConnectorJarFromLocal (:464), getClassLoader (:471, including the NOT_FOUND_JAR check at DefaultClassLoaderService.java:79-89), deserialization (:476-484), or createTaskGroup (:489) lands in the catch and releases correctly. This is not a race-only or recovery-only fix. The regression test exercises exactly this path.
Is the claimed leak real?
Yes, verified independently. DefaultClassLoaderService.getClassLoader increments at :71 on a cache hit and initialises to 1 at :97 on a miss. releaseClassLoader is the only decrement (:117). Before this PR, the loop at TaskExecutionService.java:455-488 had no compensating release on the exception path — the only releases were the failover loop at :515-517 (unreachable when the exception is thrown before :501) and recycleClassLoader at :1473-1479, which reads executionContexts.get(location) and therefore cannot see a context that was never published. So K acquired references, 0 released. The leak is real.
One severity nuance the PR description still does not carry: classloader-cache-mode defaults to true (ServerConfigOptions.java:31-36, wired at EngineConfig.java:81). In cache mode, releaseClassLoader decrements and then returns at DefaultClassLoaderService.java:119-121 without removing the classloader or closing anything. So under the default configuration the original bug leaks a counter value only — the metaspace and file-handle consequences described in #11808 (my own issue text, so this correction is on me) apply to classloader-cache-mode: false. Worth one sentence in the description so future readers calibrate. Recorded as Issue 6 (Low).
Is it released on every failure path, or only some?
I enumerated every exit of deployTask and checked the acquire/release balance:
| # | Path | Acquired | Released | Balanced? |
|---|---|---|---|---|
| A | Full success (:521-524) |
N | N later via recycleClassLoader (:1473-1479) |
Yes |
| B | Throw inside the acquisition loop — missing jar (DefaultClassLoaderService.java:79-89), classloader construction (:94), deserialization (:476-484) |
K (0..N) | K in catch (:527) |
Yes — this is the fix |
| C | Throw at createTaskGroup (:489-494) |
N | N in catch |
Yes |
| D | Master-failover "already active" branch (:502-519) |
N | N via the taskJars loop at :515-517; branch returns so catch is unreachable |
Yes today; latent edge, Issue 3 |
| E | Throw inside deployLocalTask, swallowed at :629-632, no escape |
N | None — ledger cleared at :523, deployTask returns success() |
No — leak, Issue 2 |
| F | Throw escaping deployLocalTask at :633 after executionContexts.put at :619 |
N | N released by catch while the published context still owns them |
No — premature release, Issue 1 |
Paths A–D are correct, and I want to credit the author for path A specifically: recognising that acquiredClassLoaderJars.clear() must happen after deployLocalTask returns, and that ArrayList.clear() cannot throw, is the subtle part of this patch and it is reasoned correctly for the paths where deployLocalTask returns normally. Paths E and F are the two remaining gaps.
Premature release — the specific mechanism (Issue 1 in detail)
This is the (a) risk category, and it is real. Walking it precisely:
deployLocalTaskpublishes theTaskGroupContextat:619-621. From this instant,recycleClassLoader(:1473) can find it and is the designated owner of the N references.submitThreadShareTaskat:623addsTaskTrackers tothreadShareTaskQueue(:367). A liveCooperativeTaskWorkerpicks one up, sets its thread context classloader from the published context at:1237-1241, and callstask.call()at:1242. The task is now executing on that classloader.submitBlockingTaskat:624mapsmdcExecutorService::submitover its tasks and forces the stream with.collect(toList())(:398-399). If the executor cannot accept work —executorService.shutdownNow()was called byTaskExecutionService.shutdown()(:295) during a rolling restart, ornewCachedThreadPool(:172-173) hitsOutOfMemoryError: unable to create new native threadunder thread exhaustion — this throws. Note that earlier submits in the same stream may already have succeeded, soBlockingWorkers may also already be running with the TCCL set at:1103-1104.- The throw is caught at
:629, logged, andresultFuture.completeExceptionally(t)runs at:631.deployLocalTaskdoes not rethrow. - Execution reaches
:633.resultFutureis now already complete, soCompletableFuture.whenCompleteAsync(action, executor)does not defer — it constructs the completion and fires it synchronously, andUniCompletion.claim()callsexecutor.execute(this)on the caller's thread.MDCTracer.tracing(executorService)delegates straight to the sameexecutorService. It rejects for the same root cause as step 3, andRejectedExecutionException(or the sameOutOfMemoryError) propagates out ofdeployLocalTask— there is notryaround:633. deployTask'scatch (Throwable t)at:526runsreleaseClassLoadersAfterFailedDeployment(...), releasing all N references that the published, liveTaskGroupContextstill owns.- With
classloader-cache-mode: false, the count reaches zero,DefaultClassLoaderService.java:122-127removes the classloader from the cache and callsrecycleClassLoaderFromThread(:134-142), which nulls the context classloader of every thread currently pointing at it — including the worker thread from step 2 that is insidetask.call(). - That task's next
Thread.currentThread().getContextClassLoader().loadClass(...)throwsNullPointerException, and any class not yet resolved from the evictedSeaTunnelChildFirstClassLoaderyieldsNoClassDefFoundError. Silent, mid-flight, in a job the master has just been told failed to deploy.
This is the correction to my previous Issue 5. I had reasoned that a shutdown executor would fail at step 3 "inside the try, hence caught," and concluded the window needed the submits to succeed and only whenCompleteAsync to be rejected — two independent conditions, hence unreachable. That is backwards. The catch at :629 does not stop the escape; by completing the future it is what causes :633 to dispatch immediately instead of deferring. Steps 3 and 5 share one root cause (the executor cannot accept work), so this is a single-condition trigger, not a double-coincidence.
Two further points on confidence, stated plainly:
- I have not run this; the escape at step 5 is derived from the JDK 8
CompletableFuture.uniWhenCompleteStage/UniCompletion.claim()implementation, whereclaim()callse.execute(this)with no surrounding try. I am confident in the reading but a reviewer who wants certainty should confirm it before acting on the severity. - No double-release results in the traced scenario, because
completionLatch(:1348) is sized to the full task count and the tasks that were never submitted never calltaskDone, so:1423never reaches zero andrecycleClassLoadernever runs. The harm here is premature release of a live classloader, not a negative counter.
Before this PR, this window was harmless — the catch released nothing, so an escape merely produced a leak. This PR is what converts it into an in-flight classloader eviction. That is why I am treating it as a blocker rather than a pre-existing defect to be filed separately.
Release-before-use on the paths the PR is actually aimed at
To be fair and precise: on paths B and C — the paths this PR targets — there is no premature-release risk, and I verified this three ways.
- Release is exactly counter-balanced: the ledger is appended at
:474only aftergetClassLoaderreturns successfully, so the helper releases exactly what this attempt acquired, never more.DefaultClassLoaderService.getClassLoadercannot partially acquire — on a cache hit,incrementAndGet()andreturnare adjacent (:71-72); on a miss,new SeaTunnelChildFirstClassLoader(jars)at:94precedes bothputcalls at:96-97, so a construction failure registers nothing. - A concurrent holder of the same key keeps the counter above zero, so
:122-127does not evict andrecycleClassLoaderFromThreadis not invoked.JobMaster,PhysicalPlanGenerator,DAGUtils, andMultipleTableJobConfigParserall hold their own balanced references and are unaffected. - On paths B and C no
TaskGroupContextwas published and no task was started, so nothing on the node is executing code from that classloader.
Thread safety and idempotency of the release
deployTask runs on a Hazelcast operation thread. getClassLoader and releaseClassLoader are both synchronized on the DefaultClassLoaderService instance (:58, :103), so concurrent deployments cannot interleave a decrement with an eviction. The ledger itself is a method-local ArrayList never published to another thread — no synchronisation needed, correctly.
On double-release idempotency: releaseClassLoader is not idempotent — it decrements unconditionally at :117 once the key is present, so a second release drives the counter negative and, in non-cache mode, referenceCount == 0 at :122 is then never satisfied again and the entry is never evicted. There is no guard. The design therefore depends entirely on each release being matched to exactly one acquisition. The new helper honours that; the concern is only the ownership-boundary question in Issue 1. Worth knowing that the safety net does not exist.
The new helper is invoked from the catch at :526, outside the synchronized (this) block at :501-525, whereas the failover branch's releases at :515-517 are inside it. Both orderings acquire the TaskExecutionService monitor before the DefaultClassLoaderService monitor or neither, so no lock-order inversion is introduced.
1.2 Compatibility Impact
Explicit conclusion: no observable change to failure, restart, or redeploy behaviour for existing jobs on any path I could construct, with the single exception of the escape scenario in Issue 1 (which is a new behaviour, and a harmful one). Detail:
- Public API / SPI / Option: nothing added, removed, renamed, or re-defaulted.
ClassLoaderServiceis untouched.classloader-cache-modesemantics are unchanged in both settings. - Serialization / wire format: the only cross-node payloads on this path are
TaskGroupImmutableInformation(in) andTaskDeployState(out); neither is modified, andDeployTaskOperationis unchanged. A new-version worker and an old-version master interoperate exactly as before. Rolling upgrade and mixed-version clusters are safe. TaskGroupContext.jarsvalue type change (:487): previously theSet<URL>from:456/:468, now theArrayList<URL>copy.TaskGroupContextis node-local and notSerializable, so this never crosses the wire. The sole consumer isrecycleClassLoaderat:1477, which feeds each value tocovertJarsToKey(DefaultClassLoaderService.java:144-146) — a sorted concatenation ofURL.toString(), soSetandListof the same elements produce an identical key. I checked this specifically because a type-sensitive key would have broken the existing release path. It is correct.testClassloaderSplitasserts withassertIterableEqualsonURLClassLoader.getURLs()(TaskExecutionServiceTest.java:228-232), which is unaffected.- Checkpoint / savepoint / restore: nothing in the change is persisted or restored.
NotifyTaskRestoreOperationand friends consumeTaskGroupContext.getClassLoader(taskId), which is untouched. - Master failover: the idempotency branch at
:502-519retains its behaviour precisely, including its own classloader release.testDeployTaskIdempotentWhenAlreadyRunning(:464) is unmodified and still covers it. - Existing job semantics: a job that deployed successfully before deploys identically after. A job that failed to deploy before still fails with the same
TaskDeployState.failedresult and the same reported message, plus any suppressed cleanup exception (which will not occur in practice).
1.3 Performance / Side-Effect Analysis
Normal path — negligible. One ArrayList per deployTask call (:447). The per-task Lists.newArrayList(jars) copy at :470 already existed before the PR — it was created inline as the getClassLoader argument and discarded; the change hoists it into a variable and reuses it for both the ledger and taskJars, so the net allocation delta is one list per deployment. taskJars now retains the copy rather than a reference into taskImmutableInfo, which is marginally better for GC. Deployment happens once per task group per job start — not a hot path.
Failure path — a new expensive JVM call, non-cache mode only. When a release drops the count to zero, DefaultClassLoaderService.java:126 calls recycleClassLoaderFromThread, which executes Thread.getAllStackTraces() (:135) — a stop-the-world-ish capture of every live thread's stack. Before this PR these releases never happened on the failure path, so this cost is new there: up to N invocations per failed deployment, multiplied across task groups during a deployment-failure storm. Under the default classloader-cache-mode: true the early return at :119-121 makes it unreachable. Recorded as Issue 7 (Low) — an observation, not an objection; leaking is clearly worse.
Exception mutation. deploymentFailure.addSuppressed(cleanupFailure) at :557 mutates the throwable that TaskDeployState.failed(t) converts via ExceptionUtils.getMessage(e), so cleanup failures surface in the message returned to the master. That is intended and desirable. Self-suppression (which would throw IllegalArgumentException) is unreachable: cleanupFailure originates inside the helper and can never be the same object as deploymentFailure.
1.4 Error Handling and Logging
This is the strongest part of the patch and I want to say so clearly.
- The release is defensive against throwing. The
trysits inside the loop (:554-560), so one failing release does not abort the remaining entries. This is the right shape and the author got it right the first time. - A failure to release cannot mask the original deployment error. The deployment exception stays primary; cleanup failures are attached via
addSuppressedat:557and additionally logged at:558-559.TaskDeployState.failed(t)at:536still reports the deployment failure. Correct. - Ordering.
releaseClassLoadersAfterFailedDeploymentis called at:527before thelogger.severeat:529-535. Since the helper cannot throw (every body is wrapped), the original error is still logged. Fine, though calling cleanup after the log would read slightly more naturally. logger.severe(String, Throwable)at:558-559is a valid HazelcastILoggeroverload. NoSystem.out.println, no emoji or special symbols, no sensitive data logged. Log levels are appropriate.
One accuracy problem: the new Javadoc at :543-545 states "This cleanup only runs before ownership is transferred to a published TaskGroupContext." That is the invariant the code intends, but as shown in Issue 1 the code does not enforce it. Documentation that asserts an unenforced invariant is worse than none, because the next reader will trust it. Folded into Issue 1.
2. Code Quality Assessment
2.1 Coding Standards
- Google Java Format (AOSP) is respected; the formatting matches Spotless output. No wildcard imports.
Listsis the shadedorg.apache.seatunnel.shade.com.google.common.collect.Listsalready in use in this file. - No new imports were needed in
TaskExecutionService.java—ArrayList,Collection,List, andURLwere all already imported. The three test imports (DefaultClassLoaderService,TaskGroupContextNotFoundException,java.util.Set) are all used. No unused imports. - No new files, so no ASF header question arises.
- The new method is
private, placed directly after its single caller — correct visibility and reasonable placement. - Comment completeness — resolved from last round. The helper now carries proper multi-line Javadoc (
:540-546), and the two invariant-bearing lines are annotated at:446and:522. The wording at:522("TaskGroupContext now owns these references and recycleClassLoader releases them") names exactly the right mechanism. This is what I asked for and it was delivered well; the only remaining problem is that the statement is not yet true on all paths. - The new test carries a Javadoc block (
TaskExecutionServiceTest.java:240-243) describing the production behaviour it protects, and correctly avoids@DisplayName.
2.2 Test Coverage and Test Stability
Stability rating: Stable. This is an upgrade from "Risk present" last round, and it is deserved.
The order-dependence I flagged previously is genuinely gone. I re-derived it rather than taking the commit message's word: File.createTempFile("failed-deployment", ".jar") at :250 produces a path unique to the run; covertJarsToKey (DefaultClassLoaderService.java:144-146) keys the cache on that URL string; therefore queryClassLoaderReferenceCount(testJobId, testJars) at :278-279 reads a counter no other test in the class can touch, including under the default cacheMode = true where jobId is rewritten to 1L (:169-172). The collision with testDeployTaskIdempotentWhenAlreadyRunning (:464) that made the previous version order-dependent is structurally impossible now.
I also verified the test still discriminates — that it actually fails without the production fix:
- Both tasks share
testJars(:266), sogetClassLoaderis called twice on the same key: refcount 1, then 2. - Task 0 (
validTask, aTestTask) deserializes successfully throughCustomClassLoadedObject.deserializeWithCustomClassLoader(:479-483) becauseSeaTunnelChildFirstClassLoader'sDEFAULT_PARENT_FIRST_PATTERNSincludes"org.apache.seatunnel."(SeaTunnelChildFirstClassLoader.java:39), soTestTaskis loaded parent-first from the application classloader (:56) and the zero-byte temp jar is never consulted. Good — the test genuinely exercises the K=2 partial-acquisition scenario, not a degenerate K=1 case. - Task 1 deserializes to a
String, and the compiler-inserted cast toTaskat:479throwsClassCastException. - Without the fix: 2 references leak, the assertion reads 2, the test fails. With the fix: 0. Correctly discriminating.
Also verified: File.createTempFile guarantees the file exists, so DefaultClassLoaderService's NOT_FOUND_JAR check at :79-89 passes; and assertThrows(TaskGroupContextNotFoundException.class, ...) at :273-277 is deterministic because deployment fails before deployLocalTask is ever entered, so no context is published. No Thread.sleep, no new shared static mutable state, no unclosed resources, no timing assumption, no floating-point comparison. TestTask at :255 is never executed, so no background thread is left behind.
No test weakening. I diffed the test file against the merge base b1e21631f: the change is purely additive (+45/-0). No existing assertion was removed, relaxed, or made more tolerant; no test was skipped or disabled. The contains("ClassCastException") assertion removed in the follow-up commit was introduced by this same PR two commits ago and never existed on dev, so removing it does not reduce the historical strictness of the suite — and as noted in 1.1 it was removed for a correctness reason, not for convenience.
Remaining coverage gaps (none blocking):
- The zero assertion cannot distinguish "acquired then released" from "never acquired." A future refactor that stopped acquiring classloaders would keep this test green. Cheap fix in Issue 4.
- No test for the
deployLocalTaskwindow (Issue 2) or the escape path (Issue 1). The escape is hard to test without a seam; the pre-publicationdeployLocalTaskleak is testable by makingtaskGroup.init()throw. - No test for K=0 (first task's jar resolution fails), which would prove the helper is a no-op on an empty ledger. Cheap and worth having.
2.3 Documentation Updates
None needed, and none provided — correct. This is internal engine cleanup: no user-facing configuration, no Option, no connector behaviour, no incompatible change. Neither docs/en nor docs/zh nor docs/en/introduction/concepts/incompatible-changes.md requires an update, and the PR checklist reflects this accurately.
The one documentation item I would still ask for is in the PR description, not the docs tree — see Issues 2 and 6.
3. Architectural Soundness
3.1 Elegance of the Solution
Classification: Precise fix, with the ownership boundary drawn one statement too late.
The shape is textbook and correct: an acquisition ledger local to the attempt, dropped at handover, drained in the failure handler. Nothing is papered over; no sentinel, retry, or symptom suppression is introduced. The compensation lives exactly where the resource is acquired.
The single architectural criticism is that the handover point is expressed as "after deployLocalTask returns" (:523) rather than as "when the context is published" (:619). Those coincide only when deployLocalTask either returns normally or throws before publishing — which is almost always, but not structurally guaranteed. Making the boundary structural rather than positional is a small change and would close Issue 1:
try {
deployLocalTask(taskGroup, classLoaders, taskJars);
} finally {
// Ownership passes to TaskGroupContext the moment deployLocalTask publishes it;
// from that point recycleClassLoader() is the sole owner, however we exit.
if (executionContexts.containsKey(taskGroup.getTaskGroupLocation())) {
acquiredClassLoaderJars.clear();
}
}
return TaskDeployState.success();That keys the ledger on the same condition the release path itself keys on, so it stays correct under any future change to deployLocalTask. Moving resultFuture.whenCompleteAsync(...) (:633-657) inside deployLocalTask's try is a good complementary hardening but is not sufficient alone, since it only closes the one escape I found rather than the class of them.
On the "is this the best repair site?" question a maintainer owes the project: I considered pushing ownership tracking down into DefaultClassLoaderService as a scoped, auto-closing handle. That would fix every caller at once — JobMaster, PhysicalPlanGenerator, DAGUtils, and MultipleTableJobConfigParser all hand-balance the same acquire/release pair and are all one early return away from this bug. But it changes a public SPI used across three modules, and minimal blast radius clearly favours the local fix for a bug fix on dev. The author chose the right site. The broader refactor is worth an issue, not a demand on this PR.
3.2 Maintainability
Good, with one standing reservation. The helper is small, single-purpose, side-effect-local, and now properly documented. The reservation is that deployTask still contains two release mechanisms for the same references — the failover loop at :515-517 and the new helper at :547-562 (Issue 3) — and that the Javadoc at :543-545 asserts an invariant the code does not enforce (Issue 1). Unifying on one mechanism and making the boundary structural would take roughly five lines and would materially help the next reader. deployTask is now ~99 lines with three exit points plus nested try/synchronized; it is at the edge of comfortable, though splitting it is out of scope here.
3.3 Extensibility
Neutral, which is the right answer for a bug fix. No new abstraction, interface, or extension point is introduced, and none is needed. The List<Collection<URL>> ledger is a local implementation detail a future refactor can replace freely. If the project later adopts a scoped classloader handle, this is the natural first migration site and will delete cleanly.
3.4 Historical-Version Compatibility
No historical-compatibility concerns, verified rather than assumed — see 1.2 for the evidence. Rolling upgrade, mixed-version cluster, checkpoint/savepoint restore, master failover re-deploy, existing job semantics, and configuration are all unaffected. Nothing in the change is persisted, and nothing crosses the wire.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Ledger is cleared after deployLocalTask returns rather than at publication, so a Throwable escaping deployLocalTask at :633 after executionContexts.put causes the catch to release classloaders a live, executing TaskGroupContext still owns; new Javadoc asserts the unenforced invariant |
TaskExecutionService.java:521-528, :619-621, :623-624, :629-633, :540-546; DefaultClassLoaderService.java:122-127, :134-142 |
High |
| 2 | Failures inside deployLocalTask are swallowed at :629-632, so the ledger is cleared and success() returned while N references leak permanently; the PR description's bounding sentence claims these are handled by "the existing task-group lifecycle," which is not true for pre-publication failures |
TaskExecutionService.java:521-524, :579, :592-600, :629-632, :1473-1479; PR description |
Medium |
| 3 | Failover branch uses a second, unguarded release mechanism and does not clear the ledger; latent over-release if releaseClassLoader throws mid-loop |
TaskExecutionService.java:513-519 |
Low |
| 4 | Test cannot distinguish "released" from "never acquired" — a zero count would also pass if acquisition were removed | TaskExecutionServiceTest.java:278-279 |
Low |
| 5 | Test leaves its temp jar to deleteOnExit and leaves a permanently cached classloader entry behind, unlike testClassloaderSplit which deletes its temp files |
TaskExecutionServiceTest.java:250-251 vs :236-237 |
Low |
| 6 | PR description still omits that under the default classloader-cache-mode: true the original bug is a counter-only leak; the metaspace/handle impact applies to false |
PR description; ServerConfigOptions.java:31-36, DefaultClassLoaderService.java:119-121 |
Low |
| 7 | Failure path newly triggers Thread.getAllStackTraces() in non-cache mode; acceptable trade-off, recorded for completeness |
TaskExecutionService.java:555 -> DefaultClassLoaderService.java:126, :134-142 |
Low |
Totals: 1 High, 1 Medium, 5 Low. Resolved since the previous round: prior Issues 1, 2, 6, and 8.
Issue 1 — Ledger cleared at the wrong boundary: premature release of a live TaskGroupContext's classloaders
- Location:
TaskExecutionService.java:521-528(clear at:523, catch at:526-528), in combination with:619-621(publication),:623-624(task start),:629-633(swallow then unguarded dispatch), and the Javadoc at:540-546. Consequence sites:DefaultClassLoaderService.java:122-127,:134-142. - Problem description:
acquiredClassLoaderJars.clear()at:523marks handover positionally ("afterdeployLocalTaskreturns") rather than causally ("onceexecutionContexts.putat:619has run").deployLocalTaskswallowsThrowableat:629-632butresultFuture.whenCompleteAsync(..., MDCTracer.tracing(executorService))at:633sits outside thattry. When the catch at:631completesresultFutureexceptionally, the future is already complete when:633runs, sowhenCompleteAsyncdispatches synchronously viaUniCompletion.claim()->executor.execute(...)on the calling thread. IfexecutorService(:172-173) cannot accept work —shutdownNow()fromTaskExecutionService.shutdown()(:295) during a rolling restart, orOutOfMemoryError: unable to create new native threadunder thread exhaustion — that dispatch throws and escapesdeployLocalTask. The same root cause is what madesubmitBlockingTask'smdcExecutorService::submit(:398) fail in the first place, so these are one condition, not two. Control lands indeployTask'scatchat:526, which releases all N references — butexecutionContexts.putat:619already published the context,submitThreadShareTaskat:623already queued cooperative tasks that aCooperativeTaskWorkerruns with the TCCL set at:1237-1241, and earlierBlockingWorkers may already be running with the TCCL set at:1103-1104. My previous review dismissed this window as having no realistic trigger; that was my error and I apologise for it. - Potential risk: With
classloader-cache-mode: false, the count reaches zero,DefaultClassLoaderService.java:123evicts the classloader and:126callsrecycleClassLoaderFromThread, which nulls the context classloader of every live thread pointing at it — including a worker thread insidetask.call(). That task then hitsNullPointerExceptionon its next TCCL lookup, orNoClassDefFoundErrorfor any class not yet resolved from the evictedSeaTunnelChildFirstClassLoader. Silent, mid-flight, in a job the master has just been told failed to deploy. Under the defaultcacheMode = truethe early return at:119-121limits the damage to counter drift. NotereleaseClassLoaderhas no double-release guard — it decrements unconditionally at:117— so any over-release also permanently prevents future eviction of that key. Before this PR the escape was harmless because the catch released nothing; this PR is what makes it damaging, which is why I am raising it against this change rather than filing it separately. - Best improvement: Key the handover on the same condition the release path uses, so it is structural rather than positional:
Complementary hardening (worth doing as well, not instead): move
try { deployLocalTask(taskGroup, classLoaders, taskJars); } finally { // Ownership passes to TaskGroupContext the moment deployLocalTask publishes it; // from that point recycleClassLoader() is the sole owner, however we exit. if (executionContexts.containsKey(taskGroup.getTaskGroupLocation())) { acquiredClassLoaderJars.clear(); } } return TaskDeployState.success();
resultFuture.whenCompleteAsync(...)at:633-657insidedeployLocalTask'stryso nothing can escape after publication. Once either is in place, please adjust the Javadoc at:543-545— as written it asserts an invariant the code does not currently enforce, which is worse than no comment. - Confidence note: I have not executed this; the synchronous-dispatch step is derived from the JDK 8
CompletableFuture.uniWhenCompleteStage/UniCompletion.claim()implementation, whereclaim()callse.execute(this)with no surrounding try-catch. I am confident in the reading, but please verify before acting on the severity — and if you find I am wrong again, say so plainly and I will withdraw it. - Severity: High
- Raised by another reviewer: No
Issue 2 — Failures inside deployLocalTask still leak, and the PR description's bounding sentence is inaccurate
- Location:
TaskExecutionService.java:521-524in combination with:629-632; leaking sub-paths at:579(taskGroup.init()),:592-600(new TaskExecutionContext(...)inside thepeek), and:346-368(submitThreadShareTask). Owner that cannot help::1473-1479. Also the PR description. - Problem description:
deployLocalTaskcatchesThrowableat:629-632, logs, completesresultFutureexceptionally, and returns normally — it never rethrows. Control therefore reachesacquiredClassLoaderJars.clear()at:523anddeployTaskreturnsTaskDeployState.success()even though deployment failed. If the failure occurred beforeexecutionContexts.put(...)at:619—taskGroup.init()at:579, ornew TaskExecutionContext(...)at:594-596— noTaskGroupContextwas ever published, sorecycleClassLoaderat:1473(executionContexts.get(location)) can never find it and the N references leak permanently. A reachable variant exists even after publication: insubmitThreadShareTask, when a task'sinit()throws at:357the handler at:359-362callstaskDonefor that task only; subsequent tasks fail the guard at:352, the mapper returnsnull, andthreadShareTaskQueue::addat:367throwsNullPointerExceptionon the null element. Those tasks never calltaskDone,completionLatchat:1423never reaches zero, andrecycleClassLoadernever runs. This is pre-existing and the PR does not make it worse. What I am raising against this PR is narrower: the description now says "cleanup for failures inside local task deployment remains part of the existing task-group lifecycle," and that is not accurate — for pre-publication failures insidedeployLocalTaskthere is no existing lifecycle that can reclaim those references, because the owner object was never created. - Potential risk: A connector whose
init()throws (bad credentials, unreachable endpoint, malformed schema) is a far more common production failure than the deserialization failure this PR reproduces. In that scenario the references still leak anddeployTaskreports success to the master, so the job appears deployed. A reader of the PR title will reasonably believe the leak on failed deployment is now closed; it is closed only for failures raised beforedeployLocalTaskis entered. - Best improvement: Keep this PR's scope as-is — it matches #11808 precisely and I do not want it to grow. Just correct the bounding sentence to say the uncovered window is not currently reclaimed, e.g. "failures inside
deployLocalTaskare swallowed and are not covered by this change; tracked separately," and open a follow-up issue. The natural fix there is fordeployLocalTask's catch at:629to release the classloaders it was handed when it fails before publishing the context, and forsubmitThreadShareTaskto calltaskDonefor the tasks it skips at:352-364rather than enqueuingnull. Happy to file that follow-up myself if you would rather not. - Severity: Medium
- Raised by another reviewer: No
Issue 3 — Failover branch uses a second, unguarded release mechanism and leaves the ledger populated
- Location:
TaskExecutionService.java:513-519 - Problem description: The method now has two ways of releasing the same references: the pre-existing loop over
taskJars.entrySet()at:515-518, and the new ledger-based helper at:547-562. The failover branch does not clearacquiredClassLoaderJarsbefore returning at:519. Today the counts match (task IDs within a group are unique, sotaskJarsholds one entry per acquisition) and the branch returns normally so thecatchis unreachable — behaviour is correct. But the loop at:515-517has notry, unlike the helper. IfreleaseClassLoaderthrew partway through, the exception would propagate to thecatchat:526, which would then release all N references a second time from the still-populated ledger, over-releasing every entry the loop had already handled. - Potential risk: Over-release drives the counter negative at
DefaultClassLoaderService.java:117; sincereferenceCount == 0at:122is then never satisfied, the entry is never evicted and never cleaned up — inverting the very bug this PR fixes. I could not construct a realistic trigger forreleaseClassLoaderthrowing (it is fullysynchronizedand null-guarded at:109-116), so I am rating this as a latent robustness and consistency defect rather than an active bug. - Best improvement: Have the failover branch reuse the same helper, or at minimum add
acquiredClassLoaderJars.clear();immediately after the loop at:518. One release mechanism instead of two also removes a maintenance trap. Note that thefinallyform proposed in Issue 1 does not cover this branch, since it returns before reachingdeployLocalTask. - Severity: Low
- Raised by another reviewer: No
Issue 4 — Test cannot distinguish "released" from "never acquired"
- Location:
TaskExecutionServiceTest.java:278-279 - Problem description:
assertEquals(0, queryClassLoaderReferenceCount(testJobId, testJars))passes both when the references were acquired and correctly released and when they were never acquired at all —queryClassLoaderReferenceCountreturns0for an absent key (DefaultClassLoaderService.java:173-180). A future refactor that stopped acquiring classloaders in the loop would keep this regression test green while removing the behaviour it guards. - Potential risk: Silent loss of regression coverage. Low impact today; the test does fail against the unfixed code, which is the property that matters most.
- Best improvement: Add one positive assertion proving acquisition actually happened. Because
cacheModedefaults totrue,releaseClassLoaderreturns atDefaultClassLoaderService.java:119-121without removing the cache entry, so the classloader is still queryable after a correct release:Also worth a one-line comment noting that this assertion is what makes the zero meaningful.Assertions.assertTrue( classLoaderService.queryClassLoaderById(testJobId, testJars).isPresent());
- Severity: Low
- Raised by another reviewer: No
Issue 5 — Test leaves its temp jar and a cached classloader behind
- Location:
TaskExecutionServiceTest.java:250-251, compared with:236-237 - Problem description: The test relies on
testJar.deleteOnExit()and never callsdelete(), unliketestClassloaderSplit, which deletes both temp files at:236-237. Additionally, becausecacheModedefaults totrue,releaseClassLoadernever removes the entry (DefaultClassLoaderService.java:119-121), so theSeaTunnelChildFirstClassLoaderbuilt over that jar stays inclassLoaderCachefor the remainder of the JVM. - Potential risk: Cosmetic only — one leaked temp file and one cached classloader per test run. No correctness or ordering impact, since the key is unique. Noted for consistency with the neighbouring test's hygiene.
- Best improvement: Call
testJar.delete()at the end of the test, matching:236-237. - Severity: Low
- Raised by another reviewer: No
Issue 6 — PR description omits the classloader-cache-mode severity nuance
- Location: PR description;
ServerConfigOptions.java:31-36,EngineConfig.java:81,DefaultClassLoaderService.java:119-121 - Problem description:
classloader-cache-modedefaults totrue, and in that modereleaseClassLoaderdecrements and returns without removing the classloader or closing anything. Under the default configuration the original bug therefore leaks a counter value only; the metaspace pressure and JAR-handle exhaustion described in #11808 apply toclassloader-cache-mode: false. Since I wrote that issue text, the imprecision is mine, not yours — but it would be good to correct it here so the record is accurate. - Potential risk: Future readers over- or under-estimate the production impact of both the bug and the fix; backport decisions get made on the wrong basis.
- Best improvement: One sentence in the PR description.
- Severity: Low
- Raised by another reviewer: No
Issue 7 — Failure path newly performs Thread.getAllStackTraces() (non-cache mode only)
- Location:
TaskExecutionService.java:555reachingDefaultClassLoaderService.java:126->:134-142 - Problem description: When a released reference drops the count to zero,
recycleClassLoaderFromThreadcallsThread.getAllStackTraces(), capturing stack traces for every live thread. Prior to this PR the failure path never released, so this cost is new there — up to N invocations per failed deployment, multiplied when a high-parallelism job fails to deploy across many task groups. Under the defaultclassloader-cache-mode: truethe early return at:119-121makes it unreachable. - Potential risk: Brief pauses on Hazelcast operation threads during a deployment-failure storm in non-cache mode. Bounded and strictly preferable to leaking.
- Best improvement: No change requested in this PR. If it ever matters,
recycleClassLoaderFromThreaditself is the right place to optimise — it is a pre-existing implementation detail ofDefaultClassLoaderService. - Severity: Low
- Raised by another reviewer: No
5. Merge Recommendation
Conclusion: Ready to merge after fixes
-
Blockers — must be fixed
- Issue 1 (High) — premature release of a live
TaskGroupContext's classloaders. The ledger is dropped at:523on the basis of "deployLocalTaskreturned" rather than "the context was published at:619." BecausedeployLocalTaskswallows at:629-632and then dispatcheswhenCompleteAsyncat:633outside thattry, an executor that cannot accept work causes aThrowableto escape after publication and after tasks have started — anddeployTask'scatchthen releases classloaders that running task threads are using. Inclassloader-cache-mode: falsethat evicts the classloader and nulls the context classloader of live worker threads (DefaultClassLoaderService.java:126,:134-142), producingNullPointerException/NoClassDefFoundErrormid-flight. This window existed before the PR but was harmless, because the catch released nothing; this change is what arms it. The fix is the smallfinally+ publication-check shown in Issue 1, and the Javadoc at:543-545should then match reality. Given this is engine classloader-lifecycle code whose failure mode is silent corruption of a running job, I cannot sign off with the boundary drawn positionally.
To be explicit about what I did not find, since the acquire/release balance is the heart of this change: on the paths this PR actually targets — failures during jar resolution, classloader creation, deserialization, and
createTaskGroup— I found no double-release, no release-before-use, and no leak newly introduced. The ledger is appended only after a successful acquisition (:474),getClassLoadercannot partially acquire, the helper releases exactly what this attempt acquired and never more, and reference counting correctly protects concurrent holders of the same key. Issue 1 is about one boundary condition, not about the fix's core logic, which is sound. - Issue 1 (High) — premature release of a live
-
Recommended fixes — non-blocking
- Issue 2 (Medium): correct the PR description's bounding sentence — pre-publication failures inside
deployLocalTaskare not reclaimed by the existing task-group lifecycle — and open a follow-up issue for that window and thesubmitThreadShareTasknull-enqueue path. I am happy to file it if you prefer. - Issue 3 (Low): unify on a single release mechanism, or add
acquiredClassLoaderJars.clear();after the failover loop at:518. - Issue 4 (Low): add
assertTrue(classLoaderService.queryClassLoaderById(testJobId, testJars).isPresent())so the zero-count assertion cannot pass vacuously. - Issue 5 (Low):
testJar.delete()at the end of the test, matchingtestClassloaderSplitat:236-237. - Issue 6 (Low): one sentence on the
classloader-cache-modenuance. - Issue 7 needs no action.
- Optional, out of scope: an issue for a scoped, auto-closing classloader handle on
ClassLoaderService.JobMaster,PhysicalPlanGenerator,DAGUtils, andMultipleTableJobConfigParserall hand-balance the same acquire/release pair and are structurally exposed to the identical bug. This PR is good evidence the pattern is worth having.
- Issue 2 (Medium): correct the PR description's bounding sentence — pre-publication failures inside
-
CI status
No results at this head. The apache-side
Buildcheck forc6a7ac1f3is queued, and the corresponding run in the contributor's fork (goutamadwant/seatunnel, run31892655769, created 2026-08-15T15:25Z) is also queued. The previous head's fork run (31856511698) completed as cancelled — superseded by the new push, not a real failure.Notify test workflowandlabelerhave passed.mergeStateStatusisBLOCKED(awaiting review),mergeableisMERGEABLE, no conflict againstdev. Green CI on the current head remains a gate and this review does not substitute for it. Note that CI cannot retire Issue 1 either way: the escape requires an executor that cannot accept work, which no test in the suite creates.
Overall assessment: You addressed every point from the last round cleanly, and two of them better than I asked. Giving the test its own temp-jar-derived cache key fully removes the order-dependence — I re-derived the key computation rather than taking it on trust, and it is airtight under both cacheMode settings. Dropping the ClassCastException message assertion was not just a nit fix but genuinely necessary, since moving to non-empty jars switched the deserialization to the CustomClassLoadedObject branch; noticing that shows you traced the consequence rather than just deleting a line I complained about. The comments at :446, :522, :551 and the helper Javadoc are exactly the invariant documentation I wanted. The error-handling design — per-entry try, primary exception preserved, cleanup failures suppressed onto it, loop continues past a failure — remains the pattern I would want to see, and compatibility is clean in every dimension I checked: no wire format, no state, no config, no API, and existing failover behaviour untouched.
What holds it back is one boundary condition that I should have caught properly last round and did not. The ledger is cleared on a positional signal rather than the causal one, and the one path where those diverge is a path where this PR turns a previously harmless escape into an in-flight classloader eviction. It is a handful of lines to make structural, and once it is, the invariant your new Javadoc already describes becomes true. Fix that, take whichever of the Low items you find worthwhile, and this is a clean merge on a genuinely worthwhile fix. Thank you for the careful work and for the patience through a second round — the analysis quality on this patch has been high throughout.
Signed-off-by: goutamadwant <workwithgoutam@gmail.com>
|
@DanielLeens Updated the deployment ownership handling so cleanup follows whether the execution context was actually published, including failures after deployLocalTask starts. Failover skips also clear the deployment ledger. The full engine module passes with 381 tests and 5 skipped. |
nzw921rx
left a comment
There was a problem hiding this comment.
The current ownership check can release the same classloader references twice
The new finally block uses:
executionContexts.containsKey(taskGroup.getTaskGroupLocation())to determine whether ownership of the classloader references has been transferred to TaskGroupContext.
However, this only indicates whether the context is active at that moment. It does not indicate whether the context was previously published.
The following sequence is possible:
deployLocalTask()publishes the context throughexecutionContexts.put(...). Ownership is transferred.- The tasks finish quickly.
TaskGroupExecutionTracker.taskDone()releases the classloader references and removes the context fromexecutionContexts. - The completed
resultFuturereacheswhenCompleteAsync(...). If the executor is concurrently shutting down, callback submission can be rejected anddeployLocalTask()exits exceptionally. - The
finallyblock now observescontainsKey(...) == false, soacquiredClassLoaderJarsis not cleared. - The outer
catchreleases every entry inacquiredClassLoaderJarsagain.
If another active task group shares the same jobId + jars classloader, the second release consumes references owned by that task group. In non-cache mode, this may recycle a classloader that is still in use. In cache mode, it can leave the reference count incorrect or negative.
Current map membership therefore cannot safely represent whether ownership has been transferred.
Could we instead use a monotonic publication flag or ownership token that is set immediately after a successful executionContexts.put(...) and is not reset when the context later completes? The outer failure cleanup should release these references only when ownership was never transferred.
DanielLeens
left a comment
There was a problem hiding this comment.
Two things up front, before the structured review.
First, thank you for implementing the fix the way you did — the try/finally around deployLocalTask(...) keyed on executionContexts.containsKey(...) is essentially the exact shape I suggested as the "Best improvement" in my previous review's Issue 1. Second, and more important: @nzw921rx found a real gap in that very fix, and it is a gap in my own suggestion, not just an implementation slip. I recommended containsKey(...) as the ownership signal without accounting for the fact that a task group can finish (and be removed from executionContexts by TaskGroupExecutionTracker.taskDone) before deployLocalTask returns. I re-derived the mechanism independently below and I agree with the finding: it is correct, and it is more severe than the report describes because of what it can do to an unrelated live task group. I'm marking this as Issue 1 (High) — not carryover in the strict sense, since this exact code path did not exist before this commit, but I want to be upfront that it grew directly out of advice I gave last round. My apologies for not stress-testing my own suggestion against the async completion path before proposing it.
Everything below is a complete re-review of head 32a7c757bd6577d639d1baccb74ef9f6ee31f7d5, re-traced from source.
What Problem Does This PR Solve?
- User pain point:
TaskExecutionService.deployTask(...)acquires one reference-counted classloader per task, one at a time, inside a loop (TaskExecutionService.java:455-488). Before this PR existed at all, if any task failed during jar resolution, classloader creation, or deserialization, the outercatch (Throwable t)returnedTaskDeployState.failed(t)without releasing the references already acquired in that attempt — a permanent reference-count leak (issue #11808). - Fix approach, current head: Track the jar collections acquired by the current attempt in a local ledger
acquiredClassLoaderJars(:447), append after each successfulgetClassLoader(...)(:474), and release everything still in the ledger from the outercatchviareleaseClassLoadersAfterFailedDeployment(...)(:534-535, helper at:554-569). The new work in this commit is the ownership-transfer boundary:deployLocalTask(...)is now called inside its owntry/finally(:522-530), and the ledger is cleared only ifexecutionContexts.containsKey(taskGroup.getTaskGroupLocation())is still true when the call returns or throws. The master-failover branch also now clears the ledger before returning (:519), closing a Low item from last round. - One-sentence summary: The fix now correctly avoids releasing a live task group's classloaders in the simple escape case (deployment fails before any task has finished), which is real progress — but the
containsKey(...)check cannot distinguish "never published" from "published, already finished, and already released by the normal completion path," and that gap reopens a double-release that can evict a classloader still in active use by a different, healthy task group.
1. Code Change Review
1.1 Core Logic Analysis
Scope, this commit relative to the previous reviewed head (c6a7ac1f3 → 32a7c757b): one production file, TaskExecutionService.java, net effect is the try/finally wrapper around deployLocalTask(...) (:522-530), the failover-branch .clear() (:519), and updated Javadoc/comments. No test file changes beyond what was already reviewed (testDeployTaskReleasesClassLoadersWhenDeserializationFails, unchanged since c6a7ac1f3, now also asserting queryClassLoaderById(...).isPresent() and deleting its temp jar — both were my Issue 4/5 asks from last round, done correctly).
Runtime-flow trace: deployment, task completion, and the new escape/release race
[deploying thread — Hazelcast operation thread]
TaskExecutionService.deployTask(TaskGroupImmutableInformation) :440
447 acquiredClassLoaderJars = new ArrayList<>()
455-488 acquisition loop -> ledger append at :474 after each getClassLoader()
501 synchronized (this) {
502 if (executionContexts.containsKey(location)) -- failover branch --
519 acquiredClassLoaderJars.clear(); return success() [FIXED: old Low Issue 3]
522 try {
523 deployLocalTask(taskGroup, classLoaders, taskJars) ------------------------+
524 } finally { |
527 if (executionContexts.containsKey(location)) |
528 acquiredClassLoaderJars.clear(); <-- ownership signal, SEE BELOW |
530 } |
531 return TaskDeployState.success(); |
533 } catch (Throwable t) { |
534 releaseClassLoadersAfterFailedDeployment(jobId, ledger, t) |
:559 reverse iteration, :562 classLoaderService.releaseClassLoader(...) |
543 return TaskDeployState.failed(t); |
|
+----------------------------------------------------------+
v
deployLocalTask(taskGroup, classLoaders, jars) :580
586 taskGroup.init() [may throw]
626 executionContexts.put(location, new TaskGroupContext(...)) <- PUBLISH
630-631 submitThreadShareTask / submitBlockingTask -> tasks start running
632 taskGroup.setTasksContext(...)
636 } catch (Throwable t) { <-- try started at :585
637 logger.severe(...)
638 resultFuture.completeExceptionally(t) SWALLOWED, no rethrow
639 }
640 resultFuture.whenCompleteAsync(action, MDCTracer.tracing(executorService))
^ OUTSIDE the try. If resultFuture is already complete (either from :638,
or because taskDone() completed it concurrently -- see below), this
dispatches SYNCHRONOUSLY via executor.execute(...) on THIS thread and
can throw RejectedExecutionException / OutOfMemoryError -> escapes
deployLocalTask entirely, uncaught.
665 return new PassiveCompletableFuture<>(resultFuture)
[concurrently, on a worker thread running one of the started tasks]
TaskGroupExecutionTracker.taskDone(Task) :1423
1430 if (completionLatch.decrementAndGet() == 0) {
1431 recycleClassLoader(taskGroupLocation) :1480
1481-1482 context = executionContexts.get(location)
1483-1485 for (jars : context.getJars().values())
classLoaderService.releaseClassLoader(jobId, jars) <- FIRST RELEASE
1432-1433 finishedExecutionContexts.put(location, executionContexts.remove(location))
^ REMOVES the entry the
finally at :527 checks for
1454/1461/1467 future.complete(new TaskExecutionState(...)) <- completes resultFuture
}
Does the fix correctly close the simple trigger from last round?
Yes, verified. If a Throwable escapes deployLocalTask at :640 before any task in the group has finished, executionContexts still contains the location when the finally at :527 checks it, so the ledger is cleared and the outer catch releases nothing — the live, still-running TaskGroupContext keeps its references. This is a genuine fix for the scenario I described as Issue 1 last round, and I want to say clearly: the reasoning that got you here (ownership transfers at executionContexts.put, not at "deployLocalTask returned") is correct. The problem is one level more subtle than either of us modeled it.
The new race, traced precisely (Issue 1 in detail below, corroborating @nzw921rx)
executionContexts.containsKey(location) is not a reliable "ownership still held, not yet released" signal — it is only "an entry with this key currently exists," and taskDone removes the entry as part of the normal, successful release path (:1432-1433), immediately after already releasing every reference in recycleClassLoader (:1480-1486). So:
deployLocalTaskpublishes the context at:626-628. Tasks start at:630-631.- Before the deploying thread reaches
:640, all tasks in the group finish (plausible for small/trivial task groups, or under thread scheduling delay on a loaded node).taskDone's last call runsrecycleClassLoader— releasing all N references once, correctly — then removes the location fromexecutionContextsand completesresultFuturenormally (:1454). - The deploying thread now reaches
:640.resultFutureis already complete, sowhenCompleteAsyncdispatches synchronously viaexecutor.execute(...). IfexecutorServicecannot accept work at that instant —shutdownNow()from a concurrentTaskExecutionService.shutdown()during a rolling restart, or thread-pool exhaustion — this throws and escapesdeployLocalTaskuncaught (notrycovers:640). - Back in
deployTask, thefinallyat:527checksexecutionContexts.containsKey(location). It is false — not because ownership was never transferred, but because it was transferred and already correctly released in step 2. The ledger is not cleared. - The exception keeps propagating to the outer
catchat:533, which callsreleaseClassLoadersAfterFailedDeploymenton the still-populated ledger — releasing all N references a second time, even thoughrecycleClassLoaderalready released them in step 2.
Why this is worse than a simple double-decrement
DefaultClassLoaderService.releaseClassLoader (:103-132) guards against releasing a key that no longer exists at all (:109-111, :114-116 — silent no-op), so if this task group's own jar key was uniquely its own and already evicted in step 2 (non-cache mode, refcount hit 0 and the entry was removed), the spurious second release is harmless.
The dangerous case is when the same (jobId, jars) key is also held by a different, still-running task group — which is the ordinary situation for any job with parallelism > 1 whose task groups share the same connector jars. In that case:
- Non-cache mode (
classloader-cache-mode: false): after step 2's legitimate release, the shared counter is still > 0 because the other task group holds its own reference — the key is still inclassLoaderMap. The spurious extra release in step 5 decrements that shared counter one time too many. If it reaches 0,DefaultClassLoaderService.java:122-127evicts the classloader and callsrecycleClassLoaderFromThread(:134-142), which nulls the context classloader of every live thread currently pointing at it — including worker threads belonging to the other, healthy, still-executing task group. Those tasks then hitNullPointerExceptionorNoClassDefFoundErroron their next classloading, silently, in a job the master was never told anything was wrong with. - Cache mode (
classloader-cache-mode: true, the default):releaseClassLoaderdecrements and returns before the eviction check (:119-121), so the eviction branch is entirely unreachable regardless of the counter's value. The spurious extra decrement corrupts the accounting number only (and, since cache mode normalizesjobIdto1L, it corrupts a counter shared across all jobs using that jar set) — no functional crash, no thread corruption, under the default configuration. Worth stating precisely so the severity isn't over-read for the common deployment.
Confidence note
I have not executed this. The synchronous-dispatch mechanism at :640 is the same JDK 8 CompletableFuture.uniWhenCompleteStage/UniCompletion.claim() behavior I cited last round (claim() calls e.execute(this) with no surrounding try). What's new to this round is the additional precondition that taskDone races ahead of the deploying thread and removes the executionContexts entry first — I verified that ordering is possible because submitThreadShareTask/submitBlockingTask at :630-631 hand tasks to other threads (CooperativeTaskWorker, BlockingWorker) that can run and complete concurrently with the deploying thread's own remaining statements at :632-640. I'm confident in the reading; a reviewer wanting certainty before acting on severity should confirm under load.
Is the fix's core ledger accounting still sound on the paths it targets?
Yes. I re-verified this independently rather than assuming it carried over: the ledger append at :474 happens only after getClassLoader succeeds, getClassLoader cannot partially acquire (DefaultClassLoaderService.java:71-72 vs. :94-98), and on paths where no TaskGroupContext is ever published and no task starts (failures during jar resolution, classloader construction, deserialization, createTaskGroup), the helper releases exactly what this attempt acquired and nothing more. This portion of the fix — the actual reason issue #11808 gets closed — is correct and I found no double-release or leak on those paths.
Issue 3 from my previous round — still open
Failures inside deployLocalTask's own try (:585-635) are caught at :636-639, logged, and swallowed — deployLocalTask returns normally. If this happens before executionContexts.put(...) at :626 (e.g., taskGroup.init() throws at :586), no context is ever published, deployTask's finally sees containsKey == false (correctly, this time — nothing was ever transferred), but since deployLocalTask didn't throw, control reaches deployTask's own return TaskDeployState.success() at :531, bypassing the outer catch entirely. The ledger is simply discarded without draining, and the references leak permanently. This is unchanged from the last two rounds.
The PR description now states: "If deployment fails before publication, the acquired references are released in reverse order," and separately claims test coverage for "failures after local deployment begins but before the execution context is published." I could not find a test for that scenario in the diff — the only new test added since my first review remains testDeployTaskReleasesClassLoadersWhenDeserializationFails, which fails before deployLocalTask is ever entered (at task deserialization, :475-484), not inside it. As traced above, a failure inside deployLocalTask before publication is not released by this code — deployLocalTask never rethrows, so deployTask's catch (the only place that calls the release helper) is never reached. I'd ask that the description be corrected to match what the diff actually does, since the current wording will mislead a maintainer who doesn't re-derive the trace.
1.2 Compatibility Impact
Classification: Fully compatible, in the sense of "nothing about serialization, checkpoint/savepoint, public API, or Option changes" — verified the same way as last round: TaskGroupImmutableInformation/TaskDeployState payloads are untouched, TaskGroupContext is node-local and non-serializable so the Set→ArrayList storage change at :487 never crosses the wire, and covertJarsToKey (DefaultClassLoaderService.java:144-146) is type- and order-insensitive so the existing consumer at :1483-1485 is unaffected. Master-failover idempotency (:501-519) retains its behavior and now additionally clears the ledger, which is strictly an improvement with no observable side effect since the branch always returns before the catch would be reached.
The one caveat: Issue 1 above is a behavioral regression relative to not having this commit at all, in the narrow non-cache-mode, shared-jar, race-timing scenario — it can corrupt a live, unrelated task group's runtime classloader state. That is new behavior introduced by this fix, not a pre-existing one, so I'm not calling the whole PR "incompatible," but this specific window should not ship as-is.
1.3 Performance / Side-Effect Analysis
No new allocation patterns beyond what was already reviewed (one ArrayList per deployment, not a hot path). The failover branch's new .clear() is O(1) on an ArrayList field and cannot throw. Thread.getAllStackTraces() in recycleClassLoaderFromThread (DefaultClassLoaderService.java:135, non-cache mode only) is unchanged from last round — still an accepted trade-off (Issue 7 from round 2, no action needed).
1.4 Error Handling and Logging
The per-entry try inside releaseClassLoadersAfterFailedDeployment (:560-566), suppressed-exception attachment, and continue-past-failure behavior are unchanged and still the pattern I'd want to see. One gap specific to this round: the double-release path in Issue 1 produces no log line that distinguishes it from a normal cleanup. releaseClassLoader logs at DEBUG/INFO (DefaultClassLoaderService.java:104, :124) either way, so an operator diagnosing a mysteriously-corrupted live task group after this race would see two ordinary-looking "Release classloader" log lines with no indication that the second one was spurious or that it evicted a classloader another task group was still using. Given the silent-corruption failure mode, I'd ask for at least a WARNING when releaseClassLoadersAfterFailedDeployment runs against a ledger that historical logs would show was already published — but the real fix is closing the race (Issue 1's remedy below), not better logging around it.
2. Code Quality Assessment
2.1 Coding Standards
Google Java Format / Spotless conventions respected; no wildcard imports; no unused imports in the diff. The new comments at :446 and :525-526 and the Javadoc on releaseClassLoadersAfterFailedDeployment (:548-552) are exactly the documentation I asked for last round — good faith effort, clearly written. The problem is factual, not stylistic: :525-526 states "TaskGroupContext owns these references as soon as it is published, even if deployLocalTask exits exceptionally after publication," and the helper's Javadoc states cleanup "only releases references that have not been transferred to a published TaskGroupContext." Both describe the intended invariant, which the containsKey(...) check does not actually enforce once the group can finish before the check runs. As last round: documentation asserting an unenforced invariant is worse than none, because the next reader will trust it. Once Issue 1 is fixed structurally, these comments become accurate as written and should stay.
2.2 Test Coverage and Test Stability
Stability rating: Stable for what is tested. testDeployTaskReleasesClassLoadersWhenDeserializationFails (TaskExecutionServiceTest.java, unique temp-jar key, queryClassLoaderById(...).isPresent() plus zero-refcount assertions, testJar.delete() cleanup) is exactly what I asked for last round and I re-verified it is still correct and still order-independent under both cacheMode settings. testDeployTaskIdempotentWhenAlreadyRunning is unmodified and still covers the failover branch.
Coverage gap that matters for this round specifically: there is no test — and, being fair, one would be genuinely hard to write without a seam to inject timing — for the race in Issue 1: a task group whose tasks finish before the deploying thread reaches resultFuture.whenCompleteAsync(...), combined with an executor that rejects at that moment. There is also still no test for the deployLocalTask-internal failure window (Issue 3, carried from the last two rounds). Neither gap is something I'd block merely for missing coverage, but I want to be clear that CI passing on this PR provides no evidence against Issue 1 — the scenario requires a specific interleaving that the current test suite cannot produce.
2.3 Documentation Updates
None required for docs/en/docs/zh — correct, this is internal engine cleanup. The PR description itself needs a correction, though: the claim that failures "after local deployment begins but before the execution context is published" are tested is not accurate for the current diff (see 1.1, Issue 3 discussion) — please either add that test or adjust the sentence to describe what's actually covered.
3. Architectural Soundness
3.1 Elegance of the Solution
The ledger-plus-clear-on-handover shape remains the right one, and using executionContexts.containsKey(...) as the handover signal is an intuitive, minimal-diff choice — it's precisely why I suggested it. The flaw is that "is this key currently in the map" conflates two different facts (never inserted vs. inserted-then-already-removed-by-someone-else), and the map is mutated by a second, concurrent actor (taskDone) that this code doesn't coordinate with. A structural fix needs a signal that is monotonic with respect to this deployment attempt, not a live read of shared mutable state that another thread is also updating. Concretely, either:
// Set once, immediately after successful publication, and never reset.
boolean published = false;
try {
deployLocalTask(taskGroup, classLoaders, taskJars);
// deployLocalTask itself would need to signal successful publication back,
// e.g. via a boolean it sets right after executionContexts.put(...), since
// by the time deployLocalTask returns/throws the entry may already be gone.
} finally {
if (published) {
acquiredClassLoaderJars.clear();
}
}or, more robustly, move acquiredClassLoaderJars.clear() to execute synchronously right after executionContexts.put(...) inside deployLocalTask itself (as a direct statement, not a finally guarded by a map lookup), so the boundary is "did this specific line execute," not "does a lookup happen to succeed right now." Either way, the check needs to answer "did this deployment attempt hand off ownership," not "is some entry present under this key at the moment I look."
A second, independent hardening worth doing regardless: move resultFuture.whenCompleteAsync(...) (:640-664) inside deployLocalTask's own try, so nothing can escape deployLocalTask after publication in the first place. That closes the specific trigger for both this issue and the "simple" escape case, and I'd consider it the more robust fix since it removes the escape rather than trying to correctly classify it after the fact.
3.2 Maintainability
deployTask/deployLocalTask together now carry three release mechanisms for classloader references (failover loop :513-518, the new ledger/finally pair, and recycleClassLoader in taskDone) coordinating over shared mutable state (executionContexts) without a single source of truth for "who owns this reference right now." That's the root cause of both this round's finding and the shape of the previous one. I'd still endorse keeping the fix local to this file for a dev bug fix (per my 3.1 assessment last round), but the ownership model deserves to be written down as an actual invariant/state machine comment at the top of deployTask, not inferred per-call-site.
3.3 Extensibility
Neutral — no new abstraction introduced, none needed for a bug fix of this scope.
3.4 Historical-Version Compatibility
No change to wire format, checkpoint/savepoint, or configuration surface (see 1.2). Nothing here affects rolling upgrade or mixed-version clusters.
4. Issue Summary
| # | Issue | Location | Severity | Raised by another reviewer |
|---|---|---|---|---|
| 1 | executionContexts.containsKey(...) is not a reliable "not yet transferred" signal: if all tasks in the group finish (and release + remove themselves via taskDone) before a Throwable escapes deployLocalTask at :640, the finally fails to clear the ledger and the outer catch releases the same references a second time. In non-cache mode, if another live task group shares the same (jobId, jars) key, this can evict a classloader still in active use and null the context classloader of that unrelated task group's live threads. In cache mode (default) it corrupts the shared reference count only, no functional crash. |
TaskExecutionService.java:522-530, :626-628, :640; TaskGroupExecutionTracker.taskDone :1423-1433, recycleClassLoader :1480-1486; DefaultClassLoaderService.java:103-132 |
High | Yes — @nzw921rx |
| 2 | Failures inside deployLocalTask's own try (before or after publication) are swallowed at :636-639 and never rethrown, so the outer catch (the only caller of the release helper) is never reached; references leak permanently. PR description's test-coverage claim for this exact window is not substantiated by the diff. |
TaskExecutionService.java:522-531, :636-639; PR description |
Medium (carried from rounds 1-2, still open) | No |
| 3 | Comments/Javadoc at :525-526 and :548-552 state the ownership invariant as enforced; it is not, per Issue 1. |
TaskExecutionService.java:525-526, :548-552 |
Low (folds into Issue 1's fix) | No |
| 4 | No distinguishing log signal when the release helper runs against a ledger for an attempt that historical state suggests already completed — silent-corruption failure mode has no diagnostic trail. | TaskExecutionService.java:534-535, :554-569 |
Low | No |
Totals: 1 High, 1 Medium, 2 Low. Resolved since last round: the test-isolation fix, comment additions, ClassCastException message assertion removal, reverse-order comment, queryClassLoaderById positive assertion, temp-jar cleanup, and the failover-branch ledger clear — all verified still correct at this head.
5. Merge Recommendation
Conclusion: Not recommended for merge
-
Blockers — must be fixed
- Issue 1 (High). The
containsKey(...)ownership check can be fooled by a task group that finishes (and is legitimately, correctly released) before the escape happens, producing a double release. In the realistic case of a job with parallel task groups sharing connector jars, running inclassloader-cache-mode: false, this can silently corrupt a healthy, unrelated task group's runtime classloader — the exact class of production risk this codebase treats as unacceptable. This requires a structural fix, not a comment: either make the ownership signal monotonic per-attempt (not a live map lookup racing another thread), or eliminate the escape at its source by movingresultFuture.whenCompleteAsync(...)insidedeployLocalTask's owntry. See 3.1 for both options. I'd want to see this addressed and, ideally, a targeted test that forces the interleaving (e.g., a test double forexecutorServicethat rejects on the Nth submission, combined with a task that completes synchronously before deployment returns) before I'm comfortable signing off, given that ordinary CI cannot exercise this path.
To be explicit about what is not wrong: the acquire/release accounting on every path this PR actually targets (jar resolution, classloader construction, deserialization,
createTaskGroupfailures) remains correct, and the "simple" escape case from my previous round — where no task has finished yet — is now correctly handled. This is one boundary condition, not a flaw in the core approach. - Issue 1 (High). The
-
Recommended fixes — non-blocking
- Issue 2 (Medium): either extend the fix to cover failures inside
deployLocalTaskbefore publication (the natural place isdeployLocalTask's owncatchat:636, releasing what it was handed ifexecutionContexts.putnever ran), or correct the PR description to stop claiming this window is tested — right now the description overstates coverage. - Issue 3 (Low): once Issue 1's structural fix lands, revisit the Javadoc/comments so they describe the actual enforced invariant.
- Issue 4 (Low): consider a
WARNING-level log when cleanup runs against non-empty ledger entries for a task group that the trace shows already had a terminal state, to give operators a diagnostic trail if this class of race recurs elsewhere.
- Issue 2 (Medium): either extend the fix to cover failures inside
-
CI status
Both the apache-side
Buildcheck and the corresponding fork run (goutamadwant/seatunnel, run31925279099) are queued, no results yet, at32a7c757b.Notify test workflowandlabelerhave passed.mergeStateStatusisBLOCKED(review required),mergeableisMERGEABLE— the branch is 4 ahead / 4 behinddevwith no actual conflict. As noted in 2.2, a green run here would not retire Issue 1, since the current suite has no test that can produce the required interleaving.
On @nzw921rx's review: I independently re-derived the mechanism from source (the taskDone/recycleClassLoader removal at TaskExecutionService.java:1430-1433, the unguarded releaseClassLoader re-entry at DefaultClassLoaderService.java:103-132) and agree with the finding in full, including the "monotonic publication flag" direction for the fix. I'd add two things to what was reported: first, the consequence is conditional on non-cache mode plus a shared jar key across task groups — common in practice, but worth stating so the severity is calibrated correctly against the default configuration (cache mode limits the damage to accounting drift, no thread corruption). Second, since I'm the one who suggested the exact pattern that has this gap, I want to own that directly rather than let it read as solely the author's miss.
Overall assessment: Real, credited progress on every item from the last two rounds except the pre-publication deployLocalTask window (Issue 2 here), which remains open and whose PR-description claim needs correcting either way. The one blocking item is subtle and its own root cause is partly mine — I gave the suggestion that has the gap. I'd like to see the ownership signal made structural (not a racy map lookup) before this merges, given the failure mode is silent corruption of a different task group's running job. Thank you both for the careful back-and-forth on this — the classloader lifecycle in this file is genuinely tricky to get airtight, and this round of eyes is exactly what closes gaps like this.
Signed-off-by: goutamadwant <workwithgoutam@gmail.com>
|
@DanielLeens Fixed the ownership race. Once the execution context is published the deployment path no longer releases the classloader references, even if a short-lived task removes the context before deployTask returns. TaskExecutionServiceTest passes locally with 14 tests. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you for the quick turnaround, @goutamadwant — and thank you for the "Fixed the ownership race" summary. I re-derived the mechanism from source rather than taking the summary on trust, and the description is accurate: the ownership signal is now a monotonic AtomicBoolean set once, at publication, inside deployLocalTask itself, rather than a live executionContexts.containsKey(...) lookup that a concurrent taskDone() could falsify. That closes @nzw921rx's finding and my own Issue 1 from the previous round cleanly — details below. While re-tracing the surrounding control flow to verify that fix, I found one new problem in the same commit that is more severe than what it fixes, and one problem carried over unresolved for a fourth round. Both are detailed in the structured review.
This is a complete re-review of head 1976897f5b28bb961192ed160fe3e9c5d5be03be, re-traced from source, not carried over from my prior notes.
What Problem Does This PR Solve?
- User pain point:
TaskExecutionService.deployTask(...)acquires one reference-counted classloader per task, one at a time, inside a loop (TaskExecutionService.java:455-486). Before this PR existed, if a task failed during jar resolution, classloader creation, or deserialization, the outercatch (Throwable t)returnedTaskDeployState.failed(t)without releasing the references already acquired in that attempt — a permanent reference-count leak, worse (metaspace/handle exhaustion) underclassloader-cache-mode: false(issue #11808). - Fix approach, current head: an acquisition ledger
acquiredClassLoaderJars(:447) records what this attempt acquired (:474), drained byreleaseClassLoadersAfterFailedDeployment(...)from the outercatch(:534-535, helper at:556-571). The change in this commit is the ownership-transfer signal:deployLocalTask(...)now takes anonContextPublishedcallback (:588-593) that a private overload invokes immediately afterexecutionContexts.put(...)(:637-639). The caller sets a localAtomicBoolean classLoaderOwnershipTransferredfrom that callback (:519-527) and only clears the ledger if it observes the flag set — a monotonic, per-attempt signal instead of a racy map lookup. The commit also relocatesresultFuture.whenCompleteAsync(...)from afterdeployLocalTask'stry/catchto inside thetry, immediately after task submission (:641-666), so nothing can escapedeployLocalTaskuncaught once tasks are running. - One-sentence summary: The ownership-transfer race from the last round is now genuinely fixed — I verified the boolean is monotonic and cannot be fooled by a task group finishing early — but relocating
resultFuture.whenCompleteAsync(...)inside thetryas part of that fix has an unintended side effect: any exception thrown earlier indeployLocalTask'stry(task-group init, execution-context construction, task submission) now causes the method to return without ever registering the master-notification callback, so the master is never told the task group failed. That is a new, and more serious, correctness gap than the one being fixed.
1. Code Change Review
1.1 Core Logic Analysis
Scope, this commit relative to the previously reviewed head (32a7c757bd → 1976897f5b): one production file. Net diff: the ledger/publication wiring in deployTask (:446-447, :519-527), the new onContextPublished parameter threaded through both deployLocalTask overloads (:583-593), the callback invocation at publication (:639), and the relocation of resultFuture.whenCompleteAsync(...) into the try (:641-666 vs. its old position after the whole try/catch). No test file changes since the previous head; testDeployTaskReleasesClassLoadersWhenDeserializationFails fails during the acquisition loop, so it never reaches deployLocalTask and cannot exercise either change in this commit.
Verifying the ownership-transfer fix (nzw921rx's finding, my prior Issue 1)
[deploying thread] [worker thread running a submitted task]
deployTask(...) TaskGroupExecutionTracker.taskDone(Task)
519 AtomicBoolean classLoaderOwnershipTransferred -> completionLatch reaches 0
521 deployLocalTask(taskGroup, ..., taskJars, -> recycleClassLoader(location)
() -> classLoaderOwnershipTransferred releases all N references
.set(true)) -> finishedExecutionContexts.put(
| location, executionContexts
| [inside deployLocalTask] .remove(location))
| 637 executionContexts.put(location, ctx) -> future.complete(...)
| 639 onContextPublished.run() <-- flag set,
| permanently, right here
| 641-666 submitThreadShareTask/submitBlockingTask/
| resultFuture.whenCompleteAsync(...) <-- now INSIDE try; if this
| throws (executor rejects), caught at :667-669,
| swallowed, does NOT escape deployLocalTask
v
524 if (classLoaderOwnershipTransferred.get()) <-- reads the LOCAL flag, not the map
526 acquiredClassLoaderJars.clear()
528 return TaskDeployState.success()
I re-ran the exact race @nzw921rx described: task group publishes, all its tasks finish and taskDone() removes the executionContexts entry before the deploying thread reaches the ownership check, then something in deployLocalTask throws. Two things independently close the hole now, and I want to credit both explicitly:
classLoaderOwnershipTransferredis aset(true)-only flag read from a variable local to thisdeployTaskinvocation, not a lookup intoexecutionContextsthat a second thread (taskDone) also mutates. Once publication happens, the flag is permanently true for this attempt regardless of whattaskDonedoes to the map afterward. This is exactly the "monotonic ownership token" @nzw921rx asked for.- Independently, moving
resultFuture.whenCompleteAsync(...)insidedeployLocalTask's owntrymeans the specific trigger from my previous round — aRejectedExecutionExceptionescapingdeployLocalTaskafter publication because the callback dispatch is rejected — can no longer propagate todeployTask'scatchat all. It is caught and swallowed at:667-669, insidedeployLocalTask, beforedeployTaskever sees it. Even without item 1, this alone would have closed the specific escape I found last round.
With both defenses in place I could not reconstruct any interleaving in which deployTask's outer catch sees a live, in-use TaskGroupContext's references in the ledger. This part of the fix is correct and I verified it independently rather than trusting the summary.
The new gap: notifyTaskStatusToMaster is silently skipped for failures inside deployLocalTask's try
This is not a race and does not need a specific interleaving — it is plain, deterministic Java control flow, so my confidence here is high, unlike the JDK-internals-dependent finding from last round.
Before this commit (verified against head 32a7c757bd, the one I reviewed last round), resultFuture.whenCompleteAsync(...) sat after deployLocalTask's try/catch block entirely — it ran unconditionally, whether the try succeeded or the catch at :667-669-equivalent had already run resultFuture.completeExceptionally(t). Because whenCompleteAsync on an already-completed future dispatches immediately, this was the mechanism by which the master learned, asynchronously, that a task group had failed to deploy locally — via notifyTaskStatusToMaster(location, r) inside the callback, using a synthesized ExecutionState.FAILED result when r == null. This was true regardless of where inside deployLocalTask the failure occurred: taskGroup.init() (:596, which fans out to per-task init() — connector connection setup, config validation, resource allocation — genuinely reachable production failure modes, not synthetic ones), the TaskExecutionContext construction in the peek() (:610-616), or task submission itself.
In this commit, resultFuture.whenCompleteAsync(...) was moved to inside the try, positioned after executionContexts.put(...) (:637), submitThreadShareTask/submitBlockingTask (:642-643), and taskGroup.setTasksContext(...) (:644). Consequently: if taskGroup.init() throws at :596, or the TaskExecutionContext construction throws inside the stream at :610-616, or createTaskGroup's prerequisites fail before :637, control jumps straight to the catch (Throwable t) at :667, which logs and calls resultFuture.completeExceptionally(t) — and returns. The whenCompleteAsync registration is never reached, for any exception raised before it in the try. No callback is ever attached to resultFuture, so notifyTaskStatusToMaster is never called, for this class of failure.
The combined effect: deployTask's own catch is never reached either (deployLocalTask never rethrows — same swallow-and-return behavior as every previous round), so deployTask returns TaskDeployState.success() to the master synchronously, and, as of this commit, the master will now never receive the asynchronous terminal-state notification that used to follow. Previously the master was lied to briefly and then corrected; now it is lied to and never corrected. From the master's point of view, a task group whose local deployment failed inside taskGroup.init() looks identical to one that is deployed and silently hung — there is nothing in this file that will ever tell the master otherwise for this task group. I did not trace the master-side heartbeat/liveness logic (out of scope for this file), so I can't say whether some other independent mechanism eventually notices; what I can say with certainty from this file alone is that the one notification path that existed for this exact scenario before this commit no longer fires.
I am treating this as a blocker. It is a new correctness regression introduced by the very code that fixes the ownership race — the kind of "fixed A, broke B" outcome that is easy to miss when the two changes (ledger ownership, notification timing) are reviewed as one diff instead of two separable concerns, and I want to be upfront that I did not catch this shape of problem until tracing the relocated statement line by line against every throw site above it.
- Confidence: High. This does not depend on JDK internals or timing — it is sequential control flow: statements after a thrown exception in a
tryblock do not execute, full stop. - Scope check:
deployLocalTaskhas no other production callers (public PassiveCompletableFuture<TaskExecutionState> deployLocalTask(TaskGroup, classLoaders, jars)at:582-586is only called fromdeployTaskand directly fromTaskExecutionServiceTest), so the blast radius is confined to this deployment path, not spread across the engine. - Why existing tests don't catch it: none of the current tests assert on
notifyTaskStatusToMasterinvocation or its absence; the one new regression test in this PR fails during the acquisition loop, beforedeployLocalTaskis ever called, so it cannot exercise this path.
Issue carried over for the fourth round: failures inside deployLocalTask before publication still leak classloader references
This is unchanged in substance from rounds 2–4, but I re-verified it against the current head because the PR description's wording changed again and I want to be precise about what is and isn't true now.
deployLocalTask catches Throwable at :667-669 and returns normally — it still never rethrows, with or without this commit's changes. Back in deployTask, control reaches :524 (if (classLoaderOwnershipTransferred.get())). If the failure happened before :639 (onContextPublished.run()), the flag is false, so the ledger is not cleared — but note carefully what happens next: deployTask does not check the flag's negation and call the release helper; it simply falls through to :528 return TaskDeployState.success(). The release helper (releaseClassLoadersAfterFailedDeployment) is only ever invoked from deployTask's own catch (:534-535), and that catch is never reached, because deployLocalTask doesn't throw. The ledger's still-populated contents are simply discarded when the local variable goes out of scope — never released, never even logged. This is functionally identical to the leak issue #11808 describes, just relocated to a narrower window.
The current PR description says: "releases all acquired references after a failure before context publication." That is not accurate for failures that occur inside deployLocalTask before publication — those are swallowed by deployLocalTask's own catch, not by deployTask's. It is accurate only for failures raised in deployTask's own acquisition loop and createTaskGroup call, which is exactly what the new test exercises. I raised the same description-accuracy concern in the last two rounds; I'd ask that it either be corrected precisely (the covered window is "before deployLocalTask is entered", not "before context publication") or that the fix be extended to cover it — the natural place is deployLocalTask's own catch at :667, which could call the same release helper for whatever was acquired if onContextPublished never ran.
Is the ledger accounting on the paths this PR actually targets still sound?
Yes, re-verified independently against this head. The append at :474 happens only after getClassLoader returns successfully; getClassLoader cannot partially acquire (DefaultClassLoaderService.java:71-72 vs. :94-98); and on the paths that trigger deployTask's outer catch — jar resolution, classloader construction, deserialization, createTaskGroup — the helper releases exactly what this attempt acquired and nothing more. No double-release, no release-before-use, on these paths.
1.2 Compatibility Impact
No public API, SPI, Option, serialization format, or checkpoint/savepoint surface changes — same conclusion as every previous round, re-verified: TaskGroupImmutableInformation/TaskDeployState payloads are untouched, TaskGroupContext remains node-local and non-serializable, covertJarsToKey remains type/order-insensitive. The two new parameters on deployLocalTask are additive via an overload; the public 3-arg signature is unchanged.
The one new item for this round: the notification-loss gap in section 1.1 is a behavioral regression relative to the pre-commit code, not merely relative to "no leak" — it removes an existing asynchronous failure-notification guarantee for a specific window. I am not calling the whole PR incompatible, since the affected window (failures inside deployLocalTask, before or shortly after publication) is narrow and was already a known gap for the classloader side of things, but the notification side of this specific regression did not exist before this commit and should not ship silently.
1.3 Performance / Side-Effect Analysis
No new allocation patterns beyond what was reviewed previously (one ArrayList per deployment, one AtomicBoolean per attempt — negligible, not a hot path). Thread.getAllStackTraces() in recycleClassLoaderFromThread (non-cache mode only) is unchanged from earlier rounds and remains an accepted trade-off.
1.4 Error Handling and Logging
The per-entry try, suppressed-exception attachment, and continue-past-failure behavior in releaseClassLoadersAfterFailedDeployment are unchanged and remain the pattern I'd want to see. The gap in this round is specifically the absence of any log line when deployLocalTask swallows a Throwable at :667-669 and the ownership flag was never set — the operator sees logger.severe(ExceptionUtils.getMessage(t)) at that catch, so the failure itself is logged, but nothing indicates that (a) the classloader references for this attempt are about to be silently leaked, or (b) the master will not be told. Both consequences are invisible from the log line alone.
2. Code Quality Assessment
2.1 Coding Standards
Google Java Format / Spotless conventions respected. No wildcard imports; no unused imports. The Javadoc on releaseClassLoadersAfterFailedDeployment is unchanged and still accurate for the paths it actually covers. The new onContextPublished parameter and its call site are unnamed beyond the parameter name itself — a one-line comment at :639 stating "ownership transfers to the caller's ledger-clearing decision at this exact point, before any further code in this method can fail" would help the next reader see why this line's position matters as much as its presence.
2.2 Test Coverage and Test Stability
Stability rating: Stable for what is tested; unchanged from last round since no test file changes landed in this commit. testDeployTaskReleasesClassLoadersWhenDeserializationFails continues to be order-independent and discriminating (re-verified: unique temp-jar cache key, queryClassLoaderById(...).isPresent() positive assertion, testJar.delete() cleanup).
Coverage gap specific to this round: there is no test for either finding in section 1.1 — not the (now fixed) ownership race, and not the new notification-loss gap. Both require forcing a failure inside deployLocalTask's try (e.g., a TaskGroup whose init() throws), which none of the current tests do; every existing deployLocalTask/deployTask test path either succeeds or fails during acquisition/createTaskGroup, before deployLocalTask is ever entered. I'd specifically ask for one test that forces taskGroup.init() to throw and then asserts notifyTaskStatusToMaster-equivalent behavior (or, more testably, that resultFuture has no listeners / that no NotifyTaskStatusOperation is ever sent) — that test would fail against the current head and pass once the gap is closed, which is exactly the property a regression test needs.
2.3 Documentation Updates
None required for docs/en/docs/zh — correct, internal engine cleanup. The PR description still needs the correction noted in section 1.1 (the "releases all acquired references after a failure before context publication" claim overstates coverage for the deployLocalTask-internal window) — this has now been requested in three consecutive rounds; I'd ask that it be resolved one way or the other (fix the code, or fix the sentence) before merge.
3. Architectural Soundness
3.1 Elegance of the Solution
The monotonic-flag approach for ownership transfer is the right fix for the race, and threading it through as a callback parameter (onContextPublished) rather than reaching into executionContexts from the caller is a clean way to make the signal originate at the exact statement that constitutes the transfer, rather than at a later, possibly-stale observation of it. This is a genuine improvement over both my own suggested finally+containsKey fix from round 3 and the interim containsKey-in-finally version from round 4 — it fixes the problem at its source rather than trying to infer it after the fact.
The relocation of resultFuture.whenCompleteAsync(...) was the second half of closing the ownership race (my "complementary hardening" suggestion from round 4), and it does close that race. But it conflates two responsibilities that deserved to be separated: "make sure nothing escapes deployLocalTask uncaught" and "make sure the master is always eventually told the outcome." The old code accidentally got the second one right by having the registration sit outside the try/catch entirely; the new code correctly gets the first one right but loses the second as a side effect. The fix for both simultaneously is to keep the registration where it now is (inside the try, so nothing can throw past it) but also register it (or an equivalent notification) from the catch block at :667-669 for the case where the try never reached it — e.g., calling resultFuture.whenCompleteAsync(...) from inside the catch too, since at that point resultFuture is already exceptionally complete and the callback will fire immediately, or simply calling notifyTaskStatusToMaster directly from the catch with a synthesized FAILED state.
3.2 Maintainability
deployTask/deployLocalTask now coordinate ownership through three mechanisms that all need to stay consistent: the ledger, the AtomicBoolean flag, and (unrelated to classloaders but living in the same method) the master-notification callback. All three are now correctly scoped to avoid the specific races found so far, but the method has grown enough moving parts that a written-down invariant list at the top of deployTask/deployLocalTask — "ledger cleared iff ownership flag set; notification always attempted iff try reaches the registration statement; catch swallows and never rethrows" — would materially help the next person touching this code avoid reintroducing exactly this class of "fixed one path, broke an adjacent one" issue.
3.3 Extensibility
Neutral — no new abstraction introduced beyond the callback parameter, which is proportionate to the problem.
3.4 Historical-Version Compatibility
No change to wire format, checkpoint/savepoint, or configuration surface. Nothing here affects rolling upgrade or mixed-version clusters.
4. Issue Summary
| # | Issue | Location | Severity | Raised by another reviewer |
|---|---|---|---|---|
| 1 | Relocating resultFuture.whenCompleteAsync(...) inside deployLocalTask's try (done to fix the ownership race) means any exception thrown earlier in that try (taskGroup.init(), TaskExecutionContext construction, task submission) now skips registering the notification callback entirely — notifyTaskStatusToMaster is never called, and the master is never told the task group failed, whereas before this commit it eventually was. |
TaskExecutionService.java:596, :610-616, :637-644, :641-666, :667-669 |
High | No |
| 2 | Failures inside deployLocalTask before context publication are still swallowed by its own catch and never reach deployTask's release helper; the ledger's contents are discarded without release. PR description's coverage claim remains inaccurate for this window. |
TaskExecutionService.java:519-528, :667-669 |
Medium (carried from rounds 2-4, still open) | No |
| — | (Resolved this round) Ownership-transfer race: containsKey(...) replaced by a monotonic per-attempt AtomicBoolean set from a callback invoked immediately at publication; independently, the escape trigger from round 4 (whenCompleteAsync throwing after publication) can no longer propagate out of deployLocalTask. Verified both independently. |
TaskExecutionService.java:519-527, :588-593, :639 |
— | Yes — @nzw921rx (round 3), confirmed and extended by me (round 4) |
Totals: 1 High (new), 1 Medium (carried). Resolved since last round: the ownership-transfer race (Issue 1 from round 4).
5. Merge Recommendation
Conclusion: Not recommended for merge
-
Blockers — must be fixed
- Issue 1 (High) — silent loss of master failure notification. This is the more serious of the two open items precisely because it is a regression introduced by fixing something else: before this commit, a task group that failed inside
deployLocalTaskwas at least eventually reported to the master asFAILEDvia the (previously unconditional)whenCompleteAsyncregistration. After this commit, that registration is skipped whenever the failure occurs before it in thetry, and nothing replaces it. The master will believe the task group deployed successfully (sincedeployTaskstill returnsTaskDeployState.success()in this case) and will never receive a correction. I'd ask for thecatchat:667-669to also drive the master notification — either by invokingresultFuture.whenCompleteAsync(...)there too (safe, since the future is already exceptionally complete and the callback fires immediately), or by callingnotifyTaskStatusToMasterdirectly with a synthesizedFAILEDstate, matching what the relocated registration would have produced had it been reached.
To be explicit about what is not wrong, since the ownership-transfer race was the headline finding of the last two rounds: I independently re-derived the monotonic-flag mechanism and I agree it correctly closes both my Issue 1 (round 4) and @nzw921rx's finding (round 3). No double-release, no premature release, and no leak newly introduced on the paths this PR's core ledger logic targets. That part of the fix is sound and should be kept exactly as it is.
- Issue 1 (High) — silent loss of master failure notification. This is the more serious of the two open items precisely because it is a regression introduced by fixing something else: before this commit, a task group that failed inside
-
Recommended fixes — non-blocking
- Issue 2 (Medium, carried): either extend coverage to
deployLocalTask's own pre-publication failures (natural site: itscatchat:667, releasing whatever was passed in ifonContextPublishednever ran), or correct the PR description to state precisely which window is covered. This has now been flagged in rounds 2, 3, and 4 without a code or description change; I'd like to see it resolved one way or the other this round. - Add a regression test that forces
taskGroup.init()(or equivalent) to throw insidedeployLocalTask, and assert on the resulting notification behavior — this would have caught Issue 1 directly and would also serve as the regression test for Issue 2 once it's addressed.
- Issue 2 (Medium, carried): either extend coverage to
-
CI status
The apache-side
Buildcheck for1976897f5bis FAILURE. Tracing it to the actual result (the apache-side check is a pointer; the real run is in the fork):goutamadwant/seatunnelrun31960886951. Every job passed exceptRun / unit-test (8, windows-latest)(job95198879119), which failed withjava.lang.IllegalStateException: Node failed to start!after a 311-second hang inorg.apache.seatunnel.engine.server.operation.GetNodeHttpPortOperationTest— a class completely unrelated to this PR's diff. I checked the log directly:TaskExecutionServiceTest, the class this PR actually touches, ran and passed all 14 tests in the same job before the unrelated failure occurred later in the suite. This matches a Windows-Hazelcast-node-startup flake I've now seen across four different, unrelated test classes in this module onwindows-latest; it is environmental, not caused by this PR's diff. CI failure is not attributable to this change. Separately, and more importantly: CI passing here would not have caught either open issue regardless, since neither the ownership-transfer race nor the notification-loss gap has a test that can currently produce the required failure interleaving.
Overall assessment: The ownership-transfer fix in this commit is well-conceived and, having re-derived it from source rather than trusting the description, I'm confident it correctly closes the race @nzw921rx found and the escape I found last round — using a monotonic per-attempt signal instead of a shared-state lookup is the right structural answer, and threading it through as a callback invoked at the exact moment of transfer is cleaner than either of our earlier suggestions. What holds this back is that the second half of the same commit — relocating the notification registration to make that fix safe — quietly drops the one mechanism that told the master about a class of failure this file has never fully handled. I don't think this was reachable without tracing every throw site against the new statement order line by line, and I want to be clear that this is a fresh finding on fresh code, not something anyone missed earlier. Please close the notification gap (or explicitly scope the fix so it can't be reached) and resolve the three-round-old description/coverage question on Issue 2, and this is very close to a clean merge — the core classloader-lifecycle work is now, to the best of my ability to verify statically, correct.
Signed-off-by: goutamadwant <workwithgoutam@gmail.com>
|
@DanielLeens addressed both deployment failure paths The completion callback is registered before local deployment can fail. Failures before TaskGroupContext publication release only the references acquired by that attempt while published contexts remain owned by the normal lifecycle Added a regression for context initialization failure which verifies the refcount returns to zero and FAILED is still reported. TaskExecutionServiceTest passes with 15 tests |
DanielLeens
left a comment
There was a problem hiding this comment.
Thank you, @goutamadwant — I re-read the whole file from scratch against current dev (not just the delta) and re-derived the new commit's mechanism from source rather than trusting the summary comment. "Fix pre-publication task deployment failure handling" closes both open items from my last review — the High-severity silent loss of the master notification, and the Medium carried-over pre-publication classloader leak — with a single, well-targeted change plus a new regression test that exercises exactly the failure class that caused both problems. I could not find a new issue while tracing it.
This is a complete re-review of head d638bd37bce0f5595bb45a4532f8d92ebfec5e3f, re-traced from source.
What Problem Does This PR Solve?
- User pain point:
TaskExecutionService.deployTask(...)acquires one reference-counted classloader per task, one at a time, inside a loop. Before this PR existed, if a task failed during jar resolution, classloader creation, or deserialization, the outercatch (Throwable t)returnedTaskDeployState.failed(t)without releasing the references already acquired in that attempt — a permanent reference-count leak, worse (metaspace/handle exhaustion) underclassloader-cache-mode: false(issue #11808). - Fix approach, current head: on top of the previously-verified acquisition ledger and monotonic ownership-transfer flag (
AtomicBoolean classLoaderOwnershipTransferred, unchanged this round), this commit adds a second callback,onFailureBeforeContextPublished: Consumer<Throwable>, threaded intodeployLocalTask(...)alongside the existingonContextPublishedcallback. A new localboolean contextPublished(unrelated to theAtomicBoolean, scoped todeployLocalTaskitself) is settrueimmediately afterexecutionContexts.put(...)succeeds. IfdeployLocalTask'scatch (Throwable t)is reached withcontextPublishedstillfalse, it now invokesonFailureBeforeContextPublished.accept(t), whichdeployTaskwires toreleaseClassLoadersAfterFailedDeployment(...)followed byacquiredClassLoaderJars.clear()— released synchronously, on the deploying thread, beforedeployLocalTaskreturns. Separately,resultFuture.whenCompleteAsync(...)— previously positioned after the wholetry/catch(before last round) and then, as of last round's commit, moved inside thetryafter context publication (the regression I flagged) — is now registered as the very first statement indeployLocalTask, before thetryblock even begins. - One-sentence summary: Both problems I raised last round are fixed at their root: the notification callback is now registered unconditionally before anything in the method can throw, so it always fires exactly once regardless of where a failure occurs; and the classloader ledger is now explicitly released from inside
deployLocalTask's owncatchwhenever a failure happens before publication, closing the four-round-old carryover gap instead of just re-describing it.
1. Code Change Review
1.1 Core Logic Analysis
Scope, this commit relative to the previously reviewed head (1976897f5b → d638bd37bce): one production file (TaskExecutionService.java, net +91/-29 across this commit) plus one new test in TaskExecutionServiceTest.java. git diff 1976897f5b..d638bd37bce -- .../TaskExecutionService.java confirms the changes are: a new Consumer<Throwable> parameter on both deployLocalTask overloads, the contextPublished local boolean and its use at the (unchanged-position) executionContexts.put(...) call, the relocation of resultFuture.whenCompleteAsync(...) to the top of the method, and the new lambda at the deployTask call site that wires the classloader release into the new callback. notifyTaskStatusToMaster's visibility was also widened from private to package-private, purely to let the new test spy on it with Mockito — a minimal, low-risk change scoped to testability, not to the public API surface (the method was never public, and remains inaccessible outside this package).
Verifying the fix for the notification-loss regression (my prior Issue 1, High)
Before this commit (the head I reviewed last round), the sequence was: try { ...; executionContexts.put(...); onContextPublished.run(); submitThreadShareTask(...); submitBlockingTask(...); taskGroup.setTasksContext(...); resultFuture.whenCompleteAsync(...); } catch (Throwable t) { ...; resultFuture.completeExceptionally(t); }. Any exception thrown before the whenCompleteAsync line — taskGroup.init(), the TaskExecutionContext construction in the .peek(...), or anything before :637-equivalent — jumped straight to catch, and the registration statement was simply never reached, so notifyTaskStatusToMaster was never invoked for that failure class.
On this head, the registration is the first statement inside deployLocalTask, before boolean contextPublished = false; and before the try even opens:
CompletableFuture<TaskExecutionState> resultFuture = new CompletableFuture<>();
resultFuture.whenCompleteAsync(withTryCatch(logger, (r, s) -> { ... notifyTaskStatusToMaster(...); }), ...);
boolean contextPublished = false;
try {
taskGroup.init();
...Since resultFuture cannot be completed (successfully or exceptionally) by anything before this registration runs — nothing holds a reference to it yet — there is no ordering hazard: the callback is attached before the future can possibly resolve, for every code path through the method, success or failure, regardless of where in the try a Throwable originates. I traced every throw site that concerned me last round (taskGroup.init(), the TaskExecutionContext construction stream, executionContexts.put(...), submitThreadShareTask/submitBlockingTask, taskGroup.setTasksContext(...)) and confirmed each one now reaches catch (Throwable t) { ...; resultFuture.completeExceptionally(t); }, which fires the already-registered callback and calls notifyTaskStatusToMaster with a synthesized FAILED state exactly as it did before this PR's ownership-transfer work ever touched this method. This is not merely "as good as before" — it is architecturally more robust than the pre-PR code, which relied on registration position (after the try/catch) to get the same unconditional guarantee; this head gets the same guarantee independent of statement ordering within the try, which is why it survives the exact class of "fixed A, broke B" mistake that caused last round's regression.
Verifying the fix for the pre-publication classloader leak (my prior Issue 2, Medium, carried 4 rounds)
Last round: a failure inside deployLocalTask before executionContexts.put(...) was swallowed by deployLocalTask's own catch, which never rethrew — so deployTask's classLoaderOwnershipTransferred.get() check (reading the flag set only by onContextPublished) was false, but nothing in deployTask acted on the negative case; the ledger's contents were silently discarded when the local variable went out of scope.
This head closes it directly at the source: contextPublished is false until immediately after executionContexts.put(...) succeeds; the catch block now reads:
} catch (Throwable t) {
logger.severe(ExceptionUtils.getMessage(t));
if (!contextPublished) {
onFailureBeforeContextPublished.accept(t);
}
resultFuture.completeExceptionally(t);
}and deployTask's call site wires the callback to the exact release helper I asked for:
deployLocalTask(
taskGroup, classLoaders, taskJars,
() -> classLoaderOwnershipTransferred.set(true),
failure -> {
releaseClassLoadersAfterFailedDeployment(
taskImmutableInfo.getJobId(), acquiredClassLoaderJars, failure);
acquiredClassLoaderJars.clear();
});I checked the ordering around the transfer point specifically for a race between contextPublished = true and onContextPublished.run(): both are two adjacent statements (a boolean assignment, which cannot throw, followed immediately by the call), so there is no window in which one is true and the other isn't from a failure between them — they are effectively atomic for this purpose. I also checked for double-release: if the failure happens after publication (contextPublished == true), onFailureBeforeContextPublished is not invoked (the if guards it), and back in deployTask, classLoaderOwnershipTransferred.get() is true, so acquiredClassLoaderJars.clear() runs there without releasing — correct, since ownership already transferred to the published context and its own lifecycle (eventual taskDone()/cancellation) owns the release. If the failure happens before publication, the new callback both releases and clears the ledger synchronously inside deployLocalTask; back in deployTask, the ownership flag is false so the outer if is skipped, and acquiredClassLoaderJars is already empty — no double release, no leak, in either branch.
Is the deploy-success / already-transferred accounting still sound?
Yes, re-verified. deployTask still returns TaskDeployState.success() unconditionally once deployLocalTask returns (it never rethrows, before or after this commit) — this is pre-existing behavior, not something this PR introduced or is expected to change; the actual terminal outcome is still communicated asynchronously via notifyTaskStatusToMaster, which is exactly the mechanism this commit restores end-to-end. The acquisition-loop and createTaskGroup-level failures (which never reach deployLocalTask at all) are unaffected by this commit and remain covered by deployTask's own outer catch and the original regression test from two rounds ago.
1.2 Compatibility Impact
No public API, SPI, Option, serialization format, or checkpoint/savepoint surface changes — same conclusion as every previous round. The widened visibility of notifyTaskStatusToMaster (private → package-private) is an internal detail with no external consumer; deployLocalTask's public 3-arg overload is preserved unchanged and still delegates to the new 5-arg private overload with no-op callbacks, so any existing internal or test caller of the public signature is unaffected.
This round is, from a compatibility standpoint, a regression fix relative to last round's own diff, not a new-behavior change relative to dev: it restores the master-notification guarantee that existed before this PR's ownership-transfer work and had been temporarily broken by it. Nothing here changes behavior relative to dev HEAD in a way that needs documenting.
1.3 Performance / Side-Effect Analysis
No new allocation patterns beyond what was already reviewed (ArrayList, AtomicBoolean, and now one Consumer lambda per deployment attempt — negligible, not a hot path). Registering resultFuture.whenCompleteAsync(...) slightly earlier in the method (before try instead of after it, or instead of conditionally inside it) has no measurable cost difference — it's the same single registration call, just moved.
1.4 Error Handling and Logging
This is the one place I'd ask for a small, non-blocking improvement: releaseClassLoadersAfterFailedDeployment's existing per-entry try/suppressed-exception pattern is unchanged and still correct. But when onFailureBeforeContextPublished releases the ledger from inside deployLocalTask's catch, there's no log line distinguishing "released before publication" from the general logger.severe(ExceptionUtils.getMessage(t)) already emitted one line above — an operator reading the log can't currently tell, from this method's output alone, whether the classloader references for a given failed attempt were released or (in some future regression) silently dropped again. A one-line logger.info/logger.fine inside the new callback (e.g., "released N classloader jar(s) for pre-publication deployment failure") would make this branch self-documenting and give future changes here a log-based tripwire, but I don't consider this blocking — the correctness is verified structurally, not just by inference from logs.
2. Code Quality Assessment
2.1 Coding Standards
Google Java Format / Spotless conventions respected. No wildcard imports; the new java.util.function.Consumer import is used and necessary. Parameter naming (onContextPublished, onFailureBeforeContextPublished) is self-explanatory and consistent with the existing Runnable onContextPublished naming from last round.
2.2 Test Coverage and Test Stability
Stability rating: Stable. The new test, testDeployTaskHandlesFailureBeforeContextPublication, is exactly the test I asked for last round: it introduces a ContextInitializationFailureTask whose setTaskExecutionContext(...) throws IllegalStateException, which fires inside deployLocalTask's .peek(...) stream, after taskGroup.init() but before executionContexts.put(...) — precisely the failure class that caused both issues last round. It asserts, all without a hard Thread.sleep:
taskDeployStateequalsTaskDeployState.success()(matches the unchanged synchronous-success/asynchronous-notification design),- the context was never published (
Assertions.assertThrows(TaskGroupContextNotFoundException.class, () -> taskExecutionService.getActiveExecutionContext(location))), - the classloader still exists but its reference count is back to
0(classLoaderService.queryClassLoaderReferenceCount(testJobId, testJars)) — directly proving the leak is closed, not just that no exception was thrown, notifyTaskStatusToMasterwas eventually invoked with aFAILEDstate, viaMockito.verify(taskExecutionService, Mockito.timeout(5000))...— a bounded, non-flaky wait on the async callback, directly proving the notification gap is closed.
This test would have failed against last round's head on the last assertion (no notifyTaskStatusToMaster call at all for this failure class) and on the reference-count assertion (ledger discarded without release) — exactly the property a regression test needs. The testJobId = System.currentTimeMillis() pattern matches the existing, previously-reviewed testDeployTaskReleasesClassLoadersWhenDeserializationFails test in this same file, so it's a consistent, already-accepted convention, not a new risk. Temp-file cleanup (deleteOnExit() plus explicit .delete()) is present. I see no order-dependence, no floating-point comparisons, and no weak readiness signal — Mockito.verify(..., timeout(...)) polls for the actual assertion rather than sleeping a fixed duration.
Coverage note: this test specifically exercises the pre-executionContexts.put(...) window. It does not add coverage for a failure occurring between executionContexts.put(...) and submitThreadShareTask/submitBlockingTask (i.e., after contextPublished = true but before the tasks are actually running) — but I traced that window above and found no code-level way for it to reach the new callback incorrectly, and the existing ownership-transfer test coverage from two rounds ago already covers the "context published, then something downstream fails" shape at a higher level. Not blocking.
2.3 Documentation Updates
None required for docs/en/docs/zh — correct, internal engine cleanup with no user-visible behavior or config change.
3. Architectural Soundness
3.1 Elegance of the Solution
Registering the notification callback as the very first statement in the method — before the local state (contextPublished) is even initialized — is a stronger fix than either option I suggested last round (re-registering from the catch, or calling notifyTaskStatusToMaster directly from the catch). Both of my suggestions would have required either a second registration site (risking double-invocation bugs of their own) or duplicating the callback's state-synthesis logic. This head instead removes the ordering dependency entirely: one registration, unconditionally first, so no future edit to the try body can silently reintroduce the same class of gap by adding a new early-return or early-throw path above the registration — because there is no code above it to add a path in front of.
3.2 Maintainability
This directly addresses the invariant-list concern I raised last round: the three previously-coordinating mechanisms (ledger, ownership flag, notification callback) are now each scoped to a single, unconditional trigger point instead of being order-dependent on each other — notification is registered unconditionally at method entry; ownership transfer and its associated ledger-clearing are tied to the single executionContexts.put(...) statement; pre-publication release is tied to the same contextPublished flag from the opposite direction. A future reader can verify each invariant locally without needing to trace statement order through the rest of the method, which is exactly the property that was missing last round.
3.3 Extensibility
Neutral — the second callback parameter is proportionate to the problem and mirrors the existing onContextPublished pattern rather than introducing a new abstraction.
3.4 Historical-Version Compatibility
No change to wire format, checkpoint/savepoint, or configuration surface. This commit only affects a single-node deployment-failure code path inside the worker.
4. Issue Summary
No open blocking issues. Both previously-open issues are resolved on this head:
| # | Previously | Location | Status |
|---|---|---|---|
| 1 | Relocating resultFuture.whenCompleteAsync(...) inside deployLocalTask's try (last round's ownership-race fix) skipped registering the notification callback for any exception thrown earlier in the try; notifyTaskStatusToMaster was never called for that failure class. (High) |
TaskExecutionService.java, deployLocalTask |
Fixed — registration moved to the first statement in the method, before the try opens; verified unconditional for every throw site I previously traced. |
| 2 | Failures inside deployLocalTask before context publication were swallowed by its own catch and never reached deployTask's release helper; the ledger's contents were discarded without release. Carried from rounds 2-4. (Medium) |
TaskExecutionService.java, deployLocalTask/deployTask |
Fixed — new onFailureBeforeContextPublished callback, gated on the new contextPublished flag, releases and clears the ledger synchronously from deployLocalTask's own catch. |
| — | (Resolved two rounds ago, re-confirmed unaffected this round) Ownership-transfer race: monotonic per-attempt AtomicBoolean set from a callback invoked immediately at publication. |
TaskExecutionService.java |
Unaffected by this commit; still correct. Raised by another reviewer: Yes — @nzw921rx. |
Recommended, non-blocking:
- A one-line log statement inside
onFailureBeforeContextPublished's call site distinguishing "released before publication" from the general failure log, for future operability (section 1.4).
5. Merge Recommendation
Conclusion: Ready to merge
-
Blockers — must be fixed:
- None.
-
Recommended fixes — non-blocking:
- Add a log line when the pre-publication release path runs, so the classloader-release outcome is visible from logs alone rather than only provable by static tracing (section 1.4).
-
CI status
The apache-side
Buildcheck ford638bd37bceis currently queued/in-progress on the fork (goutamadwant/seatunnelrun against this head) at review time — I'm reporting this as pending, not assuming an outcome. The previous head (1976897f5b)'s only CI failure was theRun / unit-test (8, windows-latest)Hazelcast-node-startup flake I diagnosed last round as environmental and unrelated to this PR's diff (TaskExecutionServiceTestitself passed all tests in that same job before the unrelated failure); I have no reason to expect a different class of failure this round, but I'm not calling CI green until it actually reports green.
Overall assessment: This is the fix I asked for last round, implemented at the right level — moving the notification registration to the top of the method rather than re-registering from the catch — which is structurally more robust than what I suggested, and closing the four-round-old pre-publication leak with a direct, symmetric callback rather than another partial description-only update. The new regression test exercises exactly the failure class that caused both problems and would have failed against last round's head on two independent assertions. I traced every throw site and every ordering question I could identify and found no new gap. Nice work getting this fully closed out.
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point:
TaskExecutionService.deployTask(...)acquires one reference-counted classloader per task. Before this PR, a failure during jar resolution, deserialization,createTaskGroup, or anywhere insidedeployLocalTaskbefore theTaskGroupContextwas published could leave those references permanently un-released — a slow metaspace/file-handle leak underclassloader-cache-mode: false(issue #11808). - Fix approach: an acquisition ledger (
acquiredClassLoaderJars) scoped to the current attempt, released through the outercatchfor failures beforedeployLocalTaskis even entered, and through a newonFailureBeforeContextPublishedcallback (gated by acontextPublishedflag) for failures insidedeployLocalTaskbefore the context is published. Ownership handover to the publishedTaskGroupContextis tracked by a per-attemptAtomicBoolean, and the master-notification callback is now registered unconditionally as the very first statement indeployLocalTask, closing a related regression from an earlier round of this PR. - One-sentence summary: every failure branch on the deployment path now has exactly one correct outcome — release, or hand off to the published context's own lifecycle — with no double-release and no leak.
This is a verification pass, not a new independent review
I re-derived the source myself rather than trusting the PR history: git diff d638bd37bce0f5595bb45a4532f8d92ebfec5e3f e76825afe719900ee53a9590cbf4a84de3d150e1 (my last fully-reviewed and approved head vs. the current head) returns zero files changed. The new commit (e76825afe7, "[Chore] Retrigger CI for PR #11812") is an empty commit — there is no code delta to re-review. So instead of re-publishing an identical multi-thousand-word analysis, I re-read TaskExecutionService.java and TaskExecutionServiceTest.java at the current head from scratch (not the diff, the whole file) to independently re-confirm the conclusion from my previous approval still holds against this exact byte-for-byte content:
- Complete runtime path, re-verified: every exit from
deployTask(...)now balances acquire/release correctly — acquisition-loop /createTaskGroupfailures release via the outercatch(TaskExecutionService.java:541-543); pre-publicationdeployLocalTaskfailures (taskGroup.init(),TaskExecutionContextconstruction) release viaonFailureBeforeContextPublished, gated oncontextPublished(:681-687); post-publication outcomes clear the local ledger without releasing, because ownership has transferred to the publishedTaskGroupContext, whose own lifecycle (taskDone()→recycleClassLoader()) owns the eventual release (:536-538). ThecontextPublished = true; onContextPublished.run();pair (:672-673) is two non-throwing statements executed back-to-back, so there is no window in which the release-callback and the ownership-transfer flag disagree — I checked this specifically for the double-release/use-after-release risk and found none, on any branch. - Master-failover / idempotent-redeploy branch: unaffected — it returns before
deployLocalTaskis ever called, so it can't interact with the new callback mechanism. - Successful path: unchanged in externally observable behavior; the only difference is bookkeeping (
AtomicBoolean,Consumerlambda) that never surfaces outside the method. - Test coverage, re-confirmed: both
testDeployTaskReleasesClassLoadersWhenDeserializationFailsandtestDeployTaskHandlesFailureBeforeContextPublicationkey off a unique per-test temp-jar URL (Collections.singleton(testJarUrl)), not the empty-jars key that made the round-1 version of this test order-dependent againstcacheMode's job-id normalization. The async-notification assertion usesMockito.verify(..., Mockito.timeout(5000)), a bounded poll, not a hard sleep. Stability rating: Stable, unchanged from last round.
No new issue, no reopened issue. My conclusion from the previous round stands unmodified: no blocking issues, no double-release, no leak newly introduced or left open on any reachable path.
Closing the loop on CI
My previous approval explicitly said "I'm not calling CI green until it actually reports green." That was still open, so I ran it down rather than leaving it stale:
- The
Buildrun ford638bd37bce(the head I approved) did complete, and it failed — two jobs:Run / unit-test (11, windows-latest)andRun / doris-connector-it (11, ubuntu-latest). unit-test (windows-latest): the single error isjava.lang.IllegalStateException: Node failed to start!inorg.apache.seatunnel.engine.server.master.FollowerRunningJobsFilterTest, at the ~311s mark — this is the known intermittent Hazelcast node-bootstrap flake onwindows-latestthat has now hit three different, unrelated test classes across recent PRs in this module.TaskExecutionServiceTestitself — the class this PR actually touches — passed all 15/15 tests in that same run (Tests run: 15, Failures: 0, Errors: 0). Not caused by this PR's diff.doris-connector-it (ubuntu-latest): 2 assertion failures inside Doris/Spark (2.4.6 and 3.3.0) E2E cases, a connector module this PR does not touch at all (Tests run: 49, Failures: 2, Errors: 0). Not caused by this PR's diff.- An empty commit (
e76825afe7) was pushed purely to retrigger CI on identical code. At the time of this comment the freshBuildrun on the fork is queued/in-progress (module-path filtering is correctly skipping the unrelated E2E suites for this engine-only change;unit-testand the previously-touched suites are queued). I'm reporting this as in-flight, not assuming an outcome — I'll take another look once it completes if anything unexpected shows up.
Merge-gate status
Both outstanding reviews are APPROVED (mine and @nzw921rx's), and I have no source-level blocker. reviewDecision currently still shows REVIEW_REQUIRED and mergeStateStatus is BLOCKED — as I don't have write-level review permissions on this repository, that gate most likely still needs a maintainer with write access to formally clear it once CI reports green; this isn't a new code-side blocker from my side.
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers — must be fixed: None. No new issue was found in this verification pass; all issues from earlier rounds were resolved and re-confirmed resolved above.
- Recommended fixes — non-blocking: carried from my last review — a one-line log statement inside
onFailureBeforeContextPublished's call site distinguishing "released before publication" from the general failure log, for operability. Not required for merge. - CI status: currently re-running after an unrelated pair of flakes on the previously-approved head (diagnosis above); waiting for the fresh run to complete before treating CI as a closed gate.
Thanks again for the thorough work across every round of this — the fix is structurally sound and I found nothing new re-reading it from scratch against the current head.
|
结论:我这边已经开始协助清理这条 PR 当前 head 的 CI 噪声,源码侧暂时没有看到新的 classloader 逻辑 blocker。 我重新核对了 current head
为了尽快给 release 一个干净、可读的 CI 结论,我已经用 Daniel 侧承接分支重新触发了一轮验证:#11907 当前正在跑新的 Build。等这一轮 current-head CI 结果出来后,我会继续同步可交付状态,并在需要时继续帮忙处理后续问题。 |
|
CI re-check follow-up (2026-08-20), as promised in my 2026-08-19 review: the fresh Build run on the empty retrigger commit (
Both are Maven Central rate-limiting/connectivity issues hitting the runner before any code from this PR (or any test) executes — nothing to do with the classloader-release fix. This matches the same window of Maven Central flakiness other PRs saw today. Updated bottom line: still no source-level blocker, still just a CI rerun away from green — the retrigger simply landed in a bad window for |
davidzollo
left a comment
There was a problem hiding this comment.
+1 if CI passes.
LGTM
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point:
TaskExecutionService.deployTask(...)acquires classloader references (viaclassLoaderService.getClassLoader(jobId, jars), ref-counted per job/jar-set) for every task in a deployingTaskGroupbefore it does anything else with them. Before this PR, every failure branch on that method — a deserialization error partway through the acquisition loop,createTaskGroupthrowing, ordeployLocalTask's own internal failure before the task group ever got published — left those already-acquired references permanently un-released. On a worker that keeps failing deployments (a bad jar, a persistently misconfigured connector, a flaky master handing out malformed task info), each failed attempt leaked one more classloader reference, and sinceDefaultClassLoaderServicekeys classloaders by job id + jar set and only tears one down once its reference count reaches zero, the leaked references keep an otherwise-dead job's classloader (and everything it pins: loaded connector classes, native handles, etc.) alive indefinitely. - Fix approach: track every classloader reference acquired during the current
deployTaskattempt in a localacquiredClassLoaderJarslist, and givedeployLocalTasktwo new callbacks —onContextPublished(fired the instant theTaskGroupContextis published intoexecutionContexts, i.e. the moment ownership of those classloader references legitimately transfers to the running task group's own lifecycle) andonFailureBeforeContextPublished(fired only ifdeployLocalTaskfails before that publish point). A newreleaseClassLoadersAfterFailedDeploymenthelper releases whatever is still inacquiredClassLoaderJars— used both from that pre-publish callback and fromdeployTask's outercatch (Throwable t)for failures in the acquisition loop itself — and always clears the list first so a later handler can't double-release the same references. - One-sentence summary: this PR makes every classloader reference acquired during a deployment attempt get released if the attempt fails before the task group is actually published and running, closing a real, easy-to-trigger reference leak, while carefully avoiding a double-release once ownership has legitimately transferred to the running task group.
1. Code Change Review
1.1 Core Logic Analysis
Before (TaskExecutionService.java, deployTask):
ClassLoader classLoader =
classLoaderService.getClassLoader(
taskImmutableInfo.getJobId(), Lists.newArrayList(jars));
// ... no tracking of what was acquired, no release on any failure branchAfter (TaskExecutionService.java:451-479):
List<Collection<URL>> acquiredClassLoaderJars = new ArrayList<>();
...
List<URL> classLoaderJars = Lists.newArrayList(jars);
ClassLoader classLoader =
classLoaderService.getClassLoader(taskImmutableInfo.getJobId(), classLoaderJars);
acquiredClassLoaderJars.add(classLoaderJars);and, at the call site of deployLocalTask (:527-542):
AtomicBoolean classLoaderOwnershipTransferred = new AtomicBoolean();
deployLocalTask(
taskGroup, classLoaders, taskJars,
() -> classLoaderOwnershipTransferred.set(true),
failure -> {
releaseClassLoadersAfterFailedDeployment(
taskImmutableInfo.getJobId(), acquiredClassLoaderJars, failure);
acquiredClassLoaderJars.clear();
});
if (classLoaderOwnershipTransferred.get()) {
acquiredClassLoaderJars.clear();
}and in deployLocalTask itself (:673-690), the publish point is now instrumented:
executionContexts.put(taskGroup.getTaskGroupLocation(), new TaskGroupContext(taskGroup, classLoaders, jars));
contextPublished = true;
onContextPublished.run();
...
} catch (Throwable t) {
logger.severe(ExceptionUtils.getMessage(t));
if (!contextPublished) {
onFailureBeforeContextPublished.accept(t);
}
resultFuture.completeExceptionally(t);
}Complete runtime path, traced against the current head (not assumed from the diff alone):
deployTask(taskImmutableInfo)
acquiredClassLoaderJars = [] :452
for each task i in the group:
classLoaderJars = ... :475
classLoader = classLoaderService.getClassLoader(jobId, classLoaderJars) :476-478 (ref-count++)
acquiredClassLoaderJars.add(classLoaderJars) :479 <- ownership captured HERE, before deserialization is attempted
deserialize task i using classLoader :480-489 <- can throw
createTaskGroup(...) :494-499 <- can throw
synchronized(this) {
if (already in executionContexts) { :507 [master-failover redeploy of a still-running group]
release via the PRE-EXISTING per-task loop, acquiredClassLoaderJars.clear() :519-524
return success
}
deployLocalTask(taskGroup, classLoaders, taskJars,
onContextPublished = set classLoaderOwnershipTransferred,
onFailureBeforeContextPublished = release + clear) :527-537
taskGroup.init() :633 <- can throw, contextPublished still false here
... build TaskExecutionContext per task, byCooperation map ... :638-672
executionContexts.put(...) :673-675 <- PUBLISH POINT
contextPublished = true; onContextPublished.run() :676-677 <- ownership legitimately transfers to the TaskGroupContext
cancellationFutures.put(...) :678
submitThreadShareTask(...) :679 <- can still throw AFTER publish (see Issue 1)
submitBlockingTask(...) :680 <- can still throw AFTER publish (see Issue 1)
taskGroup.setTasksContext(...) :681
catch (Throwable t) { if (!contextPublished) onFailureBeforeContextPublished.accept(t); resultFuture.completeExceptionally(t); } :685-690
if (classLoaderOwnershipTransferred.get()) acquiredClassLoaderJars.clear(); :540-542 (idempotency guard, already empty if the callback ran)
return TaskDeployState.success() :543 <- ALWAYS success once deployLocalTask returns normally, unchanged pre-existing behavior
}
catch (Throwable t) { :545 <- only reached for failures in the acquisition loop / createTaskGroup, NOT from deployLocalTask (it never rethrows)
releaseClassLoadersAfterFailedDeployment(jobId, acquiredClassLoaderJars, t)
return TaskDeployState.failed(t)
}
Eventual release for a SUCCESSFULLY published group:
Task execution completes -> TaskGroupExecutionTracker.taskDone(task) :1450
if completionLatch (sized to taskGroup.getTasks().size()) reaches 0: :1457
recycleClassLoader(taskGroupLocation) :1458, :1507-1513 (ref-count--, once per task's jar set)
executionContexts -> finishedExecutionContexts :1459-1460
Key Findings:
- I independently re-verified the double-release-avoidance property that is the crux of this fix, by tracing every branch above against the current head rather than trusting the PR description: the outer
catch (Throwable t)indeployTask(:545) can only be reached by an exception thrown directly insidedeployTask's owntryblock (the acquisition loop orcreateTaskGroup) —deployLocalTaskfully catchesThrowableinternally (:685-690) and never rethrows, it only completesresultFutureexceptionally. So the outer catch anddeployLocalTask's internalonFailureBeforeContextPublishedcallback are mutually exclusive on every call:deployLocalTaskis only ever invoked from inside thesynchronizedblock, after the acquisition loop has already succeeded, so a failure in the acquisition loop can never trigger the callback, and a failure insidedeployLocalTaskcan never reach the outer catch. No double-release path exists. - I confirmed the specific scenario the fix targets (a mid-loop deserialization failure) end-to-end via the new
testDeployTaskReleasesClassLoadersWhenDeserializationFailstest and the code: classloader acquisition (:476-479) happens strictly before deserialization is attempted (:480-489) for each task, so a failing task's own just-acquired reference — and every earlier task's reference in the same group — is captured inacquiredClassLoaderJarsbefore the throw, and is reachable by the outer catch. Verified correct. - New finding, not raised in any of the eight prior review rounds on this PR (across two reviewers over a week) — I'm flagging it now rather than letting it slide through again: the fix's design rests on the assumption, stated almost verbatim in the PR's own commit message and in the previous review round ("post-publication outcomes clear the local ledger without releasing, because ownership has transferred to the published
TaskGroupContext, whose own lifecycle (taskDone()→recycleClassLoader()) owns the eventual release"). That assumption is not fully accurate.contextPublishedbecomestrueat:676, immediately afterexecutionContexts.put(...)— butcancellationFutures.put(...)(:678),submitThreadShareTask(...)(:679), andsubmitBlockingTask(...)(:680) all run after that point, still inside the sametryblock.recycleClassLoader()is only ever invoked fromTaskGroupExecutionTracker.taskDone(Task)(:1450-1458), which is called once per individualTaskas it completes, and only recycles oncecompletionLatch— sized totaskGroup.getTasks().size()at tracker construction (:1382, before context publish) — reaches zero. IfsubmitThreadShareTask/submitBlockingTaskthrows partway through submitting the group's tasks (e.g.mdcExecutorService.submit(...)insubmitBlockingTask,:403, throwingRejectedExecutionExceptionifexecutorServiceis concurrently shut down — a real, not just theoretical, race if a coordinator-level cleanup runs while a deploy is still in flight, or anErrorsubtype escapingsubmitThreadShareTask's narrowercatch (Exception e)at:364), the tasks that never got submitted will never calltaskDone(),completionLatchnever reaches zero,recycleClassLoader()never runs, and — becausecontextPublishedis alreadytrue—onFailureBeforeContextPublishedis correctly not invoked either. The classloader references (and theTaskGroupContextentry itself) are then stuck inexecutionContextspermanently, reachable by neither cleanup path this PR adds nor the pre-existing one. Worse, because the entry is never removed fromexecutionContexts, a later master-failover redeploy attempt for the sameTaskGroupLocationwould hit thealready exists and is activebranch (:507-518) and short-circuit assuccess, silently treating the permanently-stuck, never-actually-running group as alive — masking the problem indefinitely instead of surfacing it. I want to be precise about scope here: this is not a regression introduced by this diff — the same gap existed identically before this PR, since there was no other release path for this window either way. But it does mean the fix's own stated completeness claim ("every failure branch... has exactly one correct outcome") is not quite true for this one narrow, post-publish, pre-full-submission window, and neither new test exercises it (both new tests only cover pre-publication failures: mid-deserialization andtask.setTaskExecutionContext()throwing beforeexecutionContexts.put).
1.2 Compatibility Impact
Fully compatible. deployLocalTask(TaskGroup, ConcurrentHashMap<Long,ClassLoader>, ConcurrentHashMap<Long,Collection<URL>>) keeps its original public signature and default (no-op) callback behavior via the new private overload (:592-597), so existing callers are unaffected. notifyTaskStatusToMaster widening from private to package-private (:701, needed for the new test's Mockito.spy) is a safe, test-only visibility change with no external API impact. No config option, checkpoint/savepoint format, or wire-protocol change.
1.3 Performance / Side-Effect Analysis
Negligible. One extra ArrayList per deployTask invocation (bounded by the task count in the group, already an existing per-deploy allocation scale) and two extra lambda allocations per call to deployLocalTask. No new locks beyond the pre-existing synchronized (this) block, no new threads, no hot-path (steady-state task execution) impact — the change is confined to the deploy/failure path.
1.4 Error Handling and Logging
releaseClassLoadersAfterFailedDeployment (:566-581) attaches any cleanup failure as a suppressed exception on the original deploymentFailure (Throwable.addSuppressed) rather than replacing it, and logs at severe, which is appropriate — it preserves the root cause while surfacing the secondary cleanup failure. Releasing in reverse-acquisition order is a reasonable, if not strictly load-bearing, convention (classloader ref-counting per job/jar-set key is order-independent, so this is a documentation nicety rather than a correctness requirement — worth knowing so nobody assumes real ordering semantics from it, but not worth a formal issue).
Issue 1: classloaders (and the TaskGroupContext entry) can leak permanently, and mask a dead task group as alive, if task submission fails after the context is published but before every task is actually submitted
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:676-681(thecontextPublished = true/submitThreadShareTask/submitBlockingTaskwindow), interacting with:1450-1461(TaskGroupExecutionTracker.taskDone) and:351-374/:384-411(submitThreadShareTask/submitBlockingTask) - Problem description: see the Key Findings analysis above —
recycleClassLoader()only fires once every task in the group has individually calledtaskDone(); a task that's never submitted (because submission itself threw partway through the group) never calls it, so the latch never reaches zero. - Potential risk: permanent classloader leak for that job's jar set (same failure class this PR exists to fix, just via a different trigger), plus a stuck
TaskGroupContextentry that causes a subsequent failover redeploy of the same task group to be silently treated as "already running" and skipped, hiding the failure from operators indefinitely. - Best improvement: Option A — wrap
cancellationFutures.put/submitThreadShareTask/submitBlockingTask/taskGroup.setTasksContextin their own try/catch that, on failure, removes the just-published entry fromexecutionContextsand releases its classloaders directly (treating a submission failure as equivalent to a pre-publish failure for cleanup purposes, even though publish already happened). Option B — makesubmitThreadShareTask/submitBlockingTaskthemselves resilient to partial failure, callingtaskDone()(or an equivalent latch-decrementing hook) for every task that didn't get submitted, so the existingrecycleClassLoader()path is reliably reached regardless of where submission stops. - Severity: Medium — narrow trigger (requires task submission itself to fail after context publish, e.g. via a concurrent executor shutdown or an
ErrorescapingsubmitThreadShareTask'sException-only catch), and not a regression (identical gap existed before this PR, since there was no release path for this window either way) — but the failure-masking side effect on a subsequent failover redeploy makes the consequence worse than a plain leak, and this exact window is squarely inside the scope this PR set out to close but ends up not fully closing. - Raised by another reviewer: No — new finding this round; also missed in my own five prior rounds on this PR, sorry for not catching it sooner given how much I emphasized "every branch balances acquire/release" in the 2026-08-19 approval.
2. Code Quality Assessment
2.1 Coding Standards
New method (releaseClassLoadersAfterFailedDeployment) and the two new callback parameters on the private deployLocalTask overload carry Javadoc/inline comments explaining purpose and lifecycle (:559-565, :451, :538-539). No missing-comment gaps on the new production code.
2.2 Test Coverage and Test Stability
Two new tests, both exercising real pre-publication failure branches with concrete assertions on DefaultClassLoaderService's reference count (not just "no exception thrown") — testDeployTaskReleasesClassLoadersWhenDeserializationFails (mid-loop deserialization failure, outer-catch release path) and testDeployTaskHandlesFailureBeforeContextPublication (a task's setTaskExecutionContext throwing before executionContexts.put, onFailureBeforeContextPublished path, including verifying the FAILED status still reaches notifyTaskStatusToMaster via a bounded Mockito.verify(..., Mockito.timeout(5000)), not a fixed sleep). Both use per-test unique temp-jar URLs (Collections.singleton(testJarUrl)), avoiding the job-id/jar-key collision that made an earlier round of this same test order-dependent (per the 2026-08-19 review). No Thread.sleep in either new test. Rating: Stable for the tests as written. Neither new test covers the post-publish partial-submission-failure window in Issue 1 above — that gap is real but, given Issue 1's own narrow trigger, I would not block merge on adding a test for it in this round; a targeted regression test for Issue 1 would be a good, cheap follow-up once the fix approach is decided.
2.3 Documentation Updates
Not applicable — internal engine implementation detail, no user-facing config, API, or behavior contract change.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix (not a workaround) for the specific, well-understood leak class it targets: pre-publication deployment failures. The ownership-transfer model (contextPublished boolean + onContextPublished/onFailureBeforeContextPublished callbacks) is a clean way to express "who currently owns cleanup responsibility for these references" without introducing a second competing release mechanism, and the mutual-exclusivity property between the outer catch and the callback is correctly maintained. Issue 1 shows the ownership-transfer boundary is drawn slightly too early relative to when tasks are actually guaranteed to run, but that's a boundary-placement gap in an otherwise sound approach, not a flaw in the approach itself.
3.2 Maintainability
Good — acquiredClassLoaderJars gives future readers a single, explicit place to see "what does this deploy attempt currently own," which didn't exist before. The two-callback interface on the private deployLocalTask overload is a bit implicit (a reader has to trace both call sites to understand the full contract); a short Javadoc note on the private overload itself, stating the ownership-transfer contract in one place, would help future maintainers more than tracing it from the call site.
3.3 Extensibility
No concerns — the pattern generalizes if more resources ever need the same acquire/transfer/release tracking.
3.4 Historical-Version Compatibility
No serialized state, checkpoint/savepoint format, or config option touched; this is pure worker-local deployment bookkeeping. A rolling upgrade with mixed old/new binaries is safe — an old worker keeps leaking on deploy failure until upgraded, a new worker doesn't, and there's no cross-version wire interaction.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Classloaders (and the TaskGroupContext entry) can leak permanently, and mask a dead task group as alive on a later failover redeploy, if task submission fails after context publish but before every task is submitted |
TaskExecutionService.java:676-681, :1450-1461 |
Medium |
5. Merge Recommendation
Conclusion: Ready to merge
This is a re-review (NEED_REREVIEW): the head has moved from e76825afe7 (my last full review, approved 2026-08-19) to 24c9de487 only via a dev-sync merge — I diffed the two directly and the only change to a file this PR touches is a single unrelated 4-line getter (getClassLoaderService()) picked up from dev, not an intentional change to this fix. I re-read the entire current diff and full runtime path from scratch per protocol rather than assuming the unchanged parts were still fine, and independently re-confirmed the core double-release-avoidance property holds. @nzw921rx approved twice ("LGTM if CI passes"), gating only on CI, and @davidzollo approved on 2026-08-21 ("+1 if CI passes... LGTM"), also CI-gated with no code-content concerns to reconcile — both are satisfied now that Build is green on this exact head (verified live: Build pass, 2026-08-22).
- Blockers — must be fixed: None. Issue 1 above is a genuine, previously-unflagged gap, but it is not a regression introduced by this diff (the same window was unprotected before this PR too, for lack of any release mechanism at all), it requires a narrow concurrent-failure trigger during task submission, and this PR is a strict improvement over the pre-fix baseline regardless of whether Issue 1 is addressed in this round or a fast follow-on.
- Recommended fixes — non-blocking:
- Issue 1: close the post-publish, pre-full-submission window (Option A or B above), ideally with a regression test exercising a forced
submitThreadShareTask/submitBlockingTaskfailure after publish. - A short Javadoc on the private
deployLocalTask(..., onContextPublished, onFailureBeforeContextPublished)overload stating the ownership-transfer contract in one place.
- Issue 1: close the post-publish, pre-full-submission window (Option A or B above), ideally with a regression test exercising a forced
Overall assessment: the core fix is correct, minimal, and well-tested for the exact failure class described in the linked issue — I traced every acquire/release branch myself against the current head and found no double-release and no leak on the paths the new tests cover. Issue 1 is a real, narrow, pre-existing gap adjacent to this PR's scope that I regret not catching in five earlier rounds; it doesn't change my merge recommendation, but I'd like it tracked (in this PR or a fast follow-on) rather than left implicit now that it's been identified. Thanks for the very thorough iteration on this one, and thanks to @nzw921rx and @davidzollo for the earlier passes.
|
Checked the failing
I don't have push/rerun rights on this fork (confirmed both via API permissions and a rejected check-run rerequest), so I can't retrigger the two failed jobs myself. @goutamadwant — could you re-run the two failed jobs from your fork's Actions tab? No code changes needed on your side. Once that's green, I don't see any remaining CI-side blocker. |
|
@goutamadwant Please rerun failed job: https://github.com/goutamadwant/seatunnel/actions/runs/32627488996 I identified the issue based on the status and believe restarting this job should resolve the stuck state😄 |
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
Before this PR, TaskExecutionService.deployTask could leak a classloader reference if deployment failed after classLoaderService.getClassLoader(...) had already been called for one or more tasks in the group but before the resulting TaskGroupContext was published into executionContexts. Any exception in that window (task deserialization failure for a later task in the group, or a failure while building the per-task TaskExecutionContext/thread-share partitioning) left those classloader references permanently un-released, since the only release path was the "normal" completion path driven by TaskGroupExecutionTracker.taskDone(), which never runs for a task group that was never published.
Fix approach: track the classloader references acquired by the current deployment attempt in a local list (acquiredClassLoaderJars), and give deployLocalTask two new callbacks — onContextPublished (fires the instant executionContexts.put(...) succeeds) and onFailureBeforeContextPublished (fires only if the deployment throws before that point). Once the context is published, deployTask clears its own tracking list and hands ownership to the existing "recycle on last task completion" lifecycle (TaskGroupExecutionTracker.recycleClassLoader); if it fails before publication, the new releaseClassLoadersAfterFailedDeployment releases everything acquired so far and re-throws/records the original failure (via addSuppressed) so cleanup failures never mask the real error.
One-sentence summary: this is a correct, well-tested, minimally-scoped fix for a genuine classloader leak in the pre-publication task-deployment path.
This is a full fresh re-review of the entire current diff and runtime path (per the re-review protocol), not just the delta since the last approval — the last four rounds of approval (2026-08-18 through 2026-08-22) were all against the same underlying fix commit (d638bd37, landed 2026-08-18); every commit since then is a no-op "Merge branch 'dev'" with no changes to this PR's own two files, so there is no new application logic to re-verify, but I re-traced everything from scratch against the current head (01a75d6c) rather than assuming the prior approvals still apply.
1. Code Change Review
1.1 Core Logic Analysis
Only two files are touched: TaskExecutionService.java (production) and TaskExecutionServiceTest.java (tests). Full current-head content re-read directly from the fork (01a75d6c), not just the diff.
deployTask (lines 445-557):
List<Collection<URL>> acquiredClassLoaderJars = new ArrayList<>();
try {
...
for (int i = 0; i < taskData.size(); i++) {
...
List<URL> classLoaderJars = Lists.newArrayList(jars);
ClassLoader classLoader = classLoaderService.getClassLoader(jobId, classLoaderJars);
acquiredClassLoaderJars.add(classLoaderJars); // tracked BEFORE deserialization can fail
task = ... deserialize ... // may throw
taskJars.put(task.getTaskID(), classLoaderJars);
}
taskGroup = TaskGroupUtils.createTaskGroup(...);
synchronized (this) {
if (executionContexts.containsKey(taskGroup.getTaskGroupLocation())) {
// failover re-deploy of an already-running group: release + return success
}
AtomicBoolean classLoaderOwnershipTransferred = new AtomicBoolean();
deployLocalTask(taskGroup, classLoaders, taskJars,
() -> classLoaderOwnershipTransferred.set(true),
failure -> { releaseClassLoadersAfterFailedDeployment(jobId, acquiredClassLoaderJars, failure); acquiredClassLoaderJars.clear(); });
if (classLoaderOwnershipTransferred.get()) { acquiredClassLoaderJars.clear(); }
return TaskDeployState.success();
}
} catch (Throwable t) {
releaseClassLoadersAfterFailedDeployment(jobId, acquiredClassLoaderJars, t);
...
return TaskDeployState.failed(t);
}deployLocalTask (lines 599-693): the two new callback parameters fire at exactly one point each — onContextPublished.run() immediately after executionContexts.put(taskGroupLocation, new TaskGroupContext(...)) succeeds (line 676-677), and onFailureBeforeContextPublished.accept(t) only when the catch block's !contextPublished guard is true (line 687-688). Because contextPublished/onContextPublished.run() both happen on the same line-676-677 boundary, any later failure in that same try block (cancellationFutures.put, submitThreadShareTask, submitBlockingTask, taskGroup.setTasksContext) is correctly treated as "after publication" — ownership has already transferred, so deployTask does not double-release.
Runtime path traced end-to-end (this is the normal task-deployment path — every task-group deployment on every worker goes through deployTask → deployLocalTask, not a rare recovery path; the specific failure windows being fixed are boundary cases within that common path, e.g. a genuinely corrupt/incompatible serialized task payload, or a Task.setTaskExecutionContext implementation throwing):
Master -> Operation (deploy) -> TaskExecutionService.deployTask()
-> classLoaderService.getClassLoader() [acquire, tracked in acquiredClassLoaderJars]
-> task deserialization [can throw -> outer catch -> release all acquired -> TaskDeployState.failed]
-> TaskGroupUtils.createTaskGroup()
-> synchronized(this) { deployLocalTask(...) }
-> taskGroup.init(), TaskExecutionContext construction [can throw -> onFailureBeforeContextPublished -> release all acquired]
-> executionContexts.put(...) [PUBLICATION POINT -> onContextPublished -> ownership transferred]
-> submitThreadShareTask/submitBlockingTask/setTasksContext [can throw, but ownership already transferred -> no release here]
-> (async, later) TaskGroupExecutionTracker.taskDone() on last task -> recycleClassLoader() -> classLoaderService.releaseClassLoader()
I independently verified the classloader-identity assumption this fix depends on: DefaultClassLoaderService.getClassLoader/releaseClassLoader key on covertJarsToKey(Collection<URL>) (seatunnel-engine-core/.../DefaultClassLoaderService.java:144-146), which sorts and concatenates URL.toString() values into a canonical String — it is content-based, not identity- or type-based. This matters because the PR changes taskJars's value type from a HashSet<URL> (pre-PR) to the same ArrayList<URL> instance already used for getClassLoader/acquiredClassLoaderJars (post-PR, classLoaderJars at line 475). Since the key derivation is content-based and order-independent (.sorted()), this Set→List change cannot cause an acquire/release key mismatch — confirmed by reading the implementation rather than assuming it.
I also verified the two new regression tests actually exercise the two distinct failure windows they claim to: testDeployTaskReleasesClassLoadersWhenDeserializationFails fails during deserialization of the second task (jars for both tasks already acquired) and asserts refcount reaches 0; testDeployTaskHandlesFailureBeforeContextPublication fails inside Task.setTaskExecutionContext (before executionContexts.put), asserts the context was never published (TaskGroupContextNotFoundException), the classloader refcount reaches 0, and that the master is still notified of the FAILED state via Mockito.verify(..., Mockito.timeout(5000)) — this last assertion is the one that actually proves "preserves the original deployment exception while continuing cleanup" from the PR description, not just the cleanup half.
Key Finding — one residual gap, not introduced by this PR (see Issue 1 below): the "once published, cleanup belongs to the normal task-group lifecycle" boundary this PR establishes assumes every task in a published group eventually calls taskDone() so completionLatch (fixed at taskGroup.getTasks().size(), set at TaskGroupExecutionTracker construction, before publication) reaches zero and triggers recycleClassLoader(). submitBlockingTask's task-submission stream (line 384-411) has no per-task exception guard around mdcExecutorService.submit(...) the way submitThreadShareTask does (which explicitly calls taskGroupExecutionTracker.taskDone(t) on a per-task init failure, line 364-367) — if the executor rejects a submission mid-stream after publication, the affected task's taskDone() is never called, the latch never reaches zero, and the classloader for that entire group leaks permanently. I confirmed by reading the pre-PR code that this exact structural gap already existed before this PR (the try/catch shape around submitThreadShareTask/submitBlockingTask is unchanged); this PR does not create or worsen it, it just formally documents the ownership boundary at which its own scope ends.
1.2 Compatibility Impact
Fully compatible. Both the public deployLocalTask(TaskGroup, ConcurrentHashMap, ConcurrentHashMap) overload's signature and behavior are preserved (delegates to the new private overload with no-op callbacks), so any other in-repo caller is unaffected. notifyTaskStatusToMaster widened from private to package-private purely to let the new test Mockito.spy() it — no external API surface change (still not public), consistent with this project's "keep APIs minimal, prefer package-private" convention. No checkpoint/savepoint state, wire protocol, or serialization format is touched — this is purely in-memory deployment bookkeeping on a single worker.
1.3 Performance / Side-Effect Analysis
Negligible: one extra ArrayList per deployTask call, one extra AtomicBoolean, two extra lambda allocations per call. No new locking beyond the pre-existing synchronized (this) block. releaseClassLoadersAfterFailedDeployment's reverse-order iteration is cosmetic (release order does not affect a simple per-entry refcount decrement in DefaultClassLoaderService) but harmless.
1.4 Error Handling and Logging
No blocking issues found. releaseClassLoadersAfterFailedDeployment correctly uses deploymentFailure.addSuppressed(cleanupFailure) rather than replacing/swallowing the original exception, and still logs the cleanup failure at severe — good practice for a cleanup-during-failure path.
Issue 1 — post-publication partial-submission-failure gap is real but pre-existing, non-blocking; carryover note. See 1.1 Key Finding. This existed in the exact form already approved across all four prior rounds (2026-08-18 through 2026-08-22) — I want to flag plainly that this is a fair thing a prior review could have raised as a documented limitation and didn't, so: apologies for not surfacing it sooner. It does not block this PR (it's strictly pre-existing behavior, not a regression, and the PR's own docstring boundary — "cleanup belongs to the normal task-group lifecycle" — is honest about where its scope ends), but it's worth a follow-up issue against submitBlockingTask mirroring submitThreadShareTask's per-task taskDone() fallback on submission failure.
- Location:
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:384-411(submitBlockingTask), interacting withTaskGroupExecutionTracker.completionLatch(line 1382) andrecycleClassLoader(line 1507-1513) - Severity: Low (non-blocking, pre-existing, recommended follow-up)
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Matches surrounding style. The new releaseClassLoadersAfterFailedDeployment has a clear Javadoc explaining its cleanup-failure-doesn't-mask-original-failure contract. One gap: the new private deployLocalTask(..., Runnable onContextPublished, Consumer<Throwable> onFailureBeforeContextPublished) overload — the actual core of this fix — has no Javadoc of its own explaining when each callback fires and what the caller may assume about ownership at that point; a reader has to reconstruct that from the call site in deployTask. Given this is genuinely non-trivial, non-self-explanatory control flow (which this project's own contribution guide calls out as needing comments for "lifecycle hooks" and "complex logic"), I'd ask for a short Javadoc block here.
- Severity: Low (non-blocking, coding-standard nit)
- Raised by another reviewer: No
2.2 Test Coverage and Test Stability
Both new tests are deterministic: no Thread.sleep hard waits, the one async assertion uses Mockito.verify(..., Mockito.timeout(5000)) (poll-with-timeout, not a fixed sleep), temp files are created with deleteOnExit() and explicitly deleted at the end of each test, and there's no shared mutable static state introduced. testJobId = System.currentTimeMillis() is used for uniqueness, matching the existing convention already used elsewhere in this same test file (not a new pattern introduced by this PR). Stability rating: Stable.
2.3 Documentation Updates
Not required — this is an internal engine cleanup behavior with no user-facing config, API, or protocol change, consistent with the PR description's own checklist.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix, not a workaround. The "acquisition list + monotonic ownership-transfer flag" pattern is a clean way to express "who is responsible for releasing this resource right now" without needing a state machine, and it composes correctly with the pre-existing failover short-circuit path (executionContexts.containsKey(...)) without duplicating release logic.
3.2 Maintainability
Good. The two new callback parameters are a bit implicit (see 2.1), but the boundary they express (before/after publication) is the right one and is now the single place this kind of fix would need to be extended if a future case is found.
3.3 Extensibility
No concerns — self-contained to this one class.
3.4 Historical-Version Compatibility
No impact on checkpoint/savepoint restore, serialization formats, or existing job configs — this is deployment-time-only, in-memory bookkeeping on a single worker node, not persisted or transmitted anywhere.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Post-publication partial-submission-failure can still leak a classloader if a task is never submitted (no per-task fallback in submitBlockingTask unlike submitThreadShareTask) — pre-existing, not introduced here |
TaskExecutionService.java:384-411, :1382, :1507-1513 |
Low (non-blocking, carryover) |
| 2 | New private deployLocalTask overload lacks a Javadoc explaining the two callback contracts |
TaskExecutionService.java:599-604 |
Low (non-blocking, coding standard) |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
The code change itself has no blocking issues — it correctly and minimally closes the reported pre-publication classloader leak, is backward compatible, and is covered by two well-targeted, deterministic regression tests. Both other reviewers (nzw921rx, davidzollo) have approved, and I agree with that assessment on the code.
- Blockers — must fix before merge:
- CI is currently failing (
Build, red) at the current head01a75d6c, but this failure is NOT caused by this PR's diff. I traced the fork's actual failing jobs (all ~24 of them, spanning unit-test/all-connectors-it/jdbc/transform/engine-v2-it across both JDKs and OSes — a pattern consistent with a single early compile failure, not scattered real test failures) and every job fails at the identical point:seatunnel-engine-server's test-compile step,JobStateEventTest.java:165: error: cannot find symbol: variable FAILED_JOB_EVENT_TIMEOUT_SECONDS. This PR's diff never touchesJobStateEventTest.java(confirmed viagh pr diff --name-only: onlyTaskExecutionService.javaandTaskExecutionServiceTest.javaare changed). I fetchedJobStateEventTest.javadirectly from livedev(current HEAD406c66789e) and confirmed the break is already present ondevitself: line 165 referencesFAILED_JOB_EVENT_TIMEOUT_SECONDS, which is neither declared in the class nor among its imports (the file only statically imports the unrelatedRESTORE_TO_FAILED_TIMEOUT_SECONDSfromCheckpointErrorRestoreEndTest). This was introduced by033612bfd6("[Fix][E2E] Address follow-up review issues for CI stabilization (#11097)", merged todev2026-08-23T14:25:35Z) and pulled into this branch by its most recent "Merge branch 'dev'" commits (29f1754b,edb177c9,01a75d6c). @davidzollo's 2026-08-23 CI comment diagnosed a different, now-stale failure (CouchbaseIT container flake, on an earlier head29f1754b) — that diagnosis was correct for its own head at the time, but the current head's failure is this newer, unrelateddev-side compile break, not the Couchbase flake. Syncingdevagain will not fix this —devitself needsJobStateEventTest.javafixed first (this belongs in a separate, dedicated CI-fix PR/commit; it is out of scope to fix here). Please hold merge until that lands ondevand this branch re-syncs and goes green.
- CI is currently failing (
- Recommended fixes — non-blocking:
- Issue 2 — add a short Javadoc to the new private
deployLocalTaskoverload documenting the two callback contracts.
- Issue 2 — add a short Javadoc to the new private
Overall assessment: the classloader-release fix itself is done and correct; the only thing standing between this and merge is an external, unrelated dev-branch compile break that needs to be fixed upstream first, after which this branch should go green on the next sync without any further code changes here.
Note on #11907: I checked the open PR #11907 (same title as this one). It is not an independent duplicate implementation — its own description states it "republishes the current head of #11812 on a writable DanielLeens fork so Apache CI can run to completion," because the original fork's Build run had finished as cancelled and only that fork's admins could re-run it; its content is explicitly identical to this PR's e76825af head, and it references #11812 as the original. That workaround already served its purpose (its Build check passed on 2026-08-21) and now that CI is actually executing directly on this PR's own head again (as seen above, just currently red for the unrelated reason above), #11907 can likely be closed once this PR is green — no duplicate-effort reconciliation with a separate contributor is needed here.
|
retried the failed jobs in the build @nzw921rx |
|
@nzw921rx build succeeded - https://github.com/goutamadwant/seatunnel/actions/runs/32741502186 |
|
@nzw921rx @goutamadwant Thanks for the quick rerun coordination — appreciate the effort keeping this moving. I want to flag an accuracy correction on the "all checks look clean" note, since a fresh sync-from-dev landed right after: the current head (
( To be clear: I re-checked @goutamadwant — could you do one more job-level rerun, this time targeting just |
|
@goutamadwant Hello, I think we need to rebase the dev and rerun the failed job |
@nzw921rx I help updated the upstream for @goutamadwant. I really hope this PR can pass CI soon. |
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point:
TaskExecutionService.deployTask(...)acquires one reference-counted classloader per task in a deployingTaskGroup. Before this PR, a failure anywhere in the acquisition loop,createTaskGroup, or insidedeployLocalTaskbefore theTaskGroupContextwas published, left those already-acquired references permanently un-released — a slow metaspace/file-handle leak underclassloader-cache-mode: false(issue #11808). - Fix approach: an acquisition ledger (
acquiredClassLoaderJars) scoped to the current attempt; a monotonic per-attemptAtomicBoolean(classLoaderOwnershipTransferred) set from anonContextPublishedcallback fired the instantexecutionContexts.put(...)succeeds; and anonFailureBeforeContextPublishedcallback, gated by acontextPublishedflag, that releases the ledger for failures insidedeployLocalTaskbefore publication. The master-notification registration (resultFuture.whenCompleteAsync(...)) is unconditionally the first statement indeployLocalTask, so it always fires regardless of where a later failure occurs. - One-sentence summary: this is the same fix I fully re-verified and approved on 2026-08-24 (head
01a75d6c); the only thing that changed since then is CI-drivingdevsyncs, not application logic.
This is a verification pass, not a new independent review
git diff 01a75d6ceed 1aa96be3cfeddd8b20c8935227e57c5e72085823 -- TaskExecutionService.java TaskExecutionServiceTest.java returns zero changes. Every commit between my last full review and the current head (1aa96be3c) is a no-op Merge branch 'dev' — confirmed directly against a freshly-fetched dev (339fb88cce0), not the stale local mirror. gh pr diff --name-only also confirms the file set is unchanged: still exactly TaskExecutionService.java and TaskExecutionServiceTest.java. So there is no new production logic to re-trace, and I'm not going to re-publish an identical multi-thousand-word analysis; instead this closes the loop on the two open threads since my last review.
@nzw921rx's rebase suggestion was the right call, and it worked
My last review (2026-08-25T10:39:56Z, head 056033fe) still showed the apache-side Build check red, traced to two unrelated Testcontainers flakes (Couchbase bootstrap, SAP HANA startup) — no source-side blocker. Independently of that, my 2026-08-24 full review (head 01a75d6c) had flagged a real blocker at the time: dev itself had a compile break in JobStateEventTest.java:165 (cannot find symbol: FAILED_JOB_EVENT_TIMEOUT_SECONDS), introduced by 033612bfd6 and pulled into this branch's own dev-sync merges — unrelated to this PR's diff, but blocking every job in the fork's Build regardless.
@nzw921rx's suggestion to rebase dev and rerun was exactly the correct fix for that: dev has since picked up 43fe63b1fca ("[Fix][Zeta] Fix undefined job event timeout constant", #11954), which replaces the dangling FAILED_JOB_EVENT_TIMEOUT_SECONDS reference with the already-imported RESTORE_TO_FAILED_TIMEOUT_SECONDS. I confirmed this fix is present at the current head (git show 43fe63b1fca applies cleanly, symbol resolves via the existing static import at line 36). @davidzollo's sync at 14:55 UTC (1aa96be3c, merging in dev's recent Oracle INTERVAL-type commit among others) carries that fix forward. So the specific compile-break blocker from my 2026-08-24 review is now resolved by the rebase, not just worked around.
Fresh CI status (not assuming an outcome)
The apache-side Build check is currently pending on 1aa96be3c. Tracing to the real run (the apache-side check is only a pointer): goutamadwant/seatunnel run 32862368706, status queued, created 2026-08-25T14:53:42Z — i.e. the rebase's own retrigger, not yet executed. I'm reporting this as in-flight; I have no reason to expect a new class of failure given the compile break is fixed and the diff itself hasn't changed, but I won't call it green until it actually reports green.
5. Merge Recommendation
Conclusion: Ready to merge, pending CI
- Blockers — must be fixed: None on the code side. My 2026-08-24 blocker (the
dev-sideJobStateEventTest.javacompile break) is resolved by the rebase@nzw921rxrequested and@davidzolloperformed. Only remaining gate is the freshBuildrun completing green on1aa96be3c. - Recommended fixes — non-blocking, carried from earlier rounds:
- A short Javadoc on the private
deployLocalTask(..., onContextPublished, onFailureBeforeContextPublished)overload documenting the two callback contracts. - A follow-up (separate issue, not this PR) for
submitBlockingTask's missing per-tasktaskDone()fallback on submission failure, mirroringsubmitThreadShareTask— pre-existing, not introduced by this PR.
- A short Javadoc on the private
Overall assessment: the classloader-release fix itself has been independently re-traced and approved across five rounds now, with no double-release and no leak found on any reachable path. The rebase closes the last known CI blocker; once the fresh Build run on 1aa96be3c reports green, I don't see anything left on my side. Thanks @nzw921rx for catching that the right fix was a dev sync rather than another job-level rerun.
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point:
TaskExecutionService.deployTask(...)acquires one reference-counted classloader per task in a deployingTaskGroup, one at a time, inside a loop (TaskExecutionService.java:460-493). I confirmed against the pre-PRdevversion of this file that before this fix existed, the outercatch (Throwable t)at the end ofdeployTasksimply logged and returnedTaskDeployState.failed(t)with no call toclassLoaderService.releaseClassLoader(...)at all for any references already acquired earlier in that same attempt — whether the failure came from a later task's deserialization,TaskGroupUtils.createTaskGroup, or from insidedeployLocalTaskitself before theTaskGroupContextwas published. SinceDefaultClassLoaderServiceis reference-counted per job id + jar set, every failed deployment permanently pinned one more reference, and underclassloader-cache-mode: false(a supported, non-default config) that keeps the actualSeaTunnelChildFirstClassLoaderand everything it loaded alive forever. This is a real leak on the ordinary failure path, not a boundary/recovery-only path — any bad task payload, missing jar, or transient init error triggers it. That matches issue #11808. - Fix approach, current head (
730a46bd44): track every classloader reference acquired by the current attempt in a local ledgeracquiredClassLoaderJars(:452, appended at:479).deployLocalTasktakes two new callbacks:onContextPublished(fired the instantexecutionContexts.put(...)succeeds,:673-677) which flips a per-attemptAtomicBoolean classLoaderOwnershipTransferred, andonFailureBeforeContextPublished(fired only ifdeployLocalTask's owncatchis reached with a localcontextPublishedstillfalse,:685-689), which drains the ledger viareleaseClassLoadersAfterFailedDeployment(:566-581). The outercatchindeployTask(:545-547) covers failures in the acquisition loop itself, beforedeployLocalTaskis even called. TheresultFuture.whenCompleteAsync(...)master-notification registration was also moved to be the unconditional first statement ofdeployLocalTask(:606-630), sonotifyTaskStatusToMasterstill fires even iftaskGroup.init()throws immediately. - One-sentence summary: a correctly-scoped, reference-count-safe fix for a genuine, reachable classloader leak on the task-deployment failure path, backed by two new regression tests that assert on the actual reference-count state rather than on log strings.
1. Code Change Review
1.1 Core Logic Analysis
I re-traced the whole mechanism from source against the current head myself rather than relying on the PR description or prior review summaries.
Before (dev, TaskExecutionService.java pre-PR):
TaskGroup taskGroup = null;
try {
...
ClassLoader classLoader = classLoaderService.getClassLoader(jobId, Lists.newArrayList(jars));
...
synchronized (this) {
...
deployLocalTask(taskGroup, classLoaders, taskJars);
return TaskDeployState.success();
}
} catch (Throwable t) {
logger.severe(...);
return TaskDeployState.failed(t); // acquired classloader refs never released
}After (:445-581):
List<Collection<URL>> acquiredClassLoaderJars = new ArrayList<>();
try {
...
acquiredClassLoaderJars.add(classLoaderJars); // :479, once per acquired ref
...
synchronized (this) {
AtomicBoolean classLoaderOwnershipTransferred = new AtomicBoolean();
deployLocalTask(taskGroup, classLoaders, taskJars,
() -> classLoaderOwnershipTransferred.set(true), // onContextPublished
failure -> { // onFailureBeforeContextPublished
releaseClassLoadersAfterFailedDeployment(jobId, acquiredClassLoaderJars, failure);
acquiredClassLoaderJars.clear();
});
if (classLoaderOwnershipTransferred.get()) {
acquiredClassLoaderJars.clear();
}
return TaskDeployState.success();
}
} catch (Throwable t) {
releaseClassLoadersAfterFailedDeployment(jobId, acquiredClassLoaderJars, t);
return TaskDeployState.failed(t);
}Runtime-path trace (why this is race-safe, since this touches engine deployment/classloader lifecycle):
deployTask() [holds `synchronized (this)` for the whole publish decision]
|
|-- acquisition loop: getClassLoader() -> acquiredClassLoaderJars.add() (per task)
|
|-- deployLocalTask() [same thread, still inside synchronized(this)]
| |-- register resultFuture.whenCompleteAsync(...) FIRST (unconditional)
| |-- taskGroup.init(); build TaskExecutionContexts
| |-- executionContexts.put(location, context) <-- publish
| |-- contextPublished = true; onContextPublished.run() <-- flag flips HERE,
| | synchronously, BEFORE any task thread can start
| |-- submitThreadShareTask / submitBlockingTask <-- only now can another
| | thread reach TaskGroupExecutionTracker.taskDone() ->
| | recycleClassLoader() -> releaseClassLoader(...)
| `-- (any throw here happens with contextPublished already true, so
| onFailureBeforeContextPublished is correctly skipped)
|
`-- back in deployTask: classLoaderOwnershipTransferred already observable-true
by construction -> acquiredClassLoaderJars.clear(), no release here.
This is the important correctness property, and it is exactly what an earlier round of this same PR got wrong (see nzw921rx's 2026-08-16 finding, since fixed): an intermediate version used executionContexts.containsKey(location) after deployLocalTask() returned as the ownership signal, which is racy — a short-lived task group can finish and be removed from executionContexts by TaskGroupExecutionTracker.taskDone() before deployTask() gets to check the map, making a successfully-published context look "not present" and triggering a second, spurious release of references that recycleClassLoader() already released once via the completion path. Since DefaultClassLoaderService.releaseClassLoader is a plain decrementAndGet() on a shared AtomicInteger keyed by job id + jar set (DefaultClassLoaderService.java:117), a double release can under-count an unrelated, still-running deployment that happens to share the same jobId+jar-set key, evicting a classloader still in use (non-cache mode) or corrupting the count (cache mode). The current head replaces that with a monotonic AtomicBoolean set synchronously at publication time, inside the same critical section, before any task thread is started — this closes the TOCTOU window correctly. I verified this by reading the full current deployLocalTask body (:599-693) line by line; the ordering guarantee holds.
Key Findings: none. I could not find a scenario, either in the acquisition loop or inside deployLocalTask, where a reference is acquired without being represented in exactly one of {ledger cleared via publish, ledger released via onFailureBeforeContextPublished, ledger released via outer catch}, nor one where a reference could be released twice.
1.2 Compatibility Impact
Fully compatible. This is internal Zeta worker-side deployment bookkeeping only:
deployTask(Data)/deployTask(TaskGroupImmutableInformation)— public signatures and return type (TaskDeployState) unchanged.deployLocalTask(TaskGroup, ConcurrentHashMap, ConcurrentHashMap)— public overload retained with identical signature, delegating to a new private overload with no-op callbacks (:592-597); I confirmed viagrepthat this public method has no callers outsideTaskExecutionServiceitself and its test class, so no external/SPI compatibility surface is touched.notifyTaskStatusToMastervisibility widened fromprivateto package-private (:702) purely to let the newtestDeployTaskHandlesFailureBeforeContextPublicationtestMockito.spy()/verify it — no protocol or wire-format change.- No config option, checkpoint/savepoint format, or serialization format is touched. No documentation update is required, and none is claimed to be needed.
1.3 Performance/Side-Effect Analysis
- Per-deployment overhead is one extra
ArrayListand, on the failure path only, one extra loop over already-collected references — negligible relative to the classloader/deserialization work already being done. - The practical severity of the bug being fixed is config-dependent, worth calling out explicitly:
ServerConfigOptions.CLASSLOADER_CACHE_MODEdefaults totrue(ServerConfigOptions.java:30-34). In cache mode,releaseClassLoaderdecrements the counter but returns before ever evicting the cached classloader (DefaultClassLoaderService.java:119-121), so under the default config the pre-fix bug mainly corrupted the reference-count bookkeeping rather than leaking a JVM-reachable object outright. The fix is most impactful — a real, unbounded metaspace/file-handle leak — for operators running withclassloader-cache-mode: false. This doesn't change my assessment of the fix (it's correct either way, and a reference-count drift is still a real correctness bug on the default path), but it's useful context for anyone triaging the original production symptom.
1.4 Error Handling and Logging
No numbered issues. releaseClassLoadersAfterFailedDeployment (:566-581) attaches any cleanup failure to the original deployment exception via addSuppressed rather than replacing it, and logs each cleanup failure at severe — this preserves root-cause visibility while still attempting to release every remaining reference, which is the correct pattern here.
2. Code Quality Assessment
2.1 Coding Standards
New non-trivial method (releaseClassLoadersAfterFailedDeployment) has a Javadoc explaining scope and the suppressed-exception contract (:559-565). The two new callback parameters on the private deployLocalTask overload are self-explanatory from their functional-interface names and the inline comments at their call sites (:451-452, :538-539). No new fields lack comments. Meets the repo's "comment important methods" standard.
2.2 Test Coverage and Test Stability
Two new tests, both asserting on DefaultClassLoaderService's actual reference-count state (queryClassLoaderReferenceCount) rather than on logs or timing, which is the right level to test a reference-counting bug at:
testDeployTaskReleasesClassLoadersWhenDeserializationFails— covers the acquisition-loop failure path (outercatchindeployTask).testDeployTaskHandlesFailureBeforeContextPublication— covers thedeployLocalTask-internal, pre-publication failure path, and additionally verifies via aMockito.spythatnotifyTaskStatusToMasterstill fires withFAILED, which is exactly the regression an earlier round of this PR introduced and then fixed (registering the completion callback unconditionally first).
I checked both tests' assumptions against DefaultClassLoaderService: the isPresent() == true / referenceCount == 0 combination they assert only holds because classloader-cache-mode defaults to true in this test's server setup (cache mode skips eviction on refcount-zero, DefaultClassLoaderService.java:119-121), so both tests are internally consistent with the actual default runtime config, not accidentally-passing.
Stability rating: Stable. Neither test depends on wall-clock timing races; testDeployTaskHandlesFailureBeforeContextPublication uses Mockito.verify(..., Mockito.timeout(5000)) only to await the async notifyTaskStatusToMaster dispatch, which is a bounded, one-directional wait rather than a tight race window.
2.3 Documentation Updates
None required — internal cleanup with no user-facing behavior, config, or API change, consistent with the PR's own checklist.
3. Architectural Soundness
3.1 Precise fix vs. workaround vs. long-term solution
This is a precise fix at the correct layer: the ownership-transfer boundary between "deployment attempt owns these classloader refs" and "the running TaskGroupContext/TaskGroupExecutionTracker owns them" is made explicit via the callbacks, rather than trying to infer ownership after the fact from map membership (which is exactly the approach that was tried and shown to be racy earlier in this same PR). No workaround shortcuts are taken.
3.2 Maintainability
The acquisition ledger + two-callback handoff is a few lines longer than a naive try/finally, but it is the minimum machinery needed to make "was this handed off before or after the point of no return" a synchronous, non-racy fact rather than something re-derived from mutable shared state later. I consider this appropriately, not excessively, complex for the invariant it protects.
3.3 Extensibility
Self-contained to TaskExecutionService; does not require any other connector/registration/plugin-matrix changes (I confirmed this touches only TaskExecutionService.java and its test — no SPI, factory, or plugin-mapping.properties involvement, so the "connector/datasource registration matrix" checks in this repo's review protocol don't apply here).
3.4 Historical-version compatibility
No checkpoint/savepoint, serialization, or wire-protocol surface is touched, and no config default changes. Nothing here affects upgrade or restore from an older-version job state.
Cross-PR overlap note (not a defect in this PR, flagging for merge-order awareness): #11757 ("Fix stale taskDone removing execution context of a newer restore generation") and #11727 ("Release the start latch when a blocking worker cannot start") both modify this exact same file, TaskExecutionService.java, in the same neighborhood this PR touches. In particular, #11757 rewrites TaskGroupExecutionTracker's constructor (adding an ownedContext parameter) and replaces recycleClassLoader/the taskDone completion path that this PR's ownership-transfer handoff depends on. Whichever of these three merges last will need a real rebase, not just a textual conflict resolution — the reviewer of that later PR should re-verify the ownership/ref-count invariants described above still hold against the other's changes. I'm not treating this as a blocker for #11812 on its own, since #11812 is correct against current dev, but it's worth the eventual merger's attention.
4. Issue Summary
No blocking issues found in this fresh, from-scratch re-derivation of the current head's logic.
| Number | Issue | Location | Severity |
|---|---|---|---|
| — | None | — | — |
Remaining risk / blind spots to name explicitly:
- The cross-PR file overlap with #11757 and #11727 described above — a merge-order risk, not a defect in this diff.
- The leak's practical JVM-memory severity is muted under the default
classloader-cache-mode: true; the fix is still correct and worth having, but reviewers triaging the original production symptom (issue #11808) should confirm whether that report came from a non-defaultclassloader-cache-mode: falsedeployment.
5. Merge Recommendation
Conclusion: Ready to merge
Blockers: none.
Recommended fixes (non-blocking): none beyond the merge-order awareness noted above.
Overall assessment: I independently re-derived the entire mechanism from the current head (730a46bd44) rather than trusting the PR history — confirmed via git diff that TaskExecutionService.java and its test have had zero changes since my last full verification and approval on 2026-08-24 (head 01a75d6c); every commit since then is a no-op Merge branch 'dev'. My independent trace reaches the same conclusion as that approval: the acquisition ledger, the two-callback ownership handoff, and the monotonic publication flag together give every failure branch exactly one correct outcome (release, or hand off to the published context's normal lifecycle), with no double-release path, and the regression tests assert on the real invariant (reference count) rather than a proxy for it. CI's apache-side Build check is currently IN_PROGRESS on this exact head at review time — no source-side blocker from my side; recommend merging once that completes green.
|
Hello, currently we only need to ensure that the CI has passed. I understand that if there is no branch conflict, there is no need to rebase dev again😄 |
|
@nzw921rx Your understanding is correct on both points — confirmed against the current head just now. CI status: current head Rebase/sync: also confirmed — comparing One thing worth noting so it doesn't cause confusion: GitHub currently shows this PR's merge state as "Unstable" rather than "Clean." That's not a real CI/code signal — it's caused by an internal repo-automation workflow ( Net: no further contributor action needed here — CI is green, no rebase required, and my source-side approval from the classloader logic review still stands (only a clean |
Purpose of this pull request
Fixes #11808.
TaskExecutionService.deployTaskacquires classloader references while constructing a task group. If deployment fails before theTaskGroupContextis published, those references must be released by the deployment attempt. Once the context is published, cleanup belongs to the normal task-group lifecycle.This change:
deployTaskreturnsDoes this PR introduce any user-facing change?
No. This changes internal Zeta task deployment cleanup only.
How was this patch tested?
Added regression coverage for failures during task deserialization and task-context initialization before context publication. The tests verify that no task-group context is published, every acquired classloader reference is released, and the failed deployment is still reported to the master.
Also ran the focused engine test class on JDK 11:
./mvnw -pl seatunnel-engine/seatunnel-engine-server \ -Dtest=TaskExecutionServiceTest \ -DfailIfNoTests=false testAll 15 tests passed.
Check list