Skip to content

[Fix][Zeta] Harden slot allocation recovery state - #12948

Merged
nzw921rx merged 3 commits into
apache:devfrom
DanielLeens:codex-static-slot-failover-upstream-20261022
Oct 26, 2026
Merged

nzw921rx merged 3 commits into
apache:devfrom
DanielLeens:codex-static-slot-failover-upstream-20261022

Conversation

@DanielLeens

@DanielLeens DanielLeens commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Purpose of this pull request

Fixes #12947.

I am contributing these verified fixes to Apache SeaTunnel after auditing the WhaleTunnel 2.6-test fixed-slot and failover repair chain against the current SeaTunnel dev branch.

A multi-slot request can partially succeed before another slot request fails. The current path completes the allocation failure before asynchronous rollback finishes, allowing a retry to race with slots still owned by the failed request. Related paths can also lose original request indexes, skip dynamic-worker fallback, publish RUNNING after failed deployment, or fail status lookup during master convergence.

What changed

  • preserve original slot request indexes across fixed-worker retries and dynamic-worker fallback;
  • carry fixed-worker pre-check misses into dynamic allocation;
  • wait for every acquired slot rollback attempt before completing a failed request;
  • retry slot release independently, including synchronous release failures, and attach exhausted rollback failures to the original allocation failure;
  • retain successful allocations for cleanup when another slot future is null, exceptional, or cancelled;
  • publish task RUNNING only after successful deployment;
  • publish pipeline RUNNING only when every vertex is RUNNING or has already finished normally;
  • return UNKNOWABLE when neither live nor historical job state is available.

Scope and duplicate audit

This is the non-duplicate subset of the audited fixes. It intentionally excludes:

No public API, configuration default, protocol ID, serialized task state, or checkpoint/savepoint format changes.

Regression coverage added

Focused unit tests cover:

  • successful and failed task deployment state publication;
  • RUNNING, FINISHED, and FAILED vertex decisions through the real pipeline state-machine entry;
  • null, exceptional, and cancelled slot futures while retaining successful slots for cleanup;
  • rollback ordering, bounded retry, synchronous and asynchronous release failure, and exhausted rollback diagnostics;
  • selective per-slot retry so an already released slot is not released again;
  • non-contiguous original request indexes and ordered completion;
  • fixed-worker pre-check misses reaching dynamic-worker allocation;
  • unavailable live and historical status returning UNKNOWABLE.

Validation

  • ./mvnw spotless:apply -pl seatunnel-engine/seatunnel-engine-server -am -nsu -Dmaven.gitcommitid.skip=true: BUILD SUCCESS for the 40-module affected reactor at the current head.
  • git diff --check: passed for the current-head import correction.
  • An independent maintainer review found no blocker: the test now uses the same engine.common.job.JobStatus type as CoordinatorService and JobHistoryService.JobState.

Per the local Apache SeaTunnel contribution protocol, local compilation, unit tests, and E2E were not executed. The prior GitHub Build failed during test compilation because this test imported the non-existent engine.core.job.JobStatus; GitHub CI for the updated PR head is the runtime verification gate.

Does this PR introduce any user-facing change?

No. This is an internal Zeta engine correctness fix. Failed allocation now waits for bounded rollback completion before the request failure becomes visible, preventing the next retry from observing slots still owned by the failed attempt.

Check list

  • No new binary dependency or jar is added.
  • No documentation change is required for this internal correctness fix.
  • No incompatible change is introduced.
  • No connector files are changed.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for putting this together. A note for transparency first: this PR is authored by the DanielLeens account, so this is a maintainer-style self-review written as neutrally and adversarially as I can, and another committer should make the final call. I reviewed the full diff at head 050472fc42c01825443cb56714f8860fc5928c7e and traced the slot request, rollback, deployment and status paths through the real call chain rather than relying on the PR description.

What Problem Does This PR Solve?

  • User pain point: when a multi-slot request partially succeeds and another slot fails, ResourceRequestHandler completed the request exceptionally first and released the acquired slots fire-and-forget afterwards. The caller could retry while the failed attempt still owned slots on the workers. Related paths published task/pipeline RUNNING after a failed deployment and could NPE on a missing history status.
  • Fix approach: track original request indexes across retries, keep pre-check misses unassigned instead of failing the whole round, complete a failed request only after every acquired slot's release attempt finishes (with retry and suppressed diagnostics), drop null/exceptional/cancelled slot futures in ResourceUtils so the pipeline fails with the successful slots retained for cleanup, publish RUNNING only after a successful deployment, and return UNKNOWABLE for missing history.
  • One-sentence summary: makes slot allocation failure visible only after rollback, and stops the engine from reporting RUNNING for vertices or pipelines that did not deploy.

