Skip to content

[Fix][Zeta] Persist pre-applied slot ownership before deployment - #13465

Open
zhangshenghang wants to merge 5 commits into
apache:devfrom
zhangshenghang:fix/13346-persist-pre-applied-slots
Open

zhangshenghang wants to merge 5 commits into
apache:devfrom
zhangshenghang:fix/13346-persist-pre-applied-slots

Conversation

@zhangshenghang

Copy link
Copy Markdown
Member

Purpose of this pull request

Yes, I am contributing to Apache SeaTunnel.

Part of #13346. This PR closes the "master crash between assignment and persistence" window that the issue lists as a fixed-slot capacity leak.

A fixed slot is assigned on the worker first. The master only records the slot-to-task ownership when the pipeline reaches SCHEDULED (ResourceUtils.applyResourceForPipeline). If the master fails between the successful pre-apply and that transition, the new master has no SlotProfile for the assignment: it can neither reuse it on restore nor release it on job completion. With dynamic-slot: false the worker never expires the slot, so the capacity is lost until the worker restarts.

What this PR changes:

  • After a successful JobMaster.preApplyResources(...), the exact TaskGroupLocation -> SlotProfile mapping is written to ownedSlotProfilesIMap immediately, grouped per pipeline, instead of waiting for SCHEDULED.
  • Only profiles of successfully completed allocation futures are persisted. Slots reused from the previous master are written again with their existing values.
  • The write uses the exact SlotProfile (worker, slot id, allocation sequence). Reuse validation (getReusableSlot/slotActiveCheck) and release still reject a slot that was meanwhile released and reassigned to another task group or attempt, so the early write cannot make a stale mapping acceptable.
  • The early write is best effort: the SCHEDULED transition remains the enforcing persistence point, so a transient IMap failure here is logged instead of failing a job whose slots have already been allocated.

Scope note: this PR addresses the durable-ownership part of #13346 only (item 2 of the suggested fix direction). Idempotent allocation requests for lost responses (item 1) and worker-side reconciliation by job (items 3/4) are not included; they need the allocation-identity/attempt contract discussed in the issue thread, and a job-id-only worker-side release would conflict with SAVEPOINT restores, which reuse the source job id (ClientJobExecutionEnvironment).

Does this PR introduce any user-facing change?

No. Allocation, reuse and release semantics are unchanged; the ownership record is written earlier.

How was this patch tested?

  • ./mvnw -pl seatunnel-engine/seatunnel-engine-server spotless:apply
  • ./mvnw -pl seatunnel-engine/seatunnel-engine-server -Dtest=JobMasterMasterFailoverResourceTest,JobMasterTest -DfailIfNoTests=false test (14 tests passed)

The new testPreApplyPersistsSlotOwnershipBeforePipelineDeployment pre-applies a fixed-slot job without starting any pipeline and asserts that every pipeline already has a persisted taskGroup -> slot map whose size matches its coordinator + task vertices. The three existing failover tests (reuse of active slots, sub-plan restore flag, stale reassigned slot rejection) still pass with the mapping now written earlier.

No E2E scenario was added: the failure window is between pre-apply and SCHEDULED, which the existing E2E allocation tests cannot stop deterministically. The embedded-cluster resource tests above exercise the same JobMaster/ResourceManager/fixed-slot SlotService path.

A fixed slot is assigned on the worker first and only recorded by the
master when the pipeline reaches SCHEDULED. A master failure in between
leaves the workers holding slots that the new master has no profile
for, so it can neither reuse nor release them; with dynamic-slot:false
that capacity is lost until the worker restarts.

Persist the exact taskGroupLocation -> SlotProfile mapping of a
successful pre-apply right away, grouped per pipeline. The profiles
keep their allocation sequence, so later reuse validation and release
still reject a slot that was reassigned to another task group. The
write is best effort because the SCHEDULED transition remains the
enforcing persistence point; a transient IMap failure is logged so a
job that already owns slots is not failed by the early write.

