openai-go icon indicating copy to clipboard operation
openai-go copied to clipboard

fix: prevent panic in retryDelay when delay overflows or is negative

Open dev-kas opened this issue 2 months ago • 0 comments

Description

This PR fixes a panic in retryDelay that occurs when the computed delay becomes negative due to integer overflow in time.Duration for large retryCount values

Problem

  • The existing exponential backoff calculation (0.5 * 2^retryCount * time.Second) can exceed the maximum int64 for time.Duration, wrapping around to negative values.
  • While I was using the API, the panic was observed at retryCount = 35, where the computed delay wrapped to -9223372036854775808.
  • When delay is negative, the subsequent rand.Int63n(delay/4) call panics.

Fix

  • Clamp delay to a safe range [1s, maxDelay] before applying jitter.
  • Ensure the jitter argument to rand.Int63n is always >= 1 second, preventing it from receiving invalid (<=0) arguments.
  • Subtract jitter safely from the clamped delay.

Impact

  • Prevents panics on high retry counts.
  • Maintains existing exponential backoff behavior within reasonable limits.

dev-kas avatar Sep 20 '25 23:09 dev-kas