1. Code Change Review

1.1 Core Logic Analysis

Changed production methods:

  • ResourceRequestHandler.request / requestSlotWithRetry / requestSlots / completeRequestWithException / addSlotToCacheMap / applyByDynamicWorker / releaseAllResourceInternal / releaseResourceWithRetry
  • ResourceUtils.applyResourceForPipeline
  • PhysicalVertex.deployInternal -> new finishDeployment
  • SubPlan.stateProcess (DEPLOYING branch) -> new areAllVerticesRunningOrFinished
  • CoordinatorService.getJobStatus -> new resolveHistoryStatus

Key before/after (rollback ordering):

// before
if (completableFuture.completeExceptionally(e)) {
    releaseAllResourceInternal();          // fire-and-forget releases
}
// after
if (!completionStarted.compareAndSet(false, true)) return;
releaseAllResourceInternal()               // allOf(per-slot release with retry)
        .whenComplete((ignored, releaseError) -> {
            if (releaseError != null) e.addSuppressed(releaseError);
            completableFuture.completeExceptionally(e);
        });

Runtime path:

SubPlan.stateProcess(CREATED)
  -> ResourceUtils.applyResourceForPipeline(jobMaster, subPlan)
       -> preApplyResourceFutures (JobMaster -> ResourceManager.applyResources -> ResourceRequestHandler.request)
            round k: requestSlots(indexes) -> RequestSlotOperation per pre-checked worker
                     allOf(round futures) -> stillNeedRequestIndexes() -> retry (max 3) -> fail
            failure: completionStarted CAS -> releaseResourceWithRetry(slot) x N (allOf) -> completeExceptionally
       -> join each future; keep only non-null successful SlotProfiles; setOwnedSlotProfiles; NoEnoughResourceException if any missing
  -> DEPLOYING: PhysicalVertex.makeTaskGroupDeploy() -> updateTaskState(DEPLOYING) -> stateProcess() (synchronous)
       -> deploy() -> finishDeployment(state): RUNNING only on success, else makeTaskGroupFailing
  -> areAllVerticesRunningOrFinished ? updatePipelineState(RUNNING) : stay DEPLOYING
       (failed vertex future -> addPhysicalVertexCallBack -> updatePipelineState(FAILING))

Key findings from tracing:

  • The ordering fix is real: on the error branch CompletableFuture.allOf has already waited for every in-flight slot future of that round, so resultSlotProfiles is a complete snapshot when rollback starts, and completionStarted prevents a late addSlotToCacheMap from completing the request successfully after a failure started.
  • The SubPlan change is safe for the normal path: makeTaskGroupDeploy() drives updateTaskState -> stateProcess -> deploy synchronously under the vertex monitor, so by the time the loop ends every vertex is RUNNING, FINISHED, or already moving to FAILING/FAILED. A failed vertex now goes DEPLOYING -> FAILING for the pipeline instead of DEPLOYING -> RUNNING -> FAILING; updatePipelineState has no transition table, so this is accepted.
  • ResourceUtils: before this PR a null slot was stored as a map value, so futures.size() == slotProfiles.size() passed and the pipeline proceeded to deploy with a null profile; a CancellationException escaped the loop before setOwnedSlotProfiles, leaking the successful slots. Both are fixed correctly.
  • supportDynamicWorker() is only implemented in AbstractResourceManager and returns false, so the applyByDynamicWorker index fix and the "pre-check miss reaches dynamic allocation" change have no production consumer today. For static clusters the real effect of the pre-check change is: a miss now goes through the 3 immediate retries and then fails with the detailed message, instead of failing in the first round. Same outcome, different message.

1.2 Compatibility Impact

Fully compatible. No config, protocol ID, IMap layout, serialized task state or checkpoint format changes. ResourceManager#applyResources keeps its signature; only failure-completion timing changes (it now waits for rollback).

1.3 Performance / Side-Effect Analysis

See Issue 2: the new release retry loop can issue up to 30 back-to-back RPCs per slot with a WARN stack trace each, and it retries deterministic failures. This delays failure visibility and can flood the master log on large jobs.

1.4 Error Handling and Logging