Add a regression test that pre-applies resources without starting any
pipeline and verifies the ownership map is already populated.
@github-actions github-actions Bot added the Zeta label Nov 26, 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 for contributing to Apache SeaTunnel! I reviewed the complete current diff and followed its entry points and failure paths. The items below need attention before merging; I hope the concrete paths make the next step straightforward.

What problem does this PR solve?

User pain: A master can allocate fixed slots and fail before SCHEDULED persists ownership; its replacement then cannot find those assignments to reuse/release.

Fix: Group completed pre-apply SlotProfiles by pipeline and write the existing ownership map before deployment.

In one sentence: Record the worker slot/sequence mapping earlier, before a pipeline starts deploying.

1. Code changes

1.1 Core logic

Complete runtime path:

CoordinatorService.pendingJobSchedule [425-449] -> JobMaster.preApplyResources
 -> all allocation futures join and success is checked [557-584]
 -> install plan futures [598-605]
 -> new persistPreAppliedSlotProfiles [682-717]
 -> group exact SlotProfiles by PipelineLocation -> setOwnedSlotProfiles [1631-1648]
 -> scheduler advances/runs pipeline -> SCHEDULED ResourceUtils enforces ownership again
Master failover -> new JobMaster reads retained owned profiles [804 onward]
 -> reuse active matching slot/sequence; release paths use that same map [1008-1092]

Key findings and correctness:

All three changed files/regions were inspected against successful all-pipeline and single-pipeline pre-apply paths, failover reuse, release and SCHEDULED persistence. The added test instantiates a real JobMaster with an explicitly injected ownership IMap, so its map name is consistent with its constructor fixture; it must not be confused with the production Constant map name. All futures are already joined before the helper reads getNow, and the helper introduces no new serialized state type. Persisting exact SlotProfiles preserves sequence fencing. The important unresolved branch is the deliberately swallowed ownership-write failure: the helper returns normally and preApplyResources still returns true even if the durable mapping was not written. That leaves the original failover/release window open under a realistic IMap error.

Before:

                // Adequate resources, pass on resources to the plan
                physicalPlan.setPreApplyResourceFutures(preApplyResourceFutures);
            }
            // Retained slots are valid only for the first successful allocation after failover.
            // A later pipeline retry must obtain a fresh allocation instead of reusing them.
            masterFailoverRestore = false;

After:

                // Adequate resources, pass on resources to the plan
                physicalPlan.setPreApplyResourceFutures(preApplyResourceFutures);
            }
            // Persist the ownership now, before any pipeline reaches SCHEDULED and starts
            // deploying. Otherwise a master failure in this window leaves the workers holding
            // slots that the new master cannot reuse or release, because it never recorded them.
            persistPreAppliedSlotProfiles(preApplyResourceFutures);
            // Retained slots are valid only for the first successful allocation after failover.
            // A later pipeline retry must obtain a fresh allocation instead of reusing them.
            masterFailoverRestore = false;

1.2 Compatibility

The same PipelineLocation/task-group-to-SlotProfile IMap layout and slot sequence are reused; no checkpoint/row serializer, option/default or public constructor signature changes. Normal successful allocation gains an earlier write. Error handling still needs Issue 1 so failure does not masquerade as durable ownership.

1.3 Performance and side effects

One additional ownership-map write per allocated pipeline and a temporary O(task groups) grouping map occur at allocation/restore time, not per row. It preserves normal resource release and slot identity; no executor, queue, connection or retry loop is added. Failure compensation must avoid releasing retained profiles owned by another allocation sequence.

1.4 Errors, logging, and findings

