package sched_test import ( "context" "errors" "sync" "sync/atomic" "testing" "time" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/db/dbtest" "github.com/noderunners/dlbot/internal/sched" "github.com/noderunners/dlbot/internal/workerproto" ) type fixture struct { t *testing.T store *db.Store s *sched.Scheduler now atomic.Int64 // unix ms, advanced by the test mu sync.Mutex events []sched.Event } func newFixture(t *testing.T, cfg sched.Config) *fixture { t.Helper() f := &fixture{t: t, store: dbtest.Open(t).Store()} f.now.Store(time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC).UnixMilli()) cfg.Now = func() time.Time { return time.UnixMilli(f.now.Load()) } if cfg.Lease == 0 { cfg.Lease = 30 * time.Second } f.s = sched.New(f.store, cfg, nil) f.s.Subscribe(func(ev sched.Event) { f.mu.Lock() f.events = append(f.events, ev) f.mu.Unlock() }) return f } func (f *fixture) advance(d time.Duration) { f.now.Add(d.Milliseconds()) } func (f *fixture) enqueue(user int64, mut ...func(*sched.EnqueueParams)) (*db.Job, *db.Delivery) { f.t.Helper() p := sched.EnqueueParams{ URL: "https://example.com/v", Profile: "720", Title: "T", UserID: user, ChatID: user, ChatType: "private", Lang: "en", } for _, m := range mut { m(&p) } f.advance(time.Millisecond) // distinct queued_at keeps FIFO deterministic j, d, err := f.s.Enqueue(context.Background(), p) if err != nil { f.t.Fatalf("enqueue: %v", err) } return j, d } func (f *fixture) claim(worker string) *workerproto.Job { f.t.Helper() j, err := f.s.Claim(context.Background(), workerproto.ClaimRequest{WorkerID: worker, Capacity: 1}) if err != nil { f.t.Fatalf("claim: %v", err) } return j } func (f *fixture) job(id string) *db.Job { f.t.Helper() j, err := f.store.GetJob(context.Background(), id) if err != nil { f.t.Fatalf("get job: %v", err) } return j } func (f *fixture) eventTypes(jobID string) []sched.EventType { f.mu.Lock() defer f.mu.Unlock() var out []sched.EventType for _, e := range f.events { if e.JobID == jobID { out = append(out, e.Type) } } return out } func wantEvents(t *testing.T, got []sched.EventType, want ...sched.EventType) { t.Helper() if len(got) != len(want) { t.Fatalf("events = %v, want %v", got, want) } for i := range want { if got[i] != want[i] { t.Fatalf("events = %v, want %v", got, want) } } } func TestLifecycleSuccess(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{}) job, del := f.enqueue(1) if job.Status != db.JobQueued || del.Status != db.DeliveryPending { t.Fatalf("new job %s, delivery %s", job.Status, del.Status) } wj := f.claim("w1") if wj == nil || wj.ID != job.ID { t.Fatalf("claim = %+v, want job %s", wj, job.ID) } if wj.Attempt != 1 || wj.UploadKey != sched.UploadKey(job.ID) { t.Fatalf("claimed job = %+v", wj) } if again := f.claim("w2"); again != nil { t.Fatalf("a running job was claimed twice: %+v", again) } resp, err := f.s.Heartbeat(ctx, workerproto.HeartbeatRequest{ WorkerID: "w1", JobID: job.ID, Stage: "downloading", Downloaded: 50, Total: 100, }) if err != nil || resp.Cancel { t.Fatalf("heartbeat = %+v, %v", resp, err) } if got := f.job(job.ID); got.ProgressBytes != 50 || got.TotalBytes != 100 || got.Stage != "downloading" { t.Fatalf("progress not stored: %+v", got) } if _, err := f.s.Heartbeat(ctx, workerproto.HeartbeatRequest{WorkerID: "intruder", JobID: job.ID}); !errors.Is(err, sched.ErrLeaseLost) { t.Fatalf("heartbeat from another worker: %v, want ErrLeaseLost", err) } if err := f.s.Complete(ctx, workerproto.CompleteRequest{WorkerID: "intruder", JobID: job.ID}); !errors.Is(err, sched.ErrLeaseLost) { t.Fatalf("complete from another worker: %v, want ErrLeaseLost", err) } err = f.s.Complete(ctx, workerproto.CompleteRequest{ WorkerID: "w1", JobID: job.ID, StorageKey: wj.UploadKey, Ext: "mp4", Size: 1234, Duration: 61, Width: 1280, Height: 720, Title: "Real Title", Extractor: "youtube", VideoID: "abc", }) if err != nil { t.Fatalf("complete: %v", err) } got := f.job(job.ID) if got.Status != db.JobDelivering || got.FileSize != 1234 || got.FileExt != "mp4" || got.Title != "Real Title" || got.Extractor != "youtube" || got.VideoID != "abc" { t.Fatalf("after complete: %+v", got) } if err := f.s.FinishDelivered(ctx, job.ID); err != nil { t.Fatal(err) } if got := f.job(job.ID); got.Status != db.JobDone { t.Fatalf("status = %s, want done", got.Status) } wantEvents(t, f.eventTypes(job.ID), sched.EventQueued, sched.EventStarted, sched.EventProgress, sched.EventStored) } func TestFailRetriesOnceThenFails(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{MaxAttempts: 2}) job, _ := f.enqueue(1) f.claim("w1") if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w1", JobID: job.ID, Code: "network", Retryable: true}); err != nil { t.Fatal(err) } if got := f.job(job.ID); got.Status != db.JobQueued || got.Attempts != 1 || got.WorkerID != "" { t.Fatalf("after first failure: status=%s attempts=%d worker=%q", got.Status, got.Attempts, got.WorkerID) } wj := f.claim("w2") if wj == nil || wj.Attempt != 2 { t.Fatalf("retry claim = %+v", wj) } if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w2", JobID: job.ID, Code: "network", Retryable: true}); err != nil { t.Fatal(err) } got := f.job(job.ID) if got.Status != db.JobFailed || got.ErrorCode != "network" { t.Fatalf("after second failure: status=%s code=%s", got.Status, got.ErrorCode) } wantEvents(t, f.eventTypes(job.ID), sched.EventQueued, sched.EventStarted, sched.EventRequeued, sched.EventStarted, sched.EventFailed) } func TestFailNotRetryableFailsAtOnce(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{MaxAttempts: 2}) job, _ := f.enqueue(1) f.claim("w1") if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w1", JobID: job.ID, Code: "private"}); err != nil { t.Fatal(err) } if got := f.job(job.ID); got.Status != db.JobFailed || got.ErrorCode != "private" { t.Fatalf("status=%s code=%s", got.Status, got.ErrorCode) } } func TestWorkerShutdownDoesNotSpendAnAttempt(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{MaxAttempts: 2}) job, _ := f.enqueue(1) for i := 0; i < 5; i++ { // more hand-backs than attempts if wj := f.claim("w1"); wj == nil { t.Fatalf("round %d: nothing to claim", i) } if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w1", JobID: job.ID, Code: "worker_lost", Retryable: true}); err != nil { t.Fatal(err) } } if got := f.job(job.ID); got.Status != db.JobQueued || got.Attempts != 0 { t.Fatalf("status=%s attempts=%d, want queued with 0 attempts", got.Status, got.Attempts) } } func TestExpiredLeaseIsRequeuedThenFailed(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{Lease: 30 * time.Second, MaxAttempts: 2}) job, _ := f.enqueue(1) f.claim("w1") f.advance(20 * time.Second) if n, err := f.s.RequeueExpired(ctx); err != nil || n != 0 { t.Fatalf("lease still valid, requeued %d, err %v", n, err) } // A heartbeat extends the lease past the original expiry. if _, err := f.s.Heartbeat(ctx, workerproto.HeartbeatRequest{WorkerID: "w1", JobID: job.ID}); err != nil { t.Fatal(err) } f.advance(20 * time.Second) if n, _ := f.s.RequeueExpired(ctx); n != 0 { t.Fatalf("heartbeat should have extended the lease, requeued %d", n) } f.advance(31 * time.Second) // the worker died if n, err := f.s.RequeueExpired(ctx); err != nil || n != 1 { t.Fatalf("requeued %d, err %v, want 1", n, err) } if got := f.job(job.ID); got.Status != db.JobQueued { t.Fatalf("status = %s, want queued", got.Status) } // The dead worker comes back late and must be turned away. if err := f.s.Complete(ctx, workerproto.CompleteRequest{WorkerID: "w1", JobID: job.ID}); !errors.Is(err, sched.ErrLeaseLost) { t.Fatalf("late complete: %v, want ErrLeaseLost", err) } if wj := f.claim("w2"); wj == nil || wj.Attempt != 2 { t.Fatalf("second worker claim = %+v", wj) } f.advance(31 * time.Second) if n, _ := f.s.RequeueExpired(ctx); n != 1 { t.Fatalf("second expiry not handled") } if got := f.job(job.ID); got.Status != db.JobFailed || got.ErrorCode != "worker_lost" { t.Fatalf("status=%s code=%s, want failed worker_lost", got.Status, got.ErrorCode) } } func TestCancelQueuedJob(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{}) job, del := f.enqueue(7) if _, err := f.s.CancelDelivery(ctx, del.ID, 999); !errors.Is(err, sched.ErrNotOwner) { t.Fatalf("cancel by a stranger: %v, want ErrNotOwner", err) } d, err := f.s.CancelDelivery(ctx, del.ID, 7) if err != nil || d.Status != db.DeliveryCancelled { t.Fatalf("cancel = %+v, %v", d, err) } if got := f.job(job.ID); got.Status != db.JobCancelled { t.Fatalf("job status = %s, want cancelled", got.Status) } if wj := f.claim("w1"); wj != nil { t.Fatalf("a cancelled job was claimed: %+v", wj) } if _, err := f.s.CancelDelivery(ctx, del.ID, 7); !errors.Is(err, sched.ErrTooLate) { t.Fatalf("second cancel: %v, want ErrTooLate", err) } } func TestCancelRunningJobStopsAtHeartbeat(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{}) job, del := f.enqueue(7) f.claim("w1") if _, err := f.s.CancelDelivery(ctx, del.ID, 7); err != nil { t.Fatal(err) } if got := f.job(job.ID); got.Status != db.JobRunning || !got.CancelRequested { t.Fatalf("running job should be flagged, got status=%s flag=%v", got.Status, got.CancelRequested) } resp, err := f.s.Heartbeat(ctx, workerproto.HeartbeatRequest{WorkerID: "w1", JobID: job.ID}) if err != nil || !resp.Cancel { t.Fatalf("heartbeat = %+v, %v, want cancel", resp, err) } if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w1", JobID: job.ID, Code: "cancelled"}); err != nil { t.Fatal(err) } if got := f.job(job.ID); got.Status != db.JobCancelled { t.Fatalf("status = %s, want cancelled", got.Status) } } func TestCompleteAfterCancelDoesNotDeliver(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{}) job, del := f.enqueue(7) f.claim("w1") if _, err := f.s.CancelDelivery(ctx, del.ID, 7); err != nil { t.Fatal(err) } // The worker finished before it saw the cancel flag. if err := f.s.Complete(ctx, workerproto.CompleteRequest{WorkerID: "w1", JobID: job.ID, StorageKey: "k"}); err != nil { t.Fatal(err) } if got := f.job(job.ID); got.Status != db.JobCancelled { t.Fatalf("status = %s, want cancelled", got.Status) } } func TestActiveLimitAndQueueCap(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{FreeMaxLen: 2}) limit1 := func(p *sched.EnqueueParams) { p.ActiveLimit = 1 } _, del := f.enqueue(1, limit1) _, _, err := f.s.Enqueue(ctx, sched.EnqueueParams{URL: "u", Profile: "720", UserID: 1, ActiveLimit: 1}) if !errors.Is(err, sched.ErrTooManyActive) { t.Fatalf("second job of a limited user: %v, want ErrTooManyActive", err) } // Cancelling frees the slot. if _, err := f.s.CancelDelivery(ctx, del.ID, 1); err != nil { t.Fatal(err) } f.enqueue(1, limit1) f.enqueue(2) _, _, err = f.s.Enqueue(ctx, sched.EnqueueParams{URL: "u", Profile: "720", UserID: 3}) if !errors.Is(err, sched.ErrQueueFull) { t.Fatalf("third queued free job: %v, want ErrQueueFull", err) } // The cap only counts the free lane. if _, _, err := f.s.Enqueue(ctx, sched.EnqueueParams{URL: "u", Profile: "720", UserID: 4, Lane: db.LanePaid}); err != nil { t.Fatalf("paid job should bypass the free queue cap: %v", err) } } func TestClaimOrderPaidFirstThenFIFO(t *testing.T) { f := newFixture(t, sched.Config{}) paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid } free1, _ := f.enqueue(1) free2, _ := f.enqueue(2) paid1, _ := f.enqueue(3, paid) paid2, _ := f.enqueue(4, paid) urgent, _ := f.enqueue(5, paid, func(p *sched.EnqueueParams) { p.Priority = 10 }) want := []string{urgent.ID, paid1.ID, paid2.ID, free1.ID, free2.ID} // Positions must agree with the claim order before anything is claimed. for i, id := range want { pos, err := f.s.Position(context.Background(), f.job(id), 1) if err != nil { t.Fatal(err) } if pos.Ahead != i { t.Errorf("position of job %d = %d, want %d", i, pos.Ahead, i) } } for i, id := range want { wj := f.claim("w") if wj == nil || wj.ID != id { t.Fatalf("claim %d = %v, want %s", i, wj, id) } } if wj := f.claim("w"); wj != nil { t.Fatalf("queue should be empty, got %+v", wj) } } func TestRetriedJobKeepsItsPlace(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{MaxAttempts: 2}) first, _ := f.enqueue(1) second, _ := f.enqueue(2) f.claim("w1") // takes first if err := f.s.Fail(ctx, workerproto.FailRequest{WorkerID: "w1", JobID: first.ID, Code: "network", Retryable: true}); err != nil { t.Fatal(err) } if wj := f.claim("w1"); wj == nil || wj.ID != first.ID { t.Fatalf("retried job should go before %s, got %+v", second.ID, wj) } } func TestConcurrentClaimsNeverShareAJob(t *testing.T) { f := newFixture(t, sched.Config{}) const jobs = 40 for i := 0; i < jobs; i++ { f.enqueue(int64(i + 1)) } var ( mu sync.Mutex seen = map[string]string{} wg sync.WaitGroup ) for w := 0; w < 8; w++ { wg.Add(1) go func(worker string) { defer wg.Done() for { wj, err := f.s.Claim(context.Background(), workerproto.ClaimRequest{WorkerID: worker}) if err != nil { t.Errorf("claim: %v", err) return } if wj == nil { return } mu.Lock() if prev, dup := seen[wj.ID]; dup { t.Errorf("job %s claimed by %s and %s", wj.ID, prev, worker) } seen[wj.ID] = worker mu.Unlock() } }(string(rune('a' + w))) } wg.Wait() if len(seen) != jobs { t.Fatalf("claimed %d jobs, want %d", len(seen), jobs) } } func TestWaitWorkWakesOnEnqueue(t *testing.T) { f := newFixture(t, sched.Config{}) done := make(chan time.Duration, 1) go func() { start := time.Now() f.s.WaitWork(context.Background(), 5*time.Second) done <- time.Since(start) }() time.Sleep(50 * time.Millisecond) f.enqueue(1) select { case d := <-done: if d > 2*time.Second { t.Fatalf("WaitWork returned after %s, expected a prompt wake-up", d) } case <-time.After(3 * time.Second): t.Fatal("WaitWork did not wake up on enqueue") } } // claimCap claims as a worker that advertises the given capacity. func (f *fixture) claimCap(worker string, capacity int) *workerproto.Job { f.t.Helper() j, err := f.s.Claim(context.Background(), workerproto.ClaimRequest{WorkerID: worker, Capacity: capacity}) if err != nil { f.t.Fatalf("claim: %v", err) } return j } func (f *fixture) finish(worker, jobID string) { f.t.Helper() if err := f.s.Complete(context.Background(), workerproto.CompleteRequest{WorkerID: worker, JobID: jobID, StorageKey: "k"}); err != nil { f.t.Fatalf("complete: %v", err) } } func wantClaim(t *testing.T, got *workerproto.Job, want *db.Job, what string) { t.Helper() switch { case want == nil && got != nil: t.Fatalf("%s: claimed %s, want nothing", what, got.ID) case want != nil && got == nil: t.Fatalf("%s: claimed nothing, want %s", what, want.ID) case want != nil && got.ID != want.ID: t.Fatalf("%s: claimed the wrong job", what) } } // Acceptance: correct priority ordering with the reserved free slot. func TestPaidFirstWithOneSlotReservedForFree(t *testing.T) { f := newFixture(t, sched.Config{}) paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid } const w, slots = "w1", 3 free1, _ := f.enqueue(1) free2, _ := f.enqueue(2) paid1, _ := f.enqueue(11, paid) paid2, _ := f.enqueue(12, paid) paid3, _ := f.enqueue(13, paid) paid4, _ := f.enqueue(14, paid) // Free jobs were queued first, yet paid jobs are served first. wantClaim(t, f.claimCap(w, slots), paid1, "slot 1") wantClaim(t, f.claimCap(w, slots), paid2, "slot 2") // The last idle slot is the reserved one: a free job waits and none // runs, so it goes to the free lane although paid jobs are waiting. wantClaim(t, f.claimCap(w, slots), free1, "slot 3 (reserved)") // A paid job finishes. A free job is already running, so the // reservation is satisfied and the slot goes to the next paid job. f.finish(w, paid1.ID) wantClaim(t, f.claimCap(w, slots), paid3, "after paid1") // The free job finishes. Its slot is again the last idle one with no // free job running, so the second free job is served before paid4. f.finish(w, free1.ID) wantClaim(t, f.claimCap(w, slots), free2, "after free1 (reserved)") f.finish(w, paid2.ID) wantClaim(t, f.claimCap(w, slots), paid4, "after paid2") f.finish(w, paid3.ID) wantClaim(t, f.claimCap(w, slots), nil, "queue drained") } func TestReservationCostsNothingWhenNoFreeJobWaits(t *testing.T) { f := newFixture(t, sched.Config{}) paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid } a, _ := f.enqueue(1, paid) b, _ := f.enqueue(2, paid) c, _ := f.enqueue(3, paid) // All three slots serve paid jobs, including the reserved one. wantClaim(t, f.claimCap("w", 3), a, "slot 1") wantClaim(t, f.claimCap("w", 3), b, "slot 2") wantClaim(t, f.claimCap("w", 3), c, "slot 3") } func TestSingleSlotHasNoReservation(t *testing.T) { f := newFixture(t, sched.Config{}) free1, _ := f.enqueue(1) paid1, _ := f.enqueue(2, func(p *sched.EnqueueParams) { p.Lane = db.LanePaid }) // With one slot in total, reserving it would lock paying users out. wantClaim(t, f.claimCap("w", 1), paid1, "the only slot") f.finish("w", paid1.ID) wantClaim(t, f.claimCap("w", 1), free1, "then free") } func TestReservationCountsTheWholeFleet(t *testing.T) { f := newFixture(t, sched.Config{}) paid := func(p *sched.EnqueueParams) { p.Lane = db.LanePaid } free1, _ := f.enqueue(1) paid1, _ := f.enqueue(2, paid) paid2, _ := f.enqueue(3, paid) // Two workers with one slot each: the fleet has two slots. Worker a // claims first; nobody knows about b yet, so capacity is 1 and paid // goes first. When b claims, the fleet is 2, one slot is busy, and the // last idle slot is reserved for the waiting free job. wantClaim(t, f.claimCap("a", 1), paid1, "worker a") wantClaim(t, f.claimCap("b", 1), free1, "worker b (reserved)") if got := f.s.Capacity(); got != 2 { t.Fatalf("fleet capacity = %d, want 2", got) } f.finish("a", paid1.ID) wantClaim(t, f.claimCap("a", 1), paid2, "worker a again") // A worker that stopped claiming drops out of the capacity. f.advance(2 * time.Minute) f.claimCap("a", 1) if got := f.s.Capacity(); got != 1 { t.Fatalf("fleet capacity after b went away = %d, want 1", got) } } func TestPromoteSkipsTheQueue(t *testing.T) { ctx := context.Background() f := newFixture(t, sched.Config{}) free1, _ := f.enqueue(1) free2, _ := f.enqueue(2) free3, _ := f.enqueue(3) ok, err := f.s.Promote(ctx, free3.ID) if err != nil || !ok { t.Fatalf("promote = %v, %v", ok, err) } if pos, _ := f.s.Position(ctx, f.job(free3.ID), 1); pos.Ahead != 0 { t.Fatalf("promoted job has %d jobs ahead, want 0", pos.Ahead) } if pos, _ := f.s.Position(ctx, f.job(free1.ID), 1); pos.Ahead != 1 { t.Fatalf("first free job has %d jobs ahead, want 1", pos.Ahead) } wantClaim(t, f.claim("w"), free3, "promoted job first") wantClaim(t, f.claim("w"), free1, "then FIFO") // Promoting twice, or promoting a job that is no longer waiting, is a // no-op that reports false. if ok, _ := f.s.Promote(ctx, free3.ID); ok { t.Fatal("a running job cannot be promoted") } if ok, _ := f.s.Promote(ctx, free2.ID); !ok { t.Fatal("a waiting free job can be promoted") } if ok, _ := f.s.Promote(ctx, free2.ID); ok { t.Fatal("a paid job cannot be promoted again") } } func TestPriorityIsFixedAtEnqueue(t *testing.T) { // The lane is stored with the job. Whatever happens to the pass that // paid for it while it waits, the job keeps its place. f := newFixture(t, sched.Config{}) free1, _ := f.enqueue(1) paid1, _ := f.enqueue(2, func(p *sched.EnqueueParams) { p.Lane = db.LanePaid p.Source = "own_pass" }) f.advance(48 * time.Hour) // far past any pass wantClaim(t, f.claim("w"), paid1, "paid job after its pass expired") wantClaim(t, f.claim("w"), free1, "then the free job") if d, _ := f.store.DeliveriesForJob(context.Background(), paid1.ID, db.DeliveryPending); len(d) != 1 || d[0].Source != "own_pass" { t.Fatalf("the delivery must remember what paid: %+v", d) } }