From 374c77bcbe504da77f02cc7b07a98a172d9cc309 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Thu, 19 Nov 2026 22:30:52 -0800 Subject: [PATCH] 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 * 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 * 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 * 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 --------- Co-authored-by: Claude Opus 5.5 --- weed/admin/plugin/orphaned_execution.go | 119 ++++- weed/admin/plugin/orphaned_execution_test.go | 470 +++++++++++++++++++ weed/admin/plugin/plugin.go | 33 +- weed/admin/plugin/plugin_cancel_test.go | 6 +- weed/admin/plugin/plugin_monitor.go | 132 +++++- weed/admin/plugin/plugin_monitor_test.go | 20 +- weed/admin/plugin/plugin_scheduler_test.go | 6 +- 7 files changed, 741 insertions(+), 45 deletions(-) diff --git a/weed/admin/plugin/orphaned_execution.go b/weed/admin/plugin/orphaned_execution.go index 04b01dba98..d7797a2759 100644 --- a/weed/admin/plugin/orphaned_execution.go +++ b/weed/admin/plugin/orphaned_execution.go @@ -85,6 +85,123 @@ func (r *Plugin) failExecutionsMissingFromHeartbeat(session *streamSession, hear 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()) + 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) + }() } } diff --git a/weed/admin/plugin/orphaned_execution_test.go b/weed/admin/plugin/orphaned_execution_test.go index 0098472191..afeed73af9 100644 --- a/weed/admin/plugin/orphaned_execution_test.go +++ b/weed/admin/plugin/orphaned_execution_test.go @@ -11,6 +11,8 @@ import ( const orphanTestJobType = "ec_vacuum" +var restoredTestStateRunning = strings.ToLower(plugin_pb.JobState_JOB_STATE_RUNNING.String()) + type orphanTestResult struct { completed *plugin_pb.JobCompleted err error @@ -387,3 +389,471 @@ func TestExecutionNotOrphanedAfterDispatcherTookCompletion(t *testing.T) { t.Fatal("attempt whose completion was already delivered was failed as orphaned") } } + +// newPluginWithRestoredJob starts an admin whose persisted state holds the +// job a previous admin process had sent to worker-a. +func newPluginWithRestoredJob(t *testing.T, job TrackedJob, details ...TrackedJob) *Plugin { + t.Helper() + dataDir := t.TempDir() + store, err := NewConfigStore(dataDir) + if err != nil { + t.Fatalf("NewConfigStore: %v", err) + } + now := time.Now().UTC() + job.JobType = orphanTestJobType + job.WorkerID = "worker-a" + if job.State == "" { + job.State = restoredTestStateRunning + } + if job.RequestID == "" && job.State == restoredTestStateRunning { + job.RequestID = "exec-before-restart" + } + if job.Attempt == 0 { + job.Attempt = 1 + } + job.CreatedAt = timeToPtr(now.Add(-time.Hour)) + job.UpdatedAt = timeToPtr(now.Add(-time.Minute)) + if err := store.SaveTrackedJobs([]TrackedJob{job}); err != nil { + t.Fatalf("SaveTrackedJobs: %v", err) + } + for _, detail := range details { + if err := store.SaveJobDetail(detail); err != nil { + t.Fatalf("SaveJobDetail: %v", err) + } + } + p, err := New(Options{DataDir: dataDir}) + if err != nil { + t.Fatalf("New: %v", err) + } + t.Cleanup(p.Shutdown) + return p +} + +func waitTrackedState(t *testing.T, p *Plugin, jobID, want string) *TrackedJob { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + tracked, ok := p.GetTrackedJob(jobID) + if ok && tracked != nil && tracked.State == want { + return tracked + } + if time.Now().After(deadline) { + t.Fatalf("job %s: want state %s, got %+v", jobID, want, tracked) + } + time.Sleep(10 * time.Millisecond) + } +} + +// expectTrackedStateHolds checks the state once every restored-job expiry +// the heartbeats started has finished. +func expectTrackedStateHolds(t *testing.T, p *Plugin, jobID, want string) { + t.Helper() + p.restoredExpiries.Wait() + if tracked, _ := p.GetTrackedJob(jobID); tracked == nil || tracked.State != want { + t.Fatalf("job %s: want state %s, got %+v", jobID, want, tracked) + } +} + +// The admin restarted while worker-a ran the job, and the worker dropped it +// with the closed stream. Its heartbeats to the new admin do not list it, so +// the restored record is failed instead of blocking its job type for a day. +func TestRestoredJobFailsWhenWorkerDoesNotList(t *testing.T) { + t.Parallel() + const jobID = "job-from-previous-admin" + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID}) + session := connectExecutor(p, "worker-a") + + sendExecutionHeartbeat(p, session, 0) + expectTrackedStateHolds(t, p, jobID, restoredTestStateRunning) + sendExecutionHeartbeat(p, session, 0) + + tracked := waitTrackedState(t, p, jobID, StateFailed) + if want := "worker worker-a no longer runs job " + jobID; !strings.Contains(tracked.ErrorMessage, want) { + t.Fatalf("error %q does not say %q", tracked.ErrorMessage, want) + } +} + +// A worker that keeps listing the job keeps its restored record running. +func TestRestoredJobKeptWhileWorkerLists(t *testing.T) { + t.Parallel() + const jobID = "job-survived-admin-restart" + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID}) + session := connectExecutor(p, "worker-a") + + for i := 0; i < orphanedExecutionMisses+1; i++ { + sendExecutionHeartbeat(p, session, 1, jobID) + } + expectTrackedStateHolds(t, p, jobID, restoredTestStateRunning) +} + +// A job the worker listed at first and then dropped is still failed: being +// listed once does not end the tracking. +func TestRestoredJobFailsWhenWorkerStopsListing(t *testing.T) { + t.Parallel() + const jobID = "job-dropped-after-reconnect" + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID}) + session := connectExecutor(p, "worker-a") + + sendExecutionHeartbeat(p, session, 1, jobID) + sendExecutionHeartbeat(p, session, 0) + expectTrackedStateHolds(t, p, jobID, restoredTestStateRunning) + sendExecutionHeartbeat(p, session, 0) + waitTrackedState(t, p, jobID, StateFailed) +} + +// Heartbeat ids are trimmed, so a padded job id still matches its listing. +func TestRestoredJobWithPaddedIDKeptWhileListed(t *testing.T) { + t.Parallel() + const jobID = " job-padded " + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID}) + session := connectExecutor(p, "worker-a") + + for i := 0; i < orphanedExecutionMisses+1; i++ { + sendExecutionHeartbeat(p, session, 1, jobID) + } + expectTrackedStateHolds(t, p, jobID, restoredTestStateRunning) +} + +// A job the old admin had only queued names a worker but was never sent to +// it; no heartbeat would list it, and it never ran, so it is not failed as +// a lost execution. +func TestRestoredQueuedJobNotFailed(t *testing.T) { + t.Parallel() + const jobID = "job-queued-before-restart" + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID, State: "job_state_pending"}) + session := connectExecutor(p, "worker-a") + + for i := 0; i < orphanedExecutionMisses+1; i++ { + sendExecutionHeartbeat(p, session, 0) + } + expectTrackedStateHolds(t, p, jobID, "job_state_pending") +} + +// Another worker's heartbeats say nothing about the job. +func TestRestoredJobIgnoresOtherWorkers(t *testing.T) { + t.Parallel() + const jobID = "job-on-worker-a" + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID}) + other := connectExecutor(p, "worker-b") + + for i := 0; i < orphanedExecutionMisses+1; i++ { + sendExecutionHeartbeat(p, other, 0) + } + expectTrackedStateHolds(t, p, jobID, restoredTestStateRunning) +} + +// The expiry judges the record under the lock that fails it: once the job +// runs as a newer attempt, the restored attempt's expiry leaves it alone and +// sends no cancel. +func TestRestoredExpiryLeavesNewerAttempt(t *testing.T) { + t.Parallel() + const jobID = "job-dispatched-again" + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID}) + session := connectExecutor(p, "worker-a") + + p.jobsMu.Lock() + p.jobs[jobID].RequestID = "exec-after-restart" + p.jobsMu.Unlock() + + isRestoredAttempt := func(job *TrackedJob) bool { + return job != nil && job.RequestID == "exec-before-restart" + } + p.expireActiveJob(activeJobSnapshot{jobID: jobID, jobType: orphanTestJobType, workerID: "worker-a", requestID: "exec-before-restart"}, + "stale", time.Now().UTC(), isRestoredAttempt) + + expectTrackedStateHolds(t, p, jobID, restoredTestStateRunning) + select { + case msg := <-session.outgoing: + t.Fatalf("expected no cancel, got %+v", msg) + default: + } +} + +// The expiry leaves the stored detail alone once a newer dispatch wrote it, +// so a restart does not load the newer attempt as failed. +func TestRestoredExpiryKeepsNewerAttemptDetail(t *testing.T) { + t.Parallel() + const jobID = "job-detail-moved-on" + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID}) + p.persistJobDetailSnapshot(jobID, func(detail *TrackedJob) bool { + detail.RequestID = "exec-after-restart" + detail.State = restoredTestStateRunning + detail.Attempt = 2 + detail.UpdatedAt = timeToPtr(time.Now().UTC()) + return true + }) + + p.expireActiveJob(activeJobSnapshot{jobID: jobID, jobType: orphanTestJobType, workerID: "worker-a", requestID: "exec-before-restart"}, + "stale", time.Now().UTC(), func(*TrackedJob) bool { return true }) + + detail, err := p.store.LoadJobDetail(jobID) + if err != nil || detail == nil { + t.Fatalf("LoadJobDetail: %+v %v", detail, err) + } + if detail.RequestID != "exec-after-restart" || detail.State != restoredTestStateRunning { + t.Fatalf("newer attempt's detail was overwritten: request=%s state=%s", detail.RequestID, detail.State) + } +} + +// A retry that finished after the job list was last saved is restored from +// its detail, request id included, rather than as the running attempt the +// job list still names. +func TestRestoreTakesFinishedRetryFromDetail(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + trackedAttempt, detailAttempt int32 + }{ + {name: "by attempt", trackedAttempt: 1, detailAttempt: 2}, + {name: "by time"}, + } { + t.Run(tc.name, func(t *testing.T) { + dataDir := t.TempDir() + store, err := NewConfigStore(dataDir) + if err != nil { + t.Fatalf("NewConfigStore: %v", err) + } + now := time.Now().UTC() + const jobID = "job-retried" + if err := store.SaveTrackedJobs([]TrackedJob{{JobID: jobID, JobType: orphanTestJobType, RequestID: "exec-a", WorkerID: "worker-a", State: restoredTestStateRunning, Attempt: tc.trackedAttempt, + CreatedAt: timeToPtr(now.Add(-time.Hour)), UpdatedAt: timeToPtr(now.Add(-time.Minute))}}); err != nil { + t.Fatalf("SaveTrackedJobs: %v", err) + } + if err := store.SaveJobDetail(TrackedJob{JobID: jobID, JobType: orphanTestJobType, RequestID: "exec-b", WorkerID: "worker-b", State: StateSucceeded, Attempt: tc.detailAttempt, + UpdatedAt: timeToPtr(now), CompletedAt: timeToPtr(now)}); err != nil { + t.Fatalf("SaveJobDetail: %v", err) + } + p, err := New(Options{DataDir: dataDir}) + if err != nil { + t.Fatalf("New: %v", err) + } + defer p.Shutdown() + tracked, _ := p.GetTrackedJob(jobID) + if tracked == nil || tracked.State != StateSucceeded || tracked.RequestID != "exec-b" || + tracked.WorkerID != "worker-b" || tracked.Attempt != tc.detailAttempt { + t.Fatalf("want exec-b on worker-b attempt %d succeeded, got %+v", tc.detailAttempt, tracked) + } + }) + } +} + +// A detail still holding an older finished attempt, after the newer retry's +// detail write failed, does not hide the retry the job list names. +func TestRestoreKeepsNewerRetryOverOlderDetail(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + trackedAttempt, detailAttempt int32 + }{ + {name: "by attempt", trackedAttempt: 2, detailAttempt: 1}, + {name: "by time"}, + } { + t.Run(tc.name, func(t *testing.T) { + dataDir := t.TempDir() + store, err := NewConfigStore(dataDir) + if err != nil { + t.Fatalf("NewConfigStore: %v", err) + } + now := time.Now().UTC() + const jobID = "job-retry-running" + if err := store.SaveTrackedJobs([]TrackedJob{{JobID: jobID, JobType: orphanTestJobType, RequestID: "exec-b", State: restoredTestStateRunning, Attempt: tc.trackedAttempt, + CreatedAt: timeToPtr(now.Add(-time.Hour)), UpdatedAt: timeToPtr(now)}}); err != nil { + t.Fatalf("SaveTrackedJobs: %v", err) + } + if err := store.SaveJobDetail(TrackedJob{JobID: jobID, JobType: orphanTestJobType, RequestID: "exec-a", State: StateFailed, Attempt: tc.detailAttempt, + UpdatedAt: timeToPtr(now.Add(-time.Minute)), CompletedAt: timeToPtr(now.Add(-time.Minute))}); err != nil { + t.Fatalf("SaveJobDetail: %v", err) + } + p, err := New(Options{DataDir: dataDir}) + if err != nil { + t.Fatalf("New: %v", err) + } + defer p.Shutdown() + tracked, _ := p.GetTrackedJob(jobID) + if tracked == nil || tracked.State != restoredTestStateRunning || tracked.RequestID != "exec-b" { + t.Fatalf("want exec-b running, got %+v", tracked) + } + }) + } +} + +// A job the list saved while still queued takes its request id from the +// finished detail, so the ended attempt stays recognizable. +func TestRestoreFillsRequestIDOfQueuedJobFromDetail(t *testing.T) { + t.Parallel() + dataDir := t.TempDir() + store, err := NewConfigStore(dataDir) + if err != nil { + t.Fatalf("NewConfigStore: %v", err) + } + now := time.Now().UTC() + const jobID = "job-queued-then-done" + if err := store.SaveTrackedJobs([]TrackedJob{{JobID: jobID, JobType: orphanTestJobType, State: "job_state_pending", + CreatedAt: timeToPtr(now.Add(-time.Hour)), UpdatedAt: timeToPtr(now.Add(-time.Minute))}}); err != nil { + t.Fatalf("SaveTrackedJobs: %v", err) + } + if err := store.SaveJobDetail(TrackedJob{JobID: jobID, JobType: orphanTestJobType, RequestID: "exec-a", State: StateSucceeded, + UpdatedAt: timeToPtr(now), CompletedAt: timeToPtr(now)}); err != nil { + t.Fatalf("SaveJobDetail: %v", err) + } + p, err := New(Options{DataDir: dataDir}) + if err != nil { + t.Fatalf("New: %v", err) + } + defer p.Shutdown() + tracked, _ := p.GetTrackedJob(jobID) + if tracked == nil || tracked.State != StateSucceeded || tracked.RequestID != "exec-a" { + t.Fatalf("want exec-a succeeded, got %+v", tracked) + } +} + +// The restored attempt's detail write failed before the restart, so the +// detail still holds an older finished attempt. Failing the restored +// attempt replaces that detail, or the next restart would load it running. +func TestRestoredExpiryReplacesOlderAttemptDetail(t *testing.T) { + t.Parallel() + const jobID = "job-detail-behind" + older := time.Now().UTC().Add(-2 * time.Hour) + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID}, TrackedJob{JobID: jobID, JobType: orphanTestJobType, + RequestID: "exec-older", State: StateFailed, UpdatedAt: timeToPtr(older), CompletedAt: timeToPtr(older)}) + session := connectExecutor(p, "worker-a") + + sendExecutionHeartbeat(p, session, 0) + sendExecutionHeartbeat(p, session, 0) + waitTrackedState(t, p, jobID, StateFailed) + p.restoredExpiries.Wait() + + detail, err := p.store.LoadJobDetail(jobID) + if err != nil || detail == nil { + t.Fatalf("LoadJobDetail: %+v %v", detail, err) + } + if detail.RequestID != "exec-before-restart" || detail.State != StateFailed { + t.Fatalf("want exec-before-restart failed in the detail, got request=%s state=%s", detail.RequestID, detail.State) + } + if detail.WorkerID != "worker-a" || detail.Attempt != 1 || detail.CompletedAt == nil || !detail.CompletedAt.After(older) { + t.Fatalf("detail kept the older attempt's fields: worker=%s attempt=%d completed=%v", detail.WorkerID, detail.Attempt, detail.CompletedAt) + } +} + +// A completion that arrives for an earlier attempt after a retry started +// leaves the retry's record alone. +func TestLateCompletionOfEarlierAttemptKeepsRetry(t *testing.T) { + t.Parallel() + const jobID = "job-retry-running" + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID, RequestID: "exec-b"}) + + p.handleJobCompleted(&plugin_pb.JobCompleted{JobId: jobID, JobType: orphanTestJobType, RequestId: "exec-a", Success: false, ErrorMessage: "late"}, nil) + + tracked, _ := p.GetTrackedJob(jobID) + if tracked == nil || tracked.State != restoredTestStateRunning || tracked.RequestID != "exec-b" { + t.Fatalf("want exec-b running, got %+v", tracked) + } +} + +// A late progress report of an earlier attempt neither takes over the +// retry's request id nor makes the retry's own completion look foreign. +func TestLateProgressOfEarlierAttemptKeepsRetry(t *testing.T) { + t.Parallel() + const jobID = "job-retry-late-progress" + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID, RequestID: "exec-b"}) + + p.handleJobProgressUpdate("worker-a", &plugin_pb.JobProgressUpdate{JobId: jobID, JobType: orphanTestJobType, RequestId: "exec-a", + State: plugin_pb.JobState_JOB_STATE_RUNNING, ProgressPercent: 10}) + if tracked, _ := p.GetTrackedJob(jobID); tracked == nil || tracked.RequestID != "exec-b" { + t.Fatalf("late progress took over the record: %+v", tracked) + } + + p.handleJobCompleted(&plugin_pb.JobCompleted{JobId: jobID, JobType: orphanTestJobType, RequestId: "exec-b", Success: true}, nil) + if tracked, _ := p.GetTrackedJob(jobID); tracked == nil || tracked.State != StateSucceeded || tracked.RequestID != "exec-b" { + t.Fatalf("want exec-b succeeded, got %+v", tracked) + } +} + +// Replacing an older attempt's detail writes the restored attempt's +// identity: its request, attempt number and worker, not the older ones. +func TestRestoredExpiryReplacesOlderAttemptIdentity(t *testing.T) { + t.Parallel() + const jobID = "job-detail-older-attempt" + older := time.Now().UTC().Add(-2 * time.Hour) + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID, RequestID: "exec-b", Attempt: 2}, TrackedJob{JobID: jobID, JobType: orphanTestJobType, + RequestID: "exec-a", WorkerID: "worker-old", Attempt: 1, State: StateFailed, UpdatedAt: timeToPtr(older), CompletedAt: timeToPtr(older)}) + session := connectExecutor(p, "worker-a") + + sendExecutionHeartbeat(p, session, 0) + sendExecutionHeartbeat(p, session, 0) + waitTrackedState(t, p, jobID, StateFailed) + p.restoredExpiries.Wait() + + detail, err := p.store.LoadJobDetail(jobID) + if err != nil || detail == nil { + t.Fatalf("LoadJobDetail: %+v %v", detail, err) + } + if detail.RequestID != "exec-b" || detail.Attempt != 2 || detail.WorkerID != "worker-a" || detail.State != StateFailed { + t.Fatalf("want exec-b/2 on worker-a failed, got request=%s attempt=%d worker=%s state=%s", + detail.RequestID, detail.Attempt, detail.WorkerID, detail.State) + } +} + +// The job list names attempt A, but the detail shows retry B was running +// when the admin stopped. The record takes B's identity, so B's completion +// is accepted rather than dropped as another attempt's. +func TestRestoreTakesNewerRunningAttemptFromDetail(t *testing.T) { + t.Parallel() + const jobID = "job-retry-running-at-restart" + p := newPluginWithRestoredJob(t, TrackedJob{JobID: jobID, RequestID: "exec-a"}, TrackedJob{JobID: jobID, JobType: orphanTestJobType, + RequestID: "exec-b", WorkerID: "worker-a", Attempt: 2, State: restoredTestStateRunning, UpdatedAt: timeToPtr(time.Now().UTC())}) + + tracked, _ := p.GetTrackedJob(jobID) + if tracked == nil || tracked.RequestID != "exec-b" || tracked.Attempt != 2 || tracked.State != restoredTestStateRunning { + t.Fatalf("want exec-b/2 running, got %+v", tracked) + } + p.handleJobCompleted(&plugin_pb.JobCompleted{JobId: jobID, JobType: orphanTestJobType, RequestId: "exec-b", Success: true}, nil) + if tracked, _ := p.GetTrackedJob(jobID); tracked == nil || tracked.State != StateSucceeded { + t.Fatalf("want exec-b succeeded, got %+v", tracked) + } +} + +// A dispatch without an attempt number is still the admin's own attempt, so a +// late completion of another request for the job does not close it. +func TestDispatchWithoutAttemptKeepsOwnRequest(t *testing.T) { + t.Parallel() + p, err := New(Options{}) + if err != nil { + t.Fatalf("New: %v", err) + } + defer p.Shutdown() + + session := connectExecutor(p, "worker-a") + executor, ok := p.registry.Get(session.workerID) + if !ok { + t.Fatal("worker-a is not registered") + } + const jobID = "job-attempt-zero" + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + p.executeJobWithExecutor(ctx, executor, &plugin_pb.JobSpec{JobId: jobID, JobType: orphanTestJobType}, &plugin_pb.ClusterContext{}, 0) + }() + defer func() { + cancel() + <-done + }() + + var requestID string + select { + case msg := <-session.outgoing: + if got := msg.GetExecuteJobRequest().GetAttempt(); got != 1 { + t.Fatalf("want attempt 1 sent to the worker, got %d", got) + } + requestID = msg.RequestId + case <-time.After(2 * time.Second): + t.Fatal("no execute request") + } + + p.handleJobCompleted(&plugin_pb.JobCompleted{JobId: jobID, JobType: orphanTestJobType, RequestId: "exec-earlier", Success: false, ErrorMessage: "late"}, nil) + tracked, _ := p.GetTrackedJob(jobID) + if tracked == nil || tracked.RequestID != requestID || !isActiveTrackedJobState(tracked.State) { + t.Fatalf("want %s still active, got %+v", requestID, tracked) + } +} diff --git a/weed/admin/plugin/plugin.go b/weed/admin/plugin/plugin.go index b25eced67d..ef11b0817b 100644 --- a/weed/admin/plugin/plugin.go +++ b/weed/admin/plugin/plugin.go @@ -107,6 +107,12 @@ type Plugin struct { pendingExecutionMu sync.Mutex pendingExecution map[string]*pendingExecutionState + // restoredExecutions are the active jobs loaded from the persisted + // state at startup, keyed by job id; see failRestoredJobsMissingFromHeartbeat. + restoredExecutionsMu sync.Mutex + restoredExecutions map[string]*restoredExecutionState + // restoredExpiries counts the restored-job expiries still running. + restoredExpiries sync.WaitGroup pendingPreviewMu sync.Mutex pendingPreview map[string]chan *plugin_pb.ObjectPreviewResponse @@ -217,6 +223,7 @@ func New(options Options) (*Plugin, error) { pendingSchema: make(map[string]chan *plugin_pb.ConfigSchemaResponse), pendingDetection: make(map[string]*pendingDetectionState), pendingExecution: make(map[string]*pendingExecutionState), + restoredExecutions: make(map[string]*restoredExecutionState), pendingPreview: make(map[string]chan *plugin_pb.ObjectPreviewResponse), observations: NewObservationStore(), nextDetectionAt: make(map[string]time.Time), @@ -788,6 +795,10 @@ func (r *Plugin) executeJobWithExecutor( if strings.TrimSpace(job.JobType) == "" { return nil, fmt.Errorf("job_type is required") } + // a dispatched record takes only its own request's reports once its attempt is set + if attempt < 1 { + attempt = 1 + } if strings.TrimSpace(job.JobId) == "" { var err error @@ -871,7 +882,7 @@ func (r *Plugin) executeJobWithExecutor( RequestId: requestID, ErrorMessage: err.Error(), CompletedAt: timestamppb.Now(), - }) + }, nil) } return nil, err } @@ -1187,6 +1198,7 @@ func (r *Plugin) handleWorkerMessage(session *streamSession, message *plugin_pb. } r.resendUndeliveredCancels(workerID, body.Heartbeat) r.failExecutionsMissingFromHeartbeat(session, body.Heartbeat) + r.failRestoredJobsMissingFromHeartbeat(workerID, body.Heartbeat) case *plugin_pb.WorkerToAdminMessage_ConfigSchemaResponse: r.handleConfigSchemaResponse(body.ConfigSchemaResponse) case *plugin_pb.WorkerToAdminMessage_DetectionProposals: @@ -1196,7 +1208,7 @@ func (r *Plugin) handleWorkerMessage(session *streamSession, message *plugin_pb. case *plugin_pb.WorkerToAdminMessage_JobProgressUpdate: r.handleJobProgressUpdate(workerID, body.JobProgressUpdate) case *plugin_pb.WorkerToAdminMessage_JobCompleted: - r.handleJobCompleted(body.JobCompleted) + r.handleJobCompleted(body.JobCompleted, nil) case *plugin_pb.WorkerToAdminMessage_Observations: r.observations.Record(workerID, body.Observations) case *plugin_pb.WorkerToAdminMessage_ObjectPreviewResponse: @@ -1471,22 +1483,28 @@ func (r *Plugin) safeSendDetectionComplete(requestID string, message *plugin_pb. } } -func (r *Plugin) handleJobCompleted(completed *plugin_pb.JobCompleted) { +// handleJobCompleted records the completion only when accept, judged under +// the jobs lock that applies it, takes the tracked record (nil when the job +// is untracked). A nil accept takes every completion. +func (r *Plugin) handleJobCompleted(completed *plugin_pb.JobCompleted, accept func(*TrackedJob) bool) bool { if completed == nil || completed.JobType == "" { - return + return false } - if completed.RequestId != "" { + if completed.RequestId != "" && accept == nil { r.safeSendJobCompleted(completed.RequestId, completed) } r.jobsMu.RLock() ended := attemptEnded(r.jobs[completed.JobId], completed.RequestId) r.jobsMu.RUnlock() if ended { - return + return false } - tracked := r.trackExecutionCompletion(completed) + tracked, accepted := r.trackExecutionCompletion(completed, accept) + if !accepted { + return false + } workerID := "" if tracked != nil && tracked.WorkerID != "" { workerID = tracked.WorkerID @@ -1528,6 +1546,7 @@ func (r *Plugin) handleJobCompleted(completed *plugin_pb.JobCompleted) { if err := r.store.AppendRunRecord(completed.JobType, record); err != nil { glog.Warningf("Plugin failed to append run record for %s: %v", completed.JobType, err) } + return true } func (r *Plugin) safeSendJobCompleted(requestID string, completed *plugin_pb.JobCompleted) { diff --git a/weed/admin/plugin/plugin_cancel_test.go b/weed/admin/plugin/plugin_cancel_test.go index ef129ea081..cfaf9be4d1 100644 --- a/weed/admin/plugin/plugin_cancel_test.go +++ b/weed/admin/plugin/plugin_cancel_test.go @@ -172,7 +172,7 @@ func TestAdminScriptExecutionBlocksOtherDetection(t *testing.T) { JobType: "admin_script", Success: true, CompletedAt: timestamppb.Now(), - }) + }, nil) if runErr := <-adminErrCh; runErr != nil { t.Fatalf("admin_script ExecuteJob error: %v", runErr) } @@ -254,7 +254,7 @@ func TestAdminScriptExecutionBlocksOtherExecution(t *testing.T) { JobType: "admin_script", Success: true, CompletedAt: timestamppb.Now(), - }) + }, nil) if runErr := <-adminErrCh; runErr != nil { t.Fatalf("admin_script ExecuteJob error: %v", runErr) } @@ -269,7 +269,7 @@ func TestAdminScriptExecutionBlocksOtherExecution(t *testing.T) { JobType: "vacuum", Success: true, CompletedAt: timestamppb.Now(), - }) + }, nil) if runErr := <-otherErrCh; runErr != nil { t.Fatalf("vacuum ExecuteJob error: %v", runErr) } diff --git a/weed/admin/plugin/plugin_monitor.go b/weed/admin/plugin/plugin_monitor.go index 0e4505a883..54503996d1 100644 --- a/weed/admin/plugin/plugin_monitor.go +++ b/weed/admin/plugin/plugin_monitor.go @@ -92,6 +92,7 @@ func (r *Plugin) loadPersistedMonitorState() error { stripTrackedJobDetailFields(&job) jobCopy := job r.jobs[job.JobID] = &jobCopy + r.trackRestoredExecution(&jobCopy) } r.pruneTrackedJobsLocked() r.jobsMu.Unlock() @@ -196,7 +197,7 @@ func (r *Plugin) ExpireJob(jobID, reason string) (*TrackedJob, bool, error) { jobType: jobType, workerID: workerID, requestID: requestID, - }, reason, now) + }, reason, now, nil) r.appendActivity(JobActivity{ JobID: normalizedJobID, JobType: jobType, @@ -239,7 +240,7 @@ func (r *Plugin) expireStaleJobs(now time.Time) int { continue } - r.expireActiveJob(snap, reason, now) + r.expireActiveJob(snap, reason, now, nil) expired++ } @@ -249,15 +250,19 @@ func (r *Plugin) expireStaleJobs(now time.Time) int { // expireActiveJob fails the tracked job and tells its worker to stop it. // Failing the record alone leaves the worker running the job and its slot // taken, which is what kept a stuck job's slot out of reach for days. -func (r *Plugin) expireActiveJob(snap activeJobSnapshot, reason string, now time.Time) { - r.handleJobCompleted(&plugin_pb.JobCompleted{ +// A non-nil accept limits this to the record it takes (see +// handleJobCompleted); nothing is failed or canceled otherwise. +func (r *Plugin) expireActiveJob(snap activeJobSnapshot, reason string, now time.Time, accept func(*TrackedJob) bool) { + if !r.handleJobCompleted(&plugin_pb.JobCompleted{ JobId: snap.jobID, JobType: snap.jobType, RequestId: snap.requestID, Success: false, ErrorMessage: reason, CompletedAt: timestamppb.New(now), - }) + }, accept) && accept != nil { + return + } // A retry reuses the job id, so the request id is what names this attempt. target := snap.requestID if target == "" { @@ -368,6 +373,14 @@ func (r *Plugin) snapshotActiveJobs() []activeJobSnapshot { return out } +// reportFromOtherAttempt reports whether a progress report or completion for +// requestID belongs to another attempt than the one the admin dispatched +// last, such as a late report of an attempt that timed out before a retry. +// A record the admin did not dispatch (attempt 0) takes any request. +func reportFromOtherAttempt(job *TrackedJob, requestID string) bool { + return job != nil && job.Attempt > 0 && job.RequestID != "" && requestID != "" && job.RequestID != requestID +} + // attemptEnded reports whether the job's record already closed the attempt // requestID names, as an expiry does while the worker is still running it. // That attempt's late reports must not reopen the record or log a second run. @@ -451,13 +464,44 @@ func mergeTerminalDetailIntoTracked(tracked *TrackedJob, detail *TrackedJob) { if tracked == nil || detail == nil { return } - if !isTerminalTrackedJobState(detail.State) { - return - } if !isActiveTrackedJobState(tracked.State) { return } - + if !isTerminalTrackedJobState(detail.State) { + // a newer attempt still running when the admin stopped: the job + // list may name the attempt before it, and only this attempt's + // reports are taken once the record names it + if detail.RequestID != "" && tracked.RequestID != "" && detail.RequestID != tracked.RequestID && + detailIsNewerAttempt(tracked, detail) { + tracked.RequestID = detail.RequestID + if detail.WorkerID != "" { + tracked.WorkerID = detail.WorkerID + } + if detail.Attempt > 0 { + tracked.Attempt = detail.Attempt + } + if detail.UpdatedAt != nil && !detail.UpdatedAt.IsZero() { + tracked.UpdatedAt = detail.UpdatedAt + } + } + return + } + if detail.RequestID != "" && tracked.RequestID != "" && detail.RequestID != tracked.RequestID { + // the two files can name different attempts either way round: the + // job list is saved periodically, and a detail write can fail + if !detailIsNewerAttempt(tracked, detail) { + return + } + } + if detail.RequestID != "" { + tracked.RequestID = detail.RequestID + if detail.WorkerID != "" { + tracked.WorkerID = detail.WorkerID + } + if detail.Attempt > 0 { + tracked.Attempt = detail.Attempt + } + } if detail.State != "" { tracked.State = detail.State } @@ -487,6 +531,19 @@ func mergeTerminalDetailIntoTracked(tracked *TrackedJob, detail *TrackedJob) { } } +// detailIsNewerAttempt reports whether detail describes a later attempt than +// tracked: the higher attempt number, else the later update. +func detailIsNewerAttempt(tracked *TrackedJob, detail *TrackedJob) bool { + if tracked.Attempt > 0 && detail.Attempt > 0 && tracked.Attempt != detail.Attempt { + return detail.Attempt > tracked.Attempt + } + detailAt := jobLastUpdated(detail) + if detail.CompletedAt != nil && detail.CompletedAt.After(detailAt) { + detailAt = *detail.CompletedAt + } + return detailAt.After(jobLastUpdated(tracked)) +} + func (r *Plugin) ListTrackedJobs(jobType string, state string, limit int) []TrackedJob { r.jobsMu.RLock() defer r.jobsMu.RUnlock() @@ -784,7 +841,7 @@ func (r *Plugin) handleJobProgressUpdate(workerID string, update *plugin_pb.JobP if strings.TrimSpace(update.JobId) != "" { r.jobsMu.Lock() job := r.jobs[update.JobId] - if attemptEnded(job, update.RequestId) { + if attemptEnded(job, update.RequestId) || reportFromOtherAttempt(job, update.RequestId) { r.jobsMu.Unlock() return } @@ -874,7 +931,7 @@ func (r *Plugin) trackExecutionStart(requestID, workerID string, job *plugin_pb. r.pruneTrackedJobsLocked() r.dirtyJobs = true r.jobsMu.Unlock() - r.persistJobDetailSnapshot(job.JobId, func(detail *TrackedJob) { + r.persistJobDetailSnapshot(job.JobId, func(detail *TrackedJob) bool { detail.JobID = job.JobId detail.JobType = job.JobType detail.RequestID = requestID @@ -901,6 +958,7 @@ func (r *Plugin) trackExecutionStart(requestID, workerID string, job *plugin_pb. detail.CreatedAt = trackedSnapshot.CreatedAt } detail.UpdatedAt = trackedSnapshot.UpdatedAt + return true }) r.appendActivity(JobActivity{ @@ -947,7 +1005,7 @@ func (r *Plugin) trackExecutionQueued(job *plugin_pb.JobSpec) { r.pruneTrackedJobsLocked() r.dirtyJobs = true r.jobsMu.Unlock() - r.persistJobDetailSnapshot(job.JobId, func(detail *TrackedJob) { + r.persistJobDetailSnapshot(job.JobId, func(detail *TrackedJob) bool { detail.JobID = job.JobId detail.JobType = job.JobType detail.DedupeKey = job.DedupeKey @@ -971,6 +1029,7 @@ func (r *Plugin) trackExecutionQueued(job *plugin_pb.JobSpec) { detail.CreatedAt = trackedSnapshot.CreatedAt } detail.UpdatedAt = trackedSnapshot.UpdatedAt + return true }) r.appendActivity(JobActivity{ @@ -1007,10 +1066,11 @@ func (r *Plugin) bindQueuedJobWorker(job *plugin_pb.JobSpec, workerID string) { r.dirtyJobs = true r.jobsMu.Unlock() - r.persistJobDetailSnapshot(job.JobId, func(detail *TrackedJob) { + r.persistJobDetailSnapshot(job.JobId, func(detail *TrackedJob) bool { detail.WorkerID = snap.WorkerID detail.Message = snap.Message detail.UpdatedAt = snap.UpdatedAt + return true }) } @@ -1060,7 +1120,7 @@ func (r *Plugin) markJobCanceled(job *plugin_pb.JobSpec, reason string) { r.dirtyJobs = true r.jobsMu.Unlock() - r.persistJobDetailSnapshot(job.JobId, func(detail *TrackedJob) { + r.persistJobDetailSnapshot(job.JobId, func(detail *TrackedJob) bool { detail.JobID = job.JobId if job.JobType != "" { detail.JobType = job.JobType @@ -1075,6 +1135,7 @@ func (r *Plugin) markJobCanceled(job *plugin_pb.JobSpec, reason string) { } detail.UpdatedAt = trackedSnapshot.UpdatedAt detail.CompletedAt = trackedSnapshot.CompletedAt + return true }) r.appendActivity(JobActivity{ @@ -1087,9 +1148,9 @@ func (r *Plugin) markJobCanceled(job *plugin_pb.JobSpec, reason string) { }) } -func (r *Plugin) trackExecutionCompletion(completed *plugin_pb.JobCompleted) *TrackedJob { +func (r *Plugin) trackExecutionCompletion(completed *plugin_pb.JobCompleted, accept func(*TrackedJob) bool) (*TrackedJob, bool) { if completed == nil || strings.TrimSpace(completed.JobId) == "" { - return nil + return nil, accept == nil } now := time.Now().UTC() @@ -1099,6 +1160,18 @@ func (r *Plugin) trackExecutionCompletion(completed *plugin_pb.JobCompleted) *Tr r.jobsMu.Lock() tracked := r.jobs[completed.JobId] + if accept != nil && !accept(tracked) { + r.jobsMu.Unlock() + return nil, false + } + if reportFromOtherAttempt(tracked, completed.RequestId) { + r.jobsMu.Unlock() + return nil, false + } + var closing TrackedJob + if tracked != nil { + closing = cloneTrackedJob(*tracked) + } if tracked == nil { tracked = &TrackedJob{ JobID: completed.JobId, @@ -1140,7 +1213,21 @@ func (r *Plugin) trackExecutionCompletion(completed *plugin_pb.JobCompleted) *Tr clone := cloneTrackedJob(*tracked) r.dirtyJobs = true r.jobsMu.Unlock() - r.persistJobDetailSnapshot(completed.JobId, func(detail *TrackedJob) { + r.persistJobDetailSnapshot(completed.JobId, func(detail *TrackedJob) bool { + // a conditional completion closes one attempt: it leaves a detail a + // newer dispatch already wrote, and replaces an older attempt's + otherAttempt := detail.RequestID != "" && completed.RequestId != "" && detail.RequestID != completed.RequestId + if accept != nil && otherAttempt && detailIsNewerAttempt(&closing, detail) { + return false + } + if otherAttempt { + // replacing an older attempt's detail: none of its fields describe this one + detail.WorkerID = clone.WorkerID + detail.Attempt = clone.Attempt + detail.CreatedAt = clone.CreatedAt + detail.UpdatedAt = clone.UpdatedAt + detail.CompletedAt = clone.CompletedAt + } detail.JobID = completed.JobId if completed.JobType != "" { detail.JobType = completed.JobType @@ -1168,6 +1255,7 @@ func (r *Plugin) trackExecutionCompletion(completed *plugin_pb.JobCompleted) *Tr if detail.CompletedAt == nil || detail.CompletedAt.IsZero() { detail.CompletedAt = clone.CompletedAt } + return true }) r.appendActivity(JobActivity{ @@ -1181,7 +1269,7 @@ func (r *Plugin) trackExecutionCompletion(completed *plugin_pb.JobCompleted) *Tr OccurredAt: timeToPtr(now), }) - return &clone + return &clone, true } func (r *Plugin) trackWorkerActivities(jobType, jobID, requestID, workerID string, events []*plugin_pb.ActivityEvent) { @@ -1407,7 +1495,9 @@ func (r *Plugin) persistTrackedJobsSnapshot() { } } -func (r *Plugin) persistJobDetailSnapshot(jobID string, apply func(detail *TrackedJob)) { +// persistJobDetailSnapshot writes the detail only when apply returns true. +// apply runs under jobDetailsMu, so its check holds for the write. +func (r *Plugin) persistJobDetailSnapshot(jobID string, apply func(detail *TrackedJob) bool) { normalizedJobID, _ := sanitizeJobID(jobID) if normalizedJobID == "" { return @@ -1427,8 +1517,8 @@ func (r *Plugin) persistJobDetailSnapshot(jobID string, apply func(detail *Track } } - if apply != nil { - apply(detail) + if apply != nil && !apply(detail) { + return } if err := r.store.SaveJobDetail(*detail); err != nil { diff --git a/weed/admin/plugin/plugin_monitor_test.go b/weed/admin/plugin/plugin_monitor_test.go index 4ef9f04454..34c3417bf8 100644 --- a/weed/admin/plugin/plugin_monitor_test.go +++ b/weed/admin/plugin/plugin_monitor_test.go @@ -88,7 +88,7 @@ func TestPluginPersistsMonitorStateAfterJobUpdates(t *testing.T) { Success: true, Result: &plugin_pb.JobResult{Summary: "done"}, CompletedAt: timestamppb.New(time.Now().UTC()), - }) + }, nil) pluginSvc.Shutdown() store, err := NewConfigStore(dataDir) @@ -317,7 +317,7 @@ func TestHandleJobCompletedCarriesWorkerIDInActivitiesAndRunHistory(t *testing.T }, }, CompletedAt: timestamppb.Now(), - }) + }, nil) pluginSvc.Shutdown() activities := pluginSvc.ListActivities("vacuum", 0) @@ -572,7 +572,7 @@ func TestBuildJobDetailIncludesActivitiesAndRunRecord(t *testing.T) { }, }, CompletedAt: timestamppb.Now(), - }) + }, nil) pluginSvc.Shutdown() detail, found, err := pluginSvc.BuildJobDetail("job-detail", 100, 5) @@ -616,7 +616,7 @@ func TestBuildJobDetailFallsBackToRunRecordAfterPrune(t *testing.T) { Success: false, ErrorMessage: "volume busy", CompletedAt: timestamppb.Now(), - }) + }, nil) // What pruneTrackedJobsLocked does once newer jobs push this one out. pluginSvc.jobsMu.Lock() @@ -654,7 +654,7 @@ func TestBuildJobDetailFallsBackToRunRecordAfterPrune(t *testing.T) { JobType: "vacuum", Success: true, CompletedAt: timestamppb.Now(), - }) + }, nil) pluginSvc.jobsMu.Lock() delete(pluginSvc.jobs, "job-pruned-ok") pluginSvc.jobsMu.Unlock() @@ -780,7 +780,7 @@ func TestBuildJobDetailKeepsFailedJobResult(t *testing.T) { }, }, CompletedAt: timestamppb.Now(), - }) + }, nil) pluginSvc.Shutdown() detail, found, err := pluginSvc.BuildJobDetail("job-failed", 100, 5) @@ -820,7 +820,7 @@ func TestRetryWithoutResultDropsFailedAttemptSummary(t *testing.T) { ErrorMessage: "walk bad-a: filer down", Result: &plugin_pb.JobResult{Summary: "pass failed"}, CompletedAt: timestamppb.Now(), - }) + }, nil) pluginSvc.trackExecutionStart("req-retry", "worker-r", job, 2) pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{ RequestId: "req-retry", @@ -828,7 +828,7 @@ func TestRetryWithoutResultDropsFailedAttemptSummary(t *testing.T) { JobType: "s3_lifecycle", Success: true, CompletedAt: timestamppb.Now(), - }) + }, nil) pluginSvc.Shutdown() detail, found, err := pluginSvc.BuildJobDetail("job-retry", 100, 5) @@ -1175,7 +1175,7 @@ func TestExpiredAttemptIgnoresItsLateReports(t *testing.T) { JobType: jobType, RequestId: "req-late-1", ErrorMessage: "context canceled", - }) + }, nil) got, _ := pluginSvc.GetTrackedJob(jobID) if got == nil || got.State != StateFailed || got.ErrorMessage != "stuck" { @@ -1195,7 +1195,7 @@ func TestExpiredAttemptIgnoresItsLateReports(t *testing.T) { JobType: jobType, RequestId: "req-late-2", Success: true, - }) + }, nil) got, _ = pluginSvc.GetTrackedJob(jobID) if got == nil || got.State != StateSucceeded { t.Fatalf("expected the retry to complete, got %+v", got) diff --git a/weed/admin/plugin/plugin_scheduler_test.go b/weed/admin/plugin/plugin_scheduler_test.go index cd1622c67f..e6352a6e26 100644 --- a/weed/admin/plugin/plugin_scheduler_test.go +++ b/weed/admin/plugin/plugin_scheduler_test.go @@ -873,7 +873,7 @@ func TestDispatchScheduledProposalsDrainsStartedJobOnWindowClose(t *testing.T) { JobType: jobType, Success: true, CompletedAt: timestamppb.Now(), - }) + }, nil) result := <-resultCh if result[0] != 1 || result[1] != 0 || result[2] != 1 { @@ -1343,7 +1343,7 @@ func TestDispatchWaitsForItsOwnLaneToReleaseCapacity(t *testing.T) { } pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{ RequestId: first.RequestId, JobId: execReq.Job.JobId, JobType: "admin_script", Success: true, CompletedAt: timestamppb.Now(), - }) + }, nil) if result := <-resultCh; result != [3]int{1, 0, 0} { t.Fatalf("unexpected dispatch counts: success=%d errors=%d canceled=%d", result[0], result[1], result[2]) } @@ -1445,7 +1445,7 @@ func TestDispatchWaitsForTheEchoOfItsOwnCompletedJob(t *testing.T) { pluginSvc.registry.UpdateHeartbeat(workerID, running) pluginSvc.handleJobCompleted(&plugin_pb.JobCompleted{ RequestId: message.RequestId, JobId: execReq.Job.JobId, JobType: "vacuum", Success: true, CompletedAt: timestamppb.Now(), - }) + }, nil) } complete(<-session.outgoing)