Issue 1: Do not report successful pre-apply when early ownership persistence failed

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:708.
  • Description and risk: The exception from setOwnedSlotProfiles is caught and reduced to a warning, after worker allocations have succeeded. The caller then advances with true. If the master is lost before the later SCHEDULED write, the replacement sees no ownership map while the workers still hold the slots—the precise window this PR is intended to close. The happy-path map assertion cannot expose this branch.
  • Best improvement: Make ownership persistence part of the successful pre-apply contract. On an unconfirmed write, prevent deployment and safely compensate/retry using the exact completed profiles, excluding reused assignments and preserving sequence ownership. Add a focused injected-IMap-failure case plus an existing failover IT assertion for pre-deployment ownership. Do not simply throw after allocation without releasing or retaining recoverable ownership.
  • Responsibility and trade-off: JobMaster is the first layer that has the complete successful pre-apply mapping, so persisting there is the best minimal boundary. A connector fix or later task deployment write cannot cover this interval. The smallest safe fix makes that early write an acknowledged allocation boundary with precise rollback/retry; broader worker/master reconciliation may be a separate defense, but cannot be claimed as supplied here.
  • Severity: High; blocking: true.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

Community input: no independent technical finding or maintainer approval/change request was present in the collected discussion.

2. Code quality

2.1 Conventions

Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.

2.2 Test coverage and stability

Stability rating: Stable. JobMasterMasterFailoverResourceTest.java:90-115 asserts that every pipeline has a complete mapping immediately after pre-apply, before it runs, and releases the persisted profiles in finally. It uses real server allocation rather than only a mocked map interaction. Stability rating: Stable for the new positive-path assertions; there is no added fixed delay or thread ordering assumption. It does not inject a persistence failure, prove compensation, or drive an actual master switch in the new interval. The existing failover integration area must cover that exception/recovery boundary as Issue 1. Current Build remains in progress; no local test execution is claimed.

2.3 Documentation

There is no new user option or upgrade format. The helper Javadoc documents best-effort behavior, but that is the unresolved correctness limitation in Issue 1; it should not be presented as a fully closed durable failover guarantee.

3. Architecture

3.1 Change location

JobMaster is the first layer that has the complete successful pre-apply mapping, so persisting there is the best minimal boundary. A connector fix or later task deployment write cannot cover this interval. The smallest safe fix makes that early write an acknowledged allocation boundary with precise rollback/retry; broader worker/master reconciliation may be a separate defense, but cannot be claimed as supplied here.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. JobMaster is the first layer that has the complete successful pre-apply mapping, so persisting there is the best minimal boundary. A connector fix or later task deployment write cannot cover this interval. The smallest safe fix makes that early write an acknowledged allocation boundary with precise rollback/retry; broader worker/master reconciliation may be a separate defense, but cannot be claimed as supplied here.

3.3 Extensibility

Prefer the existing component boundary and tests over unrelated shared abstractions.

3.4 Upgrade impact

The same PipelineLocation/task-group-to-SlotProfile IMap layout and slot sequence are reused; no checkpoint/row serializer, option/default or public constructor signature changes. Normal successful allocation gains an earlier write. Error handling still needs Issue 1 so failure does not masquerade as durable ownership.

4. Findings summary

Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.

# Finding Location Severity
1 Do not report successful pre-apply when early ownership persistence failed seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:708 High

5. Merge recommendation

Merge after fixes

Blocking items: Issues 1. Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: None beyond the validation limits above.

Overall: the approach addresses a real path, but the listed blockers must be closed. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.

CI and repository state: Signal pull request update: SUCCESS; Build: IN_PROGRESS; Build: queued. GitHub reports BLOCKED / REVIEW_REQUIRED.

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

Review time: 2026-11-26T06:57:12.519355-05:00

Local evidence: git fetch obtained head 6dc0012d871019d1ad9474da66e810a2427029ad; git merge-base returned 60e039a810844323172d4048f721bc88146e9a83; git diff --stat reports 2 files changed, 83 insertions(+). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.

@DanielLeens

Copy link
Copy Markdown
Contributor

