devbox/internal/daemon/backoff.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

46 lines
1.4 KiB
Go

package daemon
import (
"math/rand"
"time"
)
// Reconnect backoff bounds: start at 1s, double to a 30s ceiling. A stream that
// stayed up at least healthyStream is treated as a transient drop (reset to base),
// not a hard failure — so a hub/proxy that recycles SSE connections periodically
// doesn't leave the daemon stuck at the ceiling with a 30s event lag.
//
// healthyStream must sit BELOW the recycle interval (proxies commonly cap idle
// SSE around 30-60s): 2 minutes was 4x too large to ever fire, so a recycled-but-
// healthy stream still ratcheted backoff up to the ceiling.
const (
backoffBase = 1 * time.Second
backoffMax = 30 * time.Second
healthyStream = 20 * time.Second
)
// nextBackoff returns the next clean (un-jittered) backoff: base, then doubling
// up to backoffMax. Pass the previous clean value; pass <=0 to (re)start at base.
func nextBackoff(prev time.Duration) time.Duration {
switch {
case prev <= 0:
return backoffBase
case prev*2 >= backoffMax:
return backoffMax
default:
return prev * 2
}
}
// jittered spreads a backoff by ±25% so a fleet that all lost the hub at once
// doesn't reconnect in lockstep (thundering herd). Returns 0 unchanged.
func jittered(d time.Duration) time.Duration {
if d <= 0 {
return 0
}
half := int64(d / 2)
if half <= 0 {
return d // sub-2ns: no room to jitter, and rand.Int63n(0) would panic
}
return d + time.Duration(rand.Int63n(half)) - d/4
}