Skip to content

Commit 6325345

Browse files
lesnik512claude
andcommitted
feat(resilience): full-jitter exponential backoff helper
Implements full_jitter_delay() per AWS's "full jitter" formulation: sleep = uniform(0, min(max_delay, base_delay * 2**attempt_index)). Injects a deterministic _random_uniform kwarg for testability. Adds tests/test_backoff.py to keep 100% coverage gate green until Task 7 adds Retry integration tests. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 7593f1d commit 6325345

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,21 @@
11
"""Full-jitter exponential backoff helper (private)."""
2+
3+
import random
4+
from collections.abc import Callable
5+
6+
7+
def full_jitter_delay(
8+
attempt_index: int,
9+
*,
10+
base_delay: float,
11+
max_delay: float,
12+
_random_uniform: Callable[[float, float], float] = random.uniform,
13+
) -> float:
14+
"""Return a backoff delay using AWS's "full jitter" formulation.
15+
16+
sleep = uniform(0, min(max_delay, base_delay * 2 ** attempt_index))
17+
18+
`attempt_index` is 0 for the first retry, 1 for the second, etc.
19+
"""
20+
ceiling = min(max_delay, base_delay * (2**attempt_index))
21+
return _random_uniform(0.0, ceiling)

‎tests/test_backoff.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""Unit test for the full-jitter backoff helper.
2+
3+
Integration via Retry middleware lands in Task 7's tests; this file exists
4+
only to keep the 100% coverage gate passing through Tasks 6-7.
5+
"""
6+
7+
from httpware.middleware.resilience._backoff import full_jitter_delay
8+
9+
10+
BASE_DELAY = 0.1
11+
MAX_DELAY = 5.0
12+
13+
14+
def test_full_jitter_delay_bounded_by_min_of_max_and_exponential() -> None:
15+
# attempt_index=0, base=0.1 → ceiling = min(5.0, 0.1*1) = 0.1
16+
delay = full_jitter_delay(0, base_delay=BASE_DELAY, max_delay=MAX_DELAY)
17+
assert 0.0 <= delay <= BASE_DELAY
18+
19+
20+
def test_full_jitter_delay_capped_at_max_delay() -> None:
21+
# attempt_index=10, base=0.1 → exp = 102.4 → capped to 5.0
22+
delay = full_jitter_delay(10, base_delay=BASE_DELAY, max_delay=MAX_DELAY)
23+
assert 0.0 <= delay <= MAX_DELAY
24+
25+
26+
def test_full_jitter_delay_uses_injected_random() -> None:
27+
# Inject a deterministic mock that returns the upper bound
28+
delay = full_jitter_delay(
29+
0,
30+
base_delay=BASE_DELAY,
31+
max_delay=MAX_DELAY,
32+
_random_uniform=lambda _lo, hi: hi,
33+
)
34+
assert delay == BASE_DELAY

0 commit comments

Comments
 (0)