Files
uptimesebi/internal/schedule/schedule_test.go
T
Sebastian UnterschützandClaude Opus 5.5 050c9dd0a1
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m40s
ci / test (pull_request) Failing after 13m52s
ci / build (pull_request) Skipped
ci / image (pull_request) Skipped
feat(schedule): spread monitor runs evenly over their interval
A monitor's next run was its last due time plus the interval, so monitors
created together, by an import or a test, stayed due in the same second
for good, and late runs all gathered at the dispatch time. In prod, regions
fell behind in waves every interval although the checkers kept up on
average.

Each monitor now has a fixed phase within its interval, from its ID.
After the first run, still right away, it runs on its phase; late runs
snap to their next slot. Reconcile adds lost monitors on their phase, so
rebuilding a schedule causes no burst either. Monitors scheduled before
phases existed keep the old rule until reconciliation adds their phase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 16:06:40 +01:00

424 lines
13 KiB
Go

package schedule
import (
"context"
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
func newTest(t *testing.T) (*Scheduler, *time.Time) {
t.Helper()
url := os.Getenv("UPTIME_TEST_REDIS_URL")
if url == "" {
t.Skip("UPTIME_TEST_REDIS_URL not set")
}
opts, err := redis.ParseURL(url)
if err != nil {
t.Fatal(err)
}
rdb := redis.NewClient(opts)
t.Cleanup(func() { _ = rdb.Close() })
if err := rdb.FlushDB(context.Background()).Err(); err != nil {
t.Fatal(err)
}
now := time.UnixMilli(1_800_000_000_000)
s := New(rdb)
s.now = func() time.Time { return now }
return s, &now
}
func takeAll(t *testing.T, s *Scheduler, inst uuid.UUID) []Entry {
t.Helper()
e, err := s.Take(context.Background(), inst, 1000, 0)
if err != nil {
t.Fatalf("Take() failed: %v", err)
}
return e
}
func mustDispatch(t *testing.T, s *Scheduler) int {
t.Helper()
n, err := s.Dispatch(context.Background())
if err != nil {
t.Fatalf("Dispatch() failed: %v", err)
}
return n
}
// TestDispatchSpreadsRandomly runs many monitors against three instances of
// one region and expects every instance to get a substantial share.
func TestDispatchSpreadsRandomly(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
insts := []uuid.UUID{uuid.New(), uuid.New(), uuid.New()}
for _, in := range insts {
if err := s.Heartbeat(ctx, "eu", in); err != nil {
t.Fatal(err)
}
}
const monitors = 600
for range monitors {
if err := s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil); err != nil {
t.Fatal(err)
}
}
if n := mustDispatch(t, s); n != monitors {
t.Fatalf("Dispatch() = %d, want %d", n, monitors)
}
total := 0
for _, in := range insts {
got := len(takeAll(t, s, in))
total += got
if got < monitors/3-80 || got > monitors/3+80 {
t.Errorf("instance received %d of %d jobs, want about %d", got, monitors, monitors/3)
}
}
if total != monitors {
t.Errorf("instances received %d jobs, want %d", total, monitors)
}
}
func TestDispatchReschedulesAndKeepsRegionsApart(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
eu, us := uuid.New(), uuid.New()
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
m := Monitor{ID: uuid.New(), Interval: 30 * time.Second, Regions: []string{"eu", "us"}}
_ = s.Upsert(ctx, m, nil)
mustDispatch(t, s)
for _, in := range []uuid.UUID{eu, us} {
if got := takeAll(t, s, in); len(got) != 1 || got[0].MonitorID != m.ID || !got[0].ScheduledAt.Equal(*now) {
t.Errorf("instance jobs = %+v, want one run of %v at %v", got, m.ID, *now)
}
}
if n := mustDispatch(t, s); n != 0 {
t.Errorf("Dispatch() before next interval = %d, want 0", n)
}
// The next run is on the monitor's phase, at least half an interval
// after the first one.
next := dueAt(t, s, "eu", m.ID)
if off := (next.UnixMilli() - phaseOf(m.ID, m.Interval)) % m.Interval.Milliseconds(); off != 0 {
t.Errorf("next run %v is %dms off its phase", next, off)
}
if gap := next.Sub(*now); gap < m.Interval/2 || gap > 3*m.Interval/2 {
t.Errorf("next run %v after the first, want between half and one and a half intervals", gap)
}
*now = next
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
if n := mustDispatch(t, s); n != 2 {
t.Errorf("Dispatch() on the next slot = %d, want 2", n)
}
// Leaving a region stops runs there.
_ = s.Upsert(ctx, Monitor{ID: m.ID, Interval: m.Interval, Regions: []string{"eu"}}, m.Regions)
takeAll(t, s, eu)
takeAll(t, s, us)
*now = now.Add(30 * time.Second)
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
mustDispatch(t, s)
if got := takeAll(t, s, us); len(got) != 0 {
t.Errorf("us instance got %d jobs after region removal, want 0", len(got))
}
}
func TestStaleInstanceJobsMoveToLiveOne(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
dead, alive := uuid.New(), uuid.New()
_ = s.Heartbeat(ctx, "eu", dead)
m := Monitor{ID: uuid.New(), Interval: time.Hour, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
mustDispatch(t, s)
*now = now.Add(StaleAfter + time.Second)
_ = s.Heartbeat(ctx, "eu", alive)
mustDispatch(t, s)
got := takeAll(t, s, alive)
if len(got) != 1 || got[0].MonitorID != m.ID {
t.Errorf("live instance jobs = %+v, want the stale instance's run", got)
}
if n, _ := s.Instances(ctx, "eu"); n != 1 {
t.Errorf("Instances() = %d, want 1", n)
}
}
func TestReleaseHandsJobsOver(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
leaving, staying := uuid.New(), uuid.New()
_ = s.Heartbeat(ctx, "eu", leaving)
m := Monitor{ID: uuid.New(), Interval: time.Hour, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
mustDispatch(t, s)
_ = s.Heartbeat(ctx, "eu", staying)
if err := s.Release(ctx, "eu", leaving); err != nil {
t.Fatal(err)
}
if got := takeAll(t, s, staying); len(got) != 1 {
t.Errorf("staying instance got %d jobs, want 1", len(got))
}
}
func TestRemoveAndReconcile(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
keep := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
gone := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, keep, nil)
_ = s.Upsert(ctx, gone, nil)
if err := s.Reconcile(ctx, []Monitor{keep}, s.now().Add(time.Millisecond)); err != nil {
t.Fatal(err)
}
mustDispatch(t, s)
got := takeAll(t, s, in)
if len(got) != 1 || got[0].MonitorID != keep.ID {
t.Errorf("jobs after Reconcile = %+v, want only %v", got, keep.ID)
}
if s.rdb.HExists(ctx, keyPhases, gone.ID.String()).Val() {
t.Error("Reconcile left the phase of a removed monitor")
}
}
func TestTakeWaits(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
in := uuid.New()
start := time.Now()
got, err := s.Take(ctx, in, 10, 300*time.Millisecond)
if err != nil || len(got) != 0 {
t.Fatalf("Take() on empty queue = %v, %v", got, err)
}
// Not rounded up to the second that BLPOP counts in.
if waited := time.Since(start); waited < 250*time.Millisecond || waited > 800*time.Millisecond {
t.Errorf("Take() returned after %v, want it to wait about 300ms", waited)
}
}
func TestTakeGetsAJobDuringAShortWait(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
in, monitor := uuid.New(), uuid.New()
go func() {
time.Sleep(100 * time.Millisecond)
s.rdb.RPush(ctx, jobsPrefix+in.String(), monitor.String()+"|1800000000000")
}()
got, err := s.Take(ctx, in, 10, 600*time.Millisecond)
if err != nil || len(got) != 1 || got[0].MonitorID != monitor {
t.Fatalf("Take() = %v, %v; want the job pushed while waiting", got, err)
}
}
func TestTakeReturnsWhenCancelled(t *testing.T) {
s, _ := newTest(t)
ctx, cancel := context.WithCancel(context.Background())
go func() { time.Sleep(100 * time.Millisecond); cancel() }()
start := time.Now()
_, _ = s.Take(ctx, uuid.New(), 10, 20*time.Second)
if took := time.Since(start); took > 2*time.Second {
t.Errorf("Take() returned %v after cancellation, want within about a second", took)
}
}
// TestReconcileKeepsMonitorsCreatedDuringRead covers a monitor created after
// reconciliation read the database but before it pruned Redis.
func TestReconcileKeepsMonitorsCreatedDuringRead(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
asOf := *now
*now = now.Add(50 * time.Millisecond)
fresh := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, fresh, nil)
if err := s.Reconcile(ctx, nil, asOf); err != nil {
t.Fatal(err)
}
mustDispatch(t, s)
if got := takeAll(t, s, in); len(got) != 1 || got[0].MonitorID != fresh.ID {
t.Errorf("jobs after Reconcile = %+v, want the freshly created monitor", got)
}
}
func TestOverdueCountsRunsLeftBehind(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
for range 2 {
_ = s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil)
}
overdue := func() int64 {
t.Helper()
n, err := s.Overdue(ctx, "eu", 10*time.Second)
if err != nil {
t.Fatalf("Overdue() failed: %v", err)
}
return n
}
if n := overdue(); n != 0 {
t.Errorf("Overdue() right after scheduling = %d, want 0", n)
}
// No instance takes the runs.
*now = now.Add(11 * time.Second)
mustDispatch(t, s)
if n := overdue(); n != 2 {
t.Errorf("Overdue() without instances = %d, want 2", n)
}
busy := uuid.New()
_ = s.Heartbeat(ctx, "eu", busy)
mustDispatch(t, s)
// The queued runs were due 11 seconds ago and are still waiting.
if n := overdue(); n != 2 {
t.Errorf("Overdue() with the runs left in a queue = %d, want 2", n)
}
if _, err := s.Take(ctx, busy, 10, 0); err != nil {
t.Fatal(err)
}
if n := overdue(); n != 0 {
t.Errorf("Overdue() after the instance took the runs = %d, want 0", n)
}
}
func dueAt(t *testing.T, s *Scheduler, region string, id uuid.UUID) time.Time {
t.Helper()
score, err := s.rdb.ZScore(context.Background(), keyDue(region), id.String()).Result()
if err != nil {
t.Fatalf("no due time for %v in %s: %v", id, region, err)
}
return time.UnixMilli(int64(score))
}
// TestPhaseSpreadsBurst creates many monitors at once. Their first runs are
// right away; after that they spread over the interval instead of all
// running in the same second again.
func TestPhaseSpreadsBurst(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
const monitors = 600
for range monitors {
if err := s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil); err != nil {
t.Fatal(err)
}
}
perSecond := make([]int, 180)
for sec := range perSecond {
_ = s.Heartbeat(ctx, "eu", in)
perSecond[sec] = mustDispatch(t, s)
takeAll(t, s, in)
*now = now.Add(time.Second)
}
if perSecond[0] != monitors {
t.Errorf("first second dispatched %d, want all %d first runs", perSecond[0], monitors)
}
total, peak := 0, 0
for _, n := range perSecond[60:] {
total += n
peak = max(peak, n)
}
if total != 2*monitors {
t.Errorf("seconds 60 to 180 dispatched %d runs, want %d: one per monitor and minute", total, 2*monitors)
}
// 10 per second on average; all 600 at once without phases.
if peak > 30 {
t.Errorf("busiest second dispatched %d runs, want them spread at about 10 per second", peak)
}
}
// TestLateRunSnapsToPhase dispatches runs long overdue. Each comes back on
// its own phase instead of all gathering at the dispatch time.
func TestLateRunSnapsToPhase(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
ms := []Monitor{}
for range 50 {
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
ms = append(ms, m)
_ = s.Upsert(ctx, m, nil)
}
_ = s.Heartbeat(ctx, "eu", in)
mustDispatch(t, s)
// No instance for three intervals.
*now = now.Add(3*time.Minute + 7*time.Second)
_ = s.Heartbeat(ctx, "eu", in)
if n := mustDispatch(t, s); n != len(ms) {
t.Fatalf("Dispatch() of the overdue runs = %d, want %d", n, len(ms))
}
distinct := map[time.Time]bool{}
for _, m := range ms {
got := dueAt(t, s, "eu", m.ID)
want := time.UnixMilli(nextSlot(now.UnixMilli(), phaseOf(m.ID, m.Interval), m.Interval.Milliseconds()))
if !got.Equal(want) {
t.Errorf("monitor next due %v, want its next slot %v", got, want)
}
distinct[got] = true
}
if len(distinct) < len(ms)-5 {
t.Errorf("%d monitors share %d due times, want them apart", len(ms), len(distinct))
}
}
// TestReconcileAddsOnPhase rebuilds a lost schedule without a burst.
func TestReconcileAddsOnPhase(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
ms := []Monitor{}
for range 20 {
ms = append(ms, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}})
}
if err := s.Reconcile(ctx, ms, *now); err != nil {
t.Fatal(err)
}
for _, m := range ms {
want := time.UnixMilli(nextSlot(now.UnixMilli(), phaseOf(m.ID, m.Interval), m.Interval.Milliseconds()))
if got := dueAt(t, s, "eu", m.ID); !got.Equal(want) {
t.Errorf("reconciled monitor due %v, want its slot %v", got, want)
}
}
if n := mustDispatch(t, s); n != 0 {
t.Errorf("Dispatch() right after Reconcile = %d, want 0", n)
}
}
// TestPhaseFallback covers monitors scheduled before phases existed.
func TestPhaseFallback(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
s.rdb.HDel(ctx, keyPhases, m.ID.String())
mustDispatch(t, s)
if got, want := dueAt(t, s, "eu", m.ID), now.Add(time.Minute); !got.Equal(want) {
t.Errorf("monitor without phase next due %v, want one interval later, %v", got, want)
}
}
func TestNextSlot(t *testing.T) {
for _, c := range []struct{ now, phase, interval, want int64 }{
{now: 100, phase: 30, interval: 60, want: 150},
{now: 150, phase: 30, interval: 60, want: 210},
{now: 10, phase: 30, interval: 60, want: 30},
{now: 100, phase: 0, interval: 0, want: 100},
} {
if got := nextSlot(c.now, c.phase, c.interval); got != c.want {
t.Errorf("nextSlot(%d, %d, %d) = %d, want %d", c.now, c.phase, c.interval, got, c.want)
}
}
}