devbox/internal/daemon/backoff_test.go
shoemoney 56b8be924b fix(daemon): stagger rescans, guard jitter panic, tighten backoff reset 🔁⚙️
- rescan tickers for all mounts started in lockstep, so every 60s they rebuilt
  manifests simultaneously (self-synchronized load spike on big trees). Stagger
  the first tick by a random offset.
- jittered() called rand.Int63n(int64(d/2)) which panics for sub-2ns durations
  (d/2==0). Guard it. (Latent: a panic in a recover-less goroutine.)
- healthyStream was 2min — 4x larger than typical SSE recycle (~30-60s), so a
  recycled-but-healthy stream never reset backoff and sat at the 30s ceiling.
  Lowered to 20s. Regression test for the jitter panic.
2026-06-23 02:38:46 -05:00

48 lines
1.3 KiB
Go

package daemon
import (
"testing"
"time"
)
func TestNextBackoffDoublesAndCaps(t *testing.T) {
// Starts at base, doubles, then saturates at the ceiling.
want := []time.Duration{
1 * time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second,
16 * time.Second, 30 * time.Second, 30 * time.Second,
}
got := time.Duration(0)
for i, w := range want {
got = nextBackoff(got)
if got != w {
t.Fatalf("step %d: nextBackoff = %s, want %s", i, got, w)
}
}
// A non-positive input restarts at base (used to reset after a healthy stream).
if d := nextBackoff(0); d != backoffBase {
t.Fatalf("reset: nextBackoff(0) = %s, want %s", d, backoffBase)
}
}
func TestJitteredStaysWithinBand(t *testing.T) {
const d = 8 * time.Second
lo, hi := d-d/4, d+d/4 // ±25%
for range 1000 {
j := jittered(d)
if j < lo || j >= hi {
t.Fatalf("jittered(%s) = %s, want in [%s,%s)", d, j, lo, hi)
}
}
if jittered(0) != 0 {
t.Fatal("jittered(0) should be 0")
}
}
// jittered must not panic on sub-2ns durations (rand.Int63n(0) would).
func TestJitteredTinyDurationsDontPanic(t *testing.T) {
for _, d := range []time.Duration{-5, -1, 0, 1, 2, 3} {
if got := jittered(d); d >= 2 && got < 0 {
t.Fatalf("jittered(%d) = %d, unexpectedly negative", d, got)
}
}
}