@zhangshenghang, following up on the earlier review. At 6dc0012d87, persistPreAppliedSlotProfiles still logs an ownership-map write failure and lets pre-apply return success. If the active master exits before the later SCHEDULED write, the new master can still be left without the slot record. Could you make a failed or unconfirmed write stop admission, and add a test for that branch? Cleanup also needs to account for the case where the write committed but its acknowledgement was lost, so it does not release a slot the successor has already adopted.

For the remaining part of #13346, are you planning a follow-up for when the Worker grants the slot but the allocation response never reaches the Master? It would be helpful to coordinate that work with you.

…ot be persisted

setOwnedSlotProfiles already retries until the written value is readable
back, so a failure there means the ownership is unknown, not merely
delayed. Swallowing it and admitting the job anyway left the workers
holding fixed slots that a successor master had no profile for, because
the early write is the only record before the pipeline reaches SCHEDULED.

Propagate the failure: the pre-apply now releases the slots it acquired
and returns false so the scheduler does not start the job. Before the
release, the ownership records this round wrote are removed explicitly,
because an IMap write can commit while its acknowledgement is lost. A
pipeline whose record cannot be removed keeps its slots allocated, so a
master that already adopted them never sees them released underneath.

Add a regression test that fails the ownership IMap write and checks both
the rejected admission and that every fixed slot is free again.

@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 following up on the admission request. I re-read the complete current diff and ownership/release paths. Explicit write exceptions now stop admission, but the unconfirmed-write part of the original Issue 1 remains; the new compensation also needs the ownership correction below.

What problem does this PR solve?

User pain: A master can allocate fixed slots and disappear before recording the task-to-slot mapping, leaving the replacement unable to reuse or release them.

Approach: Persist successful pre-applied profiles before installing deployment futures; reject admission on persistence exceptions and compensate failed rounds.

In one sentence/example: Record who owns a worker slot before starting its task, so a replacement master can find that same allocation.

1. Code changes

1.1 Core logic

Complete runtime path:

CoordinatorService pending schedule / pipeline restore -> JobMaster.preApplyResources
 -> complete allocation futures; retain reusedSlotProfiles on failover
 -> collectPreAppliedSlotProfiles -> persistPreAppliedSlotProfiles [686-703]
 -> setOwnedSlotProfiles [1719-1736]: IMap.put then RetryUtils returning equality boolean
 -> success installs plan futures -> SCHEDULED/deploy
 failure -> reconcilePreAppliedSlotProfiles [717-737]: unconditional remove per pipeline
 -> releaseUnusedPreAppliedResources excludes reused/unreconciled profiles
 successor -> getReusableSlot [888-895] reads persisted map + validates live allocation
 worker ReleaseSlotOperation -> DefaultSlotService.releaseSlot checks job/sequence, not master epoch

Key findings and correctness:

  1. The successful early-write location is appropriate, and explicit put exceptions now prevent admission instead of merely logging and continuing. That part of prior Issue 1 is fixed.
  2. Unconfirmed read-back is still accepted: RetryUtils.retryWithException returns execution results without treating false as failure. setOwnedSlotProfiles ignores that Boolean, so its new caller's “confirmed” premise is not established (retained Issue 1).
  3. The new compensation removes ownership for reused profiles while intentionally not releasing those profiles. A rejected restored round can therefore erase the only mapping for still-active retained slots (Issue 2).
  4. Removing a map entry also does not revoke a successor that already read/adopted it. Exact allocation sequence prevents release of a different allocation, but not release of the same allocation now adopted by another master; Issue 2 covers that ownership boundary.
  5. The separate worker-granted/allocation-response-lost window in #13346 is not solved by persistence after a successful future and remains outside this patch's supplied guarantee.

Before:

// ownership was recorded later when the pipeline reached SCHEDULED
physicalPlan.setPreApplyResourceFutures(preApplyResourceFutures);

After (key excerpts):