Issue 1: Test compilation fails at the current head, so no CI lane can run

  • Location: seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/CoordinatorServiceStatusTest.java:20
  • Problem: the test imports org.apache.seatunnel.engine.core.job.JobStatus, but the class lives in org.apache.seatunnel.engine.common.job.JobStatus. The fork Build run for this head fails with cannot find symbol: class JobStatus in seatunnel-engine-server test-compile, which cascades into 78 red jobs (unit-test on all platforms, engine-v2-it, all connector IT lanes).
  • Risk: none of the new or existing tests were actually executed; every runtime claim in this PR is currently unverified.
  • Best improvement: fix the import, then re-run the full Build on the new head before asking for review. Javac may report further errors once this one is fixed, so a local test-compile of seatunnel-engine-server is worth doing.
  • Severity: High
  • Raised by another reviewer: No

Issue 2: Slot release retry has no backoff and retries non-retryable failures

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceRequestHandler.java:382-416 (releaseResourceWithRetry, called with Constant.OPERATION_RETRY_TIME = 30)
  • Problem: every failure, including WrongTargetSlotException thrown deterministically by DefaultSlotService.releaseSlot (DefaultSlotService.java:205-223, slot already released, wrong sequence or wrong owner), is retried immediately up to 30 times, each with a WARN log carrying the full stack trace. The existing engine pattern (RetryUtils.retryWithException with ExceptionUtil::isOperationNeedRetryException and Constant.OPERATION_RETRY_SLEEP) is not used.
  • Risk: for a large job, a partial failure can produce slots x 30 release RPCs and stack traces in a tight loop, and the allocation failure (now gated on rollback) is delayed accordingly. A slot that the worker already freed is reported as an exhausted rollback failure, which is misleading during incident analysis.
  • Best improvement: treat WrongTargetSlotException (slot no longer assigned to this job) as an idempotent success; retry only exceptions accepted by ExceptionUtil.isOperationNeedRetryException; add a small delay between attempts (or reuse RetryUtils) and a lower attempt budget; log the stack trace only on the final failure. Add a test asserting a WrongTargetSlotException is not retried.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 3: The failure-completion callback is not guarded

  • Location: ResourceRequestHandler.java:215-227 (completeRequestWithException)
  • Problem: completionStarted is set before rollback starts, and completableFuture.completeExceptionally(e) is only reached if the whenComplete lambda runs without throwing. Unlike the other callbacks in this class, this one is not wrapped in withTryCatch, and no finally guarantees completion.
  • Risk: if anything in the callback throws (for example addSuppressed rejecting its argument), the request future never completes and the caller waits forever; the CAS also prevents any later completion.
  • Best improvement: complete the future in a finally block (or wrap with withTryCatch and complete in both branches).
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Issue 4: New non-trivial methods and the new state field have no comments

  • Location: ResourceRequestHandler.java:79 (completionStarted), :382 (releaseResourceWithRetry); SubPlan.java:769 (areAllVerticesRunningOrFinished); PhysicalVertex.java:328 (finishDeployment); CoordinatorService.java:1649 (resolveHistoryStatus)
  • Problem: completionStarted encodes the "first completion wins, success or failure" contract and the retry method encodes the rollback guarantee described in ResourceManager#applyResources, but neither explains it. areAllVerticesRunningOrFinished silently leaves the pipeline in DEPLOYING when a vertex failed, which deserves a sentence about who moves it to FAILING.
  • Best improvement: add short Javadoc that explains the why and the ownership/ordering contract.
  • Severity: Medium
  • Raised by another reviewer: No

Minor: PhysicalVertex.stateProcess (DEPLOYING, line 613) still calls updateTaskState(RUNNING) after finishDeployment already did it on success. It is skipped as "current equals target", but now that finishDeployment owns this transition the duplicate can be removed for clarity.

2.2 Test Coverage and Test Stability

The new tests are well targeted and would fail if the fix were reverted: partialAllocationFailureWaitsForRollbackBeforeCompletingRequest asserts the request is not done until the release future completes, rollbackRetriesOnlyTheSlotWhoseReleaseFailed guards double release, ResourceUtilsTest covers null, exceptional and cancelled futures, and SubPlanDeploymentTest drives the real stateProcess entry. They use completed or manually completed futures, no sleeps, no fixed ports and no shared static state.

Stability rating: Stable by design, but currently unverified because of Issue 1. Missing case: a non-retryable release failure (Issue 2).

