Skip to content

The agent that grows with you

fix(pm): retry transient network failures

ethernet8e4a804f53b3
diff --git a/pm/downloader.py b/pm/downloader.py
index e7fff1b07b6..392ad28069f 100644
--- a/pm/downloader.py
+++ b/pm/downloader.py
@@ -21,6 +21,7 @@ The progress callback reports the whole job AND the per-dest bitmap:
from __future__ import annotations
import hashlib
+import http.client
import json
import shutil
import logging
@@ -31,6 +32,8 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Optional, Sequence
+from pm.network import is_transient, retry_network
+
# GitHub's release-asset CDN (release-assets.githubusercontent.com, which
# TUR's pool 302s to) 403s unknown tool UAs from CI runner IP ranges --
# their docs require a real User-Agent. A browser-shaped one is the
@@ -259,10 +262,21 @@ class Download:
progress(done_base + sum(b - a for a, b in written),
overall_total, ranges)
- if total and supported:
- self._fetch_ranged(source, total, tick)
- else:
- self._fetch_single(source, total, tick)
+ def fetch():
+ if self._paused.is_set():
+ 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)
@@ -270,13 +284,18 @@ class Download:
# ── internals ─────────────────────────────────────────────
- @staticmethod
- def _probe(url: str) -> tuple[int, bool]:
+ 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)."""
- req = urllib.request.Request(url, headers={**_UA, "Range": "bytes=0-0"})
- try:
+ def request():
+ if self._paused.is_set():
+ raise DownloadPaused(url)
+ 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", "")
@@ -285,6 +304,9 @@ class Download:
return 0, False
length = int(r.headers.get("Content-Length") or 0)
return length, False
+
+ try:
+ return retry_network(request, wait=self._wait_retry)
except urllib.error.HTTPError as exc:
if exc.code in (401, 403):
raise DownloadError(
@@ -292,7 +314,7 @@ class Download:
"This is a catalog problem, not yours — please report it."
) from exc
raise
- except Exception: # noqa: BLE001 - unknown length, fall back
+ except ValueError:
return 0, False
def _key(self, url: str) -> str:
@@ -311,7 +333,7 @@ class Download:
side.parent.mkdir(parents=True, exist_ok=True)
side.write_text(json.dumps(covered), encoding="utf-8")
- def _fetch_ranged(self, source: Source, total: int, tick) -> None:
+ def _fetch_ranged(self, source: Source, total: int, tick) -> tuple[Path, Path]:
key = self._key(source.url)
part = self.partials_dir / f"{key}.part"
side = self.partials_dir / f"{key}.ranges"
@@ -360,6 +382,8 @@ class Download:
written[0] += len(chunk)
tick(list(covered))
except Exception as exc: # noqa: BLE001
+ if isinstance(exc, urllib.error.HTTPError):
+ exc.close()
with lock:
errors.append(exc)
stop.set()
@@ -369,42 +393,41 @@ class Download:
name=f"dl-{key[:8]}-{i}")
for i, b in enumerate(ranges)
]
- for t in threads:
- t.start()
- for t in threads:
- t.join()
+ if self.connections == 1:
+ for bounds in ranges:
+ if self._paused.is_set() or stop.is_set():
+ break
+ worker(*bounds)
+ else:
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
if self._paused.is_set():
self._write_sidecar(side, covered)
raise DownloadPaused(source.url)
if errors:
self._write_sidecar(side, covered)
- # Parallel ranged GETs trip edge/CDN rate limits that a single
- # connection does not (observed live: every single-request probe
- # green while the 4-thread fetch 404ed, same runner, same URL).
- # Retry once single-stream; the digest check still proves the
- # bytes. A partial from the failed attempt is kept (covered is
- # persisted above), so the retry only fetches the gaps.
- if self.connections > 1:
+ # Some CDNs reject parallel ranges after accepting the probe.
+ # Retry these refusals once with serial requests for the gaps.
+ if self.connections > 1 and all(
+ isinstance(exc, urllib.error.HTTPError) and exc.code in (403, 404)
+ for exc in errors
+ ):
logging.getLogger(__name__).warning(
"parallel ranged fetch failed for %s (%s); retrying single-stream",
source.url, errors[0],
)
- saved = self.connections
- try:
- self.connections = 1
- self._fetch_ranged(source, total, tick)
- finally:
- self.connections = saved
- return
- raise errors[0]
+ self.connections = 1
+ return self._fetch_ranged(source, total, tick)
+ raise next((exc for exc in errors if not is_transient(exc)), errors[0])
if written[0] != total:
self._write_sidecar(side, covered)
- raise DownloadError(
- f"download incomplete ({written[0]} of {total} bytes)")
- self._finalize(source, part, side)
+ raise http.client.IncompleteRead(b"", total - written[0])
+ return part, side
- def _fetch_single(self, source: Source, total: int, tick) -> None:
+ def _fetch_single(self, source: Source, total: int, tick) -> tuple[Path, Path]:
"""No-Range fallback: one stream. A server without Range support
cannot resume, so each run restarts the file."""
key = self._key(source.url)
@@ -430,20 +453,15 @@ class Download:
if self._paused.is_set():
self._write_sidecar(side, covered)
raise DownloadPaused(source.url)
- if declared and pos != declared:
- raise DownloadError(
- f"download ended at {pos:,} bytes but the server "
- f"said {declared:,} — connection dropped?")
+ 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 DownloadError:
- self._write_sidecar(side, covered)
- raise
except Exception:
self._write_sidecar(side, covered)
raise
- self._finalize(source, part, side)
+ return part, side
def _finalize(self, source: Source, part: Path, side: Path) -> None:
if source.sha256:
diff --git a/pm/ensure.py b/pm/ensure.py
index 68f71a36414..5a68dc81238 100644
--- a/pm/ensure.py
+++ b/pm/ensure.py
@@ -277,33 +277,6 @@ def _install(
package.migrate(previous["version"], version)
-def _fetch_with_retry(store, url: str, sha256: str, scratch, progress=None, attempts: int = 5):
- """store.fetch with a bounded retry: release-asset CDNs (TUR's pool
- 302s to GitHub's) throw transient 404/403 windows at their edges --
- observed live, the identical request green minutes later. The digest
- still proves the bytes; a retry cannot smuggle anything past the pin.
- """
- import time
- from pm.downloader import DownloadPaused, HashError
-
- last: Exception | None = None
- for attempt in range(attempts):
- try:
- return store.fetch(url, sha256, scratch, progress=progress)
- except (HashError, DownloadPaused):
- raise
- except Exception as exc: # noqa: BLE001 -- transient fetch failures retain bounded retries
- last = exc
- if attempt + 1 < attempts:
- wait = 30 * (attempt + 1)
- logging.getLogger(__name__).warning(
- "fetch failed (attempt %d/%d) for %s: %s; retrying in %ds",
- attempt + 1, attempts, url, exc, wait,
- )
- time.sleep(wait)
- raise last
-
-
def stage_only(name: str, target: str, progress=None) -> "Path":
"""Cross-target staging: publish the pinned (package, version, target)
entry into the store and return its path. No facts are written and no
@@ -355,8 +328,8 @@ def stage_only(name: str, target: str, progress=None) -> "Path":
with store.scratch() as scratch:
staged = scratch / "tree"
for index, artifact in enumerate(artifacts):
- archive = _fetch_with_retry(
- store, artifact["url"], artifact["sha256"], scratch,
+ archive = store.fetch(
+ artifact["url"], artifact["sha256"], scratch,
progress=_artifact_progress(progress, index, len(artifacts)),
)
if index == 0:
diff --git a/pm/network.py b/pm/network.py
new file mode 100644
index 00000000000..c110a0a7d76
--- /dev/null
+++ b/pm/network.py
@@ -0,0 +1,85 @@
+"""Bounded retries for PM-owned, idempotent network operations."""
+
+from __future__ import annotations
+
+import errno
+import http.client
+import logging
+import socket
+import ssl
+import time
+import urllib.error
+from datetime import timezone
+from email.utils import parsedate_to_datetime
+from typing import Callable, TypeVar
+
+_T = TypeVar("_T")
+_ATTEMPTS = 4
+_MAX_DELAY = 30.0
+_HTTP_RETRY = frozenset({408, 429, 500, 502, 503, 504})
+_NETWORK_ERRNOS = frozenset({
+ errno.ECONNABORTED, errno.ECONNREFUSED, errno.ECONNRESET,
+ errno.ENETDOWN, errno.ENETRESET, errno.ENETUNREACH,
+ errno.EHOSTUNREACH, errno.EPIPE, errno.ETIMEDOUT,
+})
+
+
+def is_transient(exc: Exception) -> bool:
+ if isinstance(exc, urllib.error.HTTPError):
+ return exc.code in _HTTP_RETRY
+ if isinstance(exc, urllib.error.URLError):
+ return isinstance(exc.reason, Exception) and is_transient(exc.reason)
+ if isinstance(exc, (ssl.SSLEOFError, ssl.SSLZeroReturnError)):
+ return True
+ if isinstance(exc, ssl.SSLError):
+ return False
+ if isinstance(exc, socket.gaierror):
+ return exc.errno == socket.EAI_AGAIN
+ if isinstance(exc, (TimeoutError, ConnectionError, http.client.IncompleteRead)):
+ return True
+ return isinstance(exc, OSError) and exc.errno in _NETWORK_ERRNOS
+
+
+def _delay(exc: Exception, attempt: int) -> float:
+ delay = float(2 ** attempt)
+ if isinstance(exc, urllib.error.HTTPError):
+ value = exc.headers.get("Retry-After", "") if exc.headers else ""
+ if value:
+ try:
+ retry_after = int(value)
+ except ValueError:
+ try:
+ when = parsedate_to_datetime(value)
+ if when.tzinfo is None:
+ when = when.replace(tzinfo=timezone.utc)
+ retry_after = when.timestamp() - time.time()
+ except (TypeError, ValueError, OverflowError):
+ retry_after = 0.0
+ delay = max(delay, retry_after)
+ return min(delay, _MAX_DELAY)
+
+
+def retry_network(
+ operation: Callable[[], _T], *, wait: Callable[[float], None] | None = None,
+) -> _T:
+ """Retry the complete request and body read, never an install or publish.
+
+ The caller resets attempt-local buffers and keeps any resumable bytes.
+ A download supplies an interruptible wait so pause does not wait for backoff.
+ """
+ attempt = 1
+ while True:
+ try:
+ return operation()
+ except Exception as exc:
+ if isinstance(exc, urllib.error.HTTPError):
+ exc.close()
+ if not is_transient(exc) or attempt >= _ATTEMPTS:
+ raise
+ delay = _delay(exc, attempt - 1)
+ attempt += 1
+ logging.getLogger(__name__).warning(
+ "network request failed (%s); retrying in %gs (attempt %d/%d)",
+ exc, delay, attempt, _ATTEMPTS,
+ )
+ (wait or time.sleep)(delay)
diff --git a/pm/packages.py b/pm/packages.py
index d8af8140ee0..6e4d3fa743b 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -1050,12 +1050,17 @@ def _github_release_digests(repo: str, tag: str) -> dict[str, str]:
token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
if token:
headers["Authorization"] = f"Bearer {token}"
- try:
+ from pm.network import retry_network
+
+ def request():
with urllib.request.urlopen(
urllib.request.Request(url, headers=headers),
timeout=120,
) as resp:
- release = json.load(resp)
+ return json.load(resp)
+
+ try:
+ release = retry_network(request)
except Exception:
return {}
digests = {}
diff --git a/pm/store.py b/pm/store.py
index 2d4370367b0..6ae61376e7f 100644
--- a/pm/store.py
+++ b/pm/store.py
@@ -114,17 +114,27 @@ def sha256_file(path: Path) -> str:
def hash_url(url: str) -> str:
"""sha256 of a url's content, streamed. `pm lock` uses this to pin."""
import hashlib
+ import http.client
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:
diff --git a/pm/update.py b/pm/update.py
index f7008193fe5..648a556a06a 100644
--- a/pm/update.py
+++ b/pm/update.py
@@ -32,6 +32,7 @@ import urllib.request
from dataclasses import dataclass, field
from typing import Optional
+from pm.network import retry_network
from pm.registry import get_package
# ---------------------------------------------------------------------------
@@ -176,20 +177,27 @@ def _github_headers() -> dict:
def _get_json(url: str) -> dict | list:
- with urllib.request.urlopen(
- urllib.request.Request(url, headers=_github_headers()), timeout=60
- ) as resp:
- return json.load(resp)
+ def request():
+ with urllib.request.urlopen(
+ urllib.request.Request(url, headers=_github_headers()), 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)
if headers:
hdrs.update(headers)
- with urllib.request.urlopen(
- urllib.request.Request(url, headers=hdrs), timeout=60
- ) as resp:
- return resp.read().decode("utf-8", "replace")
+
+ def request():
+ with urllib.request.urlopen(
+ 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 --git a/tests/pm/_range_server.py b/tests/pm/_range_server.py
index 414b061fa92..311f19d9cb2 100644
--- a/tests/pm/_range_server.py
+++ b/tests/pm/_range_server.py
@@ -18,7 +18,7 @@ import pytest
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
chunk: int = 1 << 20 # serve piece size
@@ -73,12 +73,15 @@ class RangeHandler(BaseHTTPRequestHandler):
self.end_headers()
served = 0
while served < len(body):
- if self.abort_after is not None and served >= self.abort_after:
+ if self.abort_after is not None and start + served >= self.abort_after:
self.connection.close()
return
if self.slow_per_chunk:
time.sleep(self.slow_per_chunk)
- piece = body[served:served + self.chunk]
+ end = served + self.chunk
+ if self.abort_after is not None:
+ end = min(end, self.abort_after - start)
+ piece = body[served:end]
self.wfile.write(piece)
self.wfile.flush()
served += len(piece)
diff --git a/tests/pm/test_download_retry_limits.py b/tests/pm/test_download_retry_limits.py
new file mode 100644
index 00000000000..6eca09b48e2
--- /dev/null
+++ b/tests/pm/test_download_retry_limits.py
@@ -0,0 +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
+
+
[email protected]("failure", ["503", "404", "403", "hash", "disk"])
[email protected]("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:]
+ 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
+
+
[email protected]("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 waits == [network._MAX_DELAY]
+ assert not dest.exists()
diff --git a/tests/pm/test_download_serial_fallback.py b/tests/pm/test_download_serial_fallback.py
new file mode 100644
index 00000000000..9a088546bd7
--- /dev/null
+++ b/tests/pm/test_download_serial_fallback.py
@@ -0,0 +1,37 @@
+"""A CDN refusal downgrades this transfer once, including later network retries."""
+
+import hashlib
+
+import pytest
+
+from pm.downloader import Download, Source
+from tests.pm._range_server import RangeHandler, dl_server, url # noqa: F401
+
+
[email protected]("refused_status", [403, 404])
+def test_serial_fallback_survives_a_transient_retry(tmp_path, dl_server, monkeypatch, refused_status):
+ payload = b"verified bytes"
+ RangeHandler.payloads["/tool"] = payload
+ original_get = RangeHandler.do_GET
+ dest = tmp_path / "tool"
+ dl = Download([Source(url(dl_server, "/tool"), dest, hashlib.sha256(payload).hexdigest())],
+ partials_dir=tmp_path / "partials")
+ modes = []
+ waits = []
+
+ def respond(handler):
+ if handler.headers.get("Range") != "bytes=0-0":
+ modes.append(dl.connections)
+ if len(modes) < 3:
+ handler.send_error(refused_status if len(modes) == 1 else 503)
+ return
+ original_get(handler)
+
+ monkeypatch.setattr(RangeHandler, "do_GET", respond)
+ monkeypatch.setattr(dl, "_wait_retry", waits.append)
+ dl.run()
+ assert dest.read_bytes() == payload
+ assert modes[0] > 1
+ assert modes[1:] == [1, 1], "a network retry must not undo the CDN downgrade"
+ assert len(waits) == 1
+ assert dl.connections == modes[0], "the downgrade belongs to this source, not later downloads"
diff --git a/tests/pm/test_downloader.py b/tests/pm/test_downloader.py
index fb1461610a9..2c29b09da97 100644
--- a/tests/pm/test_downloader.py
+++ b/tests/pm/test_downloader.py
@@ -358,32 +358,16 @@ def test_pause_mid_plan_resumes_to_completion(dl_server, tmp_path):
_Handler.payloads["/b"] = p_b
da, db = tmp_path / "a.bin", tmp_path / "b.bin"
partials = tmp_path / "partials"
- _Handler.slow_per_chunk = 0.01
-
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
+ def pause_second_source(done, total, ranges):
+ if ranges.get(db.name):
+ dl.pause()
- 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")
+ 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 --git a/tests/pm/test_network.py b/tests/pm/test_network.py
new file mode 100644
index 00000000000..271ed5a28e5
--- /dev/null
+++ b/tests/pm/test_network.py
@@ -0,0 +1,93 @@
+"""Network retry policy keeps permanent errors immediate and attempts bounded."""
+
+import errno
+import http.client
+import socket
+import ssl
+import urllib.error
+from datetime import datetime, timezone
+from email.message import Message
+from email.utils import format_datetime
+
+import pytest
+
+from pm import network
+from pm.downloader import DownloadPaused, HashError
+
+
+def _http_error(status, retry_after=None):
+ headers = Message()
+ if retry_after is not None:
+ headers["Retry-After"] = retry_after
+ return urllib.error.HTTPError("https://example.invalid/tool", status, "failed", headers, None)
+
+
[email protected]("error,retried", [
+ *[pytest.param(_http_error(code), True, id=f"http-{code}") for code in (408, 429, 500, 502, 503, 504)],
+ *[pytest.param(_http_error(code), False, id=f"http-{code}") for code in (400, 401, 403, 404, 410, 501, 505)],
+ pytest.param(urllib.error.URLError(TimeoutError("timeout")), True, id="connect-timeout"),
+ pytest.param(TimeoutError("timeout"), True, id="read-timeout"),
+ pytest.param(ConnectionResetError("reset"), True, id="connection-reset"),
+ pytest.param(http.client.RemoteDisconnected("closed"), True, id="remote-close"),
+ pytest.param(http.client.IncompleteRead(b"prefix", 100), True, id="short-read"),
+ pytest.param(socket.gaierror(socket.EAI_AGAIN, "temporary"), True, id="temporary-dns"),
+ pytest.param(socket.gaierror(socket.EAI_NONAME, "no name"), False, id="invalid-host"),
+ pytest.param(ssl.SSLEOFError("eof"), True, id="tls-eof"),
+ pytest.param(ssl.SSLCertVerificationError("certificate"), False, id="tls-certificate"),
+ pytest.param(urllib.error.URLError(ssl.SSLCertVerificationError("certificate")), False, id="wrapped-certificate"),
+ pytest.param(OSError(errno.ENOSPC, "full"), False, id="disk-full"),
+ pytest.param(PermissionError("denied"), False, id="filesystem-denied"),
+ pytest.param(HashError("bad pin"), False, id="hash"),
+ pytest.param(DownloadPaused("pause"), False, id="pause"),
+ pytest.param(KeyboardInterrupt(), False, id="interrupt"),
+ pytest.param(ValueError("bad archive"), False, id="invalid-data"),
+])
+def test_only_transient_failures_use_a_finite_retry_budget(error, retried):
+ attempts = []
+ waits = []
+
+ def fail():
+ attempts.append(None)
+ raise error
+
+ with pytest.raises(type(error)) as caught:
+ network.retry_network(fail, wait=waits.append)
+ assert caught.value is error
+ expected = network._ATTEMPTS if retried else 1
+ assert len(attempts) == expected
+ assert len(waits) == expected - 1
+ assert all(0 < delay <= network._MAX_DELAY for delay in waits)
+ assert waits == sorted(waits)
+
+
[email protected]("retry_after,minimum", [
+ (None, 1),
+ ("7", 7),
+ ("-5", 1),
+ ("not a date", 1),
+ pytest.param("9" * 400, network._MAX_DELAY, id="oversized-delay"),
+ ("future-date", 12),
+ ("expired-date", 1),
+])
+def test_retry_after_is_bounded_and_interruptible(monkeypatch, retry_after, minimum):
+ now = datetime(2020, 1, 1, tzinfo=timezone.utc).timestamp()
+ monkeypatch.setattr(network.time, "time", lambda: now)
+ if retry_after in ("future-date", "expired-date"):
+ offset = 12 if retry_after == "future-date" else -12
+ retry_after = format_datetime(datetime.fromtimestamp(now + offset, timezone.utc), usegmt=True)
+ error = _http_error(503, retry_after)
+ attempts = []
+ waits = []
+
+ def fail():
+ attempts.append(None)
+ raise error
+
+ def cancel(delay):
+ waits.append(delay)
+ raise DownloadPaused("cancelled during backoff")
+
+ with pytest.raises(DownloadPaused):
+ network.retry_network(fail, wait=cancel)
+ assert len(attempts) == len(waits) == 1
+ assert minimum <= waits[0] <= network._MAX_DELAY
diff --git a/tests/pm/test_network_retries.py b/tests/pm/test_network_retries.py
new file mode 100644
index 00000000000..5c30d93a15e
--- /dev/null
+++ b/tests/pm/test_network_retries.py
@@ -0,0 +1,136 @@
+"""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
+
+
[email protected]("failure_phase", [
+ "probe", "probe-disconnect", "probe-empty-body", "ranged", "single",
+ "interrupted", "single-interrupted",
+])
[email protected]("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()) == []
+
+
[email protected]("reader_name", ["hash", "json", "text", "digests"])
[email protected]("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
diff --git a/tests/pm/test_stage_only.py b/tests/pm/test_stage_only.py
index 483d6d6a635..43b9acbb23f 100644
--- a/tests/pm/test_stage_only.py
+++ b/tests/pm/test_stage_only.py
@@ -171,16 +171,15 @@ def test_stage_only_repin_same_version_rebuilds(tmp_path, sandbox, monkeypatch):
@pytest.mark.parametrize("error_name", ["HashError", "DownloadPaused"])
-def test_permanent_or_paused_download_is_not_retried(monkeypatch, tmp_path, error_name):
+def test_permanent_or_paused_download_is_not_retried(error_name):
from pm import downloader
+ from pm.network import retry_network
- class FailingStore:
- def fetch(self, *args, **kwargs):
- raise getattr(downloader, error_name)("stop")
+ def fail():
+ raise getattr(downloader, error_name)("stop")
- monkeypatch.setattr("time.sleep", lambda _: pytest.fail("permanent failure was retried"))
with pytest.raises(getattr(downloader, error_name)):
- ensure_mod._fetch_with_retry(FailingStore(), "https://example.test/tool", "digest", tmp_path)
+ retry_network(fail, wait=lambda _: pytest.fail("permanent failure was retried"))
@pytest.mark.parametrize("failure", ["fetch", "publish"])
@@ -199,7 +198,7 @@ def test_repin_failure_preserves_previous_staged_entry(sandbox, monkeypatch, fai
raise InstallError("stage-test", "injected staging failure")
if failure == "fetch":
- monkeypatch.setattr(ensure_mod, "_fetch_with_retry", fail)
+ monkeypatch.setattr(sandbox, "fetch", fail)
else:
monkeypatch.setattr(sandbox, "publish", fail)
with pytest.raises(InstallError, match="injected staging failure"):
diff --git a/tests/pm/test_store_resume.py b/tests/pm/test_store_resume.py
index c6b0c359cfa..47a232028a6 100644
--- a/tests/pm/test_store_resume.py
+++ b/tests/pm/test_store_resume.py
@@ -82,7 +82,9 @@ def test_store_fetch_resumes_interrupted_download(tmp_path, dl_server, monkeypat
assert (partials / f"{key}.ranges").is_file()
first = list(_Handler.ranges_seen)
- assert len(first) == 1, f"expected a single-range first fetch, saw {first}"
+ assert first[0][1] == 0
+ assert len(first) > 1, "the persistent outage must exhaust automatic retries"
+ assert all(start == _Handler.abort_after for _, start, _ in first[1:])
# Second fetch, server intact: must resume from the durable prefix.
_Handler.abort_after = None
diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.md
index 275788ffb1e..f153f7234f0 100644
--- a/website/docs/reference/package-management.md
+++ b/website/docs/reference/package-management.md
@@ -320,6 +320,24 @@ The complete desktop builder also builds the JavaScript surfaces, generates
launchers, and invokes native packaging. Maintainers can read
[Building the Desktop Installers](https://github.com/NousResearch/hermes-agent/blob/main/apps/desktop/BUILDING.md).
+## Network retries
+
+PM retries transient HTTP failures during tool downloads, artifact hashing and
+version lookups. Each probe or transfer gets at most four attempts. Backoff
+waits are 1, 2 and 4 seconds. A `Retry-After` header can extend a wait, up to
+30 seconds. Each retry reports its cause, delay and next attempt in the log.
+
+Retryable HTTP statuses are 408, 429, 500, 502, 503 and 504. Connection resets,
+timeouts, temporary DNS failures and interrupted response bodies also retry.
+Ranged downloads retain completed bytes. Servers without range support require
+a fresh stream. Pause interrupts backoff and preserves the partial download.
+
+PM does not retry bad hashes, certificate failures, local filesystem errors or
+other permanent failures. A successful probe followed by a range GET 403 or 404
+retains the CDN fallback: one serial attempt at the missing ranges. Extraction,
+verification and publication are not repeated. Python and npm package requests
+remain under uv and npm's own retry policies.
+
## Diagnostics
- **Missing or outdated tool:** read `hermes pm doctor`, then use an explicit PM install on a writable installation.