if (!persistPreAppliedSlotProfiles(preAppliedSlotProfiles)) {
    Set<PipelineLocation> unreconciledPipelines =
            reconcilePreAppliedSlotProfiles(preAppliedSlotProfiles);
    releaseUnusedPreAppliedResources(preApplyResourceFutures, reusedSlotProfiles, unreconciledPipelines);
    return false;
}

1.2 Compatibility

The map key/value shape, SlotProfile allocation identity, options/defaults and checkpoint formats are unchanged. Successful normal allocation gets an earlier write. Compatibility does not make the new failure compensation safe; ownership/recovery semantics remain blocking until the listed paths are corrected.

1.3 Performance and side effects

Grouping is O(task groups) and adds ownership-map IO per pipeline before deployment. Failure cleanup adds map removals and bounded existing resource-release retries, not row-path work. Reused assignments must remain tracked; losing their recovery mapping can strand fixed capacity, and releasing successor-adopted slots violates execution isolation. No new thread/pool is added.

1.4 Errors, logging, and findings

Issue 2: Preserve retained/adopted ownership when compensating a failed round

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:722.
  • Description and risk: The new reconcile helper unconditionally removes every pipeline entry, including slots reused from the previous master. releaseUnusedPreAppliedResources then excludes those reused profiles. Example: restore reads active retained slots, a new persistence write fails, remove succeeds: the worker still owns the slots but the only recovery map is gone, so the next retry/successor cannot reuse or release them. Separately, a successor may already have adopted a successfully written record before this stale round removes it; map removal does not revoke that adoption, and releasing the same job/sequence passes the worker check. That can free a live slot for reuse. The current record has no master-generation fence.
  • Best improvement: Separate pre-existing retained ownership from newly acquired assignments and preserve/restore it on failed admission. Fence record mutation and release by an active-master/allocation-round ownership token; an unconditional remove or remove(key,value) alone cannot revoke an already adopted record. Add deterministic reused-slot write-failure and successor-adoption/lost-ack tests through the existing failover IT, asserting both recoverable map ownership and that an adopted slot is never released.
  • Responsibility and trade-off: JobMaster is the first layer with the complete successful pre-apply mapping and is the correct minimal persistence point. Correct compensation needs the map and worker/master ownership boundary together; a later SCHEDULED write or connector patch cannot close it. An explicit fenced allocation transaction is stronger than best-effort map removal.
  • Severity: P0; blocking: true.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

Issue 1: Retained Issue 1: reject an unconfirmed read-back as well as a thrown write

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:690.
  • Description and risk: persistPreAppliedSlotProfiles treats a normal return from setOwnedSlotProfiles as confirmed persistence. At JobMaster:1724-1732, the retry lambda returns pipelineOwnedSlotProfiles.equals(IMap.get(...)), but RetryUtils.retryWithException returns that false result immediately and the caller ignores it. A put followed by null/different read-back therefore still admits the job with unconfirmed ownership. This is the original unconfirmed-persistence blocker, not a new unrelated finding.
  • Best improvement: Make a mismatched read-back explicitly fail/retry within a bounded, owner-checked persistence contract, and propagate failure to pre-apply. Add null/different read-back tests in addition to the thrown-put test. Keep compensation safe as Issue 2; do not simply throw and abandon allocated slots.
  • Responsibility and trade-off: JobMaster is the first layer with the complete successful pre-apply mapping and is the correct minimal persistence point. Correct compensation needs the map and worker/master ownership boundary together; a later SCHEDULED write or connector patch cannot close it. An explicit fenced allocation transaction is stronger than best-effort map removal.
  • Severity: High; blocking: true.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

Community input: no independent technical finding or maintainer approval/change request was present in the collected discussion.

2. Code quality

2.1 Conventions

Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.

2.2 Test coverage and stability

Stability rating: Stable. Stable for the new deterministic assertions: a real pre-apply is observed before deployment, and a mocked IMap.put failure must return false and allow capacity probes. No fixed sleep is added. However the new failure test has no reused profiles, no false/null read-back after put, and no successor adoption interleaving. Existing engine failover IT coverage is not updated, so it does not close those required failure-window regressions.