2.3 Documentation Updates

No user-facing behavior or option changes, so no docs are needed. Please remove the line "Independent QA and technical reviews found no blocking issue and concluded that implementation matches the plan" from the PR description: it cannot be verified by readers and the head does not compile its tests.

3. Architectural Soundness

3.1 Elegance

Precise fix for the rollback ordering and the deployment-state publication; the fixes are located in the components that own each invariant (ResourceRequestHandler owns rollback, PhysicalVertex owns its own state).

3.2 Maintainability

Acceptable. Switching from List<ResourceProfile> to original indexes removes a class of index-shift bugs.

3.3 Extensibility

The dynamic-worker path benefits once a resource manager actually returns true from supportDynamicWorker().

3.4 Historical-Version Compatibility

No state, protocol or config change, so restore from older checkpoints and rolling upgrade are unaffected (inference from the diff; no upgrade test was run).

4. Issue Summary

Number Issue Location Severity
1 Test compilation fails (wrong JobStatus package), whole CI red seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/CoordinatorServiceStatusTest.java:20 High
2 Release retry: 30 immediate attempts, no backoff, retries deterministic WrongTargetSlotException seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceRequestHandler.java:382 Medium
3 Failure-completion callback not guarded; request can hang if it throws ResourceRequestHandler.java:215 Low
4 Missing comments on new non-trivial methods and completionStarted ResourceRequestHandler.java, SubPlan.java, PhysicalVertex.java, CoordinatorService.java Medium

5. Merge Recommendation

Conclusion: Not recommended for merge

Blockers (must fix):

  • Issue 1: fix the test compile error and get a green Build on the new head. Until then none of the regression tests have run.

Recommended fixes (non-blocking, but strongly suggested before merge):

  • Issue 2 (bounded, filtered retry with delay; idempotent handling of already-released slots), Issue 3, Issue 4, and the PR-description cleanup.

Overall assessment: the root cause analysis is correct and the fixes are in the right places; once the build is green and the release retry is tightened, this should be in good shape. The CI failure is caused by this PR itself, not by being 19 commits behind dev, so a sync alone will not fix it.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I re-reviewed all eleven changed files and the complete allocation/rollback/deployment path at the new head. This is a technical maintainer assessment of my own PR, not a self-approval. The new commit fixes the concrete JobStatus import error from Issue 1; the older head's failing test compilation is no longer a valid current-source blocker. Existing non-blocking suggestions are retained below without adding a new round of unrelated issues.

What problem this PR solves

  • User pain: Partial slot allocation can become visible as failed before rollback attempts finish, null/cancelled allocations can lose cleanup ownership, and failed deployments can briefly be advertised as running.
  • Fix approach: Gate the first allocation completion, await per-slot rollback attempts, preserve original indexes, retain successful allocations for cleanup and promote deployment state only after successful vertices.
  • One-line summary: Keep resource ownership and externally reported task/pipeline state consistent during allocation and deployment failure.

Example: Two requested slots yield one success and one failure. The request remains incomplete until release of the successful slot finishes; exhausted release failure is attached to the allocation failure rather than hidden.

1. Code-change review

1.1 Core logic analysis

Eleven files, +981/-50: six production resource/state components and five targeted test classes. The complete target-relative diff was read at 7e1aa69f856fbe497008da0f778b9a477843cc59, not just the latest commit. Production error-completion ordering/state publication changes; latest commit changes only the test import, but this review covers the full patch.

Before / after:

Before: completeExceptionally -> fire-and-forget partial release
After:  first-completion CAS -> all per-slot release attempts -> completeExceptionally
Before: failed deploy still publishes RUNNING; null entries counted as allocations
After:  successful deploy only; pipeline requires RUNNING/FINISHED vertices
        null/cancelled futures excluded while successful ownership is retained
Latest: test import engine.core.job.JobStatus -> engine.common.job.JobStatus

Complete relevant execution chain:

PhysicalPlan preallocation -> AbstractResourceManager.applyResources():187-199
  -> new ResourceRequestHandler -> request original resource indexes
  -> preCheckWorkerResource -> RequestSlotOperation -> await complete round
  -> missing indexes retried; dynamic manager may provision missing indexes
  -> allocation error -> completionStarted CAS -> releaseAllResourceInternal():343-380
     -> releaseResourceWithRetry():382-418 per acquired slot -> allOf -> fail request
