Skip to content

The agent that grows with you

merge: origin/main (19 commits) into ethie/pm-clean

ethernet05609d209290
diff --cc pm/downloader.py
index b93fe2e6a59,00000000000..5ee83b71811
mode 100644,000000..100644
--- a/pm/downloader.py
+++ b/pm/downloader.py
@@@ -1,610 -1,0 +1,648 @@@
+"""Resumable, hash-verified, multi-connection downloads.
+
+Every large fetch in Hermes goes through this one downloader: pm
+packages (pinned sha256 from lock.json) and local models (deliberately
+unverified — catalog sizes may lag an upstream re-upload, so sha256 is
+optional per source).
+
+Partial state is the downloader's own. Files land in a managed
+partials area keyed by sha256(url). One process owns each key while it
+transfers or publishes. Complete bytes are copied to destination-local
+staging before atomic replacement; a failed copy leaves the old destination
+intact. An interrupted download keeps its durable ranges bound to the remote
+length, strong ETag and optional pinned hash. Unidentified data restarts
+instead of mixing bytes from different upstream versions.
+
+The progress callback reports the whole job AND the per-dest bitmap:
+``progress(overall_done, overall_total, ranges)`` where ``ranges`` maps
+the destination path to half-open [start, end) runs. ``done_bytes`` is the sum;
+``ranges`` is the shape — one datum, two resolutions.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import http.client
+import json
++import os
+import re
+import shutil
+import logging
+import threading
++import time
+import urllib.error
+import urllib.request
++from contextlib import suppress
+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
+# least-privileged string every asset CDN accepts.
+_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
+
+
+class _HttpsRedirectHandler(urllib.request.HTTPRedirectHandler):
+ """The https-only gate must hold across redirects, not just the first
+ hop — an https URL could otherwise bounce to http mid-download and
+ carry the payload in the clear."""
+
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ if not (newurl.startswith("https://") or newurl.startswith(_LOOPBACK)):
+ raise DownloadError(f"refusing redirect to non-https url: {newurl}")
+ # urllib preserves our User-Agent and range headers. Do not re-add
+ # arbitrary headers after its redirect policy has processed them.
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
+
+
+_OPENER = urllib.request.build_opener(_HttpsRedirectHandler())
+
+
+class DownloadError(RuntimeError):
+ """Base class for downloader failures."""
+
+
+def _validate_range(response, start: int, end: int, total: int | None = None) -> int:
+ """A range body is useful only for the exact requested interval."""
+ match = re.fullmatch(r"bytes (\d+)-(\d+)/(\d+)", response.headers.get("Content-Range", ""))
+ if response.status != 206 or match is None:
+ raise _RangeError("server did not honor the requested byte range")
+ first, last, size = map(int, match.groups())
+ if (first, last) != (start, end - 1) or size < end or (total is not None and size != total):
+ raise _RangeError("server returned a different byte range or representation size")
+ length = response.headers.get("Content-Length")
+ if length is not None and (not length.isdecimal() or int(length) != end - start):
+ raise _RangeError("range Content-Length does not match its bounds")
+ if response.headers.get("Content-Encoding", "identity").lower() != "identity":
+ raise _RangeError("encoded response cannot be written into an identity byte range")
+ return size
+
+
+class _RangeError(DownloadError):
+ """Range or representation identity changed; partial bytes cannot be reused."""
+
+
+@dataclass(frozen=True)
+class _Remote:
+ total: int
+ ranged: bool
+ etag: str = ""
+
+
+def _strong_etag(response) -> str:
+ value = response.headers.get("ETag", "")
+ return value if value.startswith('"') and value.endswith('"') else ""
+
+
+class HashError(DownloadError):
+ """The downloaded bytes did not match the pinned sha256."""
+
+
+class DownloadPaused(DownloadError):
+ """pause() was called mid-download; partials were left intact."""
+
+
+class DownloadTransportError(DownloadError):
+ """An exhausted network request, with its original status and URL."""
+
+ def __init__(self, url: str, cause: Exception):
+ self.url = url
+ self.status = cause.code if isinstance(cause, urllib.error.HTTPError) else None
+ self.fallback_allowed = (
+ self.status in (401, 403, 404, 410) or is_transient(cause)
+ )
+ reason = f"{cause}; the host refused access" if self.status in (401, 403) else str(cause)
+ super().__init__(f"download failed from {url}: {reason}")
+
+
+@dataclass(frozen=True)
+class Source:
+ url: str
+ dest: Path
+ sha256: str = "" # "" = no integrity check (model catalog policy)
+ fallbacks: tuple[str, ...] = ()
+
+
+_Ranges = list[tuple[int, int]]
+ProgressFn = Callable[[int, int, dict[str, _Ranges]], None]
+
+
+def _coalesce(ranges: _Ranges) -> _Ranges:
+ """Merge half-open [start, end) ranges into sorted, disjoint runs."""
+ runs = sorted((a, b) for a, b in ranges if b > a)
+ if not runs:
+ return []
+ out: _Ranges = []
+ a, b = runs[0]
+ for x, y in runs[1:]:
+ if x <= b:
+ b = max(b, y)
+ else:
+ out.append((a, b))
+ a, b = x, y
+ out.append((a, b))
+ return out
+
+
+def _missing(total: int, covered: _Ranges) -> _Ranges:
+ """The gaps in [0, total) not covered by the coalesced bitmap."""
+ missing: _Ranges = []
+ cursor = 0
+ for a, b in _coalesce(covered):
+ if a > cursor:
+ missing.append((cursor, a))
+ cursor = max(cursor, b)
+ if cursor < total:
+ missing.append((cursor, total))
+ return missing
+
+
+def _sha256_file(path: Path) -> str:
+ digest = hashlib.sha256()
+ with open(path, "rb") as f:
+ for block in iter(lambda: f.read(_CHUNK), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
++# How long a finished download may wait for another process to let go of it before the
++# publication is reported as failed.
++_RELEASE_WAIT_SECONDS = 60.0
++
++
++def replace_when_released(tmp: Path, dest: Path, *, timeout: float = _RELEASE_WAIT_SECONDS) -> None:
++ """Rename a finished download into place, waiting out a transient hold on the file.
++
++ On Windows a multi-gigabyte file whose last write handle just closed is often still open
++ to an antivirus or indexing scan, and renaming it fails with a permission error until the
++ scan lets go — which for a 22 GB model can take many seconds. ``os.replace`` is retried
++ through that window; it never falls back to copying (``shutil.move`` does, which duplicates
++ the whole file and then reports the leftover's failed delete as the download's failure).
++ A hold that outlasts the window raises a plain-language error.
++ """
++ deadline = time.monotonic() + timeout
++ delay = 0.1
++ while True:
++ try:
++ os.replace(tmp, dest)
++ return
++ except PermissionError as exc:
++ if time.monotonic() >= deadline:
++ raise RuntimeError(
++ f"The download finished, but another program (usually an antivirus scan) kept "
++ f"{tmp.name} open and it could not be renamed into place. Please try again.") from exc
++ time.sleep(delay)
++ delay = min(delay * 2, 2.0)
++
++
+def _existing_dest_ok(source: "Source") -> bool:
+ """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:
+ return _sha256_file(source.dest) == source.sha256
+ except OSError:
+ return False
+
+
+class Download:
+ """One resumable download job: a plan of sources, run in parallel.
+
+ Per source: probe Range support, preallocate a flat .part in the
+ managed partials area, split into at most ``connections`` byte
+ ranges, and stream each with a ``Range:`` header from a worker
+ thread. A lock-protected bitmap records which ranges are actually
+ durable; on resume only the missing ranges are re-fetched.
+
+ ``Source.dest`` is atomically replaced only after successful transfer.
+ ``pause()`` stops between chunks or while waiting for a partial's owner;
+ ``run()`` raises :class:`DownloadPaused` and preserves resumable bytes.
+ """
+
+ CONNECTIONS = 8
+
+ def __init__(
+ self,
+ sources: Sequence[Source],
+ *,
+ resume: bool = True,
+ connections: int = CONNECTIONS,
+ partials_dir: Optional[Path] = None,
+ pause_event: Optional[threading.Event] = None,
+ ):
+ self.sources = [Source(s.url, Path(s.dest), s.sha256, tuple(s.fallbacks)) for s in sources]
+ self.resume = resume
+ self.connections = max(1, int(connections))
+ if partials_dir:
+ self.partials_dir = Path(partials_dir)
+ else:
+ from pm import paths
+
+ 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()
+
+ def pause(self) -> None:
+ """Request a stop between chunks; run() raises DownloadPaused."""
+ self._paused.set()
+
+ def run(self, progress: Optional[ProgressFn] = None) -> list[Path]:
+ """Fetch every source; return the moved destination paths."""
+ if self._owns_pause_event:
+ self._paused.clear()
+ self._check_pause()
+ self.partials_dir.mkdir(parents=True, exist_ok=True)
+ for source in self.sources:
+ if source.fallbacks and not re.fullmatch(r"[a-f0-9]{64}", source.sha256):
+ raise ValueError("mirror fallback requires a full lowercase SHA256")
+ for url in (source.url, *source.fallbacks):
+ if not (url.startswith("https://") or url.startswith(_LOOPBACK)):
+ raise ValueError(f"refusing non-https url: {url}")
+
+ # 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] = {}
+ selected: list[Source] = []
+ failures: dict[str, list[DownloadTransportError]] = {}
+ for source in self.sources:
+ self._check_pause()
+ key = str(source.dest)
+ failures[key] = []
+ if _existing_dest_ok(source):
+ remote = _Remote(source.dest.stat().st_size, False)
+ covered = [(0, remote.total)]
+ else:
+ source, remote = self._try_sources(source, lambda candidate: self._probe(candidate.url), failures[key])
+ 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)
+ selected.append(source)
+ totals[key] = remote.total
+ coverage[key] = covered
+
+ def report(key: str, written: _Ranges, total: int, *, complete: bool = False) -> None:
+ totals[key] = total
+ if total or complete:
+ unknown.discard(key)
+ else:
+ unknown.add(key)
+ # The last key identifies the source reporting this tick.
+ coverage.pop(key, None)
+ coverage[key] = list(written)
+ if progress is not None:
+ 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))
+
+ for source in selected:
+ key = str(source.dest)
+
+ def tick(written: _Ranges, total: int) -> None:
+ report(key, written, total)
+
+ _, size = self._try_sources(source, lambda candidate: self._transfer(candidate, tick), failures[key])
+ report(key, [(0, size)], size, complete=True)
+ return [source.dest for source in self.sources]
+
+ def _try_sources(self, source: Source, operation, failures: list[DownloadTransportError]):
+ urls = tuple(dict.fromkeys((source.url, *source.fallbacks)))
+ for index, url in enumerate(urls):
+ self._check_pause()
+ candidate = Source(url, source.dest, source.sha256, urls[index + 1:])
+ try:
+ return candidate, operation(candidate)
+ except DownloadTransportError as exc:
+ failures.append(exc)
+ if not exc.fallback_allowed or index == len(urls) - 1:
+ if len(failures) == 1:
+ raise
+ raise DownloadError("\n".join(str(error) for error in failures)) from exc
+ logging.getLogger(__name__).warning("%s; trying pinned mirror %s", exc, urls[index + 1])
+
+ def _transfer(self, source: Source, tick) -> int:
+ from pm.download_state import partial_lock
+
+ with partial_lock(self.partials_dir, self._key(source.url), cancelled=self._paused.is_set) as acquired:
+ if not acquired:
+ raise DownloadPaused(source.url)
+ self._check_pause()
+ if _existing_dest_ok(source):
+ 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)
+
+ 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):
+ 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)
+ except (OSError, http.client.HTTPException) as exc:
+ if isinstance(exc, urllib.error.URLError) or is_transient(exc):
+ raise DownloadTransportError(source.url, exc) from exc
+ raise
+ 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")
+ return size
+
+ # ── internals ─────────────────────────────────────────────
+
+ def _check_pause(self) -> None:
+ if self._paused.is_set():
+ raise DownloadPaused("download paused")
+
+ def _wait_retry(self, delay: float) -> None:
+ if self._paused.wait(delay):
+ raise DownloadPaused("download paused during retry backoff")
+
+ def _probe(self, url: str) -> _Remote:
+ def request():
+ self._check_pause()
+ req = urllib.request.Request(url, headers={**_UA, "Range": "bytes=0-0"})
+ with _OPENER.open(req, timeout=60) as response:
+ etag = _strong_etag(response)
+ if response.status == 206:
+ total = _validate_range(response, 0, 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 (OSError, http.client.HTTPException) as exc:
+ raise DownloadTransportError(url, exc) from exc
+ except DownloadError:
+ raise
+ except ValueError:
+ return _Remote(0, False)
+
+ def _key(self, url: str) -> str:
+ return hashlib.sha256(url.encode("utf-8")).hexdigest()
+
+ def _load_sidecar(self, side: Path, part: Path, remote: _Remote, sha256: str) -> _Ranges:
+ if not self.resume or not (sha256 or remote.etag):
+ return []
+ try:
+ data = json.loads(side.read_text(encoding="utf-8"))
+ if (data["total"], data["etag"], data["sha256"]) != (remote.total, remote.etag, sha256):
+ return []
+ size = part.stat().st_size
+ ranges = data["ranges"]
+ if not isinstance(ranges, list) or any(
+ not isinstance(row, list) or len(row) != 2
+ or any(type(value) is not int for value in row)
+ or not 0 <= row[0] < row[1] <= min(size, remote.total)
+ for row in ranges
+ ):
+ return []
+ return _coalesce([tuple(row) for row in ranges])
+ except (OSError, ValueError, KeyError, TypeError):
+ return []
+
+ def _partial_ranges(self, source: Source, remote: _Remote) -> _Ranges:
+ key = self._key(source.url)
+ return self._load_sidecar(self.partials_dir / f"{key}.ranges",
+ self.partials_dir / f"{key}.part", remote, source.sha256)
+
+ @staticmethod
+ def _write_sidecar(side: Path, part: Path, covered: _Ranges, remote: _Remote, sha256: str) -> None:
- import os
+ from hermes_cli.runtime_state import _atomic_bytes
+
+ # All writers have closed before coverage is persisted. A sidecar can
+ # describe durable bytes, never data still buffered in a worker.
+ with part.open("r+b") as stream:
+ os.fsync(stream.fileno())
+ record = {"total": remote.total, "etag": remote.etag, "sha256": sha256, "ranges": covered}
+ _atomic_bytes(side, json.dumps(record).encode("utf-8"))
+
+ def _fetch_ranged(self, source: Source, remote: _Remote, tick) -> int:
+ key = self._key(source.url)
+ part = self.partials_dir / f"{key}.part"
+ side = self.partials_dir / f"{key}.ranges"
+ 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)
+ 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 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 http.client.IncompleteRead(b"", remote.total - written)
+ return written
+
+ 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()
+ updated = threading.Event()
+ pending = len(ranges)
+ covered = list(covered)
+ reported = list(covered)
+
+ 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")
+ except Exception as exc:
+ if isinstance(exc, urllib.error.HTTPError):
+ exc.close()
+ with lock:
+ errors.append(exc)
+ stop.set()
+ finally:
+ with lock:
+ pending -= 1
+ updated.set()
+
+ with ThreadPoolExecutor(max_workers=connections, thread_name_prefix="hermes-download") as pool:
+ futures = [pool.submit(worker, start, end) for start, end in ranges]
+ observer_failed = False
+ finished = not ranges
+ while not finished:
+ updated.wait()
+ with lock:
+ snapshot = list(covered)
+ finished = pending == 0
+ updated.clear()
+ # Only the coordinator observes progress. Slow UI/worker IPC
+ # coalesces intermediate snapshots, never holds up range writes.
+ if not observer_failed and snapshot != reported:
+ try:
+ tick(snapshot)
+ except Exception as exc:
+ with lock:
+ errors.append(exc)
+ observer_failed = True
+ stop.set()
+ except BaseException:
+ stop.set()
+ raise
+ reported = snapshot
+
+ for future in futures:
+ future.result()
+ return covered, errors
+
+ def _fetch_single(self, source: Source, remote: _Remote, tick) -> int:
+ # A stream with no strong validator cannot safely reuse earlier bytes.
+ key = self._key(source.url)
+ part = self.partials_dir / f"{key}.part"
+ side = self.partials_dir / f"{key}.ranges"
+ covered: _Ranges = []
+ request = urllib.request.Request(source.url, headers=_UA)
+ try:
+ 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():
+ raise DownloadPaused(source.url)
+ chunk = response.read(_CHUNK)
+ if not chunk:
+ break
+ stream.write(chunk)
+ position += len(chunk)
+ covered = [(0, position)]
+ tick(list(covered))
+ if self._paused.is_set():
+ raise DownloadPaused(source.url)
+ 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
+ self._write_sidecar(side, part, covered, remote, source.sha256)
+ 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:
- part.unlink(missing_ok=True)
- side.unlink(missing_ok=True)
++ # Best effort: a leftover that cannot be removed must not mask the hash error.
++ with suppress(OSError):
++ part.unlink(missing_ok=True)
++ side.unlink(missing_ok=True)
+ raise HashError(
+ f"sha256 mismatch for {source.url}: pinned "
+ f"{source.sha256}, got {actual}")
- import os
+ import tempfile
+
+ self._check_pause()
+ source.dest.parent.mkdir(parents=True, exist_ok=True)
+ fd, name = tempfile.mkstemp(prefix=f".{source.dest.name}-", suffix=".download", dir=source.dest.parent)
+ staged = Path(name)
+ try:
+ with os.fdopen(fd, "wb") as target, part.open("rb") as incoming:
+ shutil.copyfileobj(incoming, target, _CHUNK)
+ target.flush()
+ os.fsync(target.fileno())
+ if staged.stat().st_size != part.stat().st_size:
+ raise DownloadError("destination copy did not preserve the complete download")
+ self._check_pause()
- os.replace(staged, source.dest)
++ replace_when_released(staged, source.dest)
+ finally:
- staged.unlink(missing_ok=True)
- part.unlink(missing_ok=True)
- side.unlink(missing_ok=True)
++ # Best effort: a leftover that cannot be removed must not hide the error that left it.
++ with suppress(OSError):
++ staged.unlink(missing_ok=True)
++ # The published file is what the caller asked for; a partial the OS still holds must not
++ # turn a completed download into a failure.
++ with suppress(OSError):
++ part.unlink(missing_ok=True)
++ side.unlink(missing_ok=True)
diff --cc tests/hermes_cli/test_local_models_routes.py
index 68a40f6a340,7ff868db928..278e29846b6
--- a/tests/hermes_cli/test_local_models_routes.py
+++ b/tests/hermes_cli/test_local_models_routes.py
@@@ -7,8 -7,8 +7,9 @@@ downloads are stubbed at the urllib bou
from __future__ import annotations
import io
+import hashlib
import json
+ import os
import time
from pathlib import Path
@@@ -409,252 -361,95 +410,303 @@@ def test_download_tolerates_stale_catal
assert status is not None and status["status"] == "done", status.get("error")
+ def test_download_survives_a_held_finished_file(client, monkeypatch):
- """The finished .part is often still open to an antivirus scan when the rename runs (Windows),
- which refuses it with a permission error. The job must wait the hold out and land the file —
- not copy it, and not report a complete download as failed."""
++ """The finished file is often still open to an antivirus or indexing scan when it is
++ published (Windows), which refuses the rename with a permission error. The job must wait the
++ hold out and land the file — not copy it, and not report a complete download as failed."""
+
+ body = b"x" * 48
+
- class FakeResponse(io.BytesIO):
- headers = {"Content-Length": str(len(body))}
-
- def __enter__(self):
- return self
-
- def __exit__(self, *a):
- return False
-
- monkeypatch.setattr("urllib.request.urlopen", lambda *a, **k: FakeResponse(body))
++ monkeypatch.setattr("pm.downloader._OPENER", _FakeRangeOpener(body))
+
+ real_replace = os.replace
+ refusals = []
+
+ def held_at_first(src, dst):
- if str(src).endswith(".part") and len(refusals) < 2:
++ if str(src).endswith(".download") and len(refusals) < 2:
+ refusals.append(src)
+ raise PermissionError(13, "Access is denied")
+ real_replace(src, dst)
+
+ monkeypatch.setattr(os, "replace", held_at_first)
+
+ from hermes_cli.local_runtime.estimator import HardwareBudget
+
- budget = HardwareBudget(usable_vram_bytes=64 << 30, total_device_bytes=64 << 30,
++ budget = HardwareBudget(usable_vram_bytes=64 << 30,
++ total_device_bytes=64 << 30,
+ ram_available_bytes=64 << 30)
- monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget", lambda **kw: budget)
- monkeypatch.setattr("hermes_cli.local_runtime.bootstrap.refresh_local_runtime", lambda: False)
++ monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",
++ lambda **kw: budget)
++ monkeypatch.setattr(
++ "hermes_cli.local_runtime.bootstrap.refresh_local_runtime",
++ lambda: False)
+
+ from hermes_cli.local_runtime.bootstrap import models_dir
+ from hermes_cli.local_runtime.catalog import CATALOG
+
- entry_id = CATALOG[0].id
- r = client.post("/api/local-models/download", json={"model_id": entry_id})
++ r = client.post("/api/local-models/download", json={"model_id": CATALOG[0].id})
+ assert r.status_code == 200
+ job_id = r.json()["job_id"]
+
- deadline = time.time() + 10
++ deadline = time.time() + 15
+ status = None
+ while time.time() < deadline:
+ status = client.get(f"/api/local-models/jobs/{job_id}").json()
+ if status["status"] in ("done", "error"):
+ break
+ time.sleep(0.05)
+ assert status is not None and status["status"] == "done", status.get("error")
+ assert len(refusals) == 2
+ assert not list(models_dir().glob("*.part"))
+ assert any(p.read_bytes() == body for p in models_dir().glob("*.gguf"))
+
+
-def test_download_failure_is_not_masked_by_a_stuck_leftover(tmp_path, monkeypatch):
- """When the rename gives up, the user must see that message — not the error from the
- cleanup that could not remove the still-held .part either."""
- from hermes_cli.web_routers import local_models
+def test_download_pause_and_resume_unknown_404(client):
+ assert client.post("/api/local-models/download/pause",
+ json={"job_id": "deadbeef"}).status_code == 404
+ assert client.post("/api/local-models/download/resume",
+ json={"job_id": "deadbeef"}).status_code == 404
- body = b"x" * 48
- class FakeResponse(io.BytesIO):
- headers = {"Content-Length": str(len(body))}
+# ── pause / resume against a real loopback range server ──────
- def __enter__(self):
- return self
- def __exit__(self, *a):
- return False
+def _pin_budget(monkeypatch):
+ """Deterministic variant selection: a generous GPU budget so the
+ download path (not selection) is what the test exercises."""
+ from hermes_cli.local_runtime.estimator import HardwareBudget
- monkeypatch.setattr("urllib.request.urlopen", lambda *a, **k: FakeResponse(body))
+ budget = HardwareBudget(usable_vram_bytes=64 << 30,
+ total_device_bytes=64 << 30,
+ ram_available_bytes=64 << 30)
+ monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",
+ lambda **kw: budget)
- def still_held(tmp, dest, **kw):
- raise RuntimeError("could not be renamed into place")
- monkeypatch.setattr("hermes_cli.local_runtime.binaries.replace_when_released", still_held)
- real_unlink = Path.unlink
+def _serve_plan(monkeypatch, dl_server, tmp_partials, bodies):
+ """Point the download plan at the real loopback range server: one
+ served body per plan file, dests under the temp models dir, partials
+ under a temp dir (never the machine's cache)."""
+ from pm import paths as pm_paths
+ from tests.pm._range_server import RangeHandler
+ from hermes_cli.local_runtime.bootstrap import models_dir
+ from hermes_cli.web_routers import local_models as lm
+
+ RangeHandler.chunk = 128 * 1024
+ RangeHandler.slow_per_chunk = 0.2
+ RangeHandler.payloads = {}
+ plan = []
+ for name, body in bodies.items():
+ RangeHandler.payloads[f"/{name}"] = body
+ dest = models_dir() / f"{name}.gguf"
+ plan.append((_srv_url(dl_server, f"/{name}"), dest, len(body)))
+ monkeypatch.setattr(pm_paths, "partials_root", lambda: Path(tmp_partials))
+ monkeypatch.setattr(lm, "_download_plan", lambda entry, variant: plan)
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.bootstrap.refresh_local_runtime",
+ lambda: False)
+ return plan
- def stuck_part(self, missing_ok=False):
- if self.suffix == ".part":
- raise PermissionError(13, "Access is denied")
- return real_unlink(self, missing_ok=missing_ok)
- monkeypatch.setattr(Path, "unlink", stuck_part)
+def _poll_job(client, job_id, deadline_s=15, until=("paused", "done", "error")):
+ deadline = time.time() + deadline_s
+ status = None
+ while time.time() < deadline:
+ status = client.get(f"/api/local-models/jobs/{job_id}").json()
+ if status["status"] in until:
+ return status
+ time.sleep(0.03)
+ return status
+
+
+def _pause_when_flowing(client, job_id):
+ """Pause once bytes are actually moving, so the pause lands mid-flight
+ (the downloader stops between chunks) rather than before the probe."""
+ deadline = time.time() + 15
+ while time.time() < deadline:
+ status = client.get(f"/api/local-models/jobs/{job_id}").json()
+ if (status.get("done_bytes") or 0) > 0:
+ break
+ time.sleep(0.03)
+ deadline = time.time() + 15
+ while time.time() < deadline:
+ pr = client.post("/api/local-models/download/pause",
+ json={"job_id": job_id})
+ if pr.status_code == 200 and pr.json().get("paused") is True:
+ return
+ time.sleep(0.03)
+ raise AssertionError("pause never reached the live download handle")
+
+
+_BIG_BODY = bytes(range(256)) * (8 * 1024 * 1024 // 256) # 8 MiB, deterministic
+
+
+def test_download_resume_completes_bytes(client, monkeypatch, dl_server,
+ tmp_path):
+ """Resume after a mid-flight pause finishes the remaining ranges and
+ stages the exact file the server serves."""
+ _pin_budget(monkeypatch)
+ from tests.pm._range_server import RangeHandler
+ from hermes_cli.local_runtime.bootstrap import models_dir
+ from hermes_cli.local_runtime.catalog import CATALOG
+ from hermes_cli.web_routers import local_models as lm
+
+ _serve_plan(monkeypatch, dl_server, tmp_path / "partials",
+ {"PartA": _BIG_BODY})
+
+ job_id = client.post("/api/local-models/download",
+ json={"model_id": CATALOG[0].id}).json()["job_id"]
+ _pause_when_flowing(client, job_id)
+ status = _poll_job(client, job_id)
+ assert status["status"] == "paused", status
+
+ RangeHandler.slow_per_chunk = 0.0 # let the resume run at full speed
+ assert status["error"] is None
+ assert lm._RUNNING[job_id].get("resume") is not None
+ partials = list((tmp_path / "partials").glob("*.part"))
+ assert partials and any(p.stat().st_size > 0 for p in partials)
+ assert client.post("/api/local-models/download/resume",
+ json={"job_id": job_id}).json()["resumed"] is True
+
+ status = _poll_job(client, job_id, until=("done", "error"))
+ assert status["status"] == "done", status
+ assert (models_dir() / "PartA.gguf").read_bytes() == _BIG_BODY
+ # Finished jobs release their handles again.
+ assert job_id not in lm._RUNNING
+
+
+def test_repeated_resume_never_spawns_concurrent_writers(
+ client, monkeypatch, dl_server, tmp_path):
+ """Spamming resume while a worker is already running must not build a
+ second Download — one writer per job, ever."""
+ import threading as _threading
+
+ _pin_budget(monkeypatch)
+ from tests.pm._range_server import RangeHandler
+ from hermes_cli.local_runtime.catalog import CATALOG
+ from hermes_cli.web_routers import local_models as lm
+
+ _serve_plan(monkeypatch, dl_server, tmp_path / "partials",
+ {"PartA": _BIG_BODY})
+
+ job_id = client.post("/api/local-models/download",
+ json={"model_id": CATALOG[0].id}).json()["job_id"]
+ _pause_when_flowing(client, job_id)
+ assert _poll_job(client, job_id)["status"] == "paused"
+
+ built = []
+ started = _threading.Event()
+ release = _threading.Event()
+ real_download = lm.Download
+
+ class _Counting(real_download):
+ def __init__(self, *a, **kw):
+ super().__init__(*a, **kw)
+ built.append(self)
+
+ def run(self, *a, **kw):
+ started.set()
+ assert release.wait(timeout=15)
+ return super().run(*a, **kw)
+
+ monkeypatch.setattr(lm, "Download", _Counting)
+
+ try:
+ client.post("/api/local-models/download/resume", json={"job_id": job_id})
+ assert started.wait(timeout=15), "resume never built a Download"
+ # Keep the real downloader parked while repeated requests contend.
+ for _ in range(2):
+ response = client.post("/api/local-models/download/resume", json={"job_id": job_id})
+ assert response.json()["resumed"] is False
+ assert len(built) == 1
+ finally:
+ RangeHandler.slow_per_chunk = 0.0
+ release.set()
+ status = _poll_job(client, job_id, until=("done", "error"))
+ assert status["status"] == "done", status
+
+
+def test_quickstart_pause_stops_the_sequence(client, monkeypatch, dl_server,
+ tmp_path):
+ """A quickstart paused mid-download must stop dead: no second file, no
+ server start, no default assignment — the job parks for a resume, and
+ its resume handle stays registered."""
+ _pin_budget(monkeypatch)
+ from tests.pm._range_server import RangeHandler
+ from hermes_cli.web_routers import local_models as lm
+
+ _serve_plan(monkeypatch, dl_server, tmp_path / "partials",
+ {"QsPartA": _BIG_BODY, "QsPartB": _BIG_BODY})
+ from hermes_cli.local_runtime.binaries import Engine
+
+ monkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_engine",
+ lambda *args, **kwargs: Engine("cpu", "b99999", Path("unused")))
+ monkeypatch.setattr(lm, "_runtime_target",
+ lambda requested=None: ("b1", "cpu"))
+
+ calls = {"server": 0, "assign": 0}
+
+ def _fail_server(*a, **kw):
+ calls["server"] += 1
+ raise RuntimeError("server must not start after a pause")
+
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.bootstrap.ensure_local_runtime", _fail_server)
+
+ class _RecordLate:
+ def __call__(self, *a, **kw):
+ calls["assign"] += 1
+
+ monkeypatch.setattr(lm.web_deps, "late", _RecordLate())
+
+ from hermes_cli.local_runtime.catalog import CATALOG
+
+ job_id = client.post("/api/local-models/quickstart",
+ json={"model_id": CATALOG[0].id}).json()["job_id"]
+ _pause_when_flowing(client, job_id)
+
+ status = _poll_job(client, job_id)
+ assert status["status"] == "paused", status
+ assert calls == {"server": 0, "assign": 0}
+ # The second plan file must never have been touched after the pause.
+ from hermes_cli.local_runtime.bootstrap import models_dir
+
+ assert not (models_dir() / "QsPartB.gguf").exists()
+ assert lm._RUNNING[job_id].get("resume") is not None
+ assert lm._QUICKSTART_LOCK.locked(), "paused quickstart must retain setup ownership"
+
+ def activate(*args, **kwargs):
+ calls["server"] += 1
+
+ def assign(*args, **kwargs):
+ calls["assign"] += 1
+
+ monkeypatch.setattr(lm, "_ensure_server", activate)
+ monkeypatch.setattr(lm, "_assign_default", assign)
+ RangeHandler.slow_per_chunk = 0
+ assert client.post("/api/local-models/quickstart", json={"model_id": CATALOG[0].id}).status_code == 409
+ assert client.post("/api/local-models/download/resume", json={"job_id": job_id}).json()["resumed"]
+ status = _poll_job(client, job_id, until=("done", "error"))
+ assert status["status"] == "done", status
+ assert calls == {"server": 1, "assign": 1}
+ assert (models_dir() / "QsPartA.gguf").read_bytes() == _BIG_BODY
+ assert (models_dir() / "QsPartB.gguf").read_bytes() == _BIG_BODY
+ assert job_id not in lm._RUNNING
+ assert not lm._QUICKSTART_LOCK.locked()
+
+
+def test_download_failure_releases_resume_handle(client, monkeypatch):
+ from hermes_cli.local_runtime.catalog import CATALOG
+ from hermes_cli.web_routers import local_models as lm
+
+ _pin_budget(monkeypatch)
+ monkeypatch.setattr(lm, "_download_plan", lambda *args: [])
+
+ def fail(*args):
+ raise OSError("download failed")
- dest = tmp_path / "models" / "model.gguf"
- with pytest.raises(RuntimeError, match="could not be renamed"):
- local_models.download_file("http://example.invalid/model.gguf", dest, {})
- assert not dest.exists()
+ monkeypatch.setattr(lm, "_download_job", fail)
+ job_id = client.post("/api/local-models/download", json={"model_id": CATALOG[0].id}).json()["job_id"]
+ status = _poll_job(client, job_id)
+ assert status["status"] == "error", status
+ assert job_id not in lm._RUNNING
diff --cc tests/pm/test_downloader.py
index 4b270000a4a,00000000000..f89b45cd908
mode 100644,000000..100644
--- a/tests/pm/test_downloader.py
+++ b/tests/pm/test_downloader.py
@@@ -1,321 -1,0 +1,422 @@@
+"""pm/downloader: resumable, hash-verified, 8-way parallel downloads.
+
+Real downloads against a loopback Range-honoring server — no mocked
+stores. Covers the seams agreed in the plan: run() semantics, the
+progress(overall_done, overall_total, ranges) contract, parallelism,
+resume-refetch-only-missing, pause, and the optional-hash policy.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
++import os
+import threading
++from pathlib import Path
+
+import pytest
+
+from pm.downloader import (Download, DownloadError, DownloadPaused,
- HashError, Source)
++ HashError, Source, replace_when_released)
+
+from tests.pm._range_server import RangeHandler as _Handler, url as _url
+from tests.pm._range_server import dl_server as dl_server
+
+
+def _payload(n: int, seed: bytes = b"x") -> bytes:
+ return seed * n
+
+
+def _sha(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+# ── parallelism ───────────────────────────────────────────────
+
+
[email protected]("connections", [2, 8])
+def test_parallel_requests_overlap_without_exceeding_limit(tmp_path, connections):
+ from http.server import ThreadingHTTPServer
+
+ total = 8 * (4 << 20) # 32 MiB -> 8 x 4 MiB ranges
+ payload = _payload(total)
+ barrier = threading.Barrier(connections)
+ lock = threading.Lock()
+ active = peak = 0
+ broken = []
+
+ class ConcurrentHandler(_Handler):
+ payloads = {"/big": payload}
+ ranges_seen = []
+
+ def do_GET(self):
+ nonlocal active, peak
+ if self.headers.get("Range") == "bytes=0-0":
+ return super().do_GET()
+ with lock:
+ active += 1
+ peak = max(peak, active)
+ try:
+ try:
+ barrier.wait(timeout=5)
+ except threading.BrokenBarrierError:
+ broken.append(self.headers.get("Range"))
+ super().do_GET()
+ finally:
+ with lock:
+ active -= 1
+
+ dest = tmp_path / "big.bin"
+ with ThreadingHTTPServer(("127.0.0.1", 0), ConcurrentHandler) as server:
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ Download([Source(_url(server, "/big"), dest, _sha(payload))],
+ connections=connections, partials_dir=tmp_path / "partials").run()
+ finally:
+ server.shutdown()
+ thread.join(timeout=5)
+ assert dest.read_bytes() == payload
+ assert not broken, "range requests were serialized instead of overlapping"
+ assert peak == connections and active == 0
+ expected = [(i * total // connections, (i + 1) * total // connections - 1) for i in range(connections)]
+ assert sorted((s, e) for _, s, e in ConcurrentHandler.ranges_seen) == expected
+
+
+def test_progress_carries_overall_and_ranges(dl_server, tmp_path):
+ p1, p2 = _payload(1000, b"x"), _payload(2000, b"y")
+ _Handler.payloads["/a"] = p1
+ _Handler.payloads["/b"] = p2
+ d1, d2 = tmp_path / "a.bin", tmp_path / "b.bin"
+ dl = Download([
+ Source(_url(dl_server, "/a"), d1, _sha(p1)),
+ Source(_url(dl_server, "/b"), d2, _sha(p2)),
+ ], partials_dir=tmp_path / "partials")
+ seen = []
+ dl.run(progress=lambda d, t, r: seen.append((d, t, dict(r))))
+ final_d, final_t, final_r = seen[-1]
+ assert final_d == 3000
+ assert final_t == 3000
+ assert final_r[str(d1)] == [(0, 1000)]
+ assert final_r[str(d2)] == [(0, 2000)]
+
+
+# ── optional hash ─────────────────────────────────────────────
+
+
+def test_hash_mismatch_raises_and_deletes_part(dl_server, tmp_path):
+ _Handler.payloads["/f"] = _payload(1 << 20)
+ dest = tmp_path / "f.bin"
+ partials = tmp_path / "partials"
+ dl = Download([Source(_url(dl_server, "/f"), dest, "0" * 64)],
+ partials_dir=partials)
+ with pytest.raises(HashError):
+ dl.run()
+ assert not dest.exists()
+ assert not [path for path in partials.iterdir() if path.name != ".locks"] # .part + .ranges both deleted
+
+
+def test_no_hash_accepts_any_bytes_of_right_size(dl_server, tmp_path):
+ payload = _payload(1 << 20)
+ _Handler.payloads["/f"] = payload
+ dest = tmp_path / "f.bin"
+ dl = Download([Source(_url(dl_server, "/f"), dest)],
+ partials_dir=tmp_path / "partials")
+ moved = dl.run()
+ assert moved == [dest]
+ assert dest.read_bytes() == payload
+
+
+# ── resume ────────────────────────────────────────────────────
+
+
+
+
+def test_partials_never_in_scratch_or_dest(dl_server, tmp_path):
+ payload = _payload(1 << 20)
+ _Handler.payloads["/p"] = payload
+ dest = tmp_path / "p.bin"
+ partials = tmp_path / "partials"
+ dl = Download([Source(_url(dl_server, "/p"), dest)],
+ partials_dir=partials)
+ dl.run()
+ # dest is the only file in its dir; partials dir is empty after mv.
+ # (The test harness may drop its own marker dir into tmp_path.)
+ assert dest.exists()
+ assert not [path for path in partials.iterdir() if path.name != ".locks"]
+ assert not [p for p in tmp_path.iterdir()
+ if p.suffix in (".part", ".ranges")]
+
+
[email protected]("hashed", [False, True])
+def test_completed_dest_is_skipped(dl_server, tmp_path, hashed):
+ payload = _payload(1 << 20)
+ _Handler.payloads["/s"] = payload
+ dest = tmp_path / "s.bin"
+ dest.write_bytes(payload)
+ dl = Download([Source(_url(dl_server, "/s"), dest, _sha(payload) if hashed else None)],
+ partials_dir=tmp_path / "partials")
+ dl.run()
+ assert _Handler.ranges_seen == [] # nothing fetched
+
+
+def test_stale_dest_with_wrong_hash_is_refetched(dl_server, tmp_path):
+ payload = _payload(1 << 20)
+ _Handler.payloads["/s"] = payload
+ dest = tmp_path / "s.bin"
+ dest.write_bytes(_payload(1 << 20, seed=b"wrong")) # wrong bytes on disk
+ dl = Download([Source(_url(dl_server, "/s"), dest, _sha(payload))],
+ partials_dir=tmp_path / "partials")
+ dl.run()
+ assert dest.read_bytes() == payload # stale dest replaced
+ assert _Handler.ranges_seen # a fetch actually happened
+
+
+
+def test_redirect_to_non_https_refused():
+ import urllib.request
+
+ from pm.downloader import _HttpsRedirectHandler
+
+ handler = _HttpsRedirectHandler()
+ req = urllib.request.Request("https://example.com/a")
+ with pytest.raises(DownloadError):
+ handler.redirect_request(req, None, 302, "Found", {},
+ "http://example.com/b")
+ # An https redirect resolves through the default handler.
+ assert handler.redirect_request(req, None, 302, "Found", {},
+ "https://example.com/b") is not None
+
+
+# ── pause ─────────────────────────────────────────────────────
+
+
+
+# ── safety ────────────────────────────────────────────────────
+
+
+def test_refuses_non_https_non_loopback(tmp_path):
+ dl = Download([Source("http://example.com/x", tmp_path / "x.bin")],
+ partials_dir=tmp_path / "partials")
+ with pytest.raises(ValueError):
+ dl.run()
+
+
+# ── edge cases: no-Range fallback, multi-source resume, pause mid-plan ──
+
+
+def test_no_range_fallback_downloads_full_body(dl_server, tmp_path):
+ """A server that ignores Range is served by the single-stream fallback:
+ the whole body arrives and progress reports the full covered range."""
+ _Handler.no_range = True
+ payload = _payload(1 << 20)
+ _Handler.payloads["/nr"] = payload
+ dest = tmp_path / "nr.bin"
+ dl = Download([Source(_url(dl_server, "/nr"), dest, _sha(payload))],
+ partials_dir=tmp_path / "partials")
+ seen = []
+ moved = dl.run(progress=lambda d, t, r: seen.append((d, t, dict(r))))
+ assert moved == [dest]
+ assert dest.read_bytes() == payload
+ assert _Handler.ranges_seen == [] # never used Range
+ d, t, r = seen[-1]
+ assert d == t == len(payload)
+ assert r[str(dest)] == [(0, len(payload))]
+
+
+def test_no_range_short_body_raises_and_leaves_no_dest(dl_server, tmp_path):
+ """The fallback errors when the server sends FEWER bytes than its
+ declared Content-Length (connection dropped mid-body), leaving the
+ partial in the managed area and NO dest."""
+ _Handler.no_range = True
+ payload = _payload(2 << 20)
+ _Handler.payloads["/ns"] = payload
+ _Handler.abort_after = 1 << 20 # server declares 2 MiB, sends 1 MiB
+ dest = tmp_path / "ns.bin"
+ partials = tmp_path / "partials"
+ dl = Download([Source(_url(dl_server, "/ns"), dest)],
+ partials_dir=partials)
+ with pytest.raises(DownloadError):
+ dl.run()
+ assert not dest.exists()
+ names = {p.name for p in partials.iterdir()}
+ assert any(n.endswith(".part") for n in names)
+ assert any(n.endswith(".ranges") for n in names)
+
+
+def test_resume_across_plan_skips_completed_source(dl_server, tmp_path):
+ """A 2-source plan: source 1 completes, source 2 aborts. A second run
+ of the SAME plan completes BOTH files without re-fetching source 1 —
+ source 1 gets exactly one request across both runs and source 2's
+ second request starts at its abort point."""
+ total_b = 8 << 20
+ p_a, p_b = _payload(1 << 20, b"a"), _payload(total_b, b"b")
+ _Handler.payloads["/a"] = p_a
+ _Handler.payloads["/b"] = p_b
+ da, db = tmp_path / "a.bin", tmp_path / "b.bin"
+ partials = tmp_path / "partials"
+
+ _Handler.abort_after = 2 << 20
+ dl = Download([Source(_url(dl_server, "/a"), da, _sha(p_a)),
+ Source(_url(dl_server, "/b"), db, _sha(p_b))],
+ partials_dir=partials, connections=1)
+ with pytest.raises(Exception):
+ dl.run()
+
+ sidecars = list(partials.glob("*.ranges"))
+ assert len(sidecars) == 1
+ assert json.loads(sidecars[0].read_text())["ranges"] == [[0, 2 << 20]]
+ assert da.read_bytes() == p_a and not db.exists()
+ _Handler.abort_after = None
+ dl = Download([Source(_url(dl_server, "/a"), da, _sha(p_a)),
+ Source(_url(dl_server, "/b"), db, _sha(p_b))],
+ partials_dir=partials, connections=1)
+ ticks = []
+ dl.run(progress=lambda d, t, r: ticks.append((d, t, dict(r))))
+ assert ticks[0] == (len(p_a) + (2 << 20), len(p_a) + len(p_b),
+ {str(da): [(0, len(p_a))], str(db): [(0, 2 << 20)]})
+ assert not list(partials.glob("*.ranges")) and not list(partials.glob("*.part"))
+ assert da.read_bytes() == p_a
+ assert db.read_bytes() == p_b
+ a_reqs = [r for r in _Handler.ranges_seen if r[0] == "/a"]
+ assert len(a_reqs) == 1 # exactly one request across both runs
+ b_reqs = [r for r in _Handler.ranges_seen if r[0] == "/b"]
+ # first request starts at 0; second (resume) starts at the abort point
+ assert b_reqs[0][1] == 0
+ assert b_reqs[1][1] == 2 << 20
+ assert b_reqs[1][1] != b_reqs[0][1]
+
+
+
+def test_pause_mid_plan_resumes_to_completion(dl_server, tmp_path):
+ """Pause after source 1 completes: DownloadPaused is raised, source 1's
+ dest is moved/complete, and source 2's partial survives in the managed
+ area; a FRESH Download over the same plan resumes to full completion."""
+ p_a, p_b = _payload(1 << 20, b"a"), _payload(32 << 20, b"b")
+ _Handler.payloads["/a"] = p_a
+ _Handler.payloads["/b"] = p_b
+ da, db = tmp_path / "a.bin", tmp_path / "b.bin"
+ partials = tmp_path / "partials"
+ dl = Download([Source(_url(dl_server, "/a"), da, _sha(p_a)),
+ Source(_url(dl_server, "/b"), db, _sha(p_b))],
+ partials_dir=partials)
+
+ def pause_second_source(done, total, ranges):
+ 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()}
+ assert any(n.endswith(".part") for n in names)
+ assert any(n.endswith(".ranges") for n in names)
+
+ # a FRESH Download over the same plan resumes to full completion
+ _Handler.slow_per_chunk = 0.0
+ dl = Download([Source(_url(dl_server, "/a"), da, _sha(p_a)),
+ Source(_url(dl_server, "/b"), db, _sha(p_b))],
+ partials_dir=partials)
+ dl.run()
+ assert da.read_bytes() == p_a
+ assert db.read_bytes() == p_b
++
++
++# ── publication: a finished file the OS still holds ──────────
++
++
++def _hold_first_two(replacements: list):
++ """An ``os.replace`` that refuses the first two publications of a download's staged file with
++ the permission error a Windows antivirus or indexing scan raises while it still has the
++ finished file open. Sidecar writes publish through the same call, so the refusal is keyed to
++ the downloader's staging suffix rather than to call order."""
++ real_replace = os.replace
++
++ def held(src, dst):
++ if str(src).endswith(".download") and len(replacements) < 2:
++ replacements.append(src)
++ raise PermissionError(13, "Access is denied")
++ real_replace(src, dst)
++
++ return held
++
++
++def test_replace_waits_out_a_transient_hold(tmp_path, monkeypatch):
++ tmp = tmp_path / "model.download"
++ dest = tmp_path / "model.gguf"
++ tmp.write_bytes(b"weights")
++ refusals = []
++ monkeypatch.setattr(os, "replace", _hold_first_two(refusals))
++
++ replace_when_released(tmp, dest, timeout=5)
++ assert len(refusals) == 2
++ assert dest.read_bytes() == b"weights"
++ assert not tmp.exists()
++
++
++def test_replace_gives_up_with_a_plain_language_error(tmp_path, monkeypatch):
++ """A hold that outlasts the window is reported as a hold — chained to the OS error, and
++ never degraded to a copy of the file."""
++ tmp = tmp_path / "model.download"
++ dest = tmp_path / "model.gguf"
++ tmp.write_bytes(b"weights")
++
++ def always_held(src, dst):
++ raise PermissionError(13, "Access is denied")
++
++ monkeypatch.setattr(os, "replace", always_held)
++ with pytest.raises(RuntimeError) as failed:
++ replace_when_released(tmp, dest, timeout=0.3)
++ assert "model.download" in str(failed.value)
++ assert "try again" in str(failed.value).lower()
++ assert isinstance(failed.value.__cause__, PermissionError)
++ assert not dest.exists()
++ assert tmp.read_bytes() == b"weights" # the finished bytes survive for the retry
++
++
++def test_download_publishes_through_a_held_finished_file(dl_server, tmp_path, monkeypatch):
++ """The publish the OS refuses twice must still land the complete file, and the download
++ must report success — this is the 22 GB model case, not a partial transfer."""
++ body = _payload(4 << 20, b"m")
++ _Handler.payloads["/held"] = body
++ dest = tmp_path / "held.gguf"
++ refusals = []
++ monkeypatch.setattr(os, "replace", _hold_first_two(refusals))
++
++ dl = Download([Source(_url(dl_server, "/held"), dest, _sha(body))],
++ partials_dir=tmp_path / "partials")
++ dl.run()
++
++ assert len(refusals) == 2
++ assert dest.read_bytes() == body
++ assert not list(tmp_path.glob("*.download"))
++ assert not [p for p in (tmp_path / "partials").iterdir() if p.suffix in (".part", ".ranges")]
++
++
++def test_download_reports_a_hold_that_never_releases(dl_server, tmp_path, monkeypatch):
++ """A stuck hold surfaces the rename error, not the failed cleanup of the partial it could
++ not remove either."""
++ body = _payload(1 << 20, b"h")
++ _Handler.payloads["/stuck"] = body
++ dest = tmp_path / "stuck.gguf"
++ partials = tmp_path / "partials"
++
++ def never_released(staged, target, **kw):
++ raise RuntimeError(f"{staged.name} could not be renamed into place")
++
++ real_unlink = Path.unlink
++
++ def stuck_partial(self, missing_ok=False):
++ if self.suffix in (".part", ".ranges"):
++ raise PermissionError(13, "Access is denied")
++ return real_unlink(self, missing_ok=missing_ok)
++
++ monkeypatch.setattr("pm.downloader.replace_when_released", never_released)
++ monkeypatch.setattr(Path, "unlink", stuck_partial)
++
++ dl = Download([Source(_url(dl_server, "/stuck"), dest, _sha(body))],
++ partials_dir=partials)
++ with pytest.raises(RuntimeError, match="could not be renamed into place"):
++ dl.run()
++ assert not dest.exists()