package jobrunner import ( "context" "errors" "fmt" "log/slog" "slices" "strings" "sync" "testing" "time" "github.com/google/uuid" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/worker/retry" "lincodex/backend/pkg/testutil" ) const ( testKind = "test.effect" otherKind = "test.other" // testLease is real time only where a test lets a handler run out of // its lease; the fake clock decides every due and lease comparison. testLease = time.Minute testBackoff = time.Second // testWait bounds every wait for a goroutine in these tests. testWait = 5 * time.Second ) var ( testStart = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) errStoreDown = errors.New("store unavailable") errEffectFail = errors.New("effect failed") ) // memoryJob mirrors one scheduled_jobs row. type memoryJob struct { id int64 kind string key string dueAt time.Time availableAt time.Time status string attempts int maxAttempts int leaseOwner uuid.UUID leaseExpiresAt time.Time started bool errorClass outbound.JobErrorClass } // memoryStore implements outbound.JobStore with the claim, guard, and // release rules of the PostgreSQL store, so the worker logic is tested // without a database. type memoryStore struct { mu sync.Mutex jobs map[int64]*memoryJob nextID int64 effects map[int64]int // locked holds the jobs whose handler runs, as the row lock of the // handler transaction does; claims skip them. locked map[int64]bool claims int // claimErr and runErr fail every claim or every run outside apply. claimErr error runErr error // beforeRun runs inside Run before the guard check, outside the lock. beforeRun func(job outbound.ClaimedJob) } func newMemoryStore() *memoryStore { return &memoryStore{jobs: make(map[int64]*memoryJob), effects: make(map[int64]int), locked: make(map[int64]bool)} } func (store *memoryStore) schedule(kind string, dueAt time.Time) int64 { return store.scheduleWithLimit(kind, dueAt, 0) } func (store *memoryStore) scheduleWithLimit(kind string, dueAt time.Time, maxAttempts int) int64 { store.mu.Lock() defer store.mu.Unlock() store.nextID++ store.jobs[store.nextID] = &memoryJob{ id: store.nextID, kind: kind, key: fmt.Sprint(store.nextID), dueAt: dueAt, availableAt: dueAt, status: "pending", maxAttempts: maxAttempts, } return store.nextID } func (store *memoryStore) job(id int64) memoryJob { store.mu.Lock() defer store.mu.Unlock() return *store.jobs[id] } func (store *memoryStore) effectCount(id int64) int { store.mu.Lock() defer store.mu.Unlock() return store.effects[id] } func (store *memoryStore) claimCount() int { store.mu.Lock() defer store.mu.Unlock() return store.claims } func (store *memoryStore) Claim(_ context.Context, claim outbound.JobClaim) ([]outbound.ClaimedJob, error) { store.mu.Lock() defer store.mu.Unlock() store.claims++ if store.claimErr != nil { return nil, store.claimErr } candidates := make([]*memoryJob, 0, len(store.jobs)) for _, job := range store.jobs { waiting := (job.status == "pending" || job.status == "failed") && !job.availableAt.After(claim.Now) expired := job.status == "running" && !job.leaseExpiresAt.After(claim.Now) if slices.Contains(claim.Kinds, job.kind) && (waiting || expired) && !store.locked[job.id] { candidates = append(candidates, job) } } slices.SortFunc(candidates, func(left, right *memoryJob) int { return left.availableAt.Compare(right.availableAt) }) candidates = candidates[:min(len(candidates), claim.Limit)] claimed := make([]outbound.ClaimedJob, 0, len(candidates)) for _, job := range candidates { maxAttempts := job.maxAttempts if maxAttempts == 0 { maxAttempts = claim.DefaultMaxAttempts } abandoned := job.status == "running" && job.started unstarted := job.status == "running" && !job.started exhausted := abandoned && job.attempts >= maxAttempts if abandoned { job.errorClass = outbound.JobErrorLeaseExpired } result := outbound.ClaimedJob{ID: job.id, Kind: job.kind, Key: job.key, DueAt: job.dueAt, MaxAttempts: maxAttempts, Exhausted: exhausted} job.started = false switch { case exhausted: job.status, job.leaseOwner, job.leaseExpiresAt = "dead", uuid.Nil, time.Time{} default: if !unstarted { job.attempts++ } job.status = "running" job.leaseOwner, job.leaseExpiresAt = claim.Owner, claim.Now.Add(claim.Lease) result.LeaseOwner, result.LeaseExpiresAt = job.leaseOwner, job.leaseExpiresAt } result.Attempt = job.attempts claimed = append(claimed, result) } return claimed, nil } // holds reports whether the lease of attempt still holds; mu must be held. func (store *memoryStore) holds(claimed outbound.ClaimedJob) (*memoryJob, bool) { job := store.jobs[claimed.ID] return job, job.status == "running" && job.leaseOwner == claimed.LeaseOwner && job.attempts == claimed.Attempt } func (store *memoryStore) Start(_ context.Context, claimed outbound.ClaimedJob, now time.Time, lease time.Duration) (outbound.ClaimedJob, bool, error) { store.mu.Lock() defer store.mu.Unlock() job, held := store.holds(claimed) if !held || !job.leaseExpiresAt.After(now) { return outbound.ClaimedJob{}, false, nil } job.started, job.leaseExpiresAt = true, now.Add(lease) claimed.LeaseExpiresAt = job.leaseExpiresAt return claimed, true, nil } func (store *memoryStore) Run(ctx context.Context, claimed outbound.ClaimedJob, apply outbound.ApplyJob) error { if store.beforeRun != nil { store.beforeRun(claimed) } store.mu.Lock() runErr := store.runErr _, held := store.holds(claimed) store.mu.Unlock() if runErr != nil { return runErr } if !held { return fmt.Errorf("memoryStore.Run: %w", outbound.ErrJobLeaseLost) } store.mu.Lock() store.locked[claimed.ID] = true store.mu.Unlock() defer func() { store.mu.Lock() delete(store.locked, claimed.ID) store.mu.Unlock() }() if err := apply(ctx, nil); err != nil { return err } if err := ctx.Err(); err != nil { // The commit of a canceled transaction fails and nothing commits. return err } store.mu.Lock() defer store.mu.Unlock() job, held := store.holds(claimed) if !held { return fmt.Errorf("memoryStore.Run - complete: %w", outbound.ErrJobLeaseLost) } job.status, job.leaseOwner, job.leaseExpiresAt, job.started = "done", uuid.Nil, time.Time{}, false store.effects[claimed.ID]++ return nil } func (store *memoryStore) Fail(_ context.Context, claimed outbound.ClaimedJob, failure outbound.JobFailure) (bool, error) { store.mu.Lock() defer store.mu.Unlock() job, held := store.holds(claimed) if !held { return false, nil } if failure.Dead { job.status = "dead" } else { job.status, job.availableAt = "failed", failure.RetryAt } job.errorClass, job.leaseOwner, job.leaseExpiresAt, job.started = failure.Class, uuid.Nil, time.Time{}, false return true, nil } func (store *memoryStore) Release(_ context.Context, jobs []outbound.ClaimedJob) ([]int64, error) { store.mu.Lock() defer store.mu.Unlock() var released []int64 for _, claimed := range jobs { job, held := store.holds(claimed) if !held { continue } job.status = "pending" if job.errorClass != "" { job.status = "failed" } job.attempts-- job.leaseOwner, job.leaseExpiresAt, job.started = uuid.Nil, time.Time{}, false released = append(released, job.id) } return released, nil } func (store *memoryStore) Backlog(_ context.Context, now time.Time) (outbound.JobBacklog, error) { store.mu.Lock() defer store.mu.Unlock() var backlog outbound.JobBacklog for _, job := range store.jobs { if (job.status == "pending" || job.status == "failed") && !job.availableAt.After(now) { backlog.Due++ } if job.status == "dead" { backlog.Dead++ } } return backlog, nil } // recordingMetrics counts outcomes by kind. type recordingMetrics struct { mu sync.Mutex prepared []string outcomes map[string]int backlog outbound.JobBacklog } func newRecordingMetrics() *recordingMetrics { return &recordingMetrics{outcomes: make(map[string]int)} } func (metrics *recordingMetrics) PrepareScheduledJobKind(kind string) { metrics.mu.Lock() defer metrics.mu.Unlock() metrics.prepared = append(metrics.prepared, kind) } func (metrics *recordingMetrics) ObserveScheduledJob(kind, outcome string) { metrics.mu.Lock() defer metrics.mu.Unlock() metrics.outcomes[kind+"/"+outcome]++ } func (metrics *recordingMetrics) ObserveScheduledJobBacklog(backlog outbound.JobBacklog) { metrics.mu.Lock() defer metrics.mu.Unlock() metrics.backlog = backlog } // count returns the outcomes of testKind. func (metrics *recordingMetrics) count(outcome string) int { metrics.mu.Lock() defer metrics.mu.Unlock() return metrics.outcomes[testKind+"/"+outcome] } // funcHandler runs handle for one kind and records the order of calls. type funcHandler struct { kind string handle func(ctx context.Context, job outbound.ClaimedJob) error mu sync.Mutex calls []int64 } func (handler *funcHandler) JobKind() string { return handler.kind } func (handler *funcHandler) Handle(ctx context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error { handler.mu.Lock() handler.calls = append(handler.calls, job.ID) handler.mu.Unlock() if handler.handle == nil { return nil } return handler.handle(ctx, job) } func (handler *funcHandler) called() []int64 { handler.mu.Lock() defer handler.mu.Unlock() return slices.Clone(handler.calls) } func testSettings() Settings { return Settings{ BatchSize: 10, PollInterval: time.Millisecond, Lease: testLease, MaxAttempts: 3, Backoff: retry.Backoff{Initial: testBackoff, Max: testBackoff}, ShutdownGrace: time.Second, StoreTimeout: time.Second, BacklogInterval: time.Millisecond, } } type harness struct { clock *testutil.FakeClock store *memoryStore metrics *recordingMetrics logs *strings.Builder logsMu *sync.Mutex } func newHarness() *harness { return &harness{ clock: testutil.NewFakeClock(testStart), store: newMemoryStore(), metrics: newRecordingMetrics(), logs: &strings.Builder{}, logsMu: &sync.Mutex{}, } } type lockedWriter struct { mu *sync.Mutex builder *strings.Builder } func (writer lockedWriter) Write(data []byte) (int, error) { writer.mu.Lock() defer writer.mu.Unlock() return writer.builder.Write(data) } func (h *harness) logText() string { h.logsMu.Lock() defer h.logsMu.Unlock() return h.logs.String() } func (h *harness) newWorker(t *testing.T, settings Settings, handlers ...inbound.JobHandler) *Worker { t.Helper() logger := slog.New(slog.NewJSONHandler(lockedWriter{mu: h.logsMu, builder: h.logs}, &slog.HandlerOptions{Level: slog.LevelDebug})) worker, err := New(handlers, h.store, h.metrics, logger, settings, h.clock.Now) if err != nil { t.Fatalf("New() error = %v", err) } return worker } func runDue(t *testing.T, worker *Worker) PassResult { t.Helper() result, err := worker.RunDue(t.Context()) if err != nil { t.Fatalf("RunDue() error = %v", err) } return result } func TestNewRejectsInvalidRegistrations(t *testing.T) { h := newHarness() logger := slog.New(slog.DiscardHandler) valid := &funcHandler{kind: testKind} tests := []struct { name string handlers []inbound.JobHandler settings func(*Settings) }{ {name: "no handler"}, {name: "invalid kind", handlers: []inbound.JobHandler{&funcHandler{kind: "Test Kind"}}}, {name: "duplicate kind", handlers: []inbound.JobHandler{valid, &funcHandler{kind: testKind}}}, {name: "zero batch", handlers: []inbound.JobHandler{valid}, settings: func(settings *Settings) { settings.BatchSize = 0 }}, {name: "too many attempts", handlers: []inbound.JobHandler{valid}, settings: func(settings *Settings) { settings.MaxAttempts = 101 }}, {name: "zero lease", handlers: []inbound.JobHandler{valid}, settings: func(settings *Settings) { settings.Lease = 0 }}, {name: "zero grace", handlers: []inbound.JobHandler{valid}, settings: func(settings *Settings) { settings.ShutdownGrace = 0 }}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { settings := testSettings() if test.settings != nil { test.settings(&settings) } if _, err := New(test.handlers, h.store, h.metrics, logger, settings, h.clock.Now); err == nil { t.Fatal("New() accepted an invalid registration") } }) } } func TestRunDueRunsOnlyDueJobsInDueOrder(t *testing.T) { h := newHarness() handler := &funcHandler{kind: testKind} worker := h.newWorker(t, testSettings(), handler, &funcHandler{kind: otherKind}) if kinds := worker.Kinds(); !slices.Equal(kinds, []string{testKind, otherKind}) || !slices.Equal(h.metrics.prepared, kinds) { t.Fatalf("Kinds() = %v, prepared %v", kinds, h.metrics.prepared) } later := h.store.schedule(testKind, testStart.Add(48*time.Hour)) second := h.store.schedule(testKind, testStart.Add(-time.Minute)) first := h.store.schedule(testKind, testStart.Add(-time.Hour)) unknown := h.store.schedule("test.unregistered", testStart.Add(-time.Hour)) if result := runDue(t, worker); result.Claimed != 2 || result.Done != 2 { t.Fatalf("first pass = %+v, want two done jobs", result) } if calls := handler.called(); !slices.Equal(calls, []int64{first, second}) { t.Fatalf("handler calls = %v, want %v in due order", calls, []int64{first, second}) } if result := runDue(t, worker); result.Claimed != 0 { t.Fatalf("second pass at the same time claimed %d jobs", result.Claimed) } h.clock.Advance(48*time.Hour - time.Nanosecond) if result := runDue(t, worker); result.Claimed != 0 { t.Fatal("a job ran before its due time") } h.clock.Advance(time.Nanosecond) if result := runDue(t, worker); result.Done != 1 || h.store.effectCount(later) != 1 { t.Fatalf("pass at the due time = %+v, effects %d", result, h.store.effectCount(later)) } if job := h.store.job(unknown); job.status != "pending" || job.attempts != 0 { t.Fatalf("a job of an unregistered kind was touched: %+v", job) } if got := h.metrics.count(OutcomeDone); got != 3 { t.Fatalf("done outcomes = %d, want 3", got) } } func TestRunDueRetriesWithBackoffAndThenKillsTheJob(t *testing.T) { h := newHarness() handler := &funcHandler{kind: testKind, handle: func(context.Context, outbound.ClaimedJob) error { return errEffectFail }} worker := h.newWorker(t, testSettings(), handler) id := h.store.schedule(testKind, testStart) for attempt := 1; attempt < 3; attempt++ { if result := runDue(t, worker); result.Retried != 1 { t.Fatalf("attempt %d = %+v, want a retry", attempt, result) } job := h.store.job(id) // Backoff with Initial == Max waits between half and the whole of it. wait := job.availableAt.Sub(h.clock.Now()) if job.status != "failed" || job.errorClass != outbound.JobErrorHandlerFailed || wait < testBackoff/2 || wait > testBackoff || !job.dueAt.Equal(testStart) { t.Fatalf("after attempt %d job = %+v, retry in %s", attempt, job, wait) } // No hot loop: the job is not due again until the backoff passed. if result := runDue(t, worker); result.Claimed != 0 { t.Fatalf("attempt %d was retried before its backoff", attempt) } h.clock.Advance(testBackoff) } if result := runDue(t, worker); result.Dead != 1 { t.Fatalf("last attempt = %+v, want a dead job", result) } if job := h.store.job(id); job.status != "dead" || job.attempts != 3 || h.store.effectCount(id) != 0 { t.Fatalf("job after the last attempt = %+v", job) } if h.metrics.count(OutcomeRetry) != 2 || h.metrics.count(OutcomeDead) != 1 { t.Fatalf("outcomes = %v", h.metrics.outcomes) } logs := h.logText() if !strings.Contains(logs, "scheduled job is dead; it needs an operator") || !strings.Contains(logs, `"level":"ERROR"`) { t.Fatalf("dead job was not logged as an error:\n%s", logs) } } func TestRunDueEndsRejectedAndPanickingJobsAtOnce(t *testing.T) { tests := []struct { name string handle func(context.Context, outbound.ClaimedJob) error class outbound.JobErrorClass }{ {name: "rejected", class: outbound.JobErrorHandlerRejected, handle: func(context.Context, outbound.ClaimedJob) error { return fmt.Errorf("unsupported payload: %w", inbound.ErrJobRejected) }}, {name: "panic", class: outbound.JobErrorHandlerPanic, handle: func(context.Context, outbound.ClaimedJob) error { panic("secret payload value") }}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { h := newHarness() worker := h.newWorker(t, testSettings(), &funcHandler{kind: testKind, handle: test.handle}) id := h.store.schedule(testKind, testStart) if result := runDue(t, worker); result.Dead != 1 { t.Fatalf("RunDue() = %+v, want a dead job", result) } if job := h.store.job(id); job.status != "dead" || job.attempts != 1 || job.errorClass != test.class { t.Fatalf("job = %+v, want dead with class %s after one attempt", job, test.class) } if strings.Contains(h.logText(), "secret payload value") { t.Fatal("the panic value reached the logs") } }) } } func TestRunDueTimesOutAHandlerAtTheEndOfItsLease(t *testing.T) { h := newHarness() settings := testSettings() // The handler context ends with the lease in real time. settings.Lease = 50 * time.Millisecond handler := &funcHandler{kind: testKind, handle: func(ctx context.Context, _ outbound.ClaimedJob) error { <-ctx.Done() return ctx.Err() }} worker := h.newWorker(t, settings, handler) id := h.store.schedule(testKind, testStart) if result := runDue(t, worker); result.Retried != 1 { t.Fatalf("RunDue() = %+v, want a retry", result) } if job := h.store.job(id); job.errorClass != outbound.JobErrorTimeout || h.store.effectCount(id) != 0 { t.Fatalf("job = %+v, want a timeout without effect", job) } } func TestRunDueSkipsAJobWhoseLeaseWasLost(t *testing.T) { h := newHarness() handler := &funcHandler{kind: testKind} worker := h.newWorker(t, testSettings(), handler) id := h.store.schedule(testKind, testStart) // Another worker reclaims the job after the lease expired, before this // worker starts it. h.store.beforeRun = func(claimed outbound.ClaimedJob) { h.store.mu.Lock() defer h.store.mu.Unlock() h.store.jobs[claimed.ID].leaseOwner = uuid.New() h.store.jobs[claimed.ID].attempts++ } if result := runDue(t, worker); result.LeaseLost != 1 || len(handler.called()) != 0 { t.Fatalf("RunDue() = %+v, handler calls %v; want a lost lease without a call", result, handler.called()) } if job := h.store.job(id); job.status != "running" || h.store.effectCount(id) != 0 { t.Fatalf("the other worker's job was changed: %+v", job) } } func TestRunDueKillsAJobWhoseLastLeaseExpired(t *testing.T) { h := newHarness() handler := &funcHandler{kind: testKind} worker := h.newWorker(t, testSettings(), handler) id := h.store.schedule(testKind, testStart) // Three earlier attempts started the handler and stopped without // finishing, as crashed workers would. for range 3 { claimed, err := h.store.Claim(t.Context(), outbound.JobClaim{ Owner: uuid.New(), Kinds: []string{testKind}, Now: h.clock.Now(), Lease: testLease, Limit: 1, DefaultMaxAttempts: 3, }) if err != nil || len(claimed) != 1 { t.Fatalf("Claim() = %v, %v", claimed, err) } if _, ok, err := h.store.Start(t.Context(), claimed[0], h.clock.Now(), testLease); !ok || err != nil { t.Fatalf("Start() = %t, %v", ok, err) } h.clock.Advance(testLease) } if result := runDue(t, worker); result.Dead != 1 || len(handler.called()) != 0 { t.Fatalf("RunDue() = %+v, handler calls %v; want a dead job without a call", result, handler.called()) } if job := h.store.job(id); job.status != "dead" || job.errorClass != outbound.JobErrorLeaseExpired { t.Fatalf("job = %+v", job) } } func TestRunDueReleasesJobsAfterADatabaseFailure(t *testing.T) { h := newHarness() worker := h.newWorker(t, testSettings(), &funcHandler{kind: testKind}) first := h.store.schedule(testKind, testStart) second := h.store.schedule(testKind, testStart.Add(time.Second)) h.clock.Advance(time.Second) h.store.runErr = errStoreDown result, err := worker.RunDue(t.Context()) if !errors.Is(err, errStoreDown) || result.Released != 2 { t.Fatalf("RunDue() = %+v, %v; want both jobs released and the store error", result, err) } for _, id := range []int64{first, second} { // The attempt is not counted: the job did not cause the failure. if job := h.store.job(id); job.status != "pending" || job.attempts != 0 { t.Fatalf("job %d after the failure = %+v", id, job) } } } func TestRunBacksOffWhileTheDatabaseFails(t *testing.T) { h := newHarness() settings := testSettings() settings.Backoff = retry.Backoff{Initial: 100 * time.Millisecond, Max: 100 * time.Millisecond} worker := h.newWorker(t, settings, &funcHandler{kind: testKind}) h.store.claimErr = errStoreDown ctx, cancel := context.WithCancel(t.Context()) stopped := make(chan struct{}) go func() { defer close(stopped) worker.Run(ctx) }() time.Sleep(300 * time.Millisecond) cancel() awaitClosed(t, stopped, "Run to return") // Waits of 50ms to 100ms allow at most seven claims in 300ms. if claims := h.store.claimCount(); claims < 2 || claims > 7 { t.Fatalf("Run claimed %d times in 300ms of failures; want a backoff, not a hot loop", claims) } } func TestRunFinishesTheJobInProgressWithinTheGrace(t *testing.T) { h := newHarness() started := make(chan struct{}) finish := make(chan struct{}) handler := &funcHandler{kind: testKind, handle: func(ctx context.Context, _ outbound.ClaimedJob) error { close(started) select { case <-finish: return nil case <-ctx.Done(): return ctx.Err() } }} worker := h.newWorker(t, testSettings(), handler) inProgress := h.store.schedule(testKind, testStart.Add(-time.Minute)) notStarted := h.store.schedule(testKind, testStart) ctx, cancel := context.WithCancel(t.Context()) stopped := make(chan struct{}) go func() { defer close(stopped) worker.Run(ctx) }() awaitClosed(t, started, "the handler to start") cancel() close(finish) awaitClosed(t, stopped, "Run to return") if job := h.store.job(inProgress); job.status != "done" || h.store.effectCount(inProgress) != 1 { t.Fatalf("job in progress = %+v, want done within the grace", job) } // The second job of the batch did not start; it went back at once. if job := h.store.job(notStarted); job.status != "pending" || job.attempts != 0 || job.leaseOwner != uuid.Nil { t.Fatalf("job not started = %+v, want released", job) } } func TestRunCancelsAndReleasesAJobThatOutlastsTheGrace(t *testing.T) { h := newHarness() settings := testSettings() settings.ShutdownGrace = 50 * time.Millisecond started := make(chan struct{}) handler := &funcHandler{kind: testKind, handle: func(ctx context.Context, _ outbound.ClaimedJob) error { close(started) <-ctx.Done() return ctx.Err() }} worker := h.newWorker(t, settings, handler) id := h.store.schedule(testKind, testStart) ctx, cancel := context.WithCancel(t.Context()) stopped := make(chan struct{}) go func() { defer close(stopped) worker.Run(ctx) }() awaitClosed(t, started, "the handler to start") cancel() awaitClosed(t, stopped, "Run to return after the grace") // The unfinished job is neither done nor counted as a failure, and it is // claimable again at once. job := h.store.job(id) if job.status != "pending" || job.attempts != 0 || job.errorClass != "" || h.store.effectCount(id) != 0 { t.Fatalf("job after shutdown = %+v, want released and not done", job) } if h.metrics.count(OutcomeReleased) != 1 || h.metrics.count(OutcomeRetry) != 0 { t.Fatalf("outcomes = %v", h.metrics.outcomes) } } func TestRunReportsTheBacklog(t *testing.T) { h := newHarness() worker := h.newWorker(t, testSettings(), &funcHandler{kind: otherKind}) h.store.schedule(testKind, testStart) ctx, cancel := context.WithCancel(t.Context()) stopped := make(chan struct{}) go func() { defer close(stopped) worker.Run(ctx) }() deadline := time.Now().Add(testWait) for { h.metrics.mu.Lock() due := h.metrics.backlog.Due h.metrics.mu.Unlock() if due == 1 { break } if time.Now().After(deadline) { t.Fatal("the backlog of a kind without a handler was not reported") } time.Sleep(time.Millisecond) } cancel() awaitClosed(t, stopped, "Run to return") } func awaitClosed(t *testing.T, signal <-chan struct{}, what string) { t.Helper() select { case <-signal: case <-time.After(testWait): t.Fatalf("timed out waiting for %s", what) } } func TestRunDueDoesNotSpendAnAttemptOnAJobWhoseTurnCameTooLate(t *testing.T) { h := newHarness() handler := &funcHandler{kind: testKind, handle: func(_ context.Context, job outbound.ClaimedJob) error { if job.ID == 1 { // The first job of the batch runs past the lease of the claim. h.clock.Advance(2 * testLease) } return nil }} worker := h.newWorker(t, testSettings(), handler) slow := h.store.schedule(testKind, testStart.Add(-time.Minute)) late := h.store.scheduleWithLimit(testKind, testStart, 1) if result := runDue(t, worker); result.Claimed != 2 || result.Done != 1 || result.Released != 1 { t.Fatalf("first pass = %+v, want the slow job done and the late one released", result) } // The late job never started, so its only allowed attempt is intact. if job := h.store.job(late); job.status != "pending" || job.attempts != 0 { t.Fatalf("late job after the slow one = %+v, want pending without an attempt", job) } if result := runDue(t, worker); result.Done != 1 || h.store.effectCount(late) != 1 || h.store.effectCount(slow) != 1 { t.Fatalf("second pass = %+v, want the late job done once", result) } } func TestAnotherWorkerRunsAJobThatABusyWorkerDidNotStart(t *testing.T) { h := newHarness() inSlowJob, finishSlowJob := make(chan struct{}), make(chan struct{}) busy := h.newWorker(t, testSettings(), &funcHandler{kind: testKind, handle: func(ctx context.Context, job outbound.ClaimedJob) error { if job.ID != 1 { return nil } close(inSlowJob) select { case <-finishSlowJob: return nil case <-ctx.Done(): return ctx.Err() } }}) other := h.newWorker(t, testSettings(), &funcHandler{kind: testKind}) h.store.schedule(testKind, testStart.Add(-time.Minute)) waiting := h.store.scheduleWithLimit(testKind, testStart, 1) finished := make(chan PassResult, 1) go func() { result, _ := busy.RunDue(t.Context()) finished <- result }() awaitClosed(t, inSlowJob, "the slow job to start") h.clock.Advance(2 * testLease) // The waiting job's attempt never started, so the other worker reuses it // instead of counting a second one, and its single attempt is not lost. if result := runDue(t, other); result.Done != 1 { t.Fatalf("other worker pass = %+v, want the waiting job done", result) } close(finishSlowJob) var result PassResult select { case result = <-finished: case <-time.After(testWait): t.Fatal("the busy worker did not finish its pass") } if result.Done != 1 || result.LeaseLost != 1 { t.Fatalf("busy worker pass = %+v, want its own job done and the taken one lost", result) } if job := h.store.job(waiting); job.status != "done" || job.attempts != 1 || h.store.effectCount(waiting) != 1 { t.Fatalf("waiting job = %+v, effects %d; want done once on its single attempt", job, h.store.effectCount(waiting)) } } func TestRunKillsAPanickingJobAlsoWhileStopping(t *testing.T) { h := newHarness() started, panicNow := make(chan struct{}), make(chan struct{}) worker := h.newWorker(t, testSettings(), &funcHandler{kind: testKind, handle: func(context.Context, outbound.ClaimedJob) error { close(started) <-panicNow panic("broken handler") }}) id := h.store.schedule(testKind, testStart) ctx, cancel := context.WithCancel(t.Context()) stopped := make(chan struct{}) go func() { defer close(stopped) worker.Run(ctx) }() awaitClosed(t, started, "the handler to start") cancel() close(panicNow) awaitClosed(t, stopped, "Run to return") // A panic is the job's own fault, so shutdown does not release it. if job := h.store.job(id); job.status != "dead" || job.errorClass != outbound.JobErrorHandlerPanic { t.Fatalf("job = %+v, want dead with handler_panic", job) } }