ResourceUtils.applyResourceForPipeline():43-79
  -> join futures -> retain only successful non-null profiles
  -> setOwnedSlotProfiles BEFORE reporting insufficient resources
SubPlan.stateProcess(CREATED -> DEPLOYING): resource/deploy flow
  -> PhysicalVertex.makeTaskGroupDeploy -> updateTaskState -> synchronous stateProcess
  -> deploy -> finishDeployment():328 -> publish RUNNING only on success
  -> failed deploy -> FAILING/FAILED -> vertex future callback -> pipeline FAILING
  -> SubPlan:719-722 promotes only if every vertex RUNNING or FINISHED
CoordinatorService.getJobStatus():1637-1654 -> null-safe history resolution

Key findings:

  1. The normal allocation failure path now waits for the round's in-flight slot requests and its rollback attempts before publishing failure. It does not promise that an exhausted rollback succeeded.
  2. Original indexes prevent retrying a missing middle resource into the wrong result slot.
  3. ResourceUtils stores successful ownership before throwing for null/exceptional/cancelled peers, allowing existing teardown to release those slots.
  4. Deployment failure no longer introduces a misleading transient RUNNING state. Already FINISHED vertices are accepted, avoiding a stuck promotion for a very short task.
  5. The compile-blocking import is corrected. Retry policy/comment coverage remain the same recommendations as the prior round, rather than newly discovered blockers.

Community context: No non-Daniel Review or inline technical finding is present in the collected PR discussion. An independent write-capable reviewer must assess this author-owned change before merge.

1.2 Compatibility impact

Fully compatible API/configuration/state formats. ResourceManager.applyResources keeps its signature; failure completion now waits for rollback attempts. No option/default, operation ID, serialized task layout or checkpoint format changes. No migration or incompatible-changes entry is needed.

1.3 Performance / side effects

Successful allocation adds a CAS and original-index bookkeeping; failed allocation now waits for cleanup. At most 30 release attempts per failed slot are currently immediate and log each retry (Issue 2). Memory is bounded by the requested slots and their futures. No new scheduler/thread pool is introduced. Existing dynamic-worker hooks are exercised by a test double; this does not establish a production dynamic manager is enabled.

1.4 Error handling and logging

Exhausted release errors are attached as suppressed allocation-failure context. Null historical status returns UNKNOWABLE rather than dereferencing absent history. ResourceUtils catches both wrapped failure and cancellation. Retry/error diagnostics include job/slot/worker identifiers, with no credential logging.

Issue 2 (carried forward): Refine rollback retry classification and pacing

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/resourcemanager/ResourceRequestHandler.java:382-418.
  • Problem: All release failures get up to 30 immediate attempts and a warning stack trace on every retry. DefaultSlotService.releaseSlot:205-224 distinguishes absent/changed/foreign assignments with deterministic WrongTargetSlotException.
  • Risk: Failure storms can produce many RPCs/logs and delay allocation-failure visibility; an already absent assignment is not necessarily an unreleased resource.
  • Best fix: Classify retryable transport/lifecycle failures, pace retry attempts and bound logging. Treat an assignment confirmed already gone as idempotent completion; do not hide a genuine wrong-target/ownership defect without checking which case occurred. Add non-retryable/already-released coverage.
  • Severity: Medium, existing non-blocking recommendation. Raised by another reviewer: No.

Issue 4 (carried forward): Explain the new lifecycle contracts in comments

  • Location: ResourceRequestHandler.java:79,215-227,382; PhysicalVertex.java:328; SubPlan.java:769; CoordinatorService.java:1649.
  • Problem: New state/helper methods encode first-completion ownership, rollback timing and state-promotion rules without nearby method/field comments.
  • Risk: Future maintenance can accidentally publish completion before cleanup or misread why a failed vertex is left for the failure callback.
  • Best fix: Add concise ownership/ordering comments, including that rollback exhaustion is reported rather than guaranteed released.
  • Severity: Medium, carried forward with its prior non-blocking disposition. Raised by another reviewer: No.

Issue 3 (carried forward, defensive only): Complete the public request in a finally guard

  • Location: ResourceRequestHandler.java:215-227.
  • Problem: The rollback callback adds suppressed context before completing the public request. A defensive finally would make completion independent of diagnostic assembly.
  • Risk: This is a robustness suggestion; I have not established a normal production path where addSuppressed actually throws, so it is not evidence of a current reproducible hang.
  • Best fix: Put exceptional completion in finally, preserving the original allocation failure.
  • Severity: Low, non-blocking. Raised by another reviewer: No.

