Skip to content

Commit 7341924

Browse files
Document the retry loop invariant on the final raise last_error
The `# type: ignore[misc]` on the final `raise last_error` silenced a real mypy complaint (`last_error` is typed `Exception | None`) without explaining why the raise is safe. The reason is a loop invariant: the only non-`return` way out of the loop is the `break` on the final attempt, which runs immediately after `last_error = e`, and the guard at line 33 rejects `max_attempts < 1`. Expand the comment so the next reader can verify the claim without tracing the function. Also add a test that exercises the one-attempt edge case — `range(1)` is the boundary where the loop body must set `last_error` and immediately break on the first iteration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 27f7aa3 commit 7341924

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

src/dqliteclient/retry.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,7 @@ async def retry_with_backoff[T](
5353

5454
await asyncio.sleep(delay)
5555

56+
# last_error is non-None here: the break on the final attempt only
57+
# runs after ``last_error = e`` executes, and max_attempts < 1 is
58+
# rejected above. mypy can't see the loop invariant.
5659
raise last_error # type: ignore[misc]

tests/test_retry.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,23 @@ async def always_fail() -> str:
4747

4848
assert call_count == 3
4949

50+
async def test_max_attempts_one_raises_on_first_failure(self) -> None:
51+
"""Edge case: with ``max_attempts=1`` the loop breaks on its first
52+
iteration. Covers the ``if attempt == max_attempts - 1: break``
53+
path that the final ``raise last_error`` relies on.
54+
"""
55+
call_count = 0
56+
57+
async def fail_once() -> str:
58+
nonlocal call_count
59+
call_count += 1
60+
raise ValueError("fail")
61+
62+
with pytest.raises(ValueError, match="fail"):
63+
await retry_with_backoff(fail_once, max_attempts=1, base_delay=0.01)
64+
65+
assert call_count == 1
66+
5067
async def test_max_attempts_zero_raises_value_error(self) -> None:
5168
async def should_not_be_called() -> str:
5269
raise AssertionError("Should not be called with max_attempts=0")

0 commit comments

Comments
 (0)