Module: Braintrust::Internal::Retry

Defined in:
lib/braintrust/internal/retry.rb

Constant Summary collapse

MAX_RETRIES =
7
BASE_DELAY =
1.0
MAX_DELAY =
8.0

Class Method Summary collapse

Class Method Details

.with_backoff(max_retries: MAX_RETRIES, base_delay: BASE_DELAY, max_delay: MAX_DELAY, until: nil, &task) ⇒ Object

Retry a block with exponential backoff.

The block is the task to attempt. Its return value is captured each attempt.

Examples:

Simple: retry until truthy

conn = Retry.with_backoff(max_retries: 5) { try_connect }

With condition: retry until non-empty

data = Retry.with_backoff(until: ->(r) { r.any? }) { api.fetch }

Parameters:

  • max_retries (Integer) (defaults to: MAX_RETRIES)

    Maximum number of retries after the first attempt

  • base_delay (Float) (defaults to: BASE_DELAY)

    Initial delay in seconds (doubles each retry)

  • max_delay (Float) (defaults to: MAX_DELAY)

    Cap on delay between retries

  • until (Proc, nil) (defaults to: nil)

    Optional condition — receives block result, truthy stops retrying. When omitted, the block result’s own truthiness decides.

Returns:

  • The last block result (whether retries were exhausted or condition was met)



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/braintrust/internal/retry.rb', line 27

def self.with_backoff(max_retries: MAX_RETRIES, base_delay: BASE_DELAY, max_delay: MAX_DELAY, until: nil, &task)
  check = binding.local_variable_get(:until)
  result = task.call
  retries = 0
  while retries < max_retries && !(check ? check.call(result) : result)
    retries += 1
    delay = [base_delay * (2**(retries - 1)), max_delay].min
    sleep(delay)
    result = task.call
  end
  result
end