Skip to content

Modern Docker Management, Designed for Everyone

fix: resolve orphaned job run activities on startup (#4572)

Kyle Mendell5f9394e397e3
diff --git a/.github/workflows/pr-quality.yml b/.github/workflows/pr-quality.yml
index 2ee9e584c..1c7b267af 100644
--- a/.github/workflows/pr-quality.yml
+++ b/.github/workflows/pr-quality.yml
@@ -5,9 +5,9 @@ permissions:
issues: read
pull-requests: write
-on:
- pull_request_target:
- types: [opened, reopened]
+# on:
+# pull_request_target:
+# types: [opened, reopened]
jobs:
pr-quality:
diff --git a/backend/internal/activity/children/sweeps/service.go b/backend/internal/activity/children/sweeps/service.go
index 873c7f831..49b1684eb 100644
--- a/backend/internal/activity/children/sweeps/service.go
+++ b/backend/internal/activity/children/sweeps/service.go
@@ -89,6 +89,16 @@ func (s *Service) OrphanedQueued(ctx context.Context, protectedIDs []string) ([]
return rows, err
}
+func (s *Service) OrphanedJobRuns(ctx context.Context, protectedIDs []string) ([]Candidate, error) {
+ var rows []Candidate
+ err := s.activities(ctx).
+ Select("id").
+ Where("type = ? AND status IN ?", activity.TypeJobRun, []activity.Status{activity.StatusQueued, activity.StatusRunning}).
+ Where("id NOT IN ?", append(protectedIDs, "")).
+ Find(&rows).Error
+ return rows, err
+}
+
// StaleAutoUpdates returns running auto-update activities outside protectedIDs.
func (s *Service) StaleAutoUpdates(ctx context.Context, protectedIDs []string) ([]Candidate, error) {
var rows []Candidate
diff --git a/backend/internal/activity/service.go b/backend/internal/activity/service.go
index 78e97ddbb..c9e9b85bd 100644
--- a/backend/internal/activity/service.go
+++ b/backend/internal/activity/service.go
@@ -1209,6 +1209,87 @@ func (s *ActivityService) SyncJobRun(ctx context.Context, run scheduler.Run, nam
return nil
}
+func (s *ActivityService) ResolveOrphanedJobRuns(ctx context.Context, finished map[string]scheduler.Run, protectedIDs ...string) (int64, error) {
+ if err := s.checkInit(); err != nil {
+ return 0, err
+ }
+ candidates, err := s.sweeps.OrphanedJobRuns(ctx, protectedIDs)
+ if err != nil {
+ return 0, fmt.Errorf("find orphaned job run activities: %w", err)
+ }
+ var resolved int64
+ var errs []error
+ for _, candidate := range candidates {
+ finalized, resolveErr := s.resolveOrphanedJobRun(ctx, candidate.ID, finished)
+ if resolveErr != nil {
+ errs = append(errs, fmt.Errorf("finalize orphaned job run activity %s: %w", candidate.ID, resolveErr))
+ continue
+ }
+ if finalized {
+ resolved++
+ }
+ }
+ return resolved, errors.Join(errs...)
+}
+
+func (s *ActivityService) resolveOrphanedJobRun(ctx context.Context, activityID string, finished map[string]scheduler.Run) (bool, error) {
+ lock := s.publishLock(activityID)
+ lock.Lock()
+ defer lock.Unlock()
+ var model Activity
+ var affected int64
+ if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ var existing Activity
+ if err := tx.First(&existing, "id = ?", activityID).Error; err != nil {
+ return err
+ }
+ run, found := finished[activityID]
+ if !found {
+ trigger, _ := existing.Metadata["trigger"].(string)
+ domainActivityID, _ := existing.Metadata["domainActivityId"].(string)
+ run = scheduler.Run{
+ ActivityID: existing.ID,
+ ID: kit.FromPtr(existing.BatchID),
+ JobID: kit.FromPtr(existing.ResourceID),
+ EnvironmentID: existing.EnvironmentID,
+ Trigger: trigger,
+ RequestedBy: kit.FromPtr(existing.StartedByUserID),
+ Status: scheduler.Failed,
+ CreatedAt: existing.StartedAt,
+ UpdatedAt: time.Now().UTC(),
+ Outcome: scheduler.Outcome{
+ Status: scheduler.Failed,
+ Message: "Job run no longer exists; its result was not recorded",
+ ActivityID: domainActivityID,
+ },
+ }
+ }
+ model = jobActivity(run, kit.FromPtr(existing.ResourceName))
+ result := tx.Table("activities").
+ Where("id = ? AND status IN ?", activityID, []activity.Status{activity.StatusQueued, activity.StatusRunning}).
+ Updates(map[string]any{
+ "environment_id": model.EnvironmentID,
+ "status": model.Status,
+ "step": model.Step,
+ "latest_message": model.LatestMessage,
+ "ended_at": model.EndedAt,
+ "duration_ms": model.DurationMs,
+ "error": model.Error,
+ "metadata": model.Metadata,
+ "updated_at": model.UpdatedAt,
+ })
+ affected = result.RowsAffected
+ return result.Error
+ }); err != nil {
+ return false, err
+ }
+ if affected == 0 {
+ return false, nil
+ }
+ s.pubsub.PublishActivity(activityToDTO(&model))
+ return true, nil
+}
+
func jobActivity(run scheduler.Run, name string) Activity {
status := activity.StatusQueued
switch run.Status {
diff --git a/backend/internal/job/service.go b/backend/internal/job/service.go
index 0bed39de9..6454b8baa 100644
--- a/backend/internal/job/service.go
+++ b/backend/internal/job/service.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"log/slog"
+ "maps"
"net"
"slices"
"strings"
@@ -436,9 +437,13 @@ func (s *JobService) ReconcileStartupActivities(ctx context.Context, extraProtec
return err
}
protected := append([]string(nil), extraProtectedIDs...)
+ finished := map[string]scheduler.Run{}
for _, record := range records {
- for _, run := range record.Runs {
+ for _, run := range slices.Concat(record.Runs, slices.Collect(maps.Values(record.Receipts))) {
if run.Status.Terminal() {
+ if run.ActivityID != "" {
+ finished[run.ActivityID] = runtime.ProjectRunOutcome(run)
+ }
continue
}
if run.ActivityID != "" {
@@ -463,7 +468,10 @@ func (s *JobService) ReconcileStartupActivities(ctx context.Context, extraProtec
if _, resolveStaleAutoUpdateActivitiesErr := s.activity.ResolveStaleAutoUpdateActivities(ctx, protected...); resolveStaleAutoUpdateActivitiesErr != nil {
return resolveStaleAutoUpdateActivitiesErr
}
- _, err = s.activity.ResolveOrphanedQueuedActivities(ctx, protected...)
+ if _, resolveOrphanedQueuedActivitiesErr := s.activity.ResolveOrphanedQueuedActivities(ctx, protected...); resolveOrphanedQueuedActivitiesErr != nil {
+ return resolveOrphanedQueuedActivitiesErr
+ }
+ _, err = s.activity.ResolveOrphanedJobRuns(ctx, finished, protected...)
return err
}