refactor(downloader): keep download()'s retry counters and their resets in one RetryBudget

This commit is contained in:
imSp4rky
2026-12-04 15:29:11 -07:00
parent 8b76bb47a6
commit cc40deeb5c
2 changed files with 279 additions and 49 deletions
+184
View File
@@ -0,0 +1,184 @@
"""RetryBudget, the retry counters of one download() call, and how download() feeds it."""
import importlib
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import requests as rq
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import RetryAction, RetryBudget, RetryVerdict
dl = importlib.import_module("unshackle.core.downloaders.requests")
MB = 1024 * 1024
@pytest.fixture(autouse=True)
def no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(dl, "retry_sleep", lambda exc, attempts: float(attempts))
def fail(
budget: RetryBudget, outage: bool = False, progress: int = 0, item_range: bool = False, stop: bool = False
) -> RetryVerdict:
return budget.on_failure(OSError("cut"), outage=outage, progress=progress, item_range=item_range, stop=stop)
@pytest.mark.parametrize(
("outage", "limit"),
[(False, dl.MAX_ATTEMPTS), (True, dl.OUTAGE_ATTEMPTS)],
ids=["attempts", "outages"],
)
def test_budget_gives_up_on_the_limit_th_failure(outage: bool, limit: int) -> None:
budget = RetryBudget()
verdicts = [fail(budget, outage=outage) for _ in range(limit)]
assert [v.action for v in verdicts] == [RetryAction.RETRY] * (limit - 1) + [RetryAction.GIVE_UP]
assert [v.tries for v in verdicts[:-1]] == list(range(1, limit))
assert [v.delay for v in verdicts[:-1]] == [float(t) for t in range(1, limit)]
assert all(v.limit == limit for v in verdicts)
assert budget.failures == limit
def test_outages_and_attempts_count_apart() -> None:
budget = RetryBudget()
for _ in range(dl.MAX_ATTEMPTS - 1):
assert fail(budget).action is RetryAction.RETRY
for _ in range(dl.OUTAGE_ATTEMPTS - 1):
assert fail(budget, outage=True).action is RetryAction.RETRY
assert fail(budget).action is RetryAction.GIVE_UP
assert budget.failures == dl.MAX_ATTEMPTS + dl.OUTAGE_ATTEMPTS - 1
def test_stop_gives_up_at_once_and_still_counts_the_failure() -> None:
budget = RetryBudget()
assert fail(budget, stop=True).action is RetryAction.GIVE_UP
assert budget.failures == 1
@pytest.mark.parametrize(
("offsets", "refreshed"),
[((None,), True), ((5,), True), ((5, 5), False), ((5, 3), False), ((5, 6), True)],
ids=["sub-range", "new-high", "same-offset", "below-high", "past-high"],
)
def test_progress_refreshes_both_counters(offsets: tuple[int | None, ...], refreshed: bool) -> None:
budget = RetryBudget()
for offset in offsets[:-1]:
budget.on_progress(offset)
fail(budget)
fail(budget, outage=True)
budget.on_progress(offsets[-1])
assert (budget.attempts, budget.outages) == ((1, 0) if refreshed else (2, 1))
def test_resume_spends_no_attempt_and_halves_the_request_limit(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(dl, "MIN_REQUEST_CHUNK", dl.REQUEST_CHUNK_SIZE // 4)
budget = RetryBudget()
limits = []
for _ in range(4):
verdict = fail(budget, progress=dl.MIN_RESUME_PROGRESS)
assert (verdict.action, verdict.tries) == (RetryAction.RESUME, 1)
limits.append(budget.request_limit)
assert limits == [dl.REQUEST_CHUNK_SIZE, dl.REQUEST_CHUNK_SIZE // 2] + [dl.REQUEST_CHUNK_SIZE // 4] * 2
assert (budget.resumes, budget.attempts) == (4, 1)
def test_item_range_resume_keeps_the_request_whole() -> None:
budget = RetryBudget()
assert fail(budget, progress=MB, item_range=True).action is RetryAction.RESUME
assert budget.request_limit is None
def test_small_progress_is_a_retry() -> None:
budget = RetryBudget()
assert fail(budget, progress=dl.MIN_RESUME_PROGRESS - 1).action is RetryAction.RETRY
assert (budget.resumes, budget.attempts) == (0, 2)
def test_resumes_are_bounded(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(dl, "MAX_RESUMES", 2)
budget = RetryBudget()
actions = [fail(budget, progress=MB).action for _ in range(2 + dl.MAX_ATTEMPTS)]
assert actions == [RetryAction.RESUME] * 2 + [RetryAction.RETRY] * (dl.MAX_ATTEMPTS - 1) + [RetryAction.GIVE_UP]
BODY = bytes(range(256)) * 64
STEP = 1024
class _StepServer(ThreadingHTTPServer):
"""Answers each range with at most STEP bytes; with ``fail_once`` the first request for each range gets a 503."""
daemon_threads = True
def __init__(self, fail_once: bool) -> None:
self.fail_once = fail_once
self.seen: set[str | None] = set()
super().__init__(("127.0.0.1", 0), _StepHandler)
self.url = f"http://127.0.0.1:{self.server_address[1]}/a"
class _StepHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
disable_nagle_algorithm = True
server: _StepServer
def log_message(self, *_: object) -> None:
pass
def do_GET(self) -> None:
header = self.headers.get("Range")
if self.server.fail_once and header not in self.server.seen:
self.server.seen.add(header)
self.send_response(503)
self.send_header("Content-Length", "0")
self.end_headers()
return
start_s, _, end_s = (header or "bytes=0-").removeprefix("bytes=").partition("-")
start = int(start_s)
end = min(int(end_s) if end_s else len(BODY) - 1, start + STEP - 1)
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
self.send_header("Content-Length", str(end - start + 1))
self.end_headers()
self.wfile.write(BODY[start : end + 1])
@pytest.fixture
def serve(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(dl, "retry_sleep", lambda exc, attempts: 0.0)
monkeypatch.setattr(dl, "MAX_ATTEMPTS", 3)
monkeypatch.setattr(dl, "MIN_RESUME_PROGRESS", STEP)
monkeypatch.setattr(dl, "REQUEST_CHUNK_SIZE", STEP)
DOWNLOAD_CANCELLED.clear()
servers: list[_StepServer] = []
def start(fail_once: bool) -> _StepServer:
server = _StepServer(fail_once)
threading.Thread(target=server.serve_forever, daemon=True).start()
servers.append(server)
return server
yield start
for server in servers:
server.shutdown()
server.server_close()
DOWNLOAD_CANCELLED.clear()
@pytest.mark.parametrize("fail_once", [False, True], ids=["clean", "each-step-fails-once"])
@pytest.mark.parametrize("part_mode", [False, True], ids=["resume", "part"])
def test_download_refreshes_the_budget_on_each_step(tmp_path, serve, part_mode: bool, fail_once: bool) -> None:
server = serve(fail_once)
save_path = tmp_path / "a.bin"
part = {}
if part_mode:
save_path.write_bytes(bytes(len(BODY)))
part = {"part_offset": 0, "part_end": len(BODY) - 1}
retried: list[Exception] = []
list(dl.download(url=server.url, save_path=save_path, session=rq.Session(), on_retry=retried.append, **part))
assert save_path.read_bytes() == BODY
assert len(retried) == (len(BODY) // STEP if fail_once else 0)
+95 -49
View File
@@ -18,12 +18,13 @@ from concurrent.futures.thread import ThreadPoolExecutor
from copy import copy from copy import copy
from datetime import UTC, datetime from datetime import UTC, datetime
from email.utils import parsedate_to_datetime from email.utils import parsedate_to_datetime
from enum import Enum
from functools import partial from functools import partial
from http.cookiejar import CookieJar from http.cookiejar import CookieJar
from pathlib import Path from pathlib import Path
from queue import Empty, Queue from queue import Empty, Queue
from string import Formatter from string import Formatter
from typing import Any, cast from typing import Any, NamedTuple, cast
from requests import Session from requests import Session
from requests.adapters import HTTPAdapter, Retry from requests.adapters import HTTPAdapter, Retry
@@ -400,6 +401,76 @@ def retries_exhausted(exc: BaseException) -> bool:
return any(str(note).startswith(GAVE_UP_NOTE) for note in getattr(exc, "__notes__", ())) return any(str(note).startswith(GAVE_UP_NOTE) for note in getattr(exc, "__notes__", ()))
class RetryAction(Enum):
GIVE_UP = "give_up"
RESUME = "resume"
RETRY = "retry"
class RetryVerdict(NamedTuple):
action: RetryAction
limit: int
delay: float = 0.0
tries: int = 0
class RetryBudget:
"""The retry counters of one download() call.
A failure spends MAX_ATTEMPTS, or OUTAGE_ATTEMPTS on a separate counter for an outage, and progress refreshes
both, so ``failures`` never resets: the give-up note reports it.
"""
def __init__(self) -> None:
self.attempts = 1
self.outages = 0
self.failures = 0
self.resumes = 0
self.request_limit: int | None = None
self.high_water = 0
def on_progress(self, offset: int | None = None) -> None:
"""Refresh the budget after a whole sub-range, or when a resume ``offset`` passes the high water."""
if offset is not None:
if offset <= self.high_water:
return
self.high_water = offset
self.attempts = 1
self.outages = 0
def on_failure(
self, exc: Exception, *, outage: bool, progress: int, item_range: bool, stop: bool = False
) -> RetryVerdict:
"""Count a failure and tell download() to give up, resume or retry after ``delay``.
``progress`` is the bytes secured since the try started; ``stop`` gives up at once (cancel, disk error).
A cut after MIN_RESUME_PROGRESS new bytes is a resume and spends no attempt, because a CDN that throttles a
flow and closes it every few seconds would otherwise spend MAX_ATTEMPTS partway into a large part.
"""
self.failures += 1
if outage:
self.outages += 1
limit = OUTAGE_ATTEMPTS if outage else MAX_ATTEMPTS
if stop or (self.outages if outage else self.attempts) >= limit:
return RetryVerdict(RetryAction.GIVE_UP, limit)
action = RetryAction.RETRY
if progress >= MIN_RESUME_PROGRESS and self.resumes < MAX_RESUMES:
action = RetryAction.RESUME
self.resumes += 1
self.attempts = 0
if not item_range:
# the host cut a body it was already delivering, so ask for less next time
self.request_limit = (
REQUEST_CHUNK_SIZE
if self.request_limit is None
else max(MIN_REQUEST_CHUNK, self.request_limit // 2)
)
tries = self.outages if outage else max(1, self.attempts)
if not outage:
self.attempts += 1
return RetryVerdict(action, limit, retry_sleep(exc, tries), tries)
def is_requests_session(session: Any) -> bool: def is_requests_session(session: Any) -> bool:
"""Whether the HTTP session is a standard requests.Session (it has ``resp.raw``).""" """Whether the HTTP session is a standard requests.Session (it has ``resp.raw``)."""
return isinstance(session, Session) return isinstance(session, Session)
@@ -873,16 +944,10 @@ def download(
mode = Mode.PART if part_mode else Mode.ITEM if item_range else Mode.RESUME mode = Mode.PART if part_mode else Mode.ITEM if item_range else Mode.RESUME
part = (part_offset, part_end) if part_offset is not None and part_end is not None else None part = (part_offset, part_end) if part_offset is not None and part_end is not None else None
attempts = 1 budget = RetryBudget()
outages = 0
# attempts resets on progress, so the give-up note counts failures on their own
failures = 0
started = _time() started = _time()
written = 0 written = 0
resumes = 0
request_limit: int | None = None
known_total: int | None = None known_total: int | None = None
high_water = 0
progress_seeded = False progress_seeded = False
while True: while True:
if claimed is not None and claimed(): if claimed is not None and claimed():
@@ -908,16 +973,16 @@ def download(
if part_mode and part_offset is not None and part_end is not None: # spelled so mypy narrows if part_mode and part_offset is not None and part_end is not None: # spelled so mypy narrows
req_start = part_offset + written req_start = part_offset + written
chunk_end = part_end chunk_end = part_end
if request_limit is not None and part_end - req_start + 1 > request_limit: if budget.request_limit is not None and part_end - req_start + 1 > budget.request_limit:
chunk_end = req_start + request_limit - 1 chunk_end = req_start + budget.request_limit - 1
req_headers["Range"] = f"bytes={req_start}-{chunk_end}" req_headers["Range"] = f"bytes={req_start}-{chunk_end}"
elif resume_offset > 0 and not item_range: elif resume_offset > 0 and not item_range:
if ( if (
request_limit is not None budget.request_limit is not None
and known_total is not None and known_total is not None
and known_total - resume_offset > request_limit and known_total - resume_offset > budget.request_limit
): ):
chunk_end = resume_offset + request_limit - 1 chunk_end = resume_offset + budget.request_limit - 1
req_headers["Range"] = f"bytes={resume_offset}-{chunk_end}" req_headers["Range"] = f"bytes={resume_offset}-{chunk_end}"
else: else:
req_headers["Range"] = f"bytes={resume_offset}-" req_headers["Range"] = f"bytes={resume_offset}-"
@@ -1060,8 +1125,7 @@ def download(
if written < expected: if written < expected:
# this request's sub-range arrived whole; the rest of the part is the next # this request's sub-range arrived whole; the rest of the part is the next
# request, not a retry, so the attempt budget starts over for it # request, not a retry, so the attempt budget starts over for it
attempts = 1 budget.on_progress()
outages = 0
continue continue
elif content_length and written < content_length: elif content_length and written < content_length:
# applies to segments too: a connection FIN'd mid-body is a clean EOF, so the # applies to segments too: a connection FIN'd mid-body is a clean EOF, so the
@@ -1079,10 +1143,7 @@ def download(
if resume_offset + written <= resume_start: if resume_offset + written <= resume_start:
raise OSError(f"range from byte {resume_start} returned no bytes past it") raise OSError(f"range from byte {resume_start} returned no bytes past it")
resume_offset += written resume_offset += written
if resume_offset > high_water: budget.on_progress(resume_offset)
high_water = resume_offset
attempts = 1
outages = 0
continue continue
os.replace(tmp_file, save_path) os.replace(tmp_file, save_path)
yield dict(file_downloaded=save_path, written=resume_offset + written) yield dict(file_downloaded=save_path, written=resume_offset + written)
@@ -1098,64 +1159,49 @@ def download(
# a superseded loser's error must not retry or kill the batch # a superseded loser's error must not retry or kill the batch
if claimed is not None and claimed(): if claimed is not None and claimed():
return return
failures += 1
cancelled = DOWNLOAD_CANCELLED.is_set() or (abort is not None and abort.is_set()) cancelled = DOWNLOAD_CANCELLED.is_set() or (abort is not None and abort.is_set())
outage = stream is None and is_outage(exc) outage = stream is None and is_outage(exc)
if outage:
outages += 1
disk_error = getattr(exc, "errno", None) in LOCAL_DISK_ERRNOS disk_error = getattr(exc, "errno", None) in LOCAL_DISK_ERRNOS
limit = OUTAGE_ATTEMPTS if outage else MAX_ATTEMPTS if not part_mode and not (cancelled or disk_error):
if cancelled or disk_error or (outages if outage else attempts) >= limit: resume_offset = tmp_file.stat().st_size if tmp_file.exists() else 0
# a slice item rewrites from scratch, so its cut is never progress
progress = written if part_mode else (0 if item_range else resume_offset)
verdict = budget.on_failure(
exc, outage=outage, progress=progress - secured, item_range=item_range, stop=cancelled or disk_error
)
if verdict.action is RetryAction.GIVE_UP:
# cancel/abort is not an error, but a genuine retry-exhaustion is, so surface it # cancel/abort is not an error, but a genuine retry-exhaustion is, so surface it
# so the caller fails fast instead of hitting a missing segment at merge time # so the caller fails fast instead of hitting a missing segment at merge time
if not cancelled: if not cancelled:
exc.add_note(f"{GAVE_UP_NOTE} {failures} failed attempts over {_time() - started:.0f}s") exc.add_note(f"{GAVE_UP_NOTE} {budget.failures} failed attempts over {_time() - started:.0f}s")
if disk_error: if disk_error:
coded(exc, APIErrorCode.DOWNLOAD_ERROR) coded(exc, APIErrorCode.DOWNLOAD_ERROR)
raise raise
return return
if not part_mode: # only a no-progress failure reaches on_retry, so the adaptive controller does not slow a healthy flow
resume_offset = tmp_file.stat().st_size if tmp_file.exists() else 0 if verdict.action is RetryAction.RETRY and on_retry is not None:
# a CDN that throttles a flow and closes it every few seconds would otherwise
# exhaust MAX_ATTEMPTS partway into a large part; a cut with no progress (or a
# slice item, which rewrites from scratch) still spends an attempt, and only
# those reach on_retry so the adaptive controller does not slow a healthy flow
progress = written if part_mode else (0 if item_range else resume_offset)
if progress - secured >= MIN_RESUME_PROGRESS and resumes < MAX_RESUMES:
resumes += 1
attempts = 0
if not item_range:
# the host cut a body it was already delivering, so ask for less next time
request_limit = (
REQUEST_CHUNK_SIZE if request_limit is None else max(MIN_REQUEST_CHUNK, request_limit // 2)
)
elif on_retry is not None:
try: try:
on_retry(exc) on_retry(exc)
except Exception: except Exception:
pass pass
tries = outages if outage else max(1, attempts)
delay = retry_sleep(exc, tries)
from unshackle.core.session import failure_reason from unshackle.core.session import failure_reason
log_event( log_event(
"segment_retry", "segment_retry",
message=f"{failure_reason(exc)}, retry {tries}/{limit - 1} in {delay:.1f}s", message=f"{failure_reason(exc)}, retry {verdict.tries}/{verdict.limit - 1} in {verdict.delay:.1f}s",
context={"file": save_path.name, "failures": failures, "resumes": resumes}, context={"file": save_path.name, "failures": budget.failures, "resumes": budget.resumes},
) )
if abort is not None: if abort is not None:
# interruptible nap: backoff can reach MAX_BACKOFF, and teardown always # interruptible nap: backoff can reach MAX_BACKOFF, and teardown always
# sets the batch abort, so a parked worker must wake and exit at once # sets the batch abort, so a parked worker must wake and exit at once
# instead of stalling shutdown (or the merge) for the full delay # instead of stalling shutdown (or the merge) for the full delay
if abort.wait(delay): if abort.wait(verdict.delay):
return return
else: else:
# no batch abort on this path, but a cross-track cancel must still wake a # no batch abort on this path, but a cross-track cancel must still wake a
# parked worker rather than stall teardown for the full backoff # parked worker rather than stall teardown for the full backoff
if DOWNLOAD_CANCELLED.wait(delay): if DOWNLOAD_CANCELLED.wait(verdict.delay):
return return
if not outage:
attempts += 1
def rebuildable_adapter(adapter: Any) -> bool: def rebuildable_adapter(adapter: Any) -> bool: