diff --git a/internal/daemon/backoff.go b/internal/daemon/backoff.go index 1d692e3..1d9f3c9 100644 --- a/internal/daemon/backoff.go +++ b/internal/daemon/backoff.go @@ -7,12 +7,16 @@ import ( // 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 that recycles SSE connections every ~30s doesn't -// leave the daemon stuck at the ceiling with a 30s event lag. +// 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 = 2 * time.Minute + healthyStream = 20 * time.Second ) // nextBackoff returns the next clean (un-jittered) backoff: base, then doubling @@ -34,5 +38,9 @@ func jittered(d time.Duration) time.Duration { if d <= 0 { return 0 } - return d + time.Duration(rand.Int63n(int64(d/2))) - d/4 + 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 } diff --git a/internal/daemon/backoff_test.go b/internal/daemon/backoff_test.go index e835e29..03291c5 100644 --- a/internal/daemon/backoff_test.go +++ b/internal/daemon/backoff_test.go @@ -37,3 +37,12 @@ func TestJitteredStaysWithinBand(t *testing.T) { 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) + } + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index da6daf3..5ebdd51 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -7,6 +7,7 @@ package daemon import ( "context" "log" + "math/rand" "sync" "time" @@ -162,8 +163,15 @@ func (d *Daemon) runMount(ctx context.Context, m config.Mount) { }() // Periodic rescan: safety net so the mount keeps converging even if the - // watcher never started (inotify limit) or an event was missed. + // watcher never started (inotify limit) or an event was missed. Stagger the + // first tick by a random offset so many mounts don't all rebuild manifests in + // lockstep every interval (a self-synchronized load spike on big trees). go func() { + select { + case <-ctx.Done(): + return + case <-time.After(time.Duration(rand.Int63n(int64(rescanInterval)))): + } t := time.NewTicker(rescanInterval) defer t.Stop() for {