class Permanent(Exception): """A failure that retrying cannot fix.""" def call_with_retry(fn, attempts=3, sleep=None): """Retries transient failures with exponential backoff. A `Permanent` failure is raised immediately — retrying it only wastes calls. `sleep` is injected so the delays are observable in tests. """ last = None for attempt in range(attempts): try: return fn() except Permanent: raise except Exception as error: last = error if attempt < attempts - 1 and sleep is not None: sleep(2 ** attempt) raise last