Skip to content

[Fix][Zeta] Stop pipeline restore when resource allocation fails - #12510

Open
hutiefang76 wants to merge 6 commits into
apache:devfrom
hutiefang76:frank/seatunnel-restore-resource-check
Open

hutiefang76 wants to merge 6 commits into
apache:devfrom
hutiefang76:frank/seatunnel-restore-resource-check

Conversation

@hutiefang76

@hutiefang76 hutiefang76 commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Purpose of this pull request

Fixes #12509. After a Worker is lost, pipeline recovery can fail to allocate replacement slots. The previous code ignored that result and deployed using futures for released slots, producing WrongTargetSlotException: Unknown slot.

Stop that recovery attempt locally when allocation fails, using the existing failure/retry path. Keep two lifecycle boundaries intact: a never-started pipeline taken over by a new Master uses the scheduler's already-reserved slots rather than canceling and allocating twice; cancellation during a recovery wait is rechecked before treating resource exhaustion as a failure. Partially deployed pipelines still cancel before redeployment.

Cancellation is rechecked after resource allocation returns for both outcomes. If allocation succeeds after cancellation was requested, completed reservations are released even before they enter the pipeline ownership map. Tracking is cleared only after release succeeds.

Does this PR introduce any user-facing change?

Yes. Failed recovery allocation no longer deploys onto stale slots. Actual failures use the existing retry budget and interval; defaults, configuration names, public APIs and checkpoint serialization are unchanged. English and Chinese documentation explain retry, cancellation and initial-dispatch behavior.

How was this patch tested?

  • The successful-allocation/cancellation and unassigned-reservation regressions fail against prior production head 6f620d8: 23 tests, two assertion failures, no errors or skips.
  • Java 11.0.33 and 17.0.18: on each, 44 tests passed with no failures, errors or skips across SubPlanResourceRestoreTest, JobMasterMasterFailoverResourceTest, JobMasterTest, ResourceManagerTest and FixSlotResourceTest. Coverage includes reallocating all five real fixed slots after cleanup, preserving tracking on controlled release failure, and existing failover/stale-profile controls.
  • On both Java versions, the extended SplitClusterPendingJobLifecycleFailoverIT#testPendingJobScheduledAfterRunningJobCanceled passed with separate real Master/Worker Hazelcast instances. It checks terminal reservation cleanup and proves queued work can reuse capacity. The focused unit regression injects the exact allocation/cancellation window.
  • Integration with dev at 89f91a8: 55 unit tests and the real split-cluster IT passed on Java 17 in a separate verification tree, including upstream restore-cause retention tests.
  • Full-root verification remains incomplete at the unchanged Spark example: offline resolution requires additional legacy transitive dependencies. The affected-reactor and dev-integration checks above passed.
  • Spotless and git diff --check passed.

Check list

  • Added focused regressions and strengthened an existing cluster IT.
  • Updated English and Chinese documentation.
  • No new dependencies or incompatible API/configuration changes.

I acknowledge this contribution to SeaTunnel.

AI assistance: implementation, tests and this text used DeepSeek and OpenAI Codex. Local validation is reported above; GitHub CI and maintainer review are separate gates.

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

Thanks @hutiefang76 for the very thorough write-up and reproduction in #12509. The diagnosis is correct: the recovery branch ignores the result of preApplyResources(this). The regression test for the main path is a good start, and the docs note is helpful. I found one blocking problem on a second caller of the same code, described below.

What Problem Does This PR Solve?

When a worker is lost and replacement capacity has not joined yet, SubPlan.stateProcess() (FAILED/CANCELED restore branch) calls jobMaster.preApplyResources(this) and discards the boolean result. On failure JobMaster releases the partial allocation but does not replace physicalPlan.preApplyResourceFutures, so the following SCHEDULED step reads the old, already-joined futures. That deploys onto slots that were released. This is the WrongTargetSlotException: Unknown slot seen in the issue.

The fix throws NoEnoughResourceException when preApplyResources(this) returns false. The goal is to reuse the existing FAILING -> cancel -> FAILED -> retry-budget path.

1. Code Change Review

1.1 Core Logic Analysis

Changed code (seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/dag/physical/SubPlan.java:738-748):

Before:

if (checkNeedRestore(state) && prepareRestorePipeline()) {
    jobMaster.releasePipelineResource(this);
    jobMaster.preApplyResources(this);      // result ignored
    restorePipeline();
    return;
}

After:

    jobMaster.releasePipelineResource(this);
    if (!jobMaster.preApplyResources(this)) {
        throw new NoEnoughResourceException("Not enough resources to restore " + pipelineFullName);
    }
    restorePipeline();

Key Findings:

  • The normal (no-failure) path is unchanged. The new branch only runs on a restore attempt where allocation fails. That is exactly the scenario in #12509.
  • This is a precise fix for the stale-future deployment. It leans on an implicit contract that the caller of stateProcess() converts the exception into FAILING (see trace below). That holds for one caller and not for the other (Issue 1).
  • JobMaster.preApplyResources already releases the partially applied slots on failure (JobMaster.java:609-657). There is no slot leak from this change.
  • Root cause is understood correctly. Alternatively the stale futures could be cleared on failure, but skipping deployment is the smaller change.

Runtime-path trace, ordinary restore (worker lost while running):

task FAILED -> SubPlan.addPhysicalVertexCallBack (SubPlan.java:198-241)
  -> updatePipelineState(FAILED)                                   SubPlan.java:346
     -> stateProcess() FAILED branch                               SubPlan.java:738
        -> checkNeedRestore + prepareRestorePipeline()             SubPlan.java:490
             reset() -> pipeline + tasks back to CREATED, initStateFuture() re-armed, sleep(interval)
        -> jobMaster.releasePipelineResource(this)                 JobMaster.java:998  (removes ownedSlotProfilesIMap entry)
        -> preApplyResources(this) == false                        JobMaster.java:659
        -> throw NoEnoughResourceException                         SubPlan.java:743   [NEW]
     <- caught by updatePipelineState catch(Exception)             SubPlan.java:399-403
        -> makePipelineFailing(e): errorByPhysicalVertex=msg, updatePipelineState(FAILING)  (CREATED -> FAILING)
           -> stateProcess() FAILING: task.startPhysicalVertex(); task.cancel()   SubPlan.java:724-737
              -> PhysicalVertex.noticeTaskExecutionServiceCancel: no owned slot -> checkTaskGroupIsExecuting false -> CANCELED   PhysicalVertex.java:418
           -> all tasks done -> getPipelineEndState: canceledTaskNum>0 and state FAILING -> FAILED   SubPlan.java:267-269
           -> updatePipelineState(FAILED) -> stateProcess FAILED -> next restore attempt (budget consumed by prepareRestorePipeline, SubPlan.java:493)

This works and mirrors the long-standing SCHEDULED allocation-failure design (see the comment at SubPlan.java:262-269). I traced it fully and it converges. On budget exhaustion subPlanDone runs and pipelineFuture completes FAILED with the NoEnoughResource message.

Second caller, master failover:

CoordinatorService.pendingJobSchedule (CoordinatorService.java:~476-500)
  executor task:
    pipelineList.forEach(SubPlan::restorePipelineState)            // no try/catch
      -> SubPlan.restorePipelineState (SubPlan.java:566-608)
         -> startSubPlanStateProcess() -> stateProcess()           // called directly, NOT via updatePipelineState
            -> FAILED/CANCELED branch (persisted end state) -> ... -> throw NoEnoughResourceException   [NEW]
    jobMaster.run() is never reached
    finally { jobMasterCompletedSuccessfully(...) -> runningJobMasterMap.remove(jobId) }

