Skip to content

The agent that grows with you

merge: combine network retries with downloader safety

ethernetbb824c381f39
diff --cc pm/downloader.py
index 7b14fd0f231,392ad28069f..be60862f3ca
--- a/pm/downloader.py
+++ b/pm/downloader.py
@@@ -22,8 -21,8 +22,9 @@@ the destination path to half-open [star
from __future__ import annotations
import hashlib
+ import http.client
import json
+import re
import shutil
import logging
import threading
@@@ -152,13 -129,12 +155,15 @@@ def _sha256_file(path: Path) -> str
def _existing_dest_ok(source: "Source") -> bool:
- """A dest already on disk counts as done only when it is a genuine
- complete download. No pinned hash (model-catalog policy): a present
- file is accepted — size is the tripwire, same as a fresh fetch. With a
- pinned sha256 the existing file must match, or it is re-fetched."""
+ """Pinned destinations are rehashed; unpinned model files are accepted as-is.
+
+ Catalog policy does not supply their expected hash or stable length.
+ Only this downloader's publication path guarantees complete new files.
+ """
if not source.dest.exists():
return False
++ if not source.dest.is_file():
++ raise IsADirectoryError(f"download destination is not a file: {source.dest}")
if not source.sha256:
return True
try:
@@@ -219,100 -230,92 +224,121 @@@ class Download
or source.url.startswith(_LOOPBACK)):
raise ValueError(f"refusing non-https url: {source.url}")
- # Probe every source up front so overall_total is the whole job.
- probed = [] # (source, total, range_supported)
+ # Probe the whole plan before reporting a denominator. A missing
+ # Content-Length keeps the bar indeterminate until that file ends.
+ from pm.download_state import partial_lock
+
+ totals: dict[str, int] = {}
+ unknown: set[str] = set()
+ coverage: dict[str, _Ranges] = {}
for source in self.sources:
- if _existing_dest_ok(source):
- probed.append((source, source.dest.stat().st_size, True))
- continue
- # A pre-existing dest that fails its pinned hash is stale — clear
- # it so the fetch below replaces it rather than trusting it.
- if source.dest.exists():
- source.dest.unlink(missing_ok=True)
- total, supported = self._probe(source.url)
- probed.append((source, total, supported))
- overall_total = sum(t for _, t, _ in probed)
-
- moved: list[Path] = []
- done_base = 0
- completed: dict = {}
- for source, total, supported in probed:
- if _existing_dest_ok(source):
- size = source.dest.stat().st_size
- completed[source.dest.name] = [(0, size)]
- done_base += size
- moved.append(source.dest)
- continue
-
- def tick(written: _Ranges) -> None:
+ self._check_pause()
+ key = str(source.dest)
+ cached = _existing_dest_ok(source)
+ if cached:
+ remote = _Remote(source.dest.stat().st_size, False)
+ covered = [(0, remote.total)]
+ else:
+ remote = self._probe(source.url)
+ covered = []
+ with partial_lock(self.partials_dir, self._key(source.url), wait=False) as acquired:
+ if acquired and remote.ranged:
+ covered = self._partial_ranges(source, remote)
+ if not remote.total:
+ unknown.add(key)
+ totals[key] = remote.total
+ coverage[key] = covered
+
+ progress_lock = threading.Lock()
+
+ def report(key: str, written: _Ranges) -> None:
+ with progress_lock:
+ # The last key identifies the source reporting this tick.
+ coverage.pop(key, None)
+ coverage[key] = list(written)
if progress is not None:
- ranges = dict(completed)
- ranges[source.dest.name] = written
- progress(done_base + sum(b - a for a, b in written),
- overall_total, ranges)
+ done = sum(b - a for rows in coverage.values() for a, b in rows)
+ progress(done, 0 if unknown else sum(totals.values()), dict(coverage))
- def fetch():
- if self._paused.is_set():
+ for source in self.sources:
+ with partial_lock(self.partials_dir, self._key(source.url), cancelled=self._paused.is_set) as acquired:
+ if not acquired:
raise DownloadPaused(source.url)
- if total and supported:
- return self._fetch_ranged(source, total, tick)
- return self._fetch_single(source, total, tick)
-
- connections = self.connections
- try:
- part, side = retry_network(fetch, wait=self._wait_retry)
- except http.client.IncompleteRead as exc:
- raise DownloadError(f"download incomplete: {exc}") from exc
- finally:
- self.connections = connections
- self._finalize(source, part, side)
- done_base += total
- completed[source.dest.name] = [(0, total)]
- moved.append(source.dest)
- return moved
+ self._check_pause()
+ key = str(source.dest)
+ if _existing_dest_ok(source):
+ size = source.dest.stat().st_size
+ else:
+ # Recheck identity after waiting for another process's partial.
+ remote = self._probe(source.url)
+ totals[key] = remote.total
+ if remote.total:
+ unknown.discard(key)
+ else:
+ unknown.add(key)
+ report(key, self._partial_ranges(source, remote) if remote.ranged else [])
+
+ def tick(written: _Ranges) -> None:
+ report(key, written)
+
- if remote.total and remote.ranged and (source.sha256 or remote.etag):
- size = self._fetch_ranged(source, remote, tick)
- else:
- size = self._fetch_single(source, remote, tick)
++ def fetch() -> int:
++ self._check_pause()
++ if remote.total and remote.ranged and (source.sha256 or remote.etag):
++ return self._fetch_ranged(source, remote, tick)
++ return self._fetch_single(source, remote, tick)
++
++ configured_connections = self.connections
++ try:
++ size = retry_network(fetch, wait=self._wait_retry)
++ except http.client.IncompleteRead as exc:
++ raise DownloadError(f"download incomplete: {exc}") from exc
++ finally:
++ self.connections = configured_connections
++ partial_key = self._key(source.url)
++ self._finalize(source, self.partials_dir / f"{partial_key}.part",
++ self.partials_dir / f"{partial_key}.ranges")
+ totals[key] = size
+ unknown.discard(key)
+ report(key, [(0, size)])
+ return [source.dest for source in self.sources]
# ── internals ─────────────────────────────────────────────
+ def _check_pause(self) -> None:
+ if self._paused.is_set():
+ raise DownloadPaused("download paused")
+
- @staticmethod
- def _probe(url: str) -> _Remote:
- req = urllib.request.Request(url, headers={**_UA, "Range": "bytes=0-0"})
- try:
+ def _wait_retry(self, delay: float) -> None:
+ if self._paused.wait(delay):
+ raise DownloadPaused("download paused during retry backoff")
+
- def _probe(self, url: str) -> tuple[int, bool]:
- """(total bytes, range_supported). A server that ignores Range
- reports its Content-Length instead; 0 means unknown (the
- single-stream fallback judges completeness by the body)."""
++ def _probe(self, url: str) -> _Remote:
+ def request():
- if self._paused.is_set():
- raise DownloadPaused(url)
++ self._check_pause()
+ req = urllib.request.Request(url, headers={**_UA, "Range": "bytes=0-0"})
- with _OPENER.open(req, timeout=60) as r:
- if r.status == 206:
- content_range = r.headers.get("Content-Range", "")
- if "/" in content_range:
- return int(content_range.rsplit("/", 1)[1]), True
- return 0, False
- length = int(r.headers.get("Content-Length") or 0)
- return length, False
-
+ with _OPENER.open(req, timeout=60) as response:
+ etag = _strong_etag(response)
+ if response.status == 206:
+ total = _validate_range(response, 0, 1)
- if len(response.read(2)) != 1:
++ body = response.read(2)
++ if not body:
++ raise http.client.IncompleteRead(b"", 1)
++ if len(body) != 1:
+ raise _RangeError("range probe returned the wrong byte count")
+ return _Remote(total, True, etag)
+ if response.status != 200:
+ raise DownloadError(f"unexpected download probe status: {response.status}")
+ return _Remote(int(response.headers.get("Content-Length") or 0), False, etag)
+ try:
+ return retry_network(request, wait=self._wait_retry)
except urllib.error.HTTPError as exc:
if exc.code in (401, 403):
- raise DownloadError(
- "the host refused the download (gated or moved). "
- "This is a catalog problem, not yours — please report it."
- ) from exc
+ raise DownloadError("the host refused the download; check source access and URL") from exc
+ raise
+ except DownloadError:
raise
- except (OSError, ValueError):
+ except ValueError:
- return 0, False
+ return _Remote(0, False)
def _key(self, url: str) -> str:
return hashlib.sha256(url.encode("utf-8")).hexdigest()
@@@ -358,78 -337,53 +384,81 @@@
key = self._key(source.url)
part = self.partials_dir / f"{key}.part"
side = self.partials_dir / f"{key}.ranges"
- covered = self._load_sidecar(side)
- if any(b > total for _, b in covered):
- covered = [] # server now serves a smaller file: stale partial
- # Create the file WITHOUT truncating an existing partial (resume),
- # then size it to total (extends with zeros / shrinks stale tails).
- open(part, "ab").close()
- with open(part, "r+b") as f:
- f.truncate(total)
- if covered:
- ranges = _missing(total, covered)
- else:
- n = max(1, min(self.connections, (total + _CHUNK - 1) // _CHUNK))
- ranges = [(i * total // n, (i + 1) * total // n) for i in range(n)]
- # NOT coalesced: the fresh split is the parallel fan-out, and
- # adjacent chunks must stay separate workers. (_missing already
- # returns disjoint gaps, so resume needs no merge either.)
- ranges = [r for r in ranges if r[1] > r[0]]
-
+ covered = self._load_sidecar(side, part, remote, source.sha256)
+ with part.open("r+b" if covered else "w+b") as stream:
+ stream.truncate(remote.total)
- gap_count = len(_missing(remote.total, covered)) if covered else (remote.total + _CHUNK - 1) // _CHUNK
- connections = max(1, min(self.connections, gap_count))
- attempts = (connections, 1) if connections > 1 else (1,)
- for connections in attempts:
++ while True:
++ gap_count = len(_missing(remote.total, covered)) if covered else (remote.total + _CHUNK - 1) // _CHUNK
++ connections = max(1, min(self.connections, gap_count))
+ covered, errors = self._ranged_attempt(source, remote, part, covered, connections, tick)
+ protocol_error = next((error for error in errors if isinstance(error, _RangeError)), None)
+ if protocol_error is not None:
+ part.unlink(missing_ok=True)
+ side.unlink(missing_ok=True)
+ raise protocol_error
+ self._write_sidecar(side, part, covered, remote, source.sha256)
+ if self._paused.is_set():
+ raise DownloadPaused(source.url)
+ if errors:
- if connections == 1:
- raise errors[0]
- logging.getLogger(__name__).warning(
- "parallel range fetch failed for %s; retrying with one connection", source.url,
- )
- continue
++ if self.connections > 1 and all(
++ isinstance(error, urllib.error.HTTPError) and error.code in (403, 404)
++ for error in errors
++ ):
++ logging.getLogger(__name__).warning(
++ "parallel range fetch refused for %s; retrying with one connection", source.url,
++ )
++ self.connections = 1
++ continue
++ raise next((error for error in errors if not is_transient(error)), errors[0])
+ written = sum(end - start for start, end in covered)
+ if written != remote.total:
- raise DownloadError(f"download incomplete ({written} of {remote.total} bytes)")
- self._finalize(source, part, side)
++ raise http.client.IncompleteRead(b"", remote.total - written)
+ return written
- raise DownloadError("ranged download exhausted its retry")
+
+ def _ranged_attempt(self, source: Source, remote: _Remote, part: Path,
+ covered: _Ranges, connections: int, tick) -> tuple[_Ranges, list[Exception]]:
+ from concurrent.futures import ThreadPoolExecutor
+
+ ranges = _missing(remote.total, covered)
+ if not covered:
+ count = max(1, min(connections, (remote.total + _CHUNK - 1) // _CHUNK))
+ ranges = [(index * remote.total // count, (index + 1) * remote.total // count)
+ for index in range(count)]
lock = threading.Lock()
errors: list[Exception] = []
stop = threading.Event()
- written = [sum(b - a for a, b in covered)]
+ covered = list(covered)
def worker(start: int, end: int) -> None:
+ if self._paused.is_set() or stop.is_set():
+ return
try:
- req = urllib.request.Request(
- source.url,
- headers={**_UA, "Range": f"bytes={start}-{end - 1}"})
- with _OPENER.open(req, timeout=120) as r, \
- open(part, "r+b") as f:
- f.seek(start)
- pos = start
- while pos < end:
+ headers = {**_UA, "Range": f"bytes={start}-{end - 1}"}
+ if remote.etag:
+ headers["If-Range"] = remote.etag
+ request = urllib.request.Request(source.url, headers=headers)
+ with _OPENER.open(request, timeout=120) as response, part.open("r+b") as stream:
+ _validate_range(response, start, end, remote.total)
+ if remote.etag and _strong_etag(response) != remote.etag:
+ raise _RangeError("remote representation changed during download")
+ stream.seek(start)
+ position = start
+ while position < end:
if self._paused.is_set() or stop.is_set():
return
- chunk = r.read(min(_CHUNK, end - pos))
+ chunk = response.read(min(_CHUNK, end - position))
if not chunk:
- raise DownloadError("range body ended before its declared bounds")
- break
- f.write(chunk)
- pos += len(chunk)
++ raise http.client.IncompleteRead(b"", end - position)
+ stream.write(chunk)
+ position += len(chunk)
with lock:
- covered[:] = _coalesce(covered + [(start, pos)])
- written[0] += len(chunk)
- tick(list(covered))
- except Exception as exc: # noqa: BLE001
+ covered[:] = _coalesce(covered + [(start, position)])
+ tick(list(covered))
+ if response.read(1):
+ raise _RangeError("range body exceeds its declared bounds")
+ except Exception as exc:
+ if isinstance(exc, urllib.error.HTTPError):
+ exc.close()
with lock:
errors.append(exc)
stop.set()
@@@ -446,41 -434,36 +475,42 @@@
part = self.partials_dir / f"{key}.part"
side = self.partials_dir / f"{key}.ranges"
covered: _Ranges = []
- req = urllib.request.Request(source.url, headers=_UA)
+ request = urllib.request.Request(source.url, headers=_UA)
try:
- with _OPENER.open(req, timeout=120) as r, open(part, "wb") as f:
- declared = int(r.headers.get("Content-Length") or 0)
- pos = 0
+ with _OPENER.open(request, timeout=120) as response, part.open("wb") as stream:
+ if response.status != 200:
+ raise DownloadError(f"unexpected download status: {response.status}")
+ if remote.etag and _strong_etag(response) != remote.etag:
+ raise _RangeError("remote representation changed during download")
+ if response.headers.get("Content-Encoding", "identity").lower() != "identity":
+ raise DownloadError("encoded response cannot be used as an identity download")
+ declared = int(response.headers.get("Content-Length") or 0)
+ position = 0
while True:
if self._paused.is_set():
- self._write_sidecar(side, covered)
raise DownloadPaused(source.url)
- chunk = r.read(_CHUNK)
+ chunk = response.read(_CHUNK)
if not chunk:
break
- f.write(chunk)
- pos += len(chunk)
- covered = [(0, pos)]
+ stream.write(chunk)
+ position += len(chunk)
+ covered = [(0, position)]
tick(list(covered))
if self._paused.is_set():
- self._write_sidecar(side, covered)
raise DownloadPaused(source.url)
- if pos < (declared or total):
- raise http.client.IncompleteRead(b"", (declared or total) - pos)
- if total and pos != total:
- raise DownloadError(
- f"download incomplete ({pos} of {total} bytes)")
- except Exception:
- self._write_sidecar(side, covered)
++ if position < (declared or remote.total):
++ raise http.client.IncompleteRead(b"", (declared or remote.total) - position)
+ if (declared and position != declared) or (remote.total and position != remote.total):
+ raise DownloadError(f"download incomplete ({position} bytes, expected {declared or remote.total})")
+ except BaseException:
+ if part.exists():
+ self._write_sidecar(side, part, covered, remote, source.sha256)
raise
- return part, side
+ self._write_sidecar(side, part, covered, remote, source.sha256)
- self._finalize(source, part, side)
+ return position
def _finalize(self, source: Source, part: Path, side: Path) -> None:
+ self._check_pause()
if source.sha256:
actual = _sha256_file(part)
if actual != source.sha256:
diff --cc pm/store.py
index c5c9d467e9a,6ae61376e7f..5305490c075
--- a/pm/store.py
+++ b/pm/store.py
@@@ -118,16 -118,43 +119,25 @@@ def hash_url(url: str) -> str
import urllib.request
from pm.downloader import _OPENER
-
- digest = hashlib.sha256()
- with _OPENER.open(
- urllib.request.Request(url, headers=_UA), timeout=600
- ) as resp:
- for block in iter(lambda: resp.read(1024 * 1024), b""):
- digest.update(block)
- return digest.hexdigest()
+ from pm.network import retry_network
+
+ def request():
+ digest = hashlib.sha256()
+ size = 0
+ with _OPENER.open(
+ urllib.request.Request(url, headers=_UA), timeout=600
+ ) as resp:
+ declared = int(resp.headers.get("Content-Length") or 0)
+ for block in iter(lambda: resp.read(1024 * 1024), b""):
+ digest.update(block)
+ size += len(block)
+ if size < declared:
+ raise http.client.IncompleteRead(b"", declared - size)
+ return digest.hexdigest()
+
+ return retry_network(request)
-def download(url: str, dest: Path, sha256: str, progress=None) -> Path:
- """Fetch url into dest dir, hash-verified, via the resumable downloader.
- The digest is proven before the caller ever sees the file.
- ``progress(done, total)`` ticks per chunk — a several-hundred-MB engine
- archive on a slow line must never look hung. Partial state lives in
- the downloader's writable partials area (outside scratch, keyed by
- sha256(url)), so an interrupted = failed fetch resumes on the next
- call instead of re-fetching the whole archive. Non-https/non-loopback
- urls are refused by Download itself (ValueError)."""
- from pm.downloader import Download, Source
-
- dest.mkdir(parents=True, exist_ok=True)
- archive = dest / url.rsplit("/", 1)[-1]
- p = (lambda d, t, r: progress(d, t)) if progress is not None else None
- Download([Source(url, archive, sha256)]).run(progress=p)
- return archive
-
-
def extract(archive: Path, dest: Path) -> None:
import tarfile
diff --cc pm/update.py
index b2a5a425c68,648a556a06a..aaeb7380437
--- a/pm/update.py
+++ b/pm/update.py
@@@ -175,36 -176,28 +176,43 @@@ def _github_headers() -> dict
return headers
+def _index_headers(url: str) -> dict:
+ from hermes_cli.urllib_security import url_origin
+
+ origin = url_origin(url)
+ if origin == ("https", "api.github.com", 443):
+ return _github_headers()
+ if origin == ("https", "huggingface.co", 443):
+ return {**_UA, **_hf_headers()}
+ return dict(_UA)
+
+
def _get_json(url: str) -> dict | list:
+ from hermes_cli.urllib_security import open_credentialed_url
+
- with open_credentialed_url(
- urllib.request.Request(url, headers=_index_headers(url)), timeout=60
- ) as resp:
- return json.load(resp)
+ def request():
- with urllib.request.urlopen(
- urllib.request.Request(url, headers=_github_headers()), timeout=60
++ with open_credentialed_url(
++ urllib.request.Request(url, headers=_index_headers(url)), timeout=60
+ ) as resp:
+ return json.load(resp)
+
+ return retry_network(request)
def _get_text(url: str, headers: Optional[dict] = None) -> str:
- hdrs = dict(_UA)
+ from hermes_cli.urllib_security import open_credentialed_url
+
+ hdrs = _index_headers(url)
if headers:
hdrs.update(headers)
- with open_credentialed_url(
- urllib.request.Request(url, headers=hdrs), timeout=60
- ) as resp:
- return resp.read().decode("utf-8", "replace")
+
+ def request():
- with urllib.request.urlopen(
++ with open_credentialed_url(
+ urllib.request.Request(url, headers=hdrs), timeout=60
+ ) as resp:
+ return resp.read().decode("utf-8", "replace")
+
+ return retry_network(request)
# ── llama.app installer bucket (ggml-org/install.sh) ──────────────────────
diff --cc tests/pm/_range_server.py
index ebfeeb94d0e,311f19d9cb2..8e017ee3d6b
--- a/tests/pm/_range_server.py
+++ b/tests/pm/_range_server.py
@@@ -19,10 -18,9 +19,10 @@@ import pytes
class RangeHandler(BaseHTTPRequestHandler):
payloads: dict = {}
ranges_seen: list = [] # (path, start, end) from real Range requests
- abort_after: int | None = None # close the connection after this many bytes
+ abort_after: int | None = None # refuse bytes beyond this payload offset
slow_per_chunk: float = 0.0 # sleep per served piece (pause tests)
no_range: bool = False # ignore Range, serve 200 full body
+ etags: bool = True
chunk: int = 1 << 20 # serve piece size
def log_message(self, *args): # noqa: A002 - silence request logging
diff --cc tests/pm/test_download_retry_limits.py
index 00000000000,6eca09b48e2..009344e68dc
mode 000000,100644..100644
--- a/tests/pm/test_download_retry_limits.py
+++ b/tests/pm/test_download_retry_limits.py
@@@ -1,0 -1,108 +1,108 @@@
+ """The real downloader bounds retries and pauses without publishing partial bytes."""
+
+ import hashlib
+ import threading
+ import urllib.error
+ from concurrent.futures import ThreadPoolExecutor
+
+ import pytest
+
+ from pm import network
+ from pm.downloader import Download, DownloadError, DownloadPaused, HashError, Source
+ from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401
+
+
+ @pytest.mark.parametrize("failure", ["503", "404", "403", "hash", "disk"])
+ @pytest.mark.parametrize("phase", ["probe", "ranged", "single"])
+ def test_download_failure_never_publishes_partial_bytes(tmp_path, dl_server, monkeypatch, failure, phase):
+ payload = b"verified bytes"
+ RangeHandler.payloads["/tool"] = payload
+ RangeHandler.no_range = phase == "single"
+ original_get = RangeHandler.do_GET
+ requests = []
+ waits = []
+
+ def respond(handler):
+ request_range = handler.headers.get("Range")
+ requests.append(request_range)
+ is_probe = request_range == "bytes=0-0"
+ if failure.isdigit() and is_probe == (phase == "probe"):
+ handler.send_error(int(failure))
+ return
+ original_get(handler)
+
+ monkeypatch.setattr(RangeHandler, "do_GET", respond)
+ dest = tmp_path / "tool"
+ digest = "0" * 64 if failure == "hash" else hashlib.sha256(payload).hexdigest()
+ dl = Download([Source(url(dl_server, "/tool"), dest, digest)],
+ partials_dir=tmp_path / "partials", connections=1)
+ monkeypatch.setattr(dl, "_wait_retry", waits.append)
+ if failure == "disk":
+ dest.mkdir()
+ (dest / "occupied").write_bytes(b"keep")
+ expected_error = {"hash": HashError, "disk": OSError}.get(failure)
+ if expected_error is None:
+ expected_error = DownloadError if failure == "403" and phase == "probe" else urllib.error.HTTPError
+
+ with pytest.raises(expected_error):
+ dl.run()
+ if failure == "disk":
+ assert (dest / "occupied").read_bytes() == b"keep"
+ assert not requests and not waits
+ else:
+ assert not dest.exists()
- error_requests = requests if phase == "probe" else requests[1:]
++ error_requests = requests if phase == "probe" else [value for value in requests if value != "bytes=0-0"]
+ if failure == "503":
+ assert len(error_requests) == network._ATTEMPTS
+ assert len(waits) == network._ATTEMPTS - 1
+ else:
+ assert not waits
+ if failure != "hash":
+ assert len(error_requests) == 1
+
+
+ @pytest.mark.parametrize("phase", ["probe", "ranged", "single"])
+ def test_pause_interrupts_real_http_retry_backoff(tmp_path, dl_server, monkeypatch, phase):
+ payload = b"keep these bytes"
+ RangeHandler.payloads["/tool"] = payload
+ RangeHandler.no_range = phase == "single"
+ original_get = RangeHandler.do_GET
+ requests = []
+ waiting = threading.Event()
+ waits = []
+
+ def respond(handler):
+ request_range = handler.headers.get("Range")
+ requests.append(request_range)
+ if (request_range == "bytes=0-0") == (phase == "probe"):
+ handler.send_response(503)
+ handler.send_header("Retry-After", "30")
+ handler.send_header("Content-Length", "0")
+ handler.end_headers()
+ return
+ original_get(handler)
+
+ monkeypatch.setattr(RangeHandler, "do_GET", respond)
+ dest = tmp_path / "tool"
+ dl = Download([Source(url(dl_server, "/tool"), dest)],
+ partials_dir=tmp_path / "partials")
+ original_wait = dl._wait_retry
+
+ def wait(delay):
+ waits.append(delay)
+ waiting.set()
+ original_wait(delay)
+
+ monkeypatch.setattr(dl, "_wait_retry", wait)
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ task = pool.submit(dl.run)
+ try:
+ assert waiting.wait(10), "the failed request never reached backoff"
+ dl.pause()
+ with pytest.raises(DownloadPaused):
+ task.result(timeout=5)
+ finally:
+ dl.pause()
- assert len(requests) == (1 if phase == "probe" else 2)
++ assert len([value for value in requests if (value == "bytes=0-0") == (phase == "probe")]) == 1
+ assert waits == [network._MAX_DELAY]
+ assert not dest.exists()
diff --cc tests/pm/test_downloader.py
index 5daafc552f8,2c29b09da97..ae79a476bfe
--- a/tests/pm/test_downloader.py
+++ b/tests/pm/test_downloader.py
@@@ -205,29 -202,29 +205,16 @@@ def test_redirect_to_non_https_refused(
def test_pause_leaves_partials_intact(dl_server, tmp_path):
_Handler.payloads["/p"] = _payload(32 << 20)
-- _Handler.slow_per_chunk = 0.01
dest = tmp_path / "p.bin"
partials = tmp_path / "partials"
dl = Download([Source(_url(dl_server, "/p"), dest)],
partials_dir=partials)
-- result: dict = {}
--
-- def run_it():
-- try:
-- dl.run()
-- result["ok"] = True
-- except DownloadPaused:
-- result["paused"] = True
--
-- thread = threading.Thread(target=run_it)
-- thread.start()
-- for _ in range(200):
-- if partials.exists() and any(partials.iterdir()):
-- break
-- time.sleep(0.05)
-- dl.pause()
-- thread.join(timeout=15)
-- assert result.get("paused")
++ def pause_after_bytes(done, total, ranges):
++ if done > 0:
++ dl.pause()
++
++ with pytest.raises(DownloadPaused):
++ dl.run(progress=pause_after_bytes)
assert not dest.exists()
names = {p.name for p in partials.iterdir()}
assert any(n.endswith(".part") for n in names)
@@@ -364,29 -361,13 +351,13 @@@ def test_pause_mid_plan_resumes_to_comp
dl = Download([Source(_url(dl_server, "/a"), da, _sha(p_a)),
Source(_url(dl_server, "/b"), db, _sha(p_b))],
partials_dir=partials)
- result: dict = {}
-
- def run_it():
- try:
- dl.run()
- result["ok"] = True
- except DownloadPaused:
- result["paused"] = True
- except Exception as exc: # noqa: BLE001
- result["err"] = exc
-
- thread = threading.Thread(target=run_it)
- thread.start()
- for _ in range(400):
- if da.exists():
- break
- time.sleep(0.05)
- assert da.exists(), "source 1 never completed"
- dl.pause()
- thread.join(timeout=20)
- assert result.get("paused"), result.get("err")
+
+ def pause_second_source(done, total, ranges):
- if ranges.get(db.name):
++ if ranges.get(str(db)):
+ dl.pause()
+
+ with pytest.raises(DownloadPaused):
+ dl.run(progress=pause_second_source)
assert da.read_bytes() == p_a # source 1 moved despite the pause
assert not db.exists()
names = {p.name for p in partials.iterdir()}
diff --cc tests/pm/test_network_retries.py
index 00000000000,5c30d93a15e..ab75c52d994
mode 000000,100644..100644
--- a/tests/pm/test_network_retries.py
+++ b/tests/pm/test_network_retries.py
@@@ -1,0 -1,136 +1,137 @@@
+ """PM retries transient HTTP failures before publishing verified bytes."""
+
+ from __future__ import annotations
+
+ import hashlib
+ import importlib
+ import io
+ import zipfile
+
+ import pytest
+
+ import pm.paths as paths
+ from pm.lock import Facts, Lockfile
+ from pm.package import Package
+ from pm.store import Store, current_target
+ from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401
+
+
+ @pytest.mark.parametrize("failure_phase", [
+ "probe", "probe-disconnect", "probe-empty-body", "ranged", "single",
+ "interrupted", "single-interrupted",
+ ])
+ @pytest.mark.parametrize("install_path", ["install", "stage"])
+ def test_install_recovers_from_transient_http_failure(tmp_path, dl_server, monkeypatch, failure_phase, install_path):
+ payload = io.BytesIO()
+ with zipfile.ZipFile(payload, "w") as archive:
+ archive.writestr("tool.txt", b"verified tool bytes")
+ body = payload.getvalue()
+ RangeHandler.payloads["/tool.zip"] = body
+ RangeHandler.no_range = failure_phase.startswith("single")
+ original_get = RangeHandler.do_GET
+ requests = []
+ failed = False
+
+ def fail_first_request(handler):
+ nonlocal failed
+ request_range = handler.headers.get("Range")
+ requests.append(request_range)
+ is_probe = request_range == "bytes=0-0"
+ if not failed and is_probe == failure_phase.startswith("probe"):
+ failed = True
+ if failure_phase in ("probe-disconnect", "probe-empty-body"):
+ if failure_phase == "probe-empty-body":
+ handler.send_response(206)
+ handler.send_header("Content-Range", f"bytes 0-0/{len(body)}")
+ handler.send_header("Content-Length", "1")
+ handler.end_headers()
+ handler.close_connection = True
+ elif failure_phase.endswith("interrupted"):
+ handler.send_response(200 if RangeHandler.no_range else 206)
+ if not RangeHandler.no_range:
+ handler.send_header("Content-Range", f"bytes 0-{len(body) - 1}/{len(body)}")
+ handler.send_header("Content-Length", str(len(body)))
+ handler.end_headers()
+ handler.wfile.write(body[: len(body) // 2])
+ handler.wfile.flush()
+ handler.close_connection = True
+ else:
+ handler.send_error(500)
+ return
+ original_get(handler)
+
+ monkeypatch.setattr(RangeHandler, "do_GET", fail_first_request)
+ monkeypatch.setattr(paths, "partials_root", lambda: tmp_path / "partials")
+ package = Package()
+ package.name = "retry-tool"
+ store = Store(tmp_path / "store")
+ facts = Facts(store.root / "facts.json")
+ lock = Lockfile(tmp_path / "lock.json")
+ lock.set_pin(package.name, "1.0", {"any": {
+ "url": url(dl_server, "/tool.zip"),
+ "sha256": hashlib.sha256(body).hexdigest(),
+ }})
+ ensure = importlib.import_module("pm.ensure")
+ if install_path == "install":
+ ensure._install(package, lock, facts, store, current_target())
+ entry = store.entry(facts.get(package.name)["entry"])
+ else:
+ monkeypatch.setattr(ensure, "_lockfile", lambda: lock)
+ monkeypatch.setattr(ensure, "_store", lambda: store)
+ monkeypatch.setattr(ensure, "get_package", lambda _: package)
+ entry = ensure.stage_only(package.name, current_target())
+ assert facts.get(package.name) is None
+
+ assert (entry / "tool.txt").read_bytes() == b"verified tool bytes"
+ assert len(requests) > 1
+ if failure_phase == "interrupted":
+ assert requests[-1] == f"bytes={len(body) // 2}-{len(body) - 1}"
- assert list((tmp_path / "partials").iterdir()) == []
++ assert not list((tmp_path / "partials").glob("*.part"))
++ assert not list((tmp_path / "partials").glob("*.ranges"))
+
+
+ @pytest.mark.parametrize("reader_name", ["hash", "json", "text", "digests"])
+ @pytest.mark.parametrize("short_body", [False, True])
+ def test_pm_metadata_reads_retry_transient_http_failure(dl_server, monkeypatch, reader_name, short_body):
+ from pm import packages, store, update
+
+ body = b'{"assets": [{"name": "tool.zip", "digest": "sha256:abc123"}]}'
+ RangeHandler.payloads["/metadata"] = body
+ original_get = RangeHandler.do_GET
+ requests = []
+
+ def fail_first_request(handler):
+ requests.append(handler.path)
+ if len(requests) == 1:
+ if short_body:
+ handler.send_response(200)
+ handler.send_header("Content-Length", str(len(body)))
+ handler.end_headers()
+ handler.wfile.write(body[: len(body) // 2])
+ handler.wfile.flush()
+ handler.close_connection = True
+ else:
+ handler.send_error(503)
+ return
+ original_get(handler)
+
+ monkeypatch.setattr(RangeHandler, "do_GET", fail_first_request)
+ endpoint = url(dl_server, "/metadata")
+ readers = {
+ "hash": (lambda: store.hash_url(endpoint), hashlib.sha256(body).hexdigest()),
+ "json": (lambda: update._get_json(endpoint), {"assets": [{"name": "tool.zip", "digest": "sha256:abc123"}]}),
+ "text": (lambda: update._get_text(endpoint), body.decode()),
+ }
+ if reader_name == "digests":
+ import urllib.request
+ original_urlopen = urllib.request.urlopen
+
+ def local_release(request, **kwargs):
+ return original_urlopen(urllib.request.Request(endpoint, headers=request.headers), **kwargs)
+
+ monkeypatch.setattr(urllib.request, "urlopen", local_release)
+ monkeypatch.setattr(packages, "_release_digest_cache", {})
+ readers["digests"] = (lambda: packages._github_release_digests("test/repo", "test"), {"tool.zip": "abc123"})
+ read, expected = readers[reader_name]
+ assert read() == expected
+ assert len(requests) == 2