Repository navigation
[Fix][Zeta] Isolate task cleanup by execution context - #12238
Conversation
b94e975 to
94ce85d
Compare
|
@davidzollo I have redesigned the lifecycle model to solve this problem. Could you please help me review it? Thank you very much.🔥 |
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
On a worker, TaskGroupLocation identifies a logical task group and is reused every time that task group is redeployed (after a pipeline restore, a checkpoint-triggered restart, etc.). Before this PR, TaskExecutionService kept the cancellation future, async-function futures, and timer-flush futures all keyed only by that reusable TaskGroupLocation. If an older deployment ("generation A") finishes its cleanup (TaskGroupExecutionTracker.taskDone -> recycleClassLoader/cancelAsyncFunction/cancelTimerFlushForTaskGroup) after a newer deployment ("generation B") has already been published at the same location — a genuinely reachable race during pipeline restore/failover — generation A's late cleanup would remove or cancel generation B's live resources: its classloaders, its cancellation signal, its in-flight async functions, or its timers. This PR fixes it by minting a TaskGroupContext per concrete deployment (keyed by an immutable executionId, already generated by the master and carried in TaskGroupImmutableInformation), rekeying the three affected maps by that context instead of by location, and using ConcurrentMap.compute to atomically check "is my context still the active one for this location?" before ever touching the active-context mapping.
Cross-PR relationship: No file or runtime-state overlap with #12235/#12237 (SeaTunnelTask.close()) or #12236 (CheckpointCoordinator.java). This PR only touches TaskExecutionService.java, TaskGroupContext.java, and their test. It is the most architecturally significant of the four PRs in this batch, and per its own description is a follow-up to a previously-discussed issue (#11755, itself based on #11757) where Daniel (this reviewer) was already credited among the people who traced the remaining cleanup/lifecycle gaps — I've re-verified the design from scratch against current dev rather than relying on that history.
1. Code Change Review
1.1 Core Logic Analysis
Files: TaskExecutionService.java, execution/TaskGroupContext.java, TaskExecutionServiceTest.java.
Key findings:
-
The race is real and I traced the full mechanism. Pre-PR,
cancellationFutures,taskAsyncFunctionFuture, andtimerFlushFutureswere allConcurrentMap<TaskGroupLocation, ...>.TaskGroupExecutionTracker.taskDone()on generation A's completion calledexecutionContexts.remove(taskGroupLocation)/cancellationFutures.remove(taskGroupLocation)/cancelAsyncFunction(taskGroupLocation)/cancelTimerFlushForTaskGroup(taskGroupLocation)— every one of those calls addresses the location, not the specific deployment. If generation B was deployed (redeploy after restore) and published its own entries at the same location while A's tracker was still winding down (A had already entered its terminal branch but hadn't yet reached thefinally-equivalent cleanup), A's cleanup would silently clobber B's live cancellation future / async futures / timers / classloaders. This is exactly the class of bug the E2E hardening commits already ondev(worker-restart restore with missing coordinator checkpoint state; task stuck in CANCELING when worker crashes mid-cancel) are targeting, so the premise is consistent with this project's known problem area, not a speculative concern. -
The fix design is sound and I verified its concurrency reasoning, not just its shape. The two-phase publish in
deployLocalTask(TaskExecutionService.java:~697-716) registerscancellationFutures,taskAsyncFunctionFuture, andtimerFlushFuturesfor the new context before publishingexecutionContexts.put(taskGroupLocation, context). The code comment claims this ordering, plusConcurrentHashMap's happens-before guarantee on put/get pairs, is sufficient to guarantee a concurrentcancelTaskGroup()(which first readsexecutionContexts.get(location), thencancellationFutures.get(context)) can never observe a published context whose cancellation future isn't visible yet. I worked through the JMM transitivity chain by hand: (put into cancellationFutures) happens-before (put into executionContexts) [program order, same thread] happens-before (get from executionContexts returns that context) [ConcurrentHashMap publish guarantee] happens-before (get from cancellationFutures using that context) [program order, same thread]. Transitivity of happens-before holds across differentConcurrentHashMapinstances, so the claim is correct — this is a subtle point and the PR is right to call it out explicitly in a comment rather than leaving it implicit. -
TaskGroupContext.equals()/hashCode()correctly excludes mutable fields. Before this PR,TaskGroupContextwas@Data @AllArgsConstructor— meaning if it had ever been used as a map key with all fields participating inequals/hashCode, mutatingclassLoadersin place (whichrecycleClassLoaderdoes viacontext.setClassLoaders(null)) while the object was live as a key would have silently corrupted whichever map's hash bucket held it (the classic "mutable object as a hash key" bug). This PR replaces@Datawith@Getter/@Setterplus a hand-writtenequals/hashCodebased solely on the immutableexecutionId, with an explicit Javadoc warning against ever including mutable fields. SinceTaskGroupContextis now used as a map key for the first time in this PR, this was the correct thing to get right, and the PR clearly understood the pitfall rather than falling into it. -
finishExecution's stale-generation guard is correctly atomic.executionContexts.compute(taskGroupLocation, (ignored, activeContext) -> { if (!context.equals(activeContext)) return activeContext; ...; return null; })(TaskExecutionService.java:522-531) makes the "is my context still active" check and the active-to-finished transition a single atomic operation underConcurrentMap.compute's per-key locking, so a stale generation A can never race a real check-then-act window with generation B's publish. Cleanup of A's own resources (cancellationFutures.remove(context),recycleClassLoader,cancelAsyncFunctionFutures,cancelTimerFlushFutures) is performed unconditionally, regardless of whether A was found to be stale — correctly, since these are keyed by A's own context and can never touch B's entries now that the maps are context-keyed. The one thing that does not happen for a stale generation is being recorded intofinishedExecutionContexts— a deliberate and correct choice, since that map should reflect the most recent finished generation for a location, not a superseded one. -
Publicly-visible API narrowed. The old 3-arg
public PassiveCompletableFuture<TaskExecutionState> deployLocalTask(TaskGroup, ConcurrentHashMap, ConcurrentHashMap)convenience overload is removed; the remaining 5-arg overload (now requiringexecutionIdand the two publish-callbacks) drops fromprivateto package-private (no modifier). I searched the whole repo for other callers ofdeployLocalTaskand found only this file,TaskExecutionServiceTest.java(same package, updated to the new 5-arg signature), andTaskDeploymentPrePublicationClassLoaderLeakIT.java(different package,org.apache.seatunnel.engine.e2e) — the latter only mentionsdeployLocalTaskin Javadoc-style comments, it never calls it directly (it goes through the publicdeployTask()entry point), so there's no compile break. Still, narrowing apublicmethod's visibility is technically an API-compatibility change worth a one-line mention in the PR's "Compatibility" section, even though I found no evidence of any external caller in this monorepo. -
Runtime-path / sequence (reproducing the PR's own well-drawn diagram, verified against source): a late generation-A tracker calling
finishExecutionafter generation B is already active for the sameTaskGroupLocationnow (a) leavesexecutionContexts.get(location)== context B untouched, (b) still releases A's classloaders viaclassLoaderService.releaseClassLoader(...)using A's ownjarsmap, (c) still cancels A's own async futures and timers via the A-keyed buckets, and (d) never touches B's cancellation future / async futures / timers because they live under a different map key (contextidentity, notlocation). This is the correct end state for all four resource types the PR's own table enumerates.
1.2 Compatibility
The PR's own "Compatibility" section states: no config/public connector API changes, no new dependency, no TaskGroupContext serialization, no checkpoint/savepoint format change, and TaskGroupImmutableInformation.executionId is an existing serialized field already populated by every production deployment. I independently confirmed TaskGroupContext is never serialized (only used worker-side, in-JVM) and that executionContexts/finishedExecutionContexts — the two maps other code paths query by TaskGroupLocation via getExecutionContext/getActiveExecutionContext (both pre-existing, unmodified by this PR) — keep their original key type, so no caller of those two lookup methods is affected. The one nuance I'd add to the "Compatibility" section: the narrowed visibility of deployLocalTask's public overload (see 1.1) is a source-compatibility change for any out-of-tree caller, even though none exists in this repository today.
1.3 Performance / Side-Effect Analysis
No new locks are introduced — the design deliberately relies on ConcurrentHashMap's existing per-bucket concurrency and ConcurrentMap.compute's per-key atomicity rather than adding a coarser service-wide lock, which the PR calls out explicitly. Memory overhead is one additional TaskGroupContext-keyed entry per map per concrete deployment instead of per logical location — since a location can now (transiently, during restore) have both an old and new context's entries live simultaneously across three maps, this is a small, bounded, and self-cleaning increase (the old context's entries are removed once its tracker's cleanup runs), not an unbounded growth risk. No new retries, no new blocking I/O, no additional serialization cost.
1.4 Error Handling and Logging
finishExecution wraps each of recycleClassLoader, cancelAsyncFunctionFutures, and cancelTimerFlushFutures in its own try { ... } catch (Throwable t) { logger.severe(...); } (TaskExecutionService.java:544-558), so a failure in one cleanup step can't prevent the others from running — consistent with the "best-effort, attempt everything" cleanup philosophy also seen in #12235/#12237's SeaTunnelTask.close() fix, applied here at the task-group level. asyncExecuteFunction/registerTimerFlushTask now throw the pre-existing TaskGroupContextNotFoundException (not a new exception type) when a deployment's resource bucket is missing, with messages that include the location and execution ID — good diagnostic detail, no sensitive data.
2. Code Quality Assessment
2.1 Coding Standards
Javadoc coverage on the touched fields and methods is thorough and, notably, explains why (e.g. the field comment on taskAsyncFunctionFuture at lines 30-35 explicitly says "Do not change the key back to TaskGroupLocation" and explains the reused-after-restore hazard) rather than restating the obvious — exactly the kind of comment this project's own conventions ask for on non-trivial concurrent/lifecycle state. TaskGroupContext's new Javadoc explicitly documents the equals/hashCode contract and why mutable fields must stay excluded. I have no missing-comment findings on the touched code.
2.2 Test Coverage and Test Stability
Three new/expanded tests in TaskExecutionServiceTest.java:
testStaleTaskDoneCleansOnlyOwnedGenerationResources(lines 716-797): directly constructs old/newTaskGroupContexts with distinct execution IDs at the same location, wires up both generations' cancellation/async/timer state via reflection, drives the old tracker'staskDone(), and asserts the new context remains untouched while the old one's resources are fully cleaned — this is a precise, deterministic reproduction of the exact race this PR fixes.testTaskGroupContextEqualityUsesExecutionId(lines 800-824): specifically tests thatLong.hashCode(1L)andLong.hashCode(1L << 32)collide (both are1) and that two contexts with those execution IDs still remain distinct map entries — a genuinely useful adversarial test that guards against a subtle hash-collision regression, not just a happy-path equals check.testStaleFailedTaskDoneCleansOnlyOwnedGenerationResources(lines 827-896): same scenario but via the exception/failure cleanup path (cancelAllTask) rather than the normal-completion path, confirming both terminal paths respect generation isolation.testRegisterAndCloseTimerFlushTaskandtestReRegisterTimerFlushCancelsPreviousFuturewere updated to install a realTaskGroupContextvia a newinstallTestContext/removeTestContexthelper pair rather than relying on the old location-keyed auto-creation, and a new assertion confirms the deployment-level timer bucket survives closing its last individual timer (only the owning tracker may remove it) — this directly covers the "no premature bucket removal from a concurrent registration racing an unrelated subtask's cleanup" design point called out in the new Javadoc.- All new tests use deterministic construction, mocked futures with
ScheduledFuturemocks stubbed viaMockito.when(...isDone()).thenReturn(false), noThread.sleep, no wall-clock timing assumptions, and clean up viatry/finallyblocks that remove their installed map entries so they can't pollute later tests sharing the sameserverinstance. Reflection-based field access is used (ReflectionUtils.getField, a pre-existing shared utility, not new), which is somewhat invasive but appropriate here given the state under test is intentionally package-private/internal. - The PR's own description reports 18/18 tests passing locally for
TaskExecutionServiceTest, and I confirmed the PR's overall fork CI Build check is green (unlike the other three PRs in this batch, none of which show a related-module failure either, but this one has no failure of any kind). - Stability rating: Stable. I found no anti-pattern from the flaky-test checklist (no sleep-based waits, no nondeterministic external state, no hard-coded ports, no unclosed resources, no order dependency between the new tests).
One coverage gap worth flagging: all new coverage here is unit-level, driving TaskGroupExecutionTracker/TaskExecutionService directly with hand-constructed contexts. Given this fixes a race specifically triggered by pipeline restore/master-failover timing, and this repository's recent history shows a deliberate pattern of adding dedicated E2E coverage for exactly this class of scenario (worker-restart restore, checkpoint-trigger failure, mid-cancel crash — all landed as separate E2E-only PRs per the current dev git log), an end-to-end test that actually forces a restore/redeploy race at the same TaskGroupLocation and asserts the new generation survives would round this out. Not a blocker given the unit coverage is already strong and precise, but a natural, in-character follow-up for this codebase.
2.3 Documentation Updates
No docs/en/docs/zh change — correct, since this is purely an internal Zeta worker lifecycle fix with no user-facing config, connector API, or CLI surface. The PR body itself already contains an unusually thorough internal design write-up (sequence diagrams for the two publish-order phases, the failover scenario, and the pipeline-restore scenario); none of that belongs in end-user docs, and I don't see anything user-facing that needs docs/en/docs/zh updates.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix, and a well-reasoned one — it correctly identifies that the actual bug is "logical identity and deployment identity were conflated as the same map key" and fixes exactly that, without touching the maps that legitimately should stay location-keyed (executionContexts, finishedExecutionContexts). It resists the temptation to add a coarser lock and instead leans on the concurrent-map primitives that were already the right tool.
3.2 Maintainability
The new TaskGroupContext equals/hashCode contract, the two-phase-publish ordering rationale, and the "never recreate a resource bucket after cleanup" invariant are all explicitly documented in code comments at the exact call sites where a future change is most likely to violate them (e.g. the warning against reverting taskAsyncFunctionFuture's key type back to TaskGroupLocation). This is exactly the kind of defensive documentation this class of concurrency fix needs to stay correct under future edits.
3.3 Extensibility
The TaskGroupContext-as-key pattern generalizes cleanly if a future change needs to add another deployment-scoped resource bucket (it would just follow the same "register under context before publishing to executionContexts" recipe already established here).
3.4 Historical-Version Compatibility
No checkpoint/savepoint state, wire protocol, or historical task JSON is touched — executionId already exists in TaskGroupImmutableInformation and is already populated by every production deployment per the PR's own compatibility note, which I have no reason to doubt given it's an existing field, not a new one. Safe for rolling upgrade: a worker running the new code and a master running old code (or vice versa) would simply continue exchanging the same executionId field that already flows through TaskGroupImmutableInformation today.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | deployLocalTask's public 3-arg convenience overload was removed and the remaining overload's visibility narrowed from private to package-private; no in-repo caller was affected, but this is technically a source-compatibility change worth a one-line mention in the PR's own "Compatibility" section |
TaskExecutionService.java (removed method, ~line 113-118 pre-PR) |
Low |
| 2 | No E2E test forces an actual restore/redeploy race at the same TaskGroupLocation; coverage is thorough but unit-level only, whereas this codebase's recent history for this exact bug class (restore/failover races) has consistently paired unit coverage with dedicated E2E coverage |
seatunnel-e2e/seatunnel-engine-e2e (no new file) |
Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
-
Blockers — must be fixed
- None. I found no correctness defect in the concurrency design, the resource-cleanup scoping, or the equals/hashCode contract, and CI (including engine-server unit tests) is green.
-
Recommended fixes — non-blocking
- Issue 1: mention the
deployLocalTaskvisibility narrowing explicitly in the PR's "Compatibility" section for the record, even though no in-repo caller is affected. - Issue 2: consider a follow-up E2E test that exercises an actual pipeline-restore race at a shared
TaskGroupLocation, matching this codebase's established pattern for this bug class.
- Issue 1: mention the
Overall assessment: this is the strongest of the four PRs in this batch. It correctly root-causes a real concurrency bug (conflating logical task-group identity with deployment identity as a map key), the fix is scoped to exactly the three maps that needed it, the JMM reasoning behind the two-phase publish ordering is sound and I verified it independently rather than taking the code comment's word for it, and the new test suite directly targets the race with deterministic, non-flaky tests including a specifically adversarial hash-collision case. I'm not aware of any prior maintainer review on this PR to agree or disagree with — this is the first review on it. No blockers; the two notes above are minor and don't need to hold up merge.
BlockingWorker.run() resolved its execution context and class loader before entering its try block, while startedLatch.countDown() sat inside it. TaskGroupLocation is reused verbatim across restore generations, so a taskDone() from an earlier generation can remove the entry the current generation just installed. When that happened the lookup threw outside try/finally entirely, the latch was never counted down, and the exception was lost on a future nobody polls. submitBlockingTask() then waited on that latch forever while holding the SubPlan monitor, so checkpoint-error handling could not move the pipeline to a terminal state and the submitting client hung. See apache#11679. Resolve the context inside the try, fail loudly with an IllegalStateException naming the task group instead of an implicit NPE, and release the latch on every exit path via a startLatchReleased-guarded finally. Two consequences of the finally now being reachable are handled here too: a missing per-task class loader fails fast rather than silently installing a null context class loader, and close() only runs on a task whose init() was actually attempted, with a widened catch so a teardown failure cannot escape and skip the context class loader restore. The cleanup-ownership side of this race is fixed separately in apache#12238.
The class javadoc still presented the stale-taskDone eviction as the live trigger. Since apache#12238 that path is no longer reachable, and the worker takes its class loader from the context its own tracker pinned rather than from the shared map, so say that instead of describing a trigger the test can no longer produce. The contract the test asserts is unchanged: deploying a task group must return even if the execution context for that location disappears mid-flight.
The race test covers one half of the family: a deployment must return even if the execution context for its location disappears mid-flight. The other half - a redeploy racing an in-flight taskDone() and tearing down the newer deployment's resources - sits in deployLocalTask() and the tracker teardown, which this change does not touch. Say so in the class javadoc and point at apache#12238, so the test is not read as covering something it does not.
…ative-worker-budget dev changed TaskExecutionService.deployLocalTask to take an execution id and the context-published and failure callbacks (apache#12238 and later). The merge has no textual conflict, but TaskExecutionServiceCooperativeBudgetTest still called the old signature, so its helper now passes the new arguments the same way TaskExecutionServiceTest does.
Closes #11755.
This PR is based on the original work in #11757 and incorporates the review findings from that discussion. Thanks to @waterWang for the original fix and to @DanielLeens, @SEZ9, @davidzollo, and @BinTaoMa for tracing the remaining cleanup and lifecycle gaps.
Implementation overview
The fix separates two concepts that previously shared the same key:
TaskGroupLocationidentifies the logical task group and is reused after restore.executionIdidentifies one concrete deployment of that task group.TaskExecutionServicestill owns all runtime resources. They are not moved intoTaskGroupContext; instead, the context carries the immutableexecutionIdand is used as thedeployment-scoped key.
TaskGroupLocationTaskGroupLocation(unchanged)TaskGroupLocationTaskGroupContextTaskGroupLocationTaskGroupContextTaskGroupLocationTaskGroupContextThe lifecycle is therefore straightforward:
active for the logical location.
TaskGroupExecutionTrackerretains the same context and cleans resources using that exact key.prevents it from removing the newer active context.
This closes both sides of the race: the new deployment remains intact, and the stale deployment's
classloaders, cancellation entry, async futures, and timer futures are still reclaimed.
Problem
TaskGroupLocationcontains onlyjobId,pipelineId, andtaskGroupId. It identifies a logical task group, so the same value is reused when that task group is restored and deployed again.Before this change, worker-side lifecycle resources were also keyed only by
TaskGroupLocation:TaskGroupContext;That loses the deployment generation. If generation A finishes late after generation B has already been installed at the same location, A's
taskDone()can remove or cancel B's resources.sequenceDiagram participant A as Generation A tracker participant W as Worker maps participant B as Generation B deployment A->>W: publish location -> context A B->>W: restore publishes same location -> context B A->>W: late taskDone(location) Note over A,W: Old cleanup addresses resources only by location A--xW: removes/cancels generation B resourcesDepending on which resource is removed, the new generation can lose its classloader, cancellation signal, asynchronous work, timer flush, or active execution context. The result can be a restore hang, an incorrect task failure, or background work continuing with the wrong generation.
Design
The implementation separates logical identity from deployment identity:
TaskGroupLocationremains the logical lookup key used by operations.executionIdis generated by the master'sFlakeIdGeneratorfor every deployment and is transferred inTaskGroupImmutableInformation.TaskGroupContextis worker-local and represents exactly one deployment.TaskGroupContext.equals()andhashCode()use only the immutableexecutionId. Mutable runtime fields (taskGroup,classLoaders, andjars) never participate in map-key identity.TaskGroupExecutionTrackercaptures the concrete context created with it.flowchart LR L[TaskGroupLocation<br/>logical task group] -->|active lookup| C[TaskGroupContext<br/>executionId] C --> TG[TaskGroup] C --> CL[Classloaders and jars] C --> CF[Cancellation future] C --> AF[Async-function bucket] C --> TF[Timer-flush bucket] TR[TaskGroupExecutionTracker] -->|owns exact deployment| CThe context itself is not serialized. Only
executionIdtravels withTaskGroupImmutableInformation; the worker builds a new runtime context after deserialization.Publication order
A deployment is published in two phases:
TaskGroupLocation -> TaskGroupContextto the active-context map last.flowchart TD A[Create TaskGroupContext with executionId] --> B[Register cancellation future by context] B --> C[Register async bucket by context] C --> D[Register timer bucket by context] D --> E[Publish location -> context last] E --> F[Submit tasks]All location-based callers resolve the active context first and then use that exact context to find its resources. Because the active-context map is a
ConcurrentHashMap, observing the final publication also makes the preceding resource registrations visible. Publishing the location first would allow a cancellation request to see an active context before its cancellation future exists.Resource buckets are created only during deployment and removed only by the owning tracker. Runtime registration methods do not recreate missing buckets, and closing the last individual timer does not detach the deployment-level timer bucket. This gives every bucket one clear lifecycle owner and avoids registration/empty-bucket removal races.
Cleanup behavior
When a tracker reaches terminal state, it atomically evaluates the active context for that location with
ConcurrentMap.compute:flowchart TD A[Tracker for context A finishes] --> B{active context executionId == A?} B -->|yes| C[Move A from active to finished] B -->|no, newer context B is active| D[Keep active mapping unchanged] C --> E[Clean resources keyed by context A] D --> E E --> F[Release A classloaders] E --> G[Remove A cancellation future] E --> H[Cancel A async futures] E --> I[Cancel A timer futures]Only the active-to-finished transition is conditional. Cleanup of the tracker's own context is always performed, including on the stale path. Since cancellation, async, and timer maps are keyed by
TaskGroupContext, generation A can clean its own resources without touching generation B.ConcurrentMap.computemakes the comparison and removal atomic for that location. No new service-wide lifecycle lock is required. The existing deployment synchronization still serializes competing deploy calls, while cleanup and publication are protected by the concurrent map's per-key atomic operations.Behavior during failover
Master failover with a surviving worker
When the active master changes, the new master reconstructs the physical vertices from distributed
state. A task recorded as
RUNNINGorDEPLOYINGis checked against its recorded worker before thestate machine decides whether it needs recovery.
sequenceDiagram participant M1 as Old master participant H as Distributed job state participant M2 as New master participant W as Existing worker M1--xH: master fails M2->>H: reconstruct PhysicalVertex and persisted state M2->>W: CheckTaskGroupIsExecuting(location) alt Context A is still active W-->>M2: true Note over M2,W: Keep the persisted RUNNING state Note over M2,W: Worker continues context A without redeployment else W-->>M2: false M2->>H: move task toward FAILING Note over M2,W: Pipeline state machine enters the normal restore flow endThe master rebuilds its scheduling objects, but a healthy task already running on the worker is not
automatically invalidated. The new master adopts that execution. If a duplicate deployment request
does reach the same worker while the context is active, the existing active-context guard skips the
deployment and releases the classloaders acquired while deserializing the duplicate request.
Pipeline restore
A pipeline failure first drives the old tasks through cancellation and terminal-state reporting.
Only after the pipeline reaches
FAILEDorCANCELEDand is eligible for retry does the schedulerrelease/reapply resources and deploy the next generation.
sequenceDiagram participant P as Pipeline state machine participant W as Worker participant A as Generation A tracker participant B as Generation B deployment P->>P: enter FAILING or CANCELING P->>W: CancelTaskOperation(location) W->>A: complete generation A cancellation signal A->>A: cancel A tasks and A-owned background futures A->>W: finish context A and release A classloaders A-->>P: report FAILED or CANCELED P->>P: wait for all task groups to reach terminal state P->>P: release and reapply pipeline resources P->>B: create deployment information with a new executionId B->>W: deploy generation B at the same logical location W->>W: publish B resource buckets, then context BThe normal state machine prevents two healthy generations from being deliberately started for the
same logical task group. This PR provides the final worker-side guard for delayed cleanup caused by
failure or failover timing: if generation A's tracker runs after B is visible, the execution-ID
comparison preserves context B and the context-keyed maps restrict cleanup to A's resources.
sequenceDiagram participant A as Late generation A tracker participant W as Worker active/resource maps participant B as Generation B B->>W: active[location] = context B A->>W: finish context A W->>W: compute(location) sees A.executionId != B.executionId W-->>B: keep context B active W->>W: remove/cancel resources[context A] onlyIf the worker process itself fails, its worker-local contexts, trackers, and resource maps disappear
with that process; the replacement worker creates a fresh context from the new deployment. The
executionIdscopes worker-local resources to a specific task-group deployment.Classloader ownership
Classloader references are owned by the deployment attempt until the runtime context is published:
TaskGroupContext;This closes the stale-generation classloader leak identified during review without releasing the newer generation's classloaders.
Compatibility
This is an internal Zeta worker lifecycle change:
TaskGroupContextserialization;TaskGroupImmutableInformation.executionIdis an existing serialized field and every production deployment already receives a generated value.Tests
The regression coverage deterministically installs two contexts with the same
TaskGroupLocationand different execution IDs, then drives the old tracker through both normal and failure cleanup paths. It verifies that:TaskGroupContextequality is based onexecutionId;ConcurrentHashMapeven whenLong.hashCodedeliberately collides;Executed locally:
Result: 18 tests run, 0 failures, 0 errors, 0 skipped.
The full Maven
verifylifecycle was not run.