Issue 1 (High, blocker). Before this PR, preApplyResources(subPlan) returning false in this path was harmless. The job-level preApplyResources() had already stored valid futures for every pipeline (JobMaster.preApplyResourcesForAll, JobMaster.java:673-679), so the following restore reused them. Now the exception escapes restorePipelineState() and, because nothing catches it, aborts the whole restore task:

  • the forEach stops, so later pipelines are never restored;
  • jobMaster.run() is never called;
  • the finally block removes the job from runningJobMasterMap, because jobMasterCompletedSuccessfully is true for RESTORE when the complete future is not exceptional;
  • jobMasterCompleteFuture never completes.

The result is an orphaned job that is still RUNNING in the IMaps with nobody driving it. In the failover path masterFailoverRestore is already cleared after the job-level allocation succeeds (JobMaster.java:608). The sub-plan-level allocation therefore has to find a fresh set of slots on top of the job-level set, which is exactly what fails on a slot-tight cluster.

Reachability: restorePipelineState() is called for every pipeline of a non-end job. A pipeline whose persisted state is FAILED or CANCELED at failover, with pipelineRestoreNum rebuilt to 0 (documented in JobEnvConfig.md), enters the FAILED branch and checkNeedRestore is true. This is my reading of the source (an inference, I did not run a failover test). If it is wrong, an explicit test should show it.

Suggested fix, which also removes the reliance on the blanket catch in updatePipelineState: handle the failure locally in the branch instead of throwing.

if (!jobMaster.preApplyResources(this)) {
    makePipelineFailing(new NoEnoughResourceException("Not enough resources to restore " + pipelineFullName));
    return;
}

At that point the pipeline has already been reset to CREATED, so makePipelineFailing -> FAILING follows exactly the same path as the ordinary case. It is safe from the failover caller too, since stateProcess and updatePipelineState are both synchronized and reentrant.

1.2 Compatibility Impact

Fully compatible with respect to APIs, config options, defaults, serialization and checkpoint state. No config or protocol change. The behavioral change (fail this attempt instead of deploying on stale slots) is strictly a bug fix for the ordinary path. The only compatibility concern is the failover-path regression in Issue 1, which is a behavioral regression rather than a format break.

1.3 Performance / Side-Effect Analysis

  • No hot-path impact. The added branch runs only on a restore attempt.
  • Retry pressure: each failed allocation now consumes one unit of job.retry.times (default 3) with job.retry.interval.seconds (default 3s), so the default recovery window for replacement capacity is about 9s. Previously the same budget was burned by deploying to stale slots, so the budget behavior is not worse, and the docs note is accurate.
  • Resource release: correct (see 1.1). releasePipelineResource runs before the attempt and preApplyResources releases its partial result on failure.

1.4 Error Handling and Logging

  • Issue 1 (High): the exception is not handled on the master-failover call path (details in 1.1).
  • Issue 2 (Low): the message is only "Not enough resources to restore " + pipelineFullName. It is the message that ends up as the job error, so include the useful bits, for example the number of task groups requested (coordinator + physical vertices). The PR description says "the error includes the pipeline context", which is true, but the required-versus-available slot info would help operators.
  • updatePipelineState logs the caught exception with log.error(ExceptionUtils.getMessage(e)) (no stack trace), which is fine for this exception.

2. Code Quality Assessment

2.1 Coding Standards

The change is minimal and idiomatic. The imports are correct. Issue 3 (Low): the new branch has no code comment. A one-line comment saying why stale futures must not be reused (JobMaster.preApplyResources does not replace the futures when allocation fails) would protect the fix against later refactors.

2.2 Test Coverage and Test Stability

New test class SubPlanResourceRestoreTest.java has three tests, all driven through reflection on the private stateProcess() (SubPlanResourceRestoreTest.java:99-103).

  • insufficientResourcesMustNotStartRestore (:41-50) is the only test that can fail if the production fix is broken. Remove the guard and restorePipeline() is called and no exception is thrown, so the test goes red.
  • allocatedResourcesAllowRestore (:52-58) and exhaustedRetryBudgetDoesNotAllocateOrRestore (:60-68) pass both with and without the fix. They protect adjacent, pre-existing behavior (Issue 4, Low: they are guards against over-blocking, not regression tests for this bug, and I do not object to keeping them).
  • Issue 5 (Medium): no test covers the property the PR depends on for its stated behavior, namely that the thrown exception becomes FAILING and consumes retry budget (i.e. the updatePipelineState -> makePipelineFailing conversion). The test asserts only that stateProcess() throws. It also has no test for the restorePipelineState() (master failover) caller, which is where Issue 1 lives. Please add a test that drives updatePipelineState(FAILED) (or restorePipelineState()) with preApplyResources returning false and asserts the pipeline ends in FAILING/FAILED with no uncaught exception, and no restorePipeline() call. Using reflection to reach a private method also makes the tests brittle. Consider testing through the public entry points.

Flaky-test analysis: Stable. The retry interval is set to 0 (:82), so Thread.sleep(0) in prepareRestorePipeline makes no timing dependence. There are no hard sleeps, no shared static state, and each test builds its own mocks and SubPlan. The only structural fragility is the reliance on RETURNS_DEEP_STUBS and a private method name.

2.3 Documentation Updates

docs/en/introduction/configuration/JobEnvConfig.md and the zh counterpart both get a matching paragraph next to job.retry.times. They are consistent with each other and with the code behavior. No further docs are needed.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix for the ordinary path, but it depends on an implicit exception-handling contract of a private method that has two callers with different handling. See Option B below.

3.2 Maintainability

Throwing from inside the state machine and relying on a distant catch in updatePipelineState is fragile. Handling it locally with makePipelineFailing is consistent with restorePipeline()'s own error handling (SubPlan.java:525-531) and with the SCHEDULED branch (SubPlan.java:700-702).

3.3 Extensibility

The change is neutral. If a future resource strategy wants to wait for capacity instead of failing the attempt, the local branch is the natural place to add it.

3.4 Historical-Version Compatibility

No persisted state or protocol changes. Behavior on older running jobs is unchanged except for the failover-path regression in Issue 1.

4. Issue Summary

Number Issue Location Severity
Issue 1 NoEnoughResourceException escapes restorePipelineState() on the master-failover path; the restore task aborts, remaining pipelines are skipped, and the job is orphaned (removed from runningJobMasterMap, never run or completed) SubPlan.java:743 via SubPlan.java:566-608, CoordinatorService.java:~485-500 High
Issue 2 Exception message lacks required-slot information SubPlan.java:743-744 Low
Issue 3 No comment explaining why the failure must not fall through to restorePipeline() SubPlan.java:742-746 Low
Issue 4 Two of the three new tests pass with or without the fix SubPlanResourceRestoreTest.java:52-68 Low
Issue 5 No test for exception-to-FAILING conversion or for the failover caller; tests use reflection on a private method SubPlanResourceRestoreTest.java:41-50,99-103 Medium

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers
    • Issue 1 (High): make the failure handling independent of the caller. Replace the throw with makePipelineFailing(new NoEnoughResourceException(...)); return; (or otherwise guarantee restorePipelineState() cannot propagate the exception), and add a regression test that covers the failover caller.
  2. Recommended fixes (non-blocking)
    • Issue 5 (Medium): assert the FAILING/FAILED transition and retry-budget consumption, not only that stateProcess() throws.
    • Issue 2, Issue 3, Issue 4 (Low): message detail, a short why-comment, and the note that two tests do not guard this regression.

Overall assessment: the root cause is correctly identified, the ordinary-path fix is right, and I traced the FAILING -> cancel -> FAILED -> retry chain end to end and it converges. The remaining problem is that the same private method is also entered directly from the master-failover restore, where an uncaught exception has a much worse outcome than the bug being fixed.

