Skip to content

[Fix][Zeta] Isolate task cleanup by execution context - #12238

Merged
davidzollo merged 2 commits into
apache:devfrom
nzw921rx:feature/fix-stale-task-cleanup
Sep 13, 2026
Merged

davidzollo merged 2 commits into
apache:devfrom
nzw921rx:feature/fix-stale-task-cleanup

Conversation

@nzw921rx

@nzw921rx nzw921rx commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

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:

  • TaskGroupLocation identifies the logical task group and is reused after restore.
  • executionId identifies one concrete deployment of that task group.

TaskExecutionService still owns all runtime resources. They are not moved into
TaskGroupContext; instead, the context carries the immutable executionId and is used as the
deployment-scoped key.

Runtime state Lookup key before Lookup key after
Active context TaskGroupLocation TaskGroupLocation (unchanged)
Cancellation future TaskGroupLocation TaskGroupContext
Async-function futures TaskGroupLocation TaskGroupContext
Timer-flush futures TaskGroupLocation TaskGroupContext

The lifecycle is therefore straightforward:

  1. Deployment creates the context and all of its resource buckets, then publishes the context as
    active for the logical location.
  2. Runtime operations resolve the active context once and register resources under that context.
  3. TaskGroupExecutionTracker retains the same context and cleans resources using that exact key.
  4. On late completion, an old tracker may clean its own resources, but an atomic execution-ID check
    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

TaskGroupLocation contains only jobId, pipelineId, and taskGroupId. 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:

  • the active TaskGroupContext;
  • the cancellation future;
  • asynchronous-function futures;
  • timer-flush futures.

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 resources
Loading

Depending 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:

  • TaskGroupLocation remains the logical lookup key used by operations.
  • The existing executionId is generated by the master's FlakeIdGenerator for every deployment and is transferred in TaskGroupImmutableInformation.
  • TaskGroupContext is worker-local and represents exactly one deployment.
  • TaskGroupContext.equals() and hashCode() use only the immutable executionId. Mutable runtime fields (taskGroup, classLoaders, and jars) never participate in map-key identity.
  • Every TaskGroupExecutionTracker captures 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| C
Loading

The context itself is not serialized. Only executionId travels with TaskGroupImmutableInformation; the worker builds a new runtime context after deserialization.

Publication order

A deployment is published in two phases:

  1. Create all execution-scoped resource buckets under the new context.
  2. Publish TaskGroupLocation -> TaskGroupContext to 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]
Loading

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]
Loading

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.compute makes 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 RUNNING or DEPLOYING is checked against its recorded worker before the
state 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
    end
Loading

The 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 FAILED or CANCELED and is eligible for retry does the scheduler
release/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 B
Loading

The 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] only
Loading

If 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
executionId scopes 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:

  • failure before publication releases every classloader acquired by that attempt;
  • after publication, ownership transfers to TaskGroupContext;
  • terminal cleanup releases the classloaders belonging to the tracker's exact context, even if that tracker has become stale.

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:

  • no configuration or public connector API changes;
  • no new dependency;
  • no TaskGroupContext serialization;
  • no checkpoint/savepoint format change;
  • TaskGroupImmutableInformation.executionId is an existing serialized field and every production deployment already receives a generated value.

Tests

The regression coverage deterministically installs two contexts with the same TaskGroupLocation and different execution IDs, then drives the old tracker through both normal and failure cleanup paths. It verifies that:

  • the newer active context remains installed;
  • the stale context is not published as the finished context;
  • old classloaders, cancellation entries, async futures, and timer futures are cleaned;
  • newer-generation resources remain untouched;
  • TaskGroupContext equality is based on executionId;
  • two different execution IDs remain distinct in ConcurrentHashMap even when Long.hashCode deliberately collides;
  • closing the last timer retains the deployment bucket for tracker-owned cleanup.

Executed locally:

./mvnw -pl seatunnel-engine/seatunnel-engine-server spotless:apply -Dtest=TaskExecutionServiceTest test

Result: 18 tests run, 0 failures, 0 errors, 0 skipped.

The full Maven verify lifecycle was not run.