2. Code-quality assessment

2.1 Code conventions

The wrong JobStatus package import is fixed at CoordinatorServiceStatusTest:20; ASF headers and explicit imports are present. Complete the existing Issue 4 comments. The scoped whitespace check is clean. The scoped whitespace check produced no entries.

2.2 Test coverage and stability

Stability rating: Stable by structure. ResourceRequestHandlerTest:53-234 uses manually controlled/completed futures and one available worker, not sleeps or network ports. ResourceUtilsTest:45-101 checks cancelled/exceptional peers retain successful ownership. SubPlanDeploymentTest:43-134 drives the actual state-process entry using deterministic map/state mocks. PhysicalVertexDeployStateTest checks success/failure publication. No process-global fixture state is modified. No local build, unit/integration test, container or service was run. Coverage establishes rollback-before-failure, selective per-slot retries, synchronous release failure, retry exhaustion, index preservation, dynamic missing indexes and deployment/history behavior. It is unit-level evidence, not worker-RPC or cluster E2E execution; the existing engine integration suite remains an important CI gate. The new import has not been compiled locally.

The head changed during this batch from 050472f to 7e1aa69. The old Build/test-compile failure belongs to the former head. No completed current-head CI result was available in the refreshed metadata; obtain the new required Build result before merge. This was a PR-owned import failure, so being behind dev did not explain it and is not a reason to prescribe a sync-only fix.

2.3 Documentation

No user-facing option/default or persisted-format migration is introduced. ResourceManager API documentation now correctly states that failure waits for rollback attempts and reports exhausted cleanup failure.

3. Architectural soundness

3.1 Solution quality

A focused ownership/ordering correction in the components that own each invariant; stronger than masking null allocations or merely delaying status publication.

3.2 Maintainability

Keep first completion and cleanup ownership explicit. The helper test plus actual SubPlan entry coverage are useful; avoid broad unrelated resource-manager refactoring.

3.3 Extensibility

Original resource indexes make future partial/dynamic allocation safer, but production dynamic support must still be evaluated independently.

3.4 Historical compatibility

No state migration is introduced. Timing changes in failure completion require current-head engine CI; static source reasoning is not an upgrade test.

4. Findings summary

Number Finding Location Severity
2 Filter/pace rollback retries ResourceRequestHandler.java:382-418 Medium, non-blocking
4 Document lifecycle ownership/ordering Resource/state helper sites above Medium, non-blocking carryover
3 Defensive finally around request completion ResourceRequestHandler.java:215-227 Low

Issue 1 (wrong JobStatus import) is closed in the latest commit.

5. Merge conclusion

Conclusion: Can merge after fixes

  1. Blocking items: No demonstrated remaining source blocker from this review. The required current-head CI and independent effective maintainer approval are still missing.
  2. Non-blocking recommendations: Carry forward Issues 2/4/3 with the same non-blocking disposition; remove unsupported blanket independent-QA claims from the description and report actual executed CI evidence.

The allocation/deployment invariants are improved and the concrete compile error is fixed. Merge requires the new-head Build and an independent maintainer review; this author-side COMMENT supplies neither a self-approval nor a runtime pass claim.

Compare against dev: diverged, ahead 2 / behind 28, merge conflict=False. Drift is recorded independently; it does not itself justify a sync-first comment without an unrelated CI failure.

Daniel has READ permission. This COMMENT is a technical assessment, not an effective write-level approval. A write-capable maintainer must confirm repository gates and supply the effective approval.

Local evidence: exact-head fetch/checkout on seatunnel-review-12948, complete diff and source call-chain reads cited above. No runtime verification was claimed.

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

+1 good job

@nzw921rx
nzw921rx added this pull request to the merge queue Oct 26, 2026
Merged via the queue into apache:dev with commit 7f87688 Oct 26, 2026
2 checks passed

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Post-merge maintainer review of the merged head 9ebebaec. Two disclosures first: this PR was authored by the DanielLeens account, so this is a self-review written as adversarially as I can and it is not an independent approval (@nzw921rx already approved and merged it). The PR is also already merged, so everything below is a follow-up list, not a merge gate. I read the full diff and the merged files by code reading only; nothing was compiled or run locally, and the head's GitHub Build is green.