2.3 Documentation

No new user option or successful format requires bilingual migration docs. The new Javadocs must match the actual confirmation/fencing contract; “readable back” is not currently guaranteed by setOwnedSlotProfiles, and clearing a record alone does not prove a successor has not adopted it.

3. Architecture

3.1 Change location

JobMaster is the first layer with the complete successful pre-apply mapping and is the correct minimal persistence point. Correct compensation needs the map and worker/master ownership boundary together; a later SCHEDULED write or connector patch cannot close it. An explicit fenced allocation transaction is stronger than best-effort map removal.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. JobMaster is the first layer with the complete successful pre-apply mapping and is the correct minimal persistence point. Correct compensation needs the map and worker/master ownership boundary together; a later SCHEDULED write or connector patch cannot close it. An explicit fenced allocation transaction is stronger than best-effort map removal.

3.3 Extensibility

Prefer the existing component boundary and tests over unrelated shared abstractions.

3.4 Upgrade impact

The map key/value shape, SlotProfile allocation identity, options/defaults and checkpoint formats are unchanged. Successful normal allocation gets an earlier write. Compatibility does not make the new failure compensation safe; ownership/recovery semantics remain blocking until the listed paths are corrected.

4. Findings summary

Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.

# Finding Location Severity
2 Preserve retained/adopted ownership when compensating a failed round seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:722 P0
1 Retained Issue 1: reject an unconfirmed read-back as well as a thrown write seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:690 High

5. Merge recommendation

Merge after fixes

Blocking items: Issue 2 (ownership compensation), then Issue 1 (unconfirmed persistence). Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: None beyond the validation limits above.

Overall: the approach addresses a real path, but the listed blockers must be closed. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.

CI and repository state: Signal pull request update: SUCCESS; Build: FAILURE; Build: queued. GitHub reports BLOCKED / REVIEW_REQUIRED.

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

Review time: 2026-11-27T04:05:59.537231-05:00

Local evidence: git fetch obtained head 0dbee9ffa396e464d70885d6e679b6b56371fa3d; git merge-base returned c0c6d04ca517f7fe039fb1994604a3643a3e59ec; git diff --stat reports 2 files changed, 293 insertions(+), 64 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.

The previous head only rejected admission when the ownership write threw.
A put that returned but whose value did not read back was still treated as
confirmed, so a job could be admitted with slot ownership that no successor
master can rely on (review Issue 1).

The compensation of a failed persistence round also removed every pipeline
record unconditionally, including slots reused from the previous master and
records that had been written and confirmed. Removing a confirmed record does
not revoke a successor's adoption and releasing those slots can free a slot
that is still in use (review Issue 2).

This change:

- makes setOwnedSlotProfiles write and then confirm the mapping by reading it
  back a bounded number of times, and return whether the read-back matched the
  written value; a thrown write still propagates.
- makes persistPreAppliedSlotProfiles report the confirmed pipelines and
  rejects admission when any pipeline is unconfirmed, not only when a put
  throws.
- rewrites the compensation to only revert ownership created by the failed
  round: confirmed records and their slots are kept, retained (failover
  reused) ownership is never removed and is restored as retained-only when
  the round had overwritten it, and the revert is read back so slots are not
  released when a successor could still adopt them.
- keeps the legacy SCHEDULED write best-effort: ResourceUtils logs when the
  read-back is unconfirmed instead of failing the pipeline.

Tests (JobMasterMasterFailoverResourceTest) add deterministic cases for an
unconfirmed read-back, for preserved retained ownership after a failed restore
write, and for a partially failed round that must keep the confirmed record
and its slots; all three fail on the previous head.

