package runner import ( "context" "errors" "testing" "time" "amadan.net/oficina/equipo/internal/runnerproto" ) type refusedSource struct { claims []time.Time cancel context.CancelFunc } func (s *refusedSource) Poll(context.Context) ([]runnerproto.Assignment, error) { return []runnerproto.Assignment{{ID: "refused", Revision: 1}}, nil } func (s *refusedSource) Claim(context.Context, runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { s.claims = append(s.claims, time.Now()) if len(s.claims) == 3 { s.cancel() } return runnerproto.ClaimResponse{}, ErrClaimRefused } func TestClaimRefusalsBackOff(t *testing.T) { s, record, _, _ := cleanupFixture(t) record.Phase = "contained" mustJournal(t, s.save(context.Background(), record)) ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) defer cancel() source := &refusedSource{cancel: cancel} service := Service{Supervisor: s, Source: source} err := service.Run(ctx) if !errors.Is(err, context.Canceled) || len(source.claims) != 3 { t.Fatalf("refusal loop: %v %d", err, len(source.claims)) } for i, want := range []time.Duration{time.Second, 2 * time.Second} { if got := source.claims[i+1].Sub(source.claims[i]); got < want { t.Fatalf("claim refusal did not back off: delay=%s want>=%s", got, want) } } } func TestClaimBackoffBounds(t *testing.T) { for failures := 1; failures <= 20; failures++ { base := time.Second * time.Duration(1< 30*time.Second { base = 30 * time.Second } for range 20 { got := claimBackoffDelay(failures) if got < base || got > min(30*time.Second, base+base/4) { t.Fatalf("backoff %d = %s outside bounded exponential jitter", failures, got) } } } }