Coverage for src/robot_dispatch/domain/policies.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-07 17:18 +0000

1from __future__ import annotations 

2 

3import random 

4from dataclasses import dataclass 

5 

6 

7@dataclass(frozen=True) 

8class RetryPolicy: 

9 """Exponential backoff with a cap and optional jitter. 

10 

11 Delays are used both for re-queueing tasks after a failed attempt and for 

12 re-delivering broken messages back to the consumer, so a dead robot or a 

13 crashed consumer never turns into a hot retry loop. 

14 """ 

15 

16 base_delay_seconds: float = 5.0 

17 max_delay_seconds: float = 120.0 

18 jitter_ratio: float = 0.2 

19 

20 def delay_seconds(self, attempt: int, *, rng: random.Random | None = None) -> float: 

21 if attempt < 1: 

22 raise ValueError("attempt must be >= 1") 

23 raw = self.base_delay_seconds * (2 ** (attempt - 1)) 

24 capped = min(raw, self.max_delay_seconds) 

25 if self.jitter_ratio <= 0: 

26 return capped 

27 generator = rng or random 

28 spread = capped * self.jitter_ratio 

29 return max(0.0, capped + generator.uniform(-spread, spread)) 

30 

31 

32def should_retry(attempts_made: int, max_attempts: int) -> bool: 

33 return attempts_made < max_attempts