@nzw921rx
nzw921rx force-pushed the feature/fix-stale-task-cleanup branch from b94e975 to 94ce85d Compare September 9, 2026 15:09
@nzw921rx nzw921rx self-assigned this Sep 9, 2026
@nzw921rx
nzw921rx requested a review from davidzollo September 9, 2026 15:10
@nzw921rx

nzw921rx commented Sep 9, 2026

Copy link
Copy Markdown
Member Author

@davidzollo I have redesigned the lifecycle model to solve this problem. Could you please help me review it? Thank you very much.🔥

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What Problem Does This PR Solve?

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, and timerFlushFutures were all ConcurrentMap<TaskGroupLocation, ...>. TaskGroupExecutionTracker.taskDone() on generation A's completion called executionContexts.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 the finally-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 on dev (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) registers cancellationFutures, taskAsyncFunctionFuture, and timerFlushFutures for the new context before publishing executionContexts.put(taskGroupLocation, context). The code comment claims this ordering, plus ConcurrentHashMap's happens-before guarantee on put/get pairs, is sufficient to guarantee a concurrent cancelTaskGroup() (which first reads executionContexts.get(location), then cancellationFutures.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 different ConcurrentHashMap instances, 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, TaskGroupContext was @Data @AllArgsConstructor — meaning if it had ever been used as a map key with all fields participating in equals/hashCode, mutating classLoaders in place (which recycleClassLoader does via context.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 @Data with @Getter/@Setter plus a hand-written equals/hashCode based solely on the immutable executionId, with an explicit Javadoc warning against ever including mutable fields. Since TaskGroupContext is 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 under ConcurrentMap.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 into finishedExecutionContexts — 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 requiring executionId and the two publish-callbacks) drops from private to package-private (no modifier). I searched the whole repo for other callers of deployLocalTask and found only this file, TaskExecutionServiceTest.java (same package, updated to the new 5-arg signature), and TaskDeploymentPrePublicationClassLoaderLeakIT.java (different package, org.apache.seatunnel.engine.e2e) — the latter only mentions deployLocalTask in Javadoc-style comments, it never calls it directly (it goes through the public deployTask() entry point), so there's no compile break. Still, narrowing a public method'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 finishExecution after generation B is already active for the same TaskGroupLocation now (a) leaves executionContexts.get(location) == context B untouched, (b) still releases A's classloaders via classLoaderService.releaseClassLoader(...) using A's own jars map, (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 (context identity, not location). 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/new TaskGroupContexts with distinct execution IDs at the same location, wires up both generations' cancellation/async/timer state via reflection, drives the old tracker's taskDone(), 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 that Long.hashCode(1L) and Long.hashCode(1L << 32) collide (both are 1) 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.
  • testRegisterAndCloseTimerFlushTask and testReRegisterTimerFlushCancelsPreviousFuture were updated to install a real TaskGroupContext via a new installTestContext/removeTestContext helper 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 ScheduledFuture mocks stubbed via Mockito.when(...isDone()).thenReturn(false), no Thread.sleep, no wall-clock timing assumptions, and clean up via try/finally blocks that remove their installed map entries so they can't pollute later tests sharing the same server instance. 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

  1. 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.
  2. Recommended fixes — non-blocking

    • Issue 1: mention the deployLocalTask visibility 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.

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.

@davidzollo davidzollo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

+1
LGTM

@davidzollo
davidzollo added this pull request to the merge queue Sep 13, 2026
Merged via the queue into apache:dev with commit dab424c Sep 13, 2026
2 of 3 checks passed
abdessalems added a commit to abdessalems/seatunnel that referenced this pull request Sep 13, 2026
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.
abdessalems added a commit to abdessalems/seatunnel that referenced this pull request Sep 13, 2026
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.
abdessalems added a commit to abdessalems/seatunnel that referenced this pull request Sep 18, 2026
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.
@nzw921rx
nzw921rx deleted the feature/fix-stale-task-cleanup branch September 18, 2026 18:08
Vivek1106-04 added a commit to Vivek1106-04/seatunnel that referenced this pull request Nov 7, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] [Zeta] A stale taskDone() can remove the execution context installed by a newer restore generation

3 participants