Option A (this PR plus local handling): in the same branch call makePipelineFailing(...) and return. Same size as the current diff, same behavior for the ordinary path, safe for the failover path. Recommended.
Option B (as submitted, throw): smallest textual change, but depends on every caller wrapping stateProcess() in a catch. It is only true for updatePipelineState.

Sorry the review is not a pure approve. The core direction is good and this should be quick to close out.

@hutiefang76

Copy link
Copy Markdown
Collaborator Author

I checked the direct restorePipelineState() call and reproduced the escaping exception in a public-entry test. Fixed in f135f7c: allocation failure now calls makePipelineFailing(...) and returns locally, so it no longer depends on the caller's catch. I also added the required task-group slot count to the message and a comment explaining the stale futures.

The tests now use public entry points. They check that both FAILED and CANCELED pipelines enter FAILING without aborting the remaining pipeline restore, consume a retry, and can restore when capacity becomes available. The earlier throw-based commit fails two of the four tests; the updated code passes all four. JDK 17 passed 19 focused/neighboring tests and reactor verify; JDK 8 passed the four focused tests and reactor verify. The success and exhausted-budget tests remain compatibility controls. This covers the pipeline takeover entry with mocked services, rather than claiming a live Master-loss test.

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

Thank you @hutiefang76 for the quick and careful turnaround. You reproduced the escaping exception through a public entry point, moved the handling into the state machine, and rewrote the tests so they no longer reflect on a private method. That is exactly the shape I was hoping for.

One correction on my own previous review, before the details. I wrote that, before this PR, preApplyResources(subPlan) returning false on the master-failover path was "harmless" because the job-level futures were still valid. That was too generous. In SubPlan.stateProcess() the call to jobMaster.releasePipelineResource(this) runs immediately before preApplyResources(this) (SubPlan.java:741-742). It removes the pipeline's ownedSlotProfilesIMap entry and releases those slots (JobMaster.java:1000-1025). The job-level failover reuse reads slots from that same map (JobMaster.java:746-754, getOwnedSlotProfiles at :1561). So the failover path had the same stale-slot hazard as the ordinary path, and the guard fixes it there too. My conclusion (handle locally, do not throw) stands, but the "harmless" reasoning was wrong. This was a carryover imprecision from my last round, not something you introduced.

What Problem Does This PR Solve?

After a worker is lost, a pipeline restore calls jobMaster.preApplyResources(this) and used to ignore a false result. JobMaster.preApplyResources(subPlan) releases its partial allocation on failure but leaves physicalPlan.preApplyResourceFutures untouched (JobMaster.java:598-605 only writes on success). The following SCHEDULED step then reads the old futures and deploys onto slots that were just released, which shows up as WrongTargetSlotException: Unknown slot and burns the retry budget while replacement capacity is still joining.

The fix: when allocation fails, put the pipeline into FAILING locally with a NoEnoughResourceException and return, so it goes through the existing FAILING, cancel, FAILED, retry-budget path instead of deploying on stale futures.

Simple example: 2 workers with 2 fixed slots each, a pipeline needing 4 slots, one worker dies. The restore attempt cannot get 4 slots. Before: it deploys onto the dead and released slots. After: this attempt fails cleanly, consumes one retry, and the next attempt allocates fresh slots once the replacement worker has joined.

1. Code Change Review

1.1 Core Logic Analysis

Change in SubPlan.java:739-756 (the FAILED/CANCELED restore branch):

Before (dev):

jobMaster.releasePipelineResource(this);
jobMaster.preApplyResources(this);   // result ignored
restorePipeline();
return;

After (PR head):

jobMaster.releasePipelineResource(this);
if (!jobMaster.preApplyResources(this)) {
    makePipelineFailing(new NoEnoughResourceException("Not enough resources to restore "
            + pipelineFullName + "; required task-group slots: "
            + (coordinatorVertexList.size() + physicalVertexList.size())));
    return;
}
restorePipeline();
return;

Does the normal path reach this? No. The branch only runs on a restore attempt (task failure, worker loss, or master failover of a FAILED/CANCELED pipeline) where allocation fails. The successful-allocation path and the exhausted-budget path are unchanged.

Runtime path, ordinary restore (worker lost while running):

task FAILED -> SubPlan.addPhysicalVertexCallBack (SubPlan.java:198-241, executorService thread)
  -> updatePipelineState(FAILED) (SubPlan.java:346, synchronized)
     -> stateProcess() FAILED branch (SubPlan.java:738-740)
        -> checkNeedRestore + prepareRestorePipeline() (SubPlan.java:490-516)
             restoreNum++, reset() -> pipeline + tasks CREATED, addPipelineEndCallback re-arms
             initStateFuture (clears errorByPhysicalVertex, SubPlan.java:183), sleep(interval)
        -> releasePipelineResource(this) (JobMaster.java:998)
        -> preApplyResources(this) == false (JobMaster.java:659)
        -> makePipelineFailing(NoEnoughResourceException) [NEW, SubPlan.java:745-751]
           -> errorByPhysicalVertex set, updatePipelineState(FAILING): CREATED -> FAILING
              -> stateProcess() FAILING: startPhysicalVertex + cancel on every vertex (SubPlan.java:724-736)
                 -> PhysicalVertex.noticeTaskExecutionServiceCancel (PhysicalVertex.java:415-420):
                    no owned slot -> checkTaskGroupIsExecuting false -> CANCELED
           -> last task callback -> getPipelineEndState: canceledTaskNum > 0, state FAILING -> FAILED (SubPlan.java:262-269)
           -> updatePipelineState(FAILED) -> next attempt, or subPlanDone + pipelineFuture.complete(FAILED, msg) when budget is spent

Runtime path, master failover (the path from my earlier blocker):

CoordinatorService.pendingJobSchedule (CoordinatorService.java:475-497), executor task
  pipelineList.forEach(SubPlan::restorePipelineState)   (:485)
    -> restorePipelineState (SubPlan.java:566-608, synchronized)
       -> startSubPlanStateProcess() -> stateProcess() FAILED/CANCELED branch
          -> ... -> preApplyResources(this) == false
          -> makePipelineFailing(...) ; return           [NEW - nothing escapes]
    -> next pipeline is restored, then jobMaster.run() (:491)

Verified at the new head: the return after makePipelineFailing means no exception can leave stateProcess() for this reason, so the job is not orphaned and the loop over the remaining pipelines continues. Issue 1 from my previous review is fixed.

Thread and lock model: stateProcess(), updatePipelineState() and restorePipelineState() are all synchronized on the SubPlan, and Java monitors are reentrant, so the nested makePipelineFailing -> updatePipelineState(FAILING) -> stateProcess() call from inside the FAILED branch is safe on both the Hazelcast/executor callback thread and the coordinator executor thread. The task-completion callbacks that eventually move FAILING to FAILED use thenAcceptAsync(..., executorService), so they wait for the monitor rather than deadlock. makePipelineFailing after reset() starts from CREATED, which is not a terminal state, so updatePipelineState will not reject the transition (SubPlan.java:369-374). prepareRestorePipeline() only returns true when the pipeline state is not terminal (SubPlan.java:507-513), which keeps that guarantee.

Error text: errorByPhysicalVertex is reset in initStateFuture() (SubPlan.java:183), which addPipelineEndCallback invokes during prepareRestorePipeline(), before makePipelineFailing writes the new message. So the reported error is this attempt's, not a stale one, and checkNeedRestore (SubPlan.java:293-297) will not treat it as an isolated multi-table failure, so the retry budget is honored.