Verification:
./mvnw -o -q -pl seatunnel-engine/seatunnel-engine-server spotless:apply
./mvnw -o -pl seatunnel-engine/seatunnel-engine-server -DskipTests \
  -Dspotless.check.skip=true -Dcheckstyle.skip=true compile
./mvnw -o -pl seatunnel-engine/seatunnel-engine-server \
  -Dtest=JobMasterMasterFailoverResourceTest -DfailIfNoTests=false test
./mvnw -o -pl seatunnel-engine/seatunnel-engine-server \
  -Dtest='ResourceUtilsTest,JobMasterTest,StateTransitionCleanupTest,JobMasterMasterFailoverResourceTest' \
  -DfailIfNoTests=false 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.

Thanks for the follow-up! I reread the complete latest head. The bounded read-back confirmation and the protection for retained or confirmed ownership address the previous points. The new conservative retention branch needs one additional same-master retry case before this is safe to merge; I have kept its number separate from the earlier findings.

What problem does this PR solve?

User pain: after an active-master switch, Workers may still own fixed slots while the replacement master cannot allocate new ones.

Approach: persist and confirm slot ownership before deployment, validate retained slot sequences and owners, and reconcile failed ownership writes.

In one sentence: recover the slots the job already owns without releasing slots a successor might have adopted. Example: a two-pipeline job should resume using its existing allocations rather than wait for capacity it is already occupying.

1. Code changes

1.1 Core logic

Complete runtime path:

Pending job -> CoordinatorService.pendingJobSchedule (seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/CoordinatorService.java:424-489)
 -> JobMaster.preApplyResources (seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:528-644)
 -> collect per-pipeline allocations; persist and read back ownership
 -> partial failure: reconcile confirmed/unconfirmed mappings
 -> keep confirmed pipeline slots; release safe unconfirmed allocations; return false
 -> WAIT scheduler retries the same JobMaster
 -> getReusableSlot (seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:992-1001): only enabled for masterFailoverRestore
 -> fresh-master retry cannot reuse its retained allocations
Successful failover path -> active sequence + job-owner validation -> physical plan receives futures
 -> pipeline deployment; reuse flag resets for later pipeline attempts

Key findings and correctness:

  1. The complete three-file diff was reread at this new head, including the updated failure compensation and every added test.
  2. Previous Issue 1 is closed: a false read-back becomes a retryable exception inside the bounded retry, the boolean result is checked by pre-admission persistence, and ResourceUtils logs the failed confirmation.
  3. Previous Issue 2 is substantially addressed: retained-only records are left intact, confirmed records and slots are conservatively retained, and uncertain compensation keeps allocations rather than releasing potentially adopted slots.
  4. The newly added confirmed-slot retention branch introduces the same-master retry gap described as Issue 3 below. It occurs without a master switch and is not a claim that an old issue was newly introduced.
  5. Normal successful allocation and the first post-failover reuse path remain coherent; the blocking case is a partial ownership-persistence failure during a fresh job admission.

Before (previous head):

ownedSlotProfilesIMap.remove(pipelineLocation);
// failed round then releases its newly acquired allocations

After:

if (confirmedPipelines.contains(pipelineLocation)) {
    unreconciledPipelines.add(pipelineLocation);
    continue; // retain both ownership and allocated slots
}
// preApplyResources returns false; a fresh master still has reuse disabled

1.2 Compatibility

Configuration names, defaults, task protocol and SlotProfile serialization are unchanged. The internal public setOwnedSlotProfiles method changes its return descriptor from void to boolean: in-tree callers are adapted, but any separately compiled caller needs rebuilding; this is not a claim of binary compatibility for external code calling an engine implementation class.

1.3 Performance and side effects

Ownership confirmation adds bounded IMap reads and retry sleeps during admission rather than the row path. Retaining confirmed ownership avoids unsafe release but currently can strand fixed capacity on ordinary WAIT retries (Issue 3). Resource RPC, retry and idempotence behavior were traced; no runtime measurement is claimed.