What Problem Does This PR Solve?

  • User pain point: a multi-slot request could fail halfway, complete its future before the asynchronous rollback of already-granted slots finished, and let the next retry race with slots the failed attempt still owned. Related paths also lost original request indexes, skipped the dynamic-worker fallback, published RUNNING after a failed deployment, and threw while looking up job status during master convergence.
  • Fix approach: track requests by original index, wait for every rollback attempt before failing the request, retry each slot release independently, publish task and pipeline RUNNING only on real success, and return UNKNOWABLE when no status is available.
  • One-sentence summary: make slot allocation failure and recovery deterministic so a retry never observes slots owned by a failed attempt.

1. Code Change Review

1.1 Core Logic Analysis

Normal path: yes. Every pipeline goes through SubPlan.stateProcess SCHEDULED -> ResourceUtils.applyResourceForPipeline -> ResourceRequestHandler.request, then DEPLOYING -> PhysicalVertex deploy. The allocation changes only differ from before on partial failure, pre-check miss and dynamic-worker paths; the deployment and pipeline-state changes touch every deployment.

SubPlan.stateProcess [SCHEDULED] (SubPlan.java:735-770)
  -> ResourceUtils.applyResourceForPipeline (null/cancelled futures no longer stored; size mismatch -> NoEnoughResourceException)
      -> ResourceRequestHandler.request (indexes 0..n-1)
          -> requestSlotWithRetry -> requestSlots(indexes): pre-check miss leaves the index unassigned
              -> allOf(in-flight RPCs) completes only when ALL return
                  -> error: completeRequestWithException -> releaseAllResourceInternal (per-slot retry) -> THEN completeExceptionally
                  -> ok but unassigned: retry with remaining indexes, then applyByDynamicWorker
SubPlan.stateProcess [DEPLOYING] (SubPlan.java:774-792)
  -> PhysicalVertex.makeTaskGroupDeploy -> updateTaskState(DEPLOYING) -> deploy() synchronously (PhysicalVertex.java:606-614)
      -> finishDeployment: RUNNING only if state.isSuccess() (PhysicalVertex.java:329-333)
  -> pipeline RUNNING only if every vertex is RUNNING or FINISHED (SubPlan.java:790)

Key findings: the ordering fix (rollback before failure becomes visible) is correct and is the heart of the PR; allOf guarantees no first-round RPC is still in flight when the error branch runs. The deployment guard is sound because deployment is synchronous inside updateTaskState, so by the time the pipeline checks the vertices they are already RUNNING, FINISHED or on the failure path (a failed vertex completes its task future and drives the pipeline to FAILING). It is a precise fix, not a workaround.

1.2 Compatibility Impact

Fully compatible. No config, default, protocol, serialized state or checkpoint/savepoint format changes. One behavior change worth knowing: with no dynamic-worker support, a pre-check miss now runs up to MAX_RETRY_TIMES (3) immediate retry rounds before failing instead of failing on the first round; the exception type stays NoEnoughResourceException.

1.3 Performance / Side-Effect Analysis

Removing the dead failed-future allocation and the extra index list are negligible. The new cost is rollback: up to Constant.OPERATION_RETRY_TIME = 30 immediate release attempts per slot with no delay (ResourceRequestHandler.java:382-415). That is acceptable for the normal path (success on first try) but see Issue 1.

1.4 Error Handling and Logging

Exhausted rollback failures are attached with addSuppressed and logged per retry at WARNING, which is good diagnostics. Issues:

Issue 1: Rollback retry has no backoff and no overall deadline

  • Location: ResourceRequestHandler.java:382-415 (and the join in ResourceUtils.applyResourceForPipeline)
  • Problem: the request future is now completed only after every slot release finishes. Retries re-send immediately (30 times, no sleep), and I did not find a per-release deadline in the path I read (AbstractResourceManager.releaseResource -> sendToMember); I expect only Hazelcast's invocation timeout to bound it, which I did not verify here.
  • Risk: a live but erroring worker means a burst of 30 back-to-back RPCs per slot, and a release future that never completes would leave the pipeline waiting in SCHEDULED, where before the failure was at least visible immediately. The PR description calls this "bounded"; it is bounded by count, not by time.
  • Best improvement: space retries with Constant.OPERATION_RETRY_SLEEP (2s) on a scheduled executor, not a blocking sleep, and apply an overall deadline (for example orTimeout) after which the request fails with the rollback error suppressed.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 2: Late slots can leak after a failed request on dynamic-worker clusters

  • Location: ResourceRequestHandler.java:140-150 (retry catch -> applyByDynamicWorker), :229-243 (addSlotToCacheMap), :317-339
  • Problem: when a nested retry round hits an RPC error, the inner call runs completeRequestWithException (rollback, completionStarted=true, future failed). The inner future then fails, the outer .get() throws, and the outer branch still calls applyByDynamicWorker when supportDynamicWorker(). Slots returned there are put into resultSlotProfiles after the rollback; completionStarted is already true so nothing completes and nothing releases them. This is from code reading, not a reproduction. The same shape existed before the PR, but this PR introduced completionStarted and claims rollback ownership, so it should close the hole.
  • Risk: extra workers requested for an already failed job and slots held until the job master or worker cleanup reclaims them.
  • Best improvement: in the catch branch return early when completionStarted.get(), and in addSlotToCacheMap release a non-null slot if completion already started with a failure.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 3: Pipeline can sit in DEPLOYING silently

  • Location: SubPlan.java:790
  • Problem: if the guard is false and no failure drives the pipeline (for example PhysicalVertex.updateTaskState returns early with "current state is null", PhysicalVertex.java:361), nothing re-evaluates the pipeline and nothing is logged.
  • Risk: a stuck pipeline that previously showed RUNNING; hard to diagnose.
  • Best improvement: log at WARN with the non-running vertices when the guard is false and the pipeline is not failing.
  • Severity: Low
  • Raised by another reviewer: No

Issue 4: Duplicate RUNNING transition causes info-log noise

  • Location: PhysicalVertex.java:331 and :613
  • Problem: on the success path finishDeployment already sets RUNNING, then the DEPLOYING case calls updateTaskState(RUNNING) again and logs "current state equals target state ... skip" once per task.
  • Best improvement: drop the second call at :613 (verify no other deploy path relies on it first).
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

New helpers (resolveHistoryStatus, areAllVerticesRunningOrFinished, finishDeployment, releaseResourceWithRetry) are small and named clearly. The non-obvious fields and methods (completionStarted, the rollback ordering) have either a Javadoc update on ResourceManager.applyResources or an inline comment; a one-line comment on completionStarted explaining that it gates both success and failure completion would help (Low, folded into Issue 2).

2.2 Test Coverage and Test Stability

Coverage is good: 20 new tests cover rollback ordering, retry, synchronous failure, exhausted rollback, selective per-slot retry, non-contiguous indexes, pre-check misses reaching dynamic allocation, deployment state, pipeline promotion and UNKNOWABLE status. Missing scenario: the nested retry failure followed by dynamic-worker allocation from Issue 2, and a release future that never completes (Issue 1).
Stability rating: Stable. The tests use fake resource managers with counters and futures completed by hand; I found no Thread.sleep, no Awaitility and no fixed waits in the added tests (ResourceRequestHandlerTest, SubPlanDeploymentTest, ResourceUtilsTest).

2.3 Documentation Updates

None required: internal Zeta behavior, no docs/en or docs/zh change, and no incompatible-changes entry.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix at the right layer (the request handler owns the rollback).

3.2 Maintainability

Index-based requests are clearer than passing profile lists around; the rollback helper is readable.

3.3 Extensibility

The per-slot retry helper could be reused by other release paths once it has a backoff.

3.4 Historical-Version Compatibility

Compatible; no serialized state or protocol touched.

4. Issue Summary

# Issue Location Severity
1 Rollback retry lacks backoff and overall deadline ResourceRequestHandler.java:382-415 Medium
2 Late dynamic-worker slots can leak after failure ResourceRequestHandler.java:140-150, 229-243 Medium
3 Pipeline can sit in DEPLOYING silently SubPlan.java:790 Low
4 Duplicate RUNNING transition log noise PhysicalVertex.java:331, 613 Low

5. Merge Recommendation

Conclusion: Ready to merge

The PR is already merged and approved; this review does not change that. I found no merge-blocking regression.

  1. Blockers - must be fixed: none.
  2. Recommended fixes - non-blocking: Issues 1 and 2 (Medium) are worth a small follow-up PR because they sit on the failure path this PR is hardening; Issues 3 and 4 are cleanups.

Overall assessment: a net improvement with a correct core ordering fix and solid tests. Option A: follow-up PR with the backoff/deadline and the completionStarted guard. Option B: leave as is and track the two Medium items in an issue. Thanks @nzw921rx for the review and merge.

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] Partial slot allocation failure can publish inconsistent recovery state

2 participants