Job-loss risk (see also #12202): I looked for a silent job-loss path from this change and found none. #12202 is about completeFailJob blocking on jobMasterCompleteFuture.join() on the schedule thread; this PR does not touch that path. Here every failed attempt either retries or, after the budget is spent, completes pipelineFuture with FAILED plus the NoEnoughResource message, so the job is surfaced as failed, not lost.

1.2 Compatibility Impact

Fully compatible. No change to config options, defaults, serialization, checkpoint/savepoint state, or public APIs. The only behavioral change is that a failed restore allocation now fails the attempt (using the existing retry budget) instead of deploying onto stale slots. Both the old and new behavior consume one retry per failed attempt, so the retry budget is not worse than before.

1.3 Performance / Side-Effect Analysis

  • No hot-path cost; the branch runs only on restore attempts.
  • Retry window: with defaults (job.retry.times = 3, job.retry.interval.seconds = 3), the pipeline waits about 9 seconds for replacement capacity before it is failed for good. The new docs paragraph states this boundary accurately. There is no "wait for capacity" mode; that would be a separate feature.
  • Resource release is correct: releasePipelineResource runs before the attempt and preApplyResources releases its own partial allocation on failure (JobMaster.java:609-657), with reused slots excluded from that release.
  • Extra log volume is one error line per failed attempt, bounded by the retry budget.

1.4 Error Handling and Logging

No blocking issues found.

Issue 1: Tests use empty vertex lists, so the slot-count message and the FAILING -> cancel -> FAILED convergence are not exercised

  • Location: SubPlanResourceRestoreTest.java:124-134 (both vertex lists are Collections.emptyList()), :70-73 (FAILED is injected by hand)
  • Problem: With no vertices, the "required task-group slots" value in the error message is always 0 and is never asserted, and the FAILING state has nothing to cancel, so the test moves to FAILED by calling updatePipelineState(FAILED) itself.
  • Potential risk: A future edit that breaks the message content, or breaks how FAILING converges to FAILED for a pipeline that has vertices, would not turn these tests red. The production guard itself is covered: deleting the return or the !preApplyResources check makes never().restorePipeline() fail.
  • Best improvement: Optional. Add one mocked coordinator/physical vertex to one test (or a small extra case) and assert the message and slot count, or drive the vertex callbacks to FAILED. Your integration evidence already covers the end-to-end convergence, so I would not hold the PR for this.
  • Severity: Low
  • Raised by another reviewer: No

Remaining risks, not issues: if updatePipelineState(FAILING) itself throws (for example a persistent IMap failure), the catch at SubPlan.java:399-403 only logs, because the target state is FAILING. That is the same pre-existing behavior as the SCHEDULED failure branch (SubPlan.java:700-702) and is not introduced here.

2. Code Quality Assessment

2.1 Coding Standards

Good. The new branch carries a short why-comment (stale futures must not be deployed), the import is correct, and the change is minimal and consistent with the existing SCHEDULED failure handling and with restorePipeline()'s own makePipelineFailing use (SubPlan.java:525-531). My earlier Low nits (message detail, missing comment) are both addressed.

2.2 Test Coverage and Test Stability

Previous Issue 5 (Medium: no test for exception-to-FAILING conversion or the failover caller, and reflection on a private method) is fixed. The tests now go through public entry points (startSubPlanStateProcess, restorePipelineState, updatePipelineState):

  • insufficientResourcesMustNotStartRestore (:37-47): asserts no throw, FAILING, restore counter 1, restorePipeline() never called, resources released.
  • masterFailoverAllocationFailureMustNotAbortRemainingPipelines (:49-74): FAILED and CANCELED pipelines both enter FAILING without escaping, each consumes one retry, and a later attempt with capacity calls restorePipeline().
  • The other two are compatibility controls (success path, exhausted budget). I raised them as guards, not regression tests, before; they are fine to keep.

Test-risk mapping (delete-a-line check): removing the !preApplyResources guard fails the never().restorePipeline() and FAILING assertions; restoring the throw variant fails assertDoesNotThrow in the failover test; removing the return fails never().restorePipeline().

Stability rating: Stable. Retry interval is 0 so Thread.sleep(0) adds no timing dependence, there are no hard waits, no shared static state, each test builds its own mocks and SubPlan, and the mocked IMap state is a local AtomicReference. The only structural fragility is reliance on deep stubs and the isRunning field, which is acceptable. See Issue 1 for the depth limit.

2.3 Documentation Updates

docs/en/introduction/configuration/JobEnvConfig.md and docs/zh/introduction/configuration/JobEnvConfig.md both gain a matching paragraph next to job.retry.times. They agree with each other and with the code behavior (allocation failure consumes the shared retry budget). No further docs needed.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix. It reuses the existing FAILING -> cancel -> FAILED -> retry path already used for SCHEDULED allocation failures, and it no longer depends on any caller's exception handler.

3.2 Maintainability

Improved versus the throw-based version: the failure handling is local and caller-independent, and the why-comment protects it from later refactors. The larger structural hazard (JobMaster.preApplyResources not replacing stale futures on failure) remains, but skipping deployment is the smaller and safer change, and I do not think it should be widened in this PR.

3.3 Extensibility

Neutral. If a "wait for capacity" strategy is added later, this branch is the natural hook.

3.4 Historical-Version Compatibility

No persisted state, protocol, or config changes. Rolling behavior on older running jobs changes only in the failed-allocation case, in the intended direction.

4. Issue Summary

Number Issue Location Severity
Issue 1 Tests use empty vertex lists: slot-count message and cancel convergence not exercised SubPlanResourceRestoreTest.java:70-73,124-134 Low

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers - must be fixed
    • None. My earlier High blocker (exception escaping restorePipelineState() on master failover) is fixed at f135f7c by local makePipelineFailing handling plus return, verified in source at SubPlan.java:742-753.
  2. Recommended fixes - non-blocking
    • Issue 1 (Low): optionally add a vertex-bearing case to assert the message and the cancel-to-FAILED convergence.

Overall assessment: the root cause is correctly addressed, the ordinary and master-failover callers now behave identically, thread and lock reentrancy is sound, resources are released correctly, and no silent job-loss path is introduced (this is unrelated to the #12202 hang). Compatibility is full.

Response to existing change requests: my previous CHANGES_REQUESTED review at d31c2e3 is fully resolved (Issue 1 High fixed, Issue 2 message detail added, Issue 3 comment added, Issue 4 acknowledged, Issue 5 fixed via public-entry tests). No other reviewers have left comments on this PR.

CI/sync status: the branch is not behind dev and has no conflicts. The apache-side Build check is a pointer to the contributor fork run and was still in progress when I looked, with no failures reported; please wait for it to go green. Nothing needs to be rebased.

@hutiefang76

Copy link
Copy Markdown
Collaborator Author

I checked the failed Master-failover tests and found two regressions in my previous update. Fixed in 148dae7.

The scheduler had already reserved slots for a never-started pipeline, but the takeover path canceled it and tried to reserve them again. That pipeline now uses the existing reservation; partially started tasks still follow the cancellation path. I also recheck cancellation after the recovery wait so a canceled job is not reported as a resource failure.

Both real-cluster tests now pass, including repeated Master handoffs and zero retries for the initial dispatch. JDK 8/17 each passed 23 tests and verify. I reran the independent Worker-loss case too: the replacement Worker completed all 400 distinct IDs, with no Unknown slot error. The stale-slot guard is still in place. The PR description and tests are updated; waiting for the new CI run.

@github-actions github-actions Bot added the e2e label Sep 28, 2026

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

Thanks @hutiefang76 for the two follow-up comments and for catching both of these yourself with the real-cluster IT before I did. I re-reviewed the current head (148dae7) from scratch, including everything since my APPROVE at f135f7c.

One thing first: I should apologize for a gap in my previous review. I approved f135f7c after tracing the allocation-failure path end to end, but I never asked "what happens if the job/pipeline is cancelled while this restore attempt is in flight?" or "what happens to a pipeline that never started when a new Master takes over?" Both are exactly the class of race/boundary condition this review is supposed to hunt for, and both turned out to be real bugs that your own cluster testing found first. That's on me, not something introduced by carelessness on your side — marking it a carryover.

What Problem Does This PR Solve?

  • User pain point: after f135f7ceb, two real-cluster scenarios still behaved wrong: (1) a pipeline that never started before a Master failover was cancelled and forced to re-request the same slots the failover scheduler had already reserved for it, wasting a retry and risking a second WrongTargetSlotException-style race; (2) a user/job cancellation that arrived while a pipeline was mid-retry-wait (or mid-allocation) for a worker-loss restore could be reported as a resource failure (NoEnoughResourceException) instead of honoring the cancellation.
  • Fix approach: restorePipelineState() now detects a CREATED pipeline whose tasks never left CREATED and drives it straight into startSubPlanStateProcess() (the ordinary CREATED -> SCHEDULED path, which reuses the job-level preApplyResourceFutures) instead of cancelling and re-requesting. In stateProcess()'s FAILED/CANCELED branch, jobMaster.isNeedRestore() is rechecked both right after the retry-interval wait and right after a failed preApplyResources() call; if it is false, the pipeline is routed through cancelPipeline() instead of makePipelineFailing().
  • One-sentence summary: two additional restore-vs-cancel/re-reservation races found by real-cluster testing are closed by rechecking cancellation state and by reusing already-reserved slots for pipelines that never deployed.

Simple example: Master A dies with a job whose pipeline P1 never got past CREATED (still queued behind resource allocation) and pipeline P2 already RUNNING. Master B takes over, and the failover scheduler pre-reserves slots for the whole job, including P1. Before this commit: restorePipelineState() saw P1's ordinal() < RUNNING and cancelled it, so P1 then re-entered the FAILED/CANCELED restore branch and called jobMaster.preApplyResources(P1) again — a second, redundant reservation request and one consumed retry attempt. After this commit: P1 is detected as "never started" and goes straight through CREATED -> SCHEDULED, which pulls its slots from the reservation the failover scheduler already made, consuming zero retries.

1. Code Change Review

1.1 Core Logic Analysis

Incremental diff since f135f7c (SubPlan.java):

// restorePipelineState(), new block right after restoreExecutionState():
if (PipelineStatus.CREATED.equals(getPipelineState())
        && physicalVertexList.stream().allMatch(t -> ExecutionState.CREATED.equals(t.getExecutionState()))
        && coordinatorVertexList.stream().allMatch(t -> ExecutionState.CREATED.equals(t.getExecutionState()))) {
    startSubPlanStateProcess();
    return;
}
// stateProcess(), FAILED/CANCELED branch:
if (checkNeedRestore(state) && prepareRestorePipeline()) {
    if (!jobMaster.isNeedRestore()) {
        cancelPipeline();
        return;
    }
    jobMaster.releasePipelineResource(this);
    if (!jobMaster.preApplyResources(this)) {
        if (!jobMaster.isNeedRestore()) {
            cancelPipeline();
            return;
        }
        makePipelineFailing(new NoEnoughResourceException(...));
        return;
    }
    restorePipeline();
    return;
}

Does the normal path reach this? No, on both counts. restorePipelineState() only runs during a Master failover (SubPlan.java:565, called from CoordinatorService.pendingJobSchedule), and the new isNeedRestore() rechecks only run inside the pre-existing worker-loss restore branch, which itself only runs on FAILED/CANCELED when a restore is being attempted. Both are boundary/recovery-path changes.

Key findings:

  1. The restorePipelineState() early-return is safe against the field-mutation race I initially suspected. My first pass worried that cancelPipeline() (SubPlan.java:407-411, if (!getPipelineState().isEndState()) updatePipelineState(CANCELING)) would be a no-op when called from inside the FAILED/CANCELED case, because getCurrPipelineStatus() there is FAILED/CANCELED (both isEndState()==true, PipelineStatus.java:63-65). That would have been a real "stuck pipeline" bug: cancelPipeline()'s guard would skip the transition, and stateProcess() would return immediately without ever calling subPlanDone()/stopSubPlanStateProcess()/pipelineFuture.complete(...), so the pipeline (and, per PhysicalPlan.addPipelineEndCallback's finishedPipelineNum == pipelineList.size() gate, the entire job) would hang forever. Tracing further disproved this: prepareRestorePipeline() calls reset() (SubPlan.java:427-435) before the retry-interval sleep, and reset() -> resetPipelineState() (SubPlan.java:453-479) sets this.currPipelineStatus = CREATED synchronously, before either isNeedRestore() recheck runs. So by the time cancelPipeline() executes, getPipelineState() is CREATED (not an end state), the guard passes, and updatePipelineState(CANCELING) runs normally, converging through the existing CANCELING -> cancel tasks -> CANCELED path. I verified this against the new unit test cancellationDuringResourceAllocationMustNotBecomeFailure, which asserts the final state is CANCELING (not stuck) with a null error — consistent with my corrected trace. I'm calling this out explicitly because it's exactly the kind of thing that looks broken from a quick read of cancelPipeline()'s guard in isolation, and I want the record to show I checked it against the actual state mutation, not just the two call sites.
  2. The restorePipelineState() reuse path is safe with respect to the resource-allocation mechanism. ResourceUtils.applyResourceForPipeline (ResourceUtils.java:41-67), which the CREATED -> SCHEDULED path calls, already reads from jobMaster.getPhysicalPlan().getPreApplyResourceFutures() rather than issuing a fresh ResourceManager request — this is the same, pre-existing job-level reservation the failover scheduler populates before any pipeline is restored. Routing a never-started pipeline through the ordinary dispatch path is therefore the natural reuse point, not a new allocation mechanism.
  3. Remaining narrow race, not closed by this commit (Low, see Issue 1 below): the two new isNeedRestore() checks cover "cancel arrives during the retry-interval sleep" and "cancel arrives while preApplyResources() is failing," but not "cancel arrives while preApplyResources() is in flight and succeeds." In that sub-case restorePipeline() still runs and the pipeline briefly redeploys. It does not hang or get lost — cancelPipeline(), stateProcess(), and updatePipelineState() are all synchronized on the SubPlan instance, so the job-level cancelJob() -> PhysicalPlan.stateProcess() (FAILING/CANCELING) -> pipelineList.forEach(SubPlan::cancelPipeline) call for this same pipeline (PhysicalPlan.java:408) simply blocks on the same monitor until the redeploy call chain unwinds to RUNNING, then cancels it from there through the ordinary RUNNING -> CANCELING -> CANCELED path. So the cancellation is delayed by one redeploy, not lost — but the new doc line "A job canceled while waiting for recovery resources remains canceled" slightly overstates this for that specific sub-case.
  4. No new resource leak in the early-cancel branch. The first isNeedRestore() check fires before jobMaster.releasePipelineResource(this) runs, so that call is skipped when cancellation is detected there. This is not a leak: subPlanDone() (SubPlan.java:310-327, unconditionally called once the pipeline reaches its true terminal CANCELED/FAILED state) calls jobMaster.releasePipelineResource(this) again as its last retried step, so the release still happens, just once instead of twice, on the eventual terminal transition.
  5. Reentrancy is safe. cancelPipeline(), updatePipelineState(), stateProcess(), and restorePipelineState() are all synchronized on this; the new nested call cancelPipeline() -> updatePipelineState(CANCELING) -> stateProcess() happens on the same thread that already holds the monitor (Java monitors are reentrant), consistent with the existing makePipelineFailing() reentrant pattern this PR already relies on.

Runtime-path diagram for the two new scenarios:

Failover, never-started pipeline:
CoordinatorService.pendingJobSchedule -> pipelineList.forEach(SubPlan::restorePipelineState)
  restorePipelineState() [SubPlan.java:565]
    restoreExecutionState() on all tasks (still CREATED)
    state==CREATED && all tasks CREATED -> startSubPlanStateProcess()   [NEW, SubPlan.java:580-589]
      stateProcess(): CREATED -> updatePipelineState(SCHEDULED)
        stateProcess(): SCHEDULED -> ResourceUtils.applyResourceForPipeline()
          reads jobMaster.getPhysicalPlan().getPreApplyResourceFutures()  (already reserved by failover scheduler)
        -> DEPLOYING -> RUNNING   (zero pipelineRestoreNum consumed)

Cancel racing a worker-loss restore:
task FAILED -> updatePipelineState(FAILED) -> stateProcess() FAILED branch [SubPlan.java:750]
  checkNeedRestore + prepareRestorePipeline()
    reset(): currPipelineStatus := CREATED, tasks := CREATED             [SubPlan.java:427-435, 453-479]
    Thread.sleep(retryIntervalSeconds)   <- concurrent thread calls jobMaster.neverNeedRestore() here
  if (!jobMaster.isNeedRestore())         [NEW, SubPlan.java:754]
      -> cancelPipeline(): currPipelineStatus==CREATED (not end state) -> updatePipelineState(CANCELING) -> converges to CANCELED
  else releasePipelineResource(); preApplyResources()
    if false && !isNeedRestore()          [NEW, SubPlan.java:762]
      -> cancelPipeline() (same convergence)
    if false && isNeedRestore() -> makePipelineFailing(NoEnoughResourceException)  (unchanged from f135f7ceb)
    if true -> restorePipeline()  (unchanged; see Issue 1 for the one sub-case cancellation doesn't preempt here)

1.2 Compatibility Impact

Fully compatible. No config option, default, public API, protocol, or checkpoint/savepoint serialization change. The behavior change is scoped to two Master-failover/worker-loss boundary cases; the ordinary running/finished/checkpoint paths are untouched by this incremental commit.

1.3 Performance / Side-Effect Analysis

  • No hot-path cost; both changes are on the failover/restore branch only.
  • The never-started-pipeline path now consumes zero retries instead of one, which is strictly better for the shared job.retry.times budget across the job's pipelines.
  • No new locking hazard: the synchronized methods touched here are the same ones already used by the pre-existing cancel/restore machinery; no new lock ordering is introduced.
  • No new log volume of concern; the two new branches don't add per-iteration logging.

1.4 Error Handling and Logging

Issue 1 (Low): a cancellation that arrives while preApplyResources() is in flight and succeeds still causes one redeploy before the pipeline is cancelled.

  • Location: SubPlan.java:757-771 (the if (!jobMaster.preApplyResources(this)) block only rechecks isNeedRestore() in the failure branch, not after a successful allocation).
  • Problem: if jobMaster.neverNeedRestore() is set by a concurrent cancel while preApplyResources() is executing and it returns true, the code proceeds straight to restorePipeline() and the pipeline redeploys.
  • Potential risk: purely cosmetic/latency, not correctness — the pending job-level cancelPipeline() call for this same pipeline (PhysicalPlan.java:408) is blocked on the same SubPlan monitor and will still cancel it once it reaches RUNNING, converging via the ordinary path. No hang, no data loss, no double counting. The main effect is a very short, unwanted redeploy-then-cancel blip, and the new doc line ("a job canceled while waiting for recovery resources remains canceled") is not 100% precise for this specific timing window.
  • Best improvement: Optional. Re-check jobMaster.isNeedRestore() once more immediately before restorePipeline() too, mirroring the two existing checks. Given how narrow the window is (has to land inside a single RPC/allocation call) and that it self-heals via the existing job-level cancel loop, I would not hold the PR for this.
  • Severity: Low.
  • Raised by another reviewer: No.

No other issues found in this incremental diff's error handling; the exception-escaping issue from my first review (Issue 1 there) remains fixed — cancelPipeline() never throws, so nothing new can escape restorePipelineState()'s caller.

2. Code Quality Assessment

2.1 Coding Standards

Good. Each new branch carries a short why-comment (SubPlan.java:580-581, :753, :760-761, :766-767), consistent with the "explain why, not what" bar from my last round. Issue 2 (Low): the !jobMaster.isNeedRestore() -> cancelPipeline(); return; pattern is duplicated verbatim at two call sites (SubPlan.java:754-756 and :762-764). A small private helper (e.g. private boolean cancelIfNoLongerNeedsRestore()) would remove the duplication and make it structurally obvious that both checks do the same thing. Non-blocking.

2.2 Test Coverage and Test Stability

The test file grew by three tests over the version I approved, all through public entry points (startSubPlanStateProcess, restorePipelineState):

  • cancellationDuringResourceAllocationMustNotBecomeFailure: flips isNeedRestore() to false from inside the mocked preApplyResources() answer, asserts final state CANCELING with a null error and restorePipeline() never called. Delete-a-line check: removing the second !jobMaster.isNeedRestore() guard (SubPlan.java:762-765) makes this test assert FAILING/a non-null error instead — it goes red. Real regression coverage.
  • neverStartedPipelineMustUseResourcesReservedByFailoverScheduler: asserts the pipeline reaches RUNNING with zero pipelineRestoreNum, setOwnedSlotProfiles called with the pre-reserved slot, and releasePipelineResource/preApplyResources never called. Delete-a-line check: removing the new restorePipelineState() early-return block makes this test hit the old cancel-and-reallocate path — releasePipelineResource/preApplyResources would be invoked instead of never, so it goes red. Real regression coverage for the exact scenario from #12509-adjacent report.
  • cancellationDuringRestorePreparationMustNotRequestNewResources: triggers the cancel from inside checkpointManager.reportedPipelineRunning(...), i.e. before the Thread.sleep, covering the first isNeedRestore() check (SubPlan.java:754) specifically. Delete-a-line check: removing that first guard makes preApplyResources get called (currently asserted never()) — goes red.
  • partiallyStartedPipelineMustStillCancelBeforeRedeployment: a compatibility control confirming a pipeline with a RUNNING task still takes the old cancel-then-redeploy path, i.e. the new early-return is correctly scoped to "never touched" pipelines only. Good regression guard against over-broadening the new branch.

Flaky-test analysis: Stable. Same mocking style as the previously-reviewed tests (retry interval 0, no real sleeps, each test builds its own mocks/SubPlan, no shared static state, no timing assumptions).

My previous Issue 1 (empty vertex lists don't exercise the slot-count message / real cancel convergence) is unchanged and still applies as a Low, non-blocking note; not worth re-raising as new.

2.3 Documentation Updates

docs/en and docs/zh JobEnvConfig.md both gained two new paragraphs describing the resource-allocation-failure and cancellation/never-started-pipeline behavior, matching each other and the code, with one caveat: see Issue 1 above (the "remains canceled" claim doesn't cover the one sub-case where a concurrent successful allocation still causes a one-time redeploy before cancellation lands). I'd treat that as a documentation nit rather than a blocker given the practical impact is nil.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix for both newly-found scenarios. The never-started-pipeline case is handled by routing through the existing CREATED -> SCHEDULED dispatch machinery rather than inventing a new one, which is the smallest correct change. The cancellation-race handling reuses the existing cancelPipeline()/CANCELING state machinery rather than adding a new terminal path.

3.2 Maintainability

The duplicated isNeedRestore() check (Issue 2) is the only maintainability nit; otherwise this keeps the same shape as the already-approved f135f7c change and is easy to follow with the inline comments.

3.3 Extensibility

Neutral to positive: the "never started, so reuse the reservation" branch in restorePipelineState() is a reasonable place to hang similar future short-circuits (e.g. SCHEDULED-but-not-yet-deployed) if that's ever desired, without needing to touch the cancellation logic.

3.4 Historical-Version Compatibility

No persisted state, protocol, or config changes. Rolling behavior on older/in-flight jobs changes only in the two narrow scenarios this PR targets, both in the intended direction (fewer wasted retries, correct cancel-vs-failure classification).

4. Issue Summary

Number Issue Location Severity
Issue 1 A cancellation that lands exactly while a preApplyResources() call is in flight and succeeds still causes one redeploy before the pipeline is cancelled through the ordinary path; docs slightly overstate "remains canceled" for this sub-case SubPlan.java:757-771 Low
Issue 2 The !jobMaster.isNeedRestore() -> cancelPipeline(); return; pattern is duplicated at two call sites SubPlan.java:754-756, 762-764 Low

(Carried over from my previous review, still open, not re-numbered: empty-vertex-list tests don't exercise the slot-count message text or a real task-cancel convergence — SubPlanResourceRestoreTest.java, Low, non-blocking.)

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers — must be fixed
    • None. I went in expecting to find a stuck-pipeline/orphaned-job bug in the restorePipelineState()/cancelPipeline() reuse (the isEndState() guard looked like it would block the CANCELING transition from inside the FAILED/CANCELED branch), but tracing reset()'s currPipelineStatus := CREATED mutation through prepareRestorePipeline() shows the guard is evaluated against CREATED, not FAILED/CANCELED, so it works correctly. I verified this against the new unit tests before writing it up.
  2. Recommended fixes — non-blocking
    • Issue 1 (Low): optionally recheck isNeedRestore() once more immediately before restorePipeline() to close the last narrow race window, or soften the doc wording slightly.
    • Issue 2 (Low): extract the duplicated cancel-check into a small private helper.

Overall assessment: this closes both gaps your real-cluster testing found after my previous approval, using the existing state-machine primitives rather than new ones, with tests that actually fail when the fix is reverted. I don't see a better alternative structure for either change — reusing CREATED -> SCHEDULED for the never-started case and reusing cancelPipeline()/CANCELING for the cancellation case are both the natural, smallest-diff options given the existing design.

CI/sync status: the branch is not behind dev and GitHub reports no merge conflicts (mergeable_state: blocked is the branch-protection "review required" gate, not a conflict). The apache-side Build check is a pointer to the fork's own Actions run; as of this review, the fork run for this exact commit (148dae7) has been queued for several hours without starting, so I cannot confirm it green — please make sure it actually runs and comes back clean before merging. Separately, I noticed the fork's run for the previous commit (f135f7c, the one I approved) later finished with failures in a few IT shards (transform-v2-it-part-1, engine-v2-it x2, all-connectors-it-7); from what I could inspect of the logs these looked like unrelated E2E/error-handling test activity rather than anything touching SubPlan/pipeline restore, but I want to flag it rather than silently assume it's unrelated — worth a look once the new run for 148dae7 completes.

@davidzollo

davidzollo commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Implementation Notes and Trade-offs

Head: 6f620d81929921833122b40be31ac15acdad480a

I synced this Apache SeaTunnel PR with dev while preserving its five-file recovery patch. In the previous Java 8 engine test, losing a worker during cancellation made the pipeline reach FAILED instead of CANCELED. The old branch lacked #12377. The sync brings in #12377's cancellation precedence and retains this PR's resource-allocation and master-failover changes.

Scoped Spotless passed in the engine server and engine E2E modules. The final patch keeps the same stable patch ID and adds no dependency changes.

Apache could not detect a fork Build after the sync. GitHub denied direct dispatch with HTTP 403, so I pushed one CI trigger commit with a byte-identical tree. GitHub verified the new head, no conflicts and the same five files. The signal ran, but no fork Build was visible at readback. The fork owner can start the first Build for the PR branch; runtime verification, including the cancellation test and restore coverage, remains pending.

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

Thanks for preserving the recovery patch during the dev sync and for detailing the earlier cancellation test result. Sorry for overlooking the successful-allocation side of the cancellation window in my previous review. That branch is still present in the current code.

What problem does this PR solve?

User problem. An engine recovery attempt used the previous allocation state when the worker pool could not provide replacement resources.

Change. Check preApplyResources before redeployment and preserve scheduler reservations for a never-started pipeline on master takeover.

If a replacement worker has not registered, a failed attempt should consume the configured retry without deploying tasks onto released slots.

1. Code changes

1.1 Core logic

Before, the terminal recovery branch called preApplyResources(this) and immediately ran restorePipeline. After, SubPlan.java:839-864 treats a false result as a local failure and rechecks cancellation on that path. SubPlan.java:647-659 preserves the existing scheduler reservation for CREATED tasks and pipelines on takeover.

Worker failure → pipeline FAILED/CANCELED → check retry budget → prepareRestorePipeline resets bookkeeping and waits → release old slot ownership → JobMaster.preApplyResources joins allocation futures and publishes new futures on success → SubPlan.restorePipeline → CREATED/SCHEDULED chooses assigned profiles → DEPLOYING starts tasks. Separately, a job cancel sets JobMaster.needRestore=false from PhysicalPlan's CANCELING path before calling the pipeline cancellation methods. Both operations participate in the same real recovery window.

1.2 Compatibility

Partially incompatible in the intended error path. Public options, retry defaults, checkpoint formats and RPCs stay the same. A failed allocation uses an attempt rather than deploying with old slots. A never-started pipeline resumes normal scheduling without using a retry. Preserve the existing cancellation contract across both allocation outcomes.

1.3 Performance and side effects

Failed allocation no longer attempts unnecessary network deployment. The implementation uses the same retry delay and reuses slots for initial dispatch. An aborted successful allocation must return any newly acquired capacity.

1.4 Errors, logging, and findings

Issue 1 (High, blocking) — Honor cancellation when allocation succeeds. SubPlan.java:846-864 only rechecks jobMaster.isNeedRestore when preApplyResources returns false. The allocation call waits for remote futures (JobMaster.java:557-604). If a cancel sets needRestore=false during that wait and slots then become available, execution bypasses the new cancellation branch and enters restorePipeline. That method restarts the pipeline state process without rechecking the flag (SubPlan.java:589-594); SCHEDULED/DEPLOYING can take and deploy the replacement slots before the synchronized pipeline cancel can proceed. Recheck after both outcomes, cancel without dispatch, and release newly reserved slots through the allocation/ownership path if they have not yet been assigned. Add a case where the allocator flips the flag and returns true, asserting zero redeploys and no retained slot. This is the successful side of the existing recovery-window concern, still present on this head.

The false branch now carries job/pipeline context and required slot count. The earlier cancellation-precedence fix in #12377 is included but does not add a guard before this successful redeployment.

2. Code quality

2.1 Conventions

The dispatch conditions state their lifecycle intent and errors use engine-specific exception context. Keep cancellation handling common to both allocation outcomes.

2.2 Test coverage and stability

Stability: Stable for the focused regressions at SubPlanResourceRestoreTest.java:48-237: deterministic mocks and zero configured backoff. The existing failover test at SplitClusterPendingJobLifecycleFailoverIT.java:585-623 relies on job and cluster state and adds a deterministic post-recovery retry count. The cancellation test only changes the flag on a false allocation; cover success and inspect release ownership.

2.3 Documentation

Both English and Chinese retry guides document resource failures, cancellation and initial scheduling. The successful-allocation branch must match the documented cancellation behavior.

3. Architecture

3.1 Change location

The SubPlan recovery state machine is the right location to keep a failed allocation local. Share the post-allocation cancel decision at the same ownership boundary.

3.2 Maintainability

A common decision after pre-apply avoids maintaining different cancellation semantics in adjacent branches.

3.3 Extensibility

The retry and error mechanism can remain shared by worker-loss recovery and later resource reasons.

3.4 Upgrade impact

No migration for existing configs or checkpoints. The user-visible change is the handling of failed recovery allocation.

4. Findings summary

# Finding Location Severity
1 Successful allocation may redeploy after cancellation SubPlan.java:846 High

5. Merge recommendation

Merge after fixes

Blocking items: Issue 1 and current-head CI. The Apache Build reports ACTION_REQUIRED at fork-run detection and no exact-head fork Build is visible. An earlier dispatch returned 403. Please have the fork owner run Build for this head or provide the matching run. The solver should not add connector, dependency or empty trigger changes.

Non-blocking suggestions: None.

The stale-slot fix and the never-started fast path are useful. The remaining source change should keep an in-flight recovery canceled regardless of the allocator's result.

CI and repository state: Signal pull request update: SUCCESS; Build: ACTION_REQUIRED; no exact-head fork Build established. GitHub reports BLOCKED / REVIEW_REQUIRED.

Verification: Reviewed all changed files and the referenced call sites at 6f620d81929921833122b40be31ac15acdad480a against merge base b3828eb141d3ca669181084dbd73bfb534064e08. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.

Release unassigned reservations and preserve tracking when release fails.

Generated-by: DeepSeek (deepseek-v4-pro)
Generated-by: OpenAI Codex
@hutiefang76

Copy link
Copy Markdown
Collaborator Author

The successful-allocation path is covered in 32cfc2e8. Cancellation is checked after pre-allocation returns for either outcome. Completed reservations for that pipeline are released even before they reach the ownership map; tracking is removed only after successful release.

The new race regression fails on the previous production code and verifies no restore plus both release calls. A real fixed-slot test reallocates all five slots after cleanup, and a release-failure test checks tracking is retained. Java 11 and 17 each pass 44 unit tests and the extended real split-cluster cancellation/capacity-reuse IT, without skips. The same patch also passes against current dev with 55 unit tests and the real split-cluster IT.

The root quick verify was attempted but remains incomplete: dependency resolution stopped in the unchanged Spark Connector V2 Example module. The fork Build dispatch currently returns HTTP 422, Actions has been disabled for this repository. No exact-head hosted Build result is claimed; the CI gate remains open.

AI-assisted implementation, tests and reply: DeepSeek and OpenAI Codex.

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

Thanks for adding the successful-allocation cancellation case and real slot-capacity reuse checks. I re-read all seven changed files and reconciled your reply with both recovery branches. Thank you for the contribution to Apache SeaTunnel.

What problem does this PR solve?

User pain: pipeline restore can deploy with stale slot futures after replacement allocation fails, or leak freshly reserved slots when cancellation arrives during allocation. Fix: gate restore on successful allocation and cancellation checks, and release completed pending reservations as well as owned slots. In one sentence: restore only with current resources and return canceled reservations. Example: losing a worker with no spare capacity must consume a retry, not redeploy using the lost worker's slot.

1. Code changes

1.1 Core logic

Before: releasePipelineResource; preApplyResources result ignored; restorePipeline unconditionally.
After: check cancellation after retry preparation and after allocation, fail locally on false, release successfully allocated pending resources on canceled restore.

pipeline FAILED/CANCELED -> retry budget/prepareRestorePipeline
 -> cancellation check -> release former pipeline resources
 -> preApplyResources waits allocation futures
 -> canceled: release successful reservations -> cancel, no restore
 -> false: makePipelineFailing(NoEnoughResourceException) -> next retry/terminal budget
 -> true: restorePipeline -> recreate/deploy tasks
master takeover CREATED + all task states CREATED -> use scheduler reservation directly
releasePipelineResource -> collect owned + completed pre-apply slots for this subplan
 -> releaseResources.join succeeds -> remove captured bookkeeping
 -> failure: keep tracking and log rather than losing reservation identity

Key findings: recovery and master-takeover paths reach the change, ordinary initial deployment is retained; successful and failed allocation now both recheck cancel; never-started failover does not double-reserve; compare-remove only removes captured future entries after release. Allocation waits settle futures before successful publication, so the new completed-reservation cleanup covers the formerly unowned success path.

1.2 Compatibility

Fully compatible for API, options/defaults, serialization and checkpoints. Resource-allocation failure now consumes the existing retry budget and preserves cancellation precedence. Both job environment guides explain the behavior; no storage migration.

1.3 Performance and side effects

Cleanup adds an O(task groups in the pipeline) scan and bounded sets/maps during terminal/recovery work, not per row. Resource release deduplicates slot identity and excludes previously released slots. It retains bookkeeping on failed release. No new scheduler thread or per-record network work.

1.4 Errors, logging, and findings

No blocking source issue found on this head. The previous successful-allocation cancellation blocker is addressed at SubPlan.java:846-858 and JobMaster.releasePipelineResource: pending completed futures are included before ownership-map insertion. NoEnoughResourceException includes the pipeline and required task-group count. Release failure still logs the existing warning but now keeps captured tracking for another cleanup attempt. There is no independent technical review from another maintainer to deduplicate; the author's runtime claims are recorded separately from this source analysis.

2. Code quality

2.1 Conventions

Cancellation/resource ownership comments explain the new branches. The existing public release helper would benefit from a concise Javadoc describing both ownership sources and remove-after-success; this is a non-blocking documentation follow-up.

2.2 Test coverage and stability

Stability rating: stable. SubPlanResourceRestoreTest exercises public state transitions with controlled callback cancellation, including successful allocation, false allocation, no restore after cancel and exhausted budget. JobMasterMasterFailoverResourceTest reallocates all five real slots after cleanup and preserves tracking on controlled release failure. The existing split-cluster IT now polls cleanup of both jobs' reservations and verifies a never-started failover uses zero retries. No sleeps/tight elapsed assertions were added.

2.3 Documentation

EN/ZH job retry documentation consistently explains failed allocation consumes retry budget, cancellation remains canceled, and never-started failover uses the scheduler's reservation.

3. Architecture

3.1 Change location

The restore gate belongs in SubPlan's lifecycle; resource ownership cleanup belongs in JobMaster. A source/sink workaround cannot repair stale worker slots. The minimal patch preserves the existing resource manager protocol.

3.2 Maintainability

Cancellation checks surround the blocking allocation boundary; resource cleanup retains original identities until release succeeds. These invariants are now independently exercised.

3.3 Extensibility

The same bookkeeping supports fixed-slot reuse after cancellation without changing the resource allocation SPI.

3.4 Upgrade impact

No checkpoint/schema changes. Existing jobs continue using their retry settings; recovery now honors resource availability rather than stale cached slot data.

4. Findings summary

# Finding Location Severity
- No new source blocker found - -

5. Merge recommendation

Merge after current-head CI and effective maintainer review.

Blocking items: No source blocker remains from Daniel on this head. No exact-head fork Build is available. The author reports dispatch HTTP 422, Actions disabled for the fork; the fork owner/account administrator must lift that execution restriction, then run Build on this same head. Repeated dispatches, an empty commit or an unrelated business patch are not remedies. Local test claims in the author reply do not replace hosted current-head CI.

Non-blocking suggestions: Add the concise releasePipelineResource ownership Javadoc when convenient.

The new success/cancel regression closes the specific earlier gap. Obtain a real current-head Build and independent maintainer approval before merge.

CI and repository state: Signal pull request update: SUCCESS; Build: ACTION_REQUIRED; no exact-head fork Build established. GitHub reports BLOCKED / REVIEW_REQUIRED.

Verification: Reviewed all changed files and the referenced call sites at 32cfc2e84145a2c46d976c1c3553f2bdd1aececc against merge base b3828eb141d3ca669181084dbd73bfb534064e08. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.

This branch has not been deployed

No deployments
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] Pipeline restore deploys stale slots after resource allocation fails

3 participants