311. Duration::try_from_secs_f64 — Your Backoff Math Went Negative, and from_secs_f64 Panicked
Duration::from_secs_f64 panics on negative, NaN, or overflowing input — exactly the values float math produces when a jittered backoff dips below zero.
Computing a delay in float land is convenient: multiply a base by a factor, subtract some jitter, done. But the conversion back to Duration is a trap:
| |
The panic conditions are anything that isn’t representable: negative values, NaN, and anything too large for Duration. All three are one arithmetic slip away — a subtraction that dips below zero, a 0.0 / 0.0 hiding in a rate calculation, an overflowing powi on the retry counter.
The fallible version hands you a Result
Duration::try_from_secs_f64 (stable since 1.66) does the same conversion but returns Err instead of panicking:
| |
For backoff code, the natural move is to clamp the failure to something sane instead of crashing the retry loop:
| |
There’s a try_from_secs_f32 twin for f32 inputs.
Like classify in bite 309, the point is that the float you’re holding can be quietly unrepresentable — and the moment of conversion is where that surfaces. try_from_secs_f64 lets it surface as a value you can handle, not a panic in the middle of your retry loop.