Skip to content

The agent that grows with you

feat(pm): preserve progress across interrupted downloads

akfostere5470c9888a2
diff --git a/pm/downloader.py b/pm/downloader.py
index bad802cc5fb..81cdff8d82d 100644
--- a/pm/downloader.py
+++ b/pm/downloader.py
@@ -48,6 +48,7 @@ from pm.network import edge_block, is_transient, retry_network
_UA = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) hermes-pm/1.0", "Accept-Encoding": "identity"}
_LOOPBACK = ("http://127.0.0.1:", "http://localhost:", "http://[::1]:")
_CHUNK = 1 << 20 # read/write block, also the minimum range size
+_CHECKPOINT_SECONDS = 5.0
class _HttpsRedirectHandler(urllib.request.HTTPRedirectHandler):
@@ -279,6 +280,7 @@ class Download:
self.partials_dir = paths.partials_root()
self._owns_pause_event = pause_event is None
self._paused = pause_event if pause_event is not None else threading.Event()
+ self._durable_done = 0
def pause(self) -> None:
"""Request a stop between chunks; run() raises DownloadPaused."""
@@ -374,20 +376,24 @@ class Download:
return source.dest.stat().st_size
# Recheck identity after waiting for another process's partial.
remote = self._probe(source.url)
- tick(self._partial_ranges(source, remote) if remote.ranged else [], remote.total)
+ covered = self._partial_ranges(source, remote) if remote.ranged else []
+ self._durable_done = sum(end - start for start, end in covered)
+ tick(covered, remote.total)
+ resumable = bool(remote.total and remote.ranged and (source.sha256 or remote.etag))
def report(written: _Ranges) -> None:
tick(written, remote.total)
def fetch() -> int:
self._check_pause()
- if remote.total and remote.ranged and (source.sha256 or remote.etag):
+ if resumable:
return self._fetch_ranged(source, remote, report)
return self._fetch_single(source, remote, report)
configured_connections = self.connections
try:
- size = retry_network(fetch, wait=self._wait_retry)
+ size = retry_network(fetch, wait=self._wait_retry,
+ progress=(lambda: self._durable_done) if self.resume and resumable else None)
except (OSError, http.client.HTTPException) as exc:
if isinstance(exc, urllib.error.URLError) or is_transient(exc):
raise DownloadTransportError(source.url, exc) from exc
@@ -467,8 +473,8 @@ class Download:
def _write_sidecar(side: Path, part: Path, covered: _Ranges, remote: _Remote, sha256: str) -> None:
from pm.filesystem import durable_write_bytes
- # All writers have closed before coverage is persisted. A sidecar can
- # describe durable bytes, never data still buffered in a worker.
+ # Workers flush before announcing coverage. Snapshot those ranges,
+ # fsync the data, then atomically publish only that durable snapshot.
with part.open("r+b") as stream:
os.fsync(stream.fileno())
record = {"total": remote.total, "etag": remote.etag, "sha256": sha256, "ranges": covered}
@@ -491,6 +497,7 @@ class Download:
side.unlink(missing_ok=True)
raise protocol_error
self._write_sidecar(side, part, covered, remote, source.sha256)
+ self._durable_done = sum(end - start for start, end in covered)
if self._paused.is_set():
raise DownloadPaused(source.url)
if errors:
@@ -509,6 +516,35 @@ class Download:
raise http.client.IncompleteRead(b"", remote.total - written)
return written
+ def _read_range(self, source: Source, remote: _Remote, part: Path,
+ start: int, end: int, stop: threading.Event, record) -> None:
+ if self._paused.is_set() or stop.is_set():
+ return
+ 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 = response.read(min(_CHUNK, end - position))
+ if not chunk:
+ raise http.client.IncompleteRead(b"", end - position)
+ stream.write(chunk)
+ stream.flush()
+ position += len(chunk)
+ # A complete checkpoint must not bypass the body-bounds check
+ # if the process dies between the last write and EOF validation.
+ if position == end and response.read(1):
+ raise _RangeError("range body exceeds its declared bounds")
+ record(start, position)
+
def _ranged_attempt(self, source: Source, remote: _Remote, part: Path,
covered: _Ranges, connections: int, tick) -> tuple[_Ranges, list[Exception]]:
from concurrent.futures import ThreadPoolExecutor
@@ -525,35 +561,18 @@ class Download:
pending = len(ranges)
covered = list(covered)
reported = list(covered)
+ checkpointed = list(covered)
+ next_checkpoint = time.monotonic() + _CHECKPOINT_SECONDS
+
+ def record(start: int, position: int) -> None:
+ with lock:
+ covered[:] = _coalesce(covered + [(start, position)])
+ updated.set()
def worker(start: int, end: int) -> None:
nonlocal pending
try:
- if self._paused.is_set() or stop.is_set():
- return
- 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 = response.read(min(_CHUNK, end - position))
- if not chunk:
- raise http.client.IncompleteRead(b"", end - position)
- stream.write(chunk)
- position += len(chunk)
- with lock:
- covered[:] = _coalesce(covered + [(start, position)])
- updated.set()
- if response.read(1):
- raise _RangeError("range body exceeds its declared bounds")
+ self._read_range(source, remote, part, start, end, stop, record)
except Exception as exc:
if isinstance(exc, urllib.error.HTTPError):
exc.close()
@@ -570,11 +589,23 @@ class Download:
observer_failed = False
finished = not ranges
while not finished:
- updated.wait()
+ updated.wait(max(0.0, next_checkpoint - time.monotonic()))
with lock:
snapshot = list(covered)
finished = pending == 0
updated.clear()
+ now = time.monotonic()
+ written = sum(end - start for start, end in snapshot)
+ if now >= next_checkpoint:
+ if snapshot != checkpointed:
+ try:
+ self._write_sidecar(part.with_suffix(".ranges"), part, snapshot, remote, source.sha256)
+ except BaseException:
+ stop.set()
+ raise
+ self._durable_done = written
+ checkpointed = snapshot
+ next_checkpoint = time.monotonic() + _CHECKPOINT_SECONDS
# Only the coordinator observes progress. Slow UI/worker IPC
# coalesces intermediate snapshots, never holds up range writes.
if not observer_failed and snapshot != reported:
diff --git a/pm/network.py b/pm/network.py
index fccc64bfbf6..cb45a5f76e2 100644
--- a/pm/network.py
+++ b/pm/network.py
@@ -17,6 +17,7 @@ from typing import Callable, TypeVar
_T = TypeVar("_T")
_ATTEMPTS = 4
_MAX_DELAY = 30.0
+_MAX_RECOVERY_DELAY = 300.0
_HTTP_RETRY = frozenset({408, 429, 500, 502, 503, 504})
_R2_HOSTS = frozenset({"hermes-assets.nousresearch.com"})
_NETWORK_ERRNOS = frozenset({
@@ -68,7 +69,7 @@ def edge_block(exc: BaseException) -> str | None:
"retry from another network")
-def _delay(exc: Exception, attempt: int) -> float:
+def _delay(exc: Exception, attempt: int, *, maximum: float | None = _MAX_DELAY) -> float:
delay = float(2 ** attempt)
if isinstance(exc, urllib.error.HTTPError):
value = exc.headers.get("Retry-After", "") if exc.headers else ""
@@ -84,30 +85,50 @@ def _delay(exc: Exception, attempt: int) -> float:
except (TypeError, ValueError, OverflowError):
retry_after = 0.0
delay = max(delay, retry_after)
- return min(delay, _MAX_DELAY)
+ return delay if maximum is None else min(delay, maximum)
def retry_network(
operation: Callable[[], _T], *, wait: Callable[[float], None] | None = None,
+ progress: Callable[[], int] | 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.
+ Downloads supply ``progress``: durable forward progress renews their
+ budget. Metadata and non-resumable requests still get four attempts.
"""
- attempt = 1
+ failures_since_progress = 0
+ backoff = 0
+ saved = progress() if progress is not None else 0
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:
+ if not is_transient(exc):
raise
- delay = _delay(exc, attempt - 1)
- attempt += 1
+ current = progress() if progress is not None else saved
+ if current > saved:
+ failures_since_progress = 0
+ backoff = 0
+ saved = current
+ else:
+ failures_since_progress += 1
+ if failures_since_progress >= _ATTEMPTS:
+ raise
+ delay = _delay(exc, backoff)
+ if progress is not None:
+ # Do not retry before Retry-After or wait hours for an embargo.
+ requested = _delay(exc, 0, maximum=None)
+ if requested > _MAX_RECOVERY_DELAY:
+ raise
+ delay = max(delay, requested)
+ backoff += 1
logging.getLogger(__name__).warning(
- "network request failed (%s); retrying in %gs (attempt %d/%d)",
- exc, delay, attempt, _ATTEMPTS,
+ "network request failed (%s); retrying in %gs (%d/%d failures without progress)",
+ exc, delay, failures_since_progress, _ATTEMPTS,
)
(wait or time.sleep)(delay)
diff --git a/tests/pm/test_download_checkpoint_policy.py b/tests/pm/test_download_checkpoint_policy.py
new file mode 100644
index 00000000000..6d4f7d0273f
--- /dev/null
+++ b/tests/pm/test_download_checkpoint_policy.py
@@ -0,0 +1,66 @@
+"""Checkpoint rate and retry delays do not grow with connection speed."""
+from __future__ import annotations
+
+import hashlib
+from http.server import BaseHTTPRequestHandler
+from types import SimpleNamespace
+
+import pytest
+
+from pm import downloader
+from tests.pm._fixtures import threaded_server
+from tests.pm._range_server import RangeHandler, dl_server as dl_server, url # noqa: PLC0414 -- pytest fixture re-export
+
+
+def test_fast_transfer_does_not_sync_each_byte_threshold(tmp_path, monkeypatch, dl_server):
+ payload = b"w" * (32 << 20)
+ RangeHandler.payloads = {"/fast": payload}
+ download = downloader.Download(
+ [downloader.Source(url(dl_server, "/fast"), tmp_path / "model", hashlib.sha256(payload).hexdigest())],
+ partials_dir=tmp_path / "partials", connections=1,
+ )
+ checkpoints = []
+ original = download._write_sidecar
+
+ def save(*args):
+ checkpoints.append(None)
+ return original(*args)
+
+ monkeypatch.setattr(download, "_write_sidecar", save)
+ monkeypatch.setattr(downloader, "time", SimpleNamespace(monotonic=lambda: 0.0))
+ download.run()
+ assert (tmp_path / "model").read_bytes() == payload
+ assert len(checkpoints) == 1 # The attempt still saves its final checkpoint.
+
+
[email protected]("failed_stage", ["probe", "single-stream"])
+def test_non_resumable_requests_keep_the_existing_retry_after_cap(tmp_path, monkeypatch, failed_stage):
+ payload = b"model bytes"
+ failed = False
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ nonlocal failed
+ probe = self.headers.get("Range") == "bytes=0-0"
+ if not failed and probe == (failed_stage == "probe"):
+ failed = True
+ self.send_response(503)
+ self.send_header("Retry-After", "60")
+ self.end_headers()
+ return
+ self.send_response(200) # This source does not support ranges.
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, *args):
+ pass
+
+ waits = []
+ with threaded_server(Handler) as server:
+ source = downloader.Source(f"http://127.0.0.1:{server.server_port}/model", tmp_path / "model")
+ download = downloader.Download([source], partials_dir=tmp_path / "partials")
+ monkeypatch.setattr(download, "_wait_retry", waits.append)
+ download.run()
+ assert waits == [30]
+ assert source.dest.read_bytes() == payload
diff --git a/tests/pm/test_download_continuity.py b/tests/pm/test_download_continuity.py
new file mode 100644
index 00000000000..4eaf3929861
--- /dev/null
+++ b/tests/pm/test_download_continuity.py
@@ -0,0 +1,115 @@
+"""Interrupted bodies retain durable progress across attempts and processes."""
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+import re
+import subprocess
+import sys
+from http.server import BaseHTTPRequestHandler
+from threading import Event
+
+from pm.downloader import Download, Source
+from tests.pm._fixtures import threaded_server
+
+
+def test_useful_progress_survives_more_than_four_interrupted_bodies(tmp_path, monkeypatch):
+ block = 1 << 20
+ payload = bytes(range(256)) * (10 * block // 256)
+ requests = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ start, end = map(int, re.fullmatch(r"bytes=(\d+)-(\d+)", self.headers["Range"]).groups())
+ probe = (start, end) == (0, 0)
+ self.send_response(206)
+ self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
+ self.send_header("Content-Length", str(end - start + 1))
+ self.send_header("ETag", '"opaque-stable-representation"')
+ self.end_headers()
+ if not probe:
+ requests.append((start, end))
+ stop = min(end + 1, start + block) if not probe and len(requests) <= 6 else end + 1
+ self.wfile.write(payload[start:stop])
+ self.wfile.flush()
+ self.close_connection = True
+
+ def log_message(self, *args):
+ pass
+
+ destination = tmp_path / "model.gguf"
+ with threaded_server(Handler) as server:
+ source = Source(f"http://127.0.0.1:{server.server_port}/model", destination,
+ hashlib.sha256(payload).hexdigest())
+ download = Download([source], connections=1, partials_dir=tmp_path / "partials")
+ monkeypatch.setattr(download, "_wait_retry", lambda _: None)
+ download.run()
+ assert destination.read_bytes() == payload
+ assert len(requests) == 7
+ assert [start for start, _ in requests] == [index * block for index in range(7)]
+
+
+def test_forced_termination_recovers_checkpoint_before_request_finishes(tmp_path):
+ payload = b"durable model bytes" * (1 << 20)
+ waiting = Event()
+ release = Event()
+ requests = []
+ checkpoint = 8 << 20
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ start, end = map(int, re.fullmatch(r"bytes=(\d+)-(\d+)", self.headers["Range"]).groups())
+ probe = (start, end) == (0, 0)
+ self.send_response(206)
+ self.send_header("Content-Range", f"bytes {start}-{end}/{len(payload)}")
+ self.send_header("Content-Length", str(end - start + 1))
+ self.send_header("ETag", '"same-file-after-restart"')
+ self.end_headers()
+ if not probe:
+ requests.append((start, end))
+ try:
+ if not probe and len(requests) == 1:
+ self.wfile.write(payload[start:start + checkpoint])
+ self.wfile.flush()
+ waiting.set()
+ release.wait(15)
+ return
+ self.wfile.write(payload[start:end + 1])
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+ def log_message(self, *args):
+ pass
+
+ partials = tmp_path / "partials"
+ destination = tmp_path / "model.gguf"
+ with threaded_server(Handler) as server:
+ url = f"http://127.0.0.1:{server.server_port}/model"
+ side = partials / (hashlib.sha256(url.encode()).hexdigest() + ".ranges")
+ script = (
+ "from pathlib import Path\nimport sys\nfrom pm.downloader import Download, Source\n"
+ "Download([Source(sys.argv[1],Path(sys.argv[2]),sys.argv[4])],"
+ "partials_dir=Path(sys.argv[3]),connections=1).run()\n"
+ )
+ child = subprocess.Popen([sys.executable, "-c", script, url, str(destination), str(partials),
+ hashlib.sha256(payload).hexdigest()],
+ cwd=Path(__file__).resolve().parents[2],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ try:
+ assert waiting.wait(10), "child never received model data"
+ from tests.waiting import wait_until
+
+ assert wait_until(side.is_file, timeout=10), "no checkpoint during an unfinished request"
+ saved = json.loads(side.read_text())
+ retained = sum(end - start for start, end in saved["ranges"])
+ assert retained >= checkpoint
+ finally:
+ child.kill()
+ child.communicate(timeout=5)
+ release.set()
+ assert not destination.exists()
+ Download([Source(url, destination, hashlib.sha256(payload).hexdigest())],
+ partials_dir=partials, connections=1).run()
+ assert destination.read_bytes() == payload
+ assert requests[1][0] >= checkpoint
diff --git a/tests/pm/test_network.py b/tests/pm/test_network.py
index 06164c54742..5f094b7e501 100644
--- a/tests/pm/test_network.py
+++ b/tests/pm/test_network.py
@@ -114,3 +114,40 @@ def test_download_failure_names_only_a_cdn_firewall_refusal(status, headers, cdn
assert "CDN firewall" not in message
else:
assert f"mirror.example's CDN firewall ({cdn}) refused this network" in message, message
+
+
[email protected]("retry_after,expected", [("7", 7), ("60", 60), ("600", None)])
+def test_resumable_transfer_honors_retry_after_or_stops(retry_after, expected):
+ attempts = []
+ waits = []
+
+ def request():
+ attempts.append(None)
+ if len(attempts) == 1:
+ raise _http_error(503, retry_after)
+ return "complete"
+
+ if expected is None:
+ with pytest.raises(urllib.error.HTTPError):
+ network.retry_network(request, wait=waits.append, progress=lambda: 0)
+ assert len(attempts) == 1 and not waits
+ else:
+ assert network.retry_network(request, wait=waits.append, progress=lambda: 0) == "complete"
+ assert waits == [expected]
+
+
+def test_progress_renews_only_the_consecutive_failure_budget():
+ attempts = []
+ waits = []
+ durable = [0]
+
+ def request():
+ attempts.append(None)
+ if len(attempts) == 1:
+ durable[0] += 1
+ raise ConnectionResetError("disconnected")
+
+ with pytest.raises(ConnectionResetError):
+ network.retry_network(request, wait=waits.append, progress=lambda: durable[0])
+ assert len(attempts) == 1 + network._ATTEMPTS
+ assert waits == [1, 2, 4, 8]
diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.md
index bea6754db2a..870c3cf2833 100644
--- a/website/docs/reference/package-management.md
+++ b/website/docs/reference/package-management.md
@@ -569,14 +569,18 @@ launchers, and invokes native packaging. Maintainers can read
## 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.
+version lookups. Probes and non-resumable transfers get at most four attempts.
+Their backoff waits are 1, 2 and 4 seconds. A `Retry-After` header can extend
+these waits up to 30 seconds. Resumable transfers renew their retry budget
+when they save new progress; four failures without new progress stop retries.
+They honor `Retry-After` up to five minutes and stop for longer requested waits.
+Each retry logs its cause, delay and consecutive failures without progress.
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.
+Ranged downloads save durable progress every five seconds and after each attempt.
+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