1.4 Errors, logging, and findings

Issue 3: Retained confirmed slots are unreachable by a fresh master on its next admission attempt

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:751-756.
  • Description and risk: The new confirmedPipelines branch preserves a successfully persisted pipeline and its active slots when a different pipeline fails persistence. preApplyResources then returns false before installing any futures in the physical plan (seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:620-629). Under WAIT, seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/CoordinatorService.java:478-484 retries this same JobMaster. A fresh job initialized with restart=false has masterFailoverRestore=false, so getReusableSlot immediately returns null (seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:992-995) and every task group requests a new free slot. With fixed capacity equal to the job requirement, the first pipeline now occupies capacity that the retry cannot reuse, and the job stays pending after the IMap fault has recovered. With spare capacity, a later successful round can overwrite the retained ownership with newly acquired profiles, leaving the old allocations untracked. This is the new conservative-retention branch, not the previous unconditional-removal complaint.
  • Best improvement: Keep confirmed or uncertain allocations in an attempt-owned retry ledger and reuse them only after owner/sequence validation, or explicitly hand off and retire this master before a replacement adopts them. Add a two-pipeline transient-persistence-failure test that restores IMap writes and retries the same fresh JobMaster with no spare fixed slots. Do not simply release confirmed slots without fencing possible successor adoption.
  • Responsibility and trade-off: JobMaster must own the complete admission-attempt resource lifecycle, including retries after persistence failure; retain the owner and allocation-sequence validation when fixing it.
  • Severity: High; blocking: true.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

Community input: no independent technical finding or maintainer approval/change request was present in the collected discussion.

2. Code quality

2.1 Conventions

Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.

2.2 Test coverage and stability

Stability rating: Stable. The real Worker tests use unique job IDs, sequence/owner checks, and finally-based resource release; no new sleep-based asynchronous assertion was found. The new partial-write test at seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/master/JobMasterMasterFailoverResourceTest.java:240-321 proves that confirmed slots remain active, but stops after the failed preApplyResources call. It must recover the storage fault and retry the same non-failover JobMaster with exact fixed capacity, then assert admission succeeds without additional allocations or lost profiles.

2.3 Documentation

No new user option or documented operational command is introduced. Both language guides can keep their current slot model; the retry behavior must be fixed and proven before describing this as transparent failover recovery.

3. Architecture

3.1 Change location

JobMaster must own the complete admission-attempt resource lifecycle, including retries after persistence failure; retain the owner and allocation-sequence validation when fixing it.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. JobMaster must own the complete admission-attempt resource lifecycle, including retries after persistence failure; retain the owner and allocation-sequence validation when fixing it.

3.3 Extensibility

Prefer the existing component boundary and tests over unrelated shared abstractions.

3.4 Upgrade impact

Configuration names, defaults, task protocol and SlotProfile serialization are unchanged. The internal public setOwnedSlotProfiles method changes its return descriptor from void to boolean: in-tree callers are adapted, but any separately compiled caller needs rebuilding; this is not a claim of binary compatibility for external code calling an engine implementation class.

4. Findings summary

Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.

# Finding Location Severity
3 Retained confirmed slots are unreachable by a fresh master on its next admission attempt seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/master/JobMaster.java:751-756 High

5. Merge recommendation

Merge after fixes

Blocking items: Issue 3. Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: None beyond the validation limits above.

Overall: the approach addresses a real path, but the listed blockers must be closed. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.

CI and repository state: Signal pull request update: SUCCESS; Build: QUEUED; Build: queued. GitHub reports BLOCKED / REVIEW_REQUIRED.

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

Review time: 2026-11-27T05:30:40.776839-05:00

Local evidence: git fetch obtained head 77d96034ea993d1a176aa9df333359676db6f58f; git merge-base returned ee0fb0d72f67edbcd6caf08360fd354fa68e002f; git diff --stat reports 3 files changed, 672 insertions(+), 78 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants