Files
seaweedfs/weed/admin/plugin/orphaned_execution.go
Chris LuandClaude Opus 5.5 374c77bcbe admin/plugin: fail a restored job its worker no longer lists (#12815)
* admin/plugin: fail a restored job its worker no longer lists

An admin restart reloads the jobs that were running from the persisted
state, but the workers drop those jobs when the old admin stream closes.
No pending execution covers a restored job, so only the 24h stale sweep
ended it, and until then it blocked dedupe and scheduling of its job type.

Track the active jobs loaded at startup by worker and fail one after two
itemized heartbeats from its worker leave it out, as is already done for
a dispatch whose worker restarted. A listed job is left to adoption.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: keep tracking a listed restored job; skip queued ones

- A restored job its worker lists only resets its miss count, so one it
  drops later is still failed.
- Track only jobs that were sent to a worker (request id set, not pending).
- Match restored ids against the trimmed heartbeat ids.
- Fail the restored attempt under the jobs lock that applies the expiry
  (handleJobCompletedIf / expireActiveJobIf), so a newer attempt of the
  same job is neither failed nor canceled.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: keep a newer attempt's detail from a restored-job expiry

- The conditional completion writes the job detail through
  persistJobDetailSnapshotIf and skips it when the stored detail already
  names another request; the check runs under jobDetailsMu with the write.
- mergeTerminalDetailIntoTracked ignores a terminal detail of another
  request, so a restart does not end the loaded attempt with it.
- Tests wait for the restored-job expiries instead of sleeping.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: restore a finished retry from its detail

The job detail is saved as each attempt changes and the job list only
periodically, so a terminal detail naming another request is the newer
attempt. Apply it with its request id instead of ignoring it; the
expiry's own detail write already refuses to overwrite another request.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: restore whichever attempt is newer

The job list and a job's detail can name different attempts either way
round: the list is saved periodically, and a detail write can fail. When
their request ids differ, apply the terminal detail only if it is the
newer attempt (higher attempt number, else later update).

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: fill a restored job's empty request id from its detail

A job the list saved while still queued has no request id; take the
finished detail's, as the merge did before the newer-attempt check.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: take the worker and attempt of a newer restored detail

When the restore takes a finished retry's detail over the job list's
attempt, the record kept the older attempt's worker and attempt number
next to the retry's request id and state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin/plugin: fold the conditional completion into the existing functions

handleJobCompleted, expireActiveJob, trackExecutionCompletion and
persistJobDetailSnapshot take the accept check themselves instead of
gaining *If twins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin/plugin: ignore a late earlier-attempt completion; replace an older detail

- A completion whose request id differs from the tracked attempt's is a
  late report of an earlier attempt and no longer ends a retry.
- A conditional completion skips the detail write only when the stored
  detail is a newer attempt (detailIsNewerAttempt), so an older finished
  attempt's detail left behind by a failed write is replaced.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: take only the dispatched attempt's reports

A late progress report of a timed-out attempt replaced the retry's request
id, after which the retry's own completion was rejected as foreign. One
rule now gates both: a record the admin dispatched (attempt > 0) takes
progress and completion only for its own request (reportFromOtherAttempt).

When an expiry replaces an older attempt's detail it also takes the
closing attempt's worker, attempt number and times.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: restore a newer running attempt's identity from its detail

The job list can name attempt A while the detail shows retry B running
when the admin stopped. The restore now takes B's request id, worker and
attempt number from such a newer running detail, so B's own reports are
accepted. Test helper keeps a given attempt number.

Claude-Session: https://claude.ai/code/session_011UpvafcfUuC2mLxNAXLQJi

* admin/plugin: keep attemptEnded's doc comment on attemptEnded

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* admin/plugin: dispatch an attempt-less job as attempt 1

The late-report guard only covers records with a positive attempt, and
ExecuteJob passed a zero attempt through, so a direct caller's dispatch
could be closed by another request's completion. The HTTP API already
raised zero to one; the dispatch path now does the same for every caller.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:30:52 -08:00

208 lines
6.8 KiB
Go

package plugin
import (
"fmt"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
)
// orphanedExecutionMisses is how many itemized heartbeats in a row from a
// newer stream of the worker must leave a dispatched job out before the
// admin fails it. The second rides out a heartbeat the worker built while
// it was still picking the job back up.
const orphanedExecutionMisses = 2
// pendingExecutionState is an execution request waiting for its JobCompleted.
type pendingExecutionState struct {
completed chan *plugin_pb.JobCompleted
jobID string
jobType string
// session is the stream the request went out on.
session *streamSession
misses int
failed bool
// completionSent is set once a completion is handed to the dispatcher,
// which may already have taken it from the buffer.
completionSent bool
}
// failExecutionsMissingFromHeartbeat fails the executions sent on an earlier
// stream of the heartbeat's worker that the worker no longer lists. A worker
// that restarted comes back under the same id without the old process's
// jobs, and nothing else ends such a dispatch before its execution timeout,
// so its slot stays reserved all that time. Jobs sent on the heartbeat's own
// stream are left alone, since a worker counts a job before it lists it, and
// so is everything while the heartbeat counts slots it does not itemize,
// since a missing id then proves nothing.
func (r *Plugin) failExecutionsMissingFromHeartbeat(session *streamSession, heartbeat *plugin_pb.WorkerHeartbeat) {
if session == nil || heartbeat == nil {
return
}
itemized := 0
listed := make(map[string]struct{}, len(heartbeat.GetRunningWork()))
for _, work := range heartbeat.GetRunningWork() {
if work.GetKind() == plugin_pb.WorkKind_WORK_KIND_EXECUTION {
listed[strings.TrimSpace(work.GetWorkId())] = struct{}{}
itemized++
}
}
itemizesAll := int(heartbeat.GetExecutionSlotsUsed()) <= itemized
var orphaned []activeJobSnapshot
r.pendingExecutionMu.Lock()
for requestID, pending := range r.pendingExecution {
if pending.failed || pending.session == nil || pending.session == session || pending.session.workerID != session.workerID {
continue
}
if _, ok := listed[strings.TrimSpace(pending.jobID)]; ok {
pending.misses = 0
continue
}
if !itemizesAll {
continue
}
if pending.completionSent {
continue
}
pending.misses++
if pending.misses < orphanedExecutionMisses {
continue
}
pending.failed = true
orphaned = append(orphaned, activeJobSnapshot{
jobID: pending.jobID,
jobType: pending.jobType,
workerID: session.workerID,
requestID: requestID,
})
}
r.pendingExecutionMu.Unlock()
for _, snap := range orphaned {
reason := fmt.Sprintf("worker %s re-registered without job %s", snap.workerID, snap.jobID)
glog.Warningf("Plugin failing %s request %s: %s", snap.jobType, snap.requestID, reason)
// off the stream's receive loop: the cancel may wait on a full buffer
go r.expireActiveJob(snap, reason, time.Now().UTC(), nil)
}
}
// restoredExecutionState is a job a previous admin process had sent to a
// worker. This process never dispatched it, so no pendingExecution entry
// covers it and only the stale sweep would otherwise end it.
type restoredExecutionState struct {
workerID string
requestID string
misses int
}
// trackRestoredExecution remembers an active job loaded at startup that was
// already sent to its worker, so the worker's heartbeats can confirm or
// disown it. A job still queued has a worker bound but no request yet, and
// no worker would list it.
func (r *Plugin) trackRestoredExecution(job *TrackedJob) {
if job == nil || !isActiveTrackedJobState(job.State) || isQueuedTrackedJobState(job.State) {
return
}
workerID := strings.TrimSpace(job.WorkerID)
if workerID == "" || strings.TrimSpace(job.RequestID) == "" {
return
}
r.restoredExecutionsMu.Lock()
r.restoredExecutions[job.JobID] = &restoredExecutionState{workerID: workerID, requestID: job.RequestID}
r.restoredExecutionsMu.Unlock()
}
func isQueuedTrackedJobState(state string) bool {
switch strings.ToLower(strings.TrimSpace(state)) {
case "pending", "job_state_pending":
return true
}
return false
}
// failRestoredJobsMissingFromHeartbeat fails the restored jobs of the
// heartbeat's worker that it leaves out of two itemized heartbeats in a row.
// A worker drops the jobs of an admin stream that closed, and a job it kept
// can no longer report its completion, so after an admin restart such a
// record would block dedupe and scheduling of its job type until the stale
// timeout. A listed job only resets its count: it can still be dropped
// later. The tracker goes once the job is failed here or found no longer to
// be the restored attempt.
func (r *Plugin) failRestoredJobsMissingFromHeartbeat(workerID string, heartbeat *plugin_pb.WorkerHeartbeat) {
if heartbeat == nil {
return
}
itemized := 0
listed := make(map[string]struct{}, len(heartbeat.GetRunningWork()))
for _, work := range heartbeat.GetRunningWork() {
if work.GetKind() == plugin_pb.WorkKind_WORK_KIND_EXECUTION {
listed[strings.TrimSpace(work.GetWorkId())] = struct{}{}
itemized++
}
}
itemizesAll := int(heartbeat.GetExecutionSlotsUsed()) <= itemized
type candidate struct {
jobID string
requestID string
}
var missing []candidate
r.restoredExecutionsMu.Lock()
for jobID, restored := range r.restoredExecutions {
if restored.workerID != workerID {
continue
}
if _, ok := listed[strings.TrimSpace(jobID)]; ok {
restored.misses = 0
continue
}
if !itemizesAll {
continue
}
restored.misses++
if restored.misses < orphanedExecutionMisses {
continue
}
delete(r.restoredExecutions, jobID)
missing = append(missing, candidate{jobID: jobID, requestID: restored.requestID})
}
r.restoredExecutionsMu.Unlock()
now := time.Now().UTC()
for _, c := range missing {
isRestoredAttempt := func(job *TrackedJob) bool {
return job != nil && isActiveTrackedJobState(job.State) &&
job.RequestID == c.requestID && strings.TrimSpace(job.WorkerID) == workerID
}
r.jobsMu.RLock()
job := r.jobs[c.jobID]
var snap activeJobSnapshot
current := isRestoredAttempt(job)
if current {
snap = activeJobSnapshot{
jobID: job.JobID,
jobType: job.JobType,
workerID: job.WorkerID,
requestID: job.RequestID,
lastUpdate: jobLastUpdated(job),
}
}
r.jobsMu.RUnlock()
if !current {
continue
}
reason := fmt.Sprintf("worker %s no longer runs job %s after the admin restarted", workerID, c.jobID)
glog.Warningf("Plugin failing restored %s job: %s", snap.jobType, reason)
// the record may change before the expiry takes the lock, so the
// expiry judges it again there
r.restoredExpiries.Add(1)
go func() {
defer r.restoredExpiries.Done()
r.expireActiveJob(snap, reason, now, isRestoredAttempt)
}()
}
}