π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): time out stalled downloads, reject truncated transfers and confine file names to the cache (#5247)
Dmytro Mishkin27e22229909a
diff --git a/changelog.d/5247.fixed.md b/changelog.d/5247.fixed.mdnew file mode 100644index 000000000..67f70b39e--- /dev/null+++ b/changelog.d/5247.fixed.md@@ -0,0 +1,29 @@+`load_state_dict_from_url`, `download_file_from_url` and `download_hf_file` no longer hang on a server that+accepts the connection and then stops sending: each connection attempt and each read now times out after 30 s+(`timeout=` overrides it per call; the `KORNIA_DOWNLOAD_TIMEOUT` environment variable, in seconds and read at+each call, sets the default, which is how callers that take no timeout, such as pretrained model constructors,+raise it; a number from either that is not greater than 0 and at most `threading.TIMEOUT_MAX`, or a variable+that holds no number, raises `ValueError` naming its source when a download function is called, and a+`timeout=` that is a `bool`, a `str` or anything else that is not an `int` or a `float` raises `TypeError`),+the timeout counts as a transient failure, so it is retried and then hands over to the next source, and the+call ends with the usual `RuntimeError` naming the source and the cache path. A response body shorter than the+`Content-Length` that framed it is now a failed transfer too, retried like the timeout, instead of being cached+as a truncated file that every later call returned; chunked and close-delimited bodies are unaffected. To apply+both checks these functions now run the transfer themselves instead of calling+`torch.hub.download_url_to_file`, keeping its temporary-file-then-replace write, hash check and progress bar;+code that patched `torch.hub.download_url_to_file` to intercept kornia's downloads no longer does so.+`load_state_dict_from_url` now rejects a `file_name` that is not a bare file name with the `ValueError`+`download_file_from_url` already raised; an absolute path or a `../` name used to make it overwrite the file+it pointed at with the checkpoint and then delete the original. Calls that passed a path as `file_name` now+raise `ValueError` before anything is read or written; a `pathlib.Path` holding a bare name is still accepted.+Both functions also check their other arguments before touching the cache or the network: a URL whose path+ends in `/`, `/.` or `/..` raises `ValueError` instead of returning the cache directory or its parent (for a+list of URLs, a first URL ending in `/` used to be cached under its directory name and now raises too), an+empty `url` list raises `ValueError` instead of `IndexError`, and a `pathlib.Path` or `bytes` URL, alone or in+a list, raises a `TypeError` that says what to pass instead of an unrelated `TypeError` or `AttributeError`.+A keyword `torch.hub.load_state_dict_from_url` does not accept raises `TypeError` at once instead of+re-downloading the checkpoint and raising `RuntimeError`, and a leading `~` in `model_dir` is expanded instead+of creating a directory named `~`. `hf_url` percent-encodes the repository and the file name, so `"a#b.pth"`+fetches that file rather than `a`; a name that was already percent-encoded (`"a%20b.pth"`) is encoded again, so+pass the plain name (`"a b.pth"`). The retry warnings raised through `download_hf_file` point at the caller's+line.diff --git a/kornia/core/download.py b/kornia/core/download.pyindex 6fefe1af2..198092ab2 100644--- a/kornia/core/download.py+++ b/kornia/core/download.py@@ -17,11 +17,18 @@from __future__ import annotations+import contextlib+import errno+import hashlibimport http.client+import inspectimport mathimport osimport sys+import tempfile+import threadingimport time+import uuidimport warningsfrom collections.abc import Callablefrom datetime import UTC, datetime@@ -29,7 +36,8 @@ from email.utils import parsedate_to_datetimefrom pathlib import Pathfrom typing import Anyfrom urllib.error import HTTPError, URLError-from urllib.parse import urlparse+from urllib.parse import quote, urlparse+from urllib.request import Request, urlopenimport torch@@ -56,12 +64,20 @@ def _hf_repo_id(repo: str) -> str:def hf_url(repo: str, filename: str) -> str:"""Return the HuggingFace URL for a file in a model repo.+ Both arguments are percent-encoded, ``/`` excepted, because they are path+ segments rather than URL syntax: unencoded, the ``#`` of ``"a#b.pth"`` would+ start a fragment and fetch the file ``a``, and a space would make the URL+ invalid. Names made of letters, digits, ``-``, ``_``, ``.`` and ``~`` are+ unchanged. Pass the plain name: one that is already percent-encoded, such as+ ``"a%20b.pth"``, is encoded again.+Args:repo: repository name under the ``kornia`` HF org (e.g. ``"hardnet"``),or a full ``owner/name`` repository id for a repo owned by anyoneelse (e.g. ``"google/siglip2-base-patch16-224"``). The two are toldapart by the ``/``, which a repository *name* cannot contain.- filename: file at the root of that repo (e.g. ``"HardNetPP.pth"``).+ filename: path of the file in that repo (e.g. ``"HardNetPP.pth"``); a+ ``/`` in it reaches into a subdirectory.Returns:A ``resolve/main`` URL that can be passed directly to@@ -73,7 +89,7 @@ def hf_url(repo: str, filename: str) -> str:>>> hf_url("google/siglip2-base-patch16-224", "model.safetensors")'https://huggingface.co/google/siglip2-base-patch16-224/resolve/main/model.safetensors'"""- return f"{_HF_BASE}/{_hf_repo_id(repo)}/resolve/main/{filename}"+ return f"{_HF_BASE}/{quote(_hf_repo_id(repo), safe='/')}/resolve/main/{quote(filename, safe='/')}"def _hf_cache_file_name(repo: str, filename: str) -> str:@@ -148,6 +164,276 @@ cause named -- beats waiting longer. The budget is per call rather than perprocess so that a long-lived process is never left permanently unable to retry."""+_DOWNLOAD_TIMEOUT_SECONDS = 30.0+"""Default bound, in seconds, on each wait of a transfer: connecting, and every read.++The fallback when neither ``timeout=`` nor :data:`_DOWNLOAD_TIMEOUT_ENV_VAR` is set.++A server that accepts the connection and then sends nothing -- overloaded, or a+half-open connection -- would otherwise hold the call forever, and the retry and+fallback logic never got control, because nothing raised. The bound applies to+each wait, not to the transfer as a whole: a multi-gigabyte checkpoint on a slow+but live link takes as long as it takes. A timeout is a transient failure, so it+is retried like a 503 and then hands over to the next source; a source that never+answers therefore costs up to :data:`_MAX_ATTEMPTS` times this, plus the backoff.+The public functions take ``timeout=`` to override it for one call.+"""++_DOWNLOAD_TIMEOUT_ENV_VAR = "KORNIA_DOWNLOAD_TIMEOUT"+"""Environment variable holding the default download timeout, in seconds.++Read at call time, whenever a download function is called without ``timeout=``, so+it reaches callers that take no timeout -- a ``pretrained=True`` constructor -- and+can be changed without restarting the process. Unset or blank means 30 s; anything+that :func:`_usable_timeout` refuses raises :class:`ValueError` naming the+variable, at the call rather than at import.+"""+++def _usable_timeout(seconds: float) -> bool:+ """Return whether *seconds* is more than 0 and at most ``threading.TIMEOUT_MAX``.++ ``threading.TIMEOUT_MAX`` is the stdlib's documented ceiling on a blocking timeout. A+ finite value far beyond it, such as ``1e300``, makes the socket raise ``OverflowError``+ once the transfer starts, which the retry logic would then report as a failed source.+ The bound does not promise that every value up to it is honoured: some platforms+ truncate a wait longer than about 49 days (2**32 milliseconds), so such a timeout can+ expire much sooner than asked. NaN and infinity fail the comparison, and an ``int`` too+ large for a ``float`` is compared exactly rather than converted.+ """+ return 0 < seconds <= threading.TIMEOUT_MAX+++_READ_CHUNK_BYTES = 128 * 1024+"""Bytes read per call during a transfer, the chunk :func:`torch.hub.download_url_to_file` uses."""+++class _TruncatedTransfer(http.client.IncompleteRead):+ """A response body that ended before the ``Content-Length`` its headers announced.++ urllib ends a ``read(n)`` loop on an early close without an error, so without this+ check a server that dropped the connection part-way left a short file in the cache,+ returned as a hit by every later call (the root cause of #4309). It is an+ :class:`~http.client.IncompleteRead`, which :func:`_is_transient` retries before the+ next source is tried. Its message counts the bytes on disk, which the parent class+ would report as 0 because it counts only a partial body held in memory, and reads+ as a sentence, because the failure summaries print it without the class name (see+ :func:`_describe`).+ """++ def __init__(self, received: int, announced: int) -> None:+ super().__init__(b"", announced - received)+ # ``args`` is what pickle and copy rebuild an exception from.+ self.args = (received, announced)+ self.received = received+ self.announced = announced++ def __repr__(self) -> str:+ return (+ f"transfer truncated: the server sent {self.received} of the {self.announced} bytes "+ f"its Content-Length announced"+ )+++def _describe(exc: BaseException) -> str:+ """Return ``"<type>: <message>"`` for a failure summary; a truncated transfer describes itself."""+ if isinstance(exc, _TruncatedTransfer):+ return str(exc)+ return f"{type(exc).__name__}: {exc}"+++def _resolve_timeout(timeout: float | None) -> float:+ """Return the timeout a call runs with, validated.++ Args:+ timeout: the caller's value, or ``None`` for the ``KORNIA_DOWNLOAD_TIMEOUT``+ environment variable, or 30 s when that is unset or blank. An explicit value+ wins, and the variable is then not read at all.++ Returns:+ The timeout in seconds.++ Raises:+ TypeError: if *timeout* is not a number.+ ValueError: if *timeout*, or the variable it falls back to, is not greater than+ 0 and at most ``threading.TIMEOUT_MAX`` (see :func:`_usable_timeout`); the+ message names which of the two it came from.+ """+ if timeout is None:+ raw = os.environ.get(_DOWNLOAD_TIMEOUT_ENV_VAR, "").strip()+ if not raw:+ return _DOWNLOAD_TIMEOUT_SECONDS+ try:+ value = float(raw)+ except ValueError:+ value = math.nan+ if not _usable_timeout(value):+ raise ValueError(+ f"{_DOWNLOAD_TIMEOUT_ENV_VAR} must be a number of seconds greater than 0 and at most "+ f"{threading.TIMEOUT_MAX!r} (threading.TIMEOUT_MAX), got {raw!r}. "+ f"Unset it to use the default of {_DOWNLOAD_TIMEOUT_SECONDS:g} s."+ )+ return value+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):+ raise TypeError(f"timeout must be a number of seconds or None, got {type(timeout).__name__}.")+ if not _usable_timeout(timeout):+ # An int too large for a float could also be too long to print.+ huge = isinstance(timeout, int) and timeout.bit_length() > 64+ shown = f"an int of {timeout.bit_length()} bits" if huge else repr(timeout)+ raise ValueError(+ f"timeout must be a number of seconds greater than 0 and at most {threading.TIMEOUT_MAX!r} "+ f"(threading.TIMEOUT_MAX), got {shown}."+ )+ return float(timeout)+++def _is_timeout(exc: BaseException) -> bool:+ """Return whether *exc* is a socket timeout, raised directly or wrapped by urllib."""+ if isinstance(exc, TimeoutError):+ return True+ return isinstance(exc, URLError) and not isinstance(exc, HTTPError) and isinstance(exc.reason, TimeoutError)+++def _warn(message: str) -> None:+ """Warn, attributed to the first frame outside this module.++ The public functions call each other -- :func:`download_hf_file` goes through+ :func:`download_file_from_url` -- so a fixed ``stacklevel`` that is right for one+ entry point points into this file for another. Walking out of the module instead+ names the caller's line whichever way it came in.++ Args:+ message: the warning text.+ """+ level = 1+ frame = inspect.currentframe()+ while frame is not None and frame.f_globals is globals():+ frame = frame.f_back+ level += 1+ warnings.warn(message, stacklevel=level)+++def _url_list(url: object) -> list[str]:+ """Return *url* as a non-empty list of URL strings, or raise naming what is wrong.++ Args:+ url: what the caller passed as ``url``.++ Returns:+ The URLs, in order.++ Raises:+ TypeError: if *url* is not a string or an iterable of strings.+ ValueError: if there is no URL, or one of them is empty.+ """+ expected = "url must be a URL string or a list of them"+ if isinstance(url, (str, bytes, os.PathLike)):+ urls: list[object] = [url]+ else:+ try:+ urls = list(url)+ except TypeError:+ raise TypeError(f"{expected}, got {type(url).__name__}.") from None+ if not urls:+ raise ValueError("url is an empty list; pass at least one URL.")+ checked: list[str] = []+ for u in urls:+ if isinstance(u, os.PathLike):+ raise TypeError(f"{expected}, got a {type(u).__name__}; for a local file pass its path.as_uri().")+ if not isinstance(u, str):+ raise TypeError(f"{expected}, got {type(u).__name__}.")+ if not u:+ raise ValueError(f"url must not be empty, got {url!r}.")+ checked.append(u)+ return checked+++_NOT_A_FILE_NAME = frozenset({"", ".", ".."})+"""Names that would make the cache path the cache directory itself, or its parent."""+++def _check_cache_file_name(urls: list[str], file_name: str | os.PathLike[str] | None) -> str | None:+ """Refuse a cache entry name that is not a single file inside the cache directory.++ The cache is one flat directory and the entry is ``<model_dir>/<name>``. A+ ``file_name`` carrying a separator, an absolute path or ``..`` would put it+ outside, where the cache repair of :func:`load_state_dict_from_url` would move+ a file it never wrote aside, write over it and delete the original. A URL whose+ path ends in ``/``, ``/.`` or ``/..`` names no file, and the name derived from it+ would make the entry the cache directory or its parent. The name derived from a+ URL is held to the same bare-name test as ``file_name``: on Windows a last+ segment such as ``d:x.pth`` is a drive-relative path, not a name in the cache.++ Args:+ urls: the URLs of the call; without ``file_name`` the first one names the entry.+ file_name: the caller's ``file_name``, a ``str`` or an :class:`os.PathLike`, or ``None``.++ Returns:+ ``file_name`` as a ``str``, or ``None`` when it was not given.++ Raises:+ TypeError: if ``file_name`` is neither a ``str`` nor a path-like naming one.+ ValueError: if the name is not a bare file name.+ """+ if file_name is not None:+ name = os.fspath(file_name)+ if not isinstance(name, str):+ raise TypeError(f"file_name must be a str or a path-like object, got {type(file_name).__name__}.")+ if name in _NOT_A_FILE_NAME or os.path.basename(name) != name:+ raise ValueError(f"file_name must be a bare filename inside the cache directory, got {file_name!r}.")+ return name+ name = os.path.basename(urlparse(urls[0]).path)+ if name in _NOT_A_FILE_NAME or os.path.basename(name) != name:+ raise ValueError(+ f"{urls[0]!r} does not end in a name that can be a file in the cache directory (its last path "+ f"segment is {name!r}); pass file_name= to name the cache entry."+ )+ return None+++def _expand_model_dir(model_dir: Any) -> Any:+ """Expand a leading ``~`` in *model_dir*, as a shell would; ``None`` passes through.++ Neither the ``makedirs`` nor the existence check expands it, so ``"~/weights"``+ used to create a directory literally named ``~`` in the working directory.+ """+ if model_dir is None:+ return None+ expanded = os.path.expanduser(model_dir)+ return model_dir if expanded == os.fspath(model_dir) else expanded+++def _check_torch_keywords(kwargs: dict[str, Any]) -> None:+ """Raise :class:`TypeError` for a keyword :func:`torch.hub.load_state_dict_from_url` does not take.++ torch raises the same error, but only when it is called -- after the cache has been+ consulted -- so the call's cache repair took a caller's typo for a corrupt entry: it+ set the entry aside, downloaded the checkpoint again and reported ``RuntimeError``.++ Args:+ kwargs: the keyword arguments destined for the torch function.++ Raises:+ TypeError: naming the first keyword torch does not accept.+ """+ try:+ parameters = inspect.signature(torch.hub.load_state_dict_from_url).parameters+ except (TypeError, ValueError): # pragma: no cover - a signature inspect cannot read+ return+ if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters.values()):+ return # a stand-in that takes anything, such as a test double+ accepted = {+ name+ for name, p in parameters.items()+ if p.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY) and name != "url"+ }+ unknown = sorted(set(kwargs) - accepted)+ if unknown:+ raise TypeError(+ f"load_state_dict_from_url() got an unexpected keyword argument {unknown[0]!r}. "+ f"It accepts timeout and the keywords of torch.hub.load_state_dict_from_url: {', '.join(sorted(accepted))}."+ )+class _SleepBudget:"""The time a single call may spend waiting between attempts."""@@ -305,10 +591,12 @@ def _is_transient(exc: BaseException) -> bool:"""if isinstance(exc, HTTPError): # a subclass of URLError, so it must be tested firstreturn exc.code in _TRANSIENT_HTTP_STATUS or _rate_limited(exc)- # IncompleteRead is a mid-transfer truncation of a chunked response. It- # inherits from HTTPException alone -- neither URLError nor ConnectionError --- # so it needs naming, or a truncation burns the fallback instead of retrying- # the source that was already serving.+ # IncompleteRead is a truncated body: http.client raises it when a chunked+ # response is cut mid-chunk, and _download_url_to_file raises its subclass+ # _TruncatedTransfer when a body ends short of its Content-Length. It inherits+ # from HTTPException alone -- neither URLError nor ConnectionError -- so it needs+ # naming, or a truncation burns the fallback instead of retrying the source+ # that was already serving.return isinstance(exc, (URLError, TimeoutError, ConnectionError, http.client.IncompleteRead))@@ -337,7 +625,107 @@ def _cached_file_path(url: str, kwargs: dict[str, Any]) -> str:return os.path.join(model_dir, filename)-def _prefetch_to_cache(url: str, kwargs: dict[str, Any]) -> bool:+def _download_url_to_file(+ url: str,+ dst: str,+ hash_prefix: str | None = None,+ progress: bool = True,+ timeout: float | None = None,+) -> None:+ """Download *url* to *dst*, failing an attempt that stalls for *timeout* seconds.++ :func:`torch.hub.download_url_to_file` with a timeout. torch's function opens+ the URL with no timeout and has no parameter for one, so a server that accepted+ the connection and then went quiet held the call forever. Giving it one from+ outside would mean replacing ``torch.hub.urlopen`` or the process-wide socket+ default, which changes torch or every other thread for everyone, so kornia runs+ the transfer itself. Everything else follows torch: the ``User-Agent``, the chunk+ size, the progress bar (torch's own ``tqdm``, or its stand-in without tqdm), the+ hash check and its message, and writing to a temporary file beside *dst* that+ replaces it only once complete, so a failed or interrupted transfer never leaves+ a partial file at *dst*. Unlike torch, a body shorter than the ``Content-Length``+ that framed it counts as failed rather than complete; a chunked or close-delimited+ body, or one whose header http.client ignores, is taken as torch takes it.++ Args:+ url: the URL to fetch; ``file://`` URLs work too.+ dst: the destination path; a leading ``~`` is expanded.+ hash_prefix: if given, the SHA256 of the download must start with it.+ progress: whether to show a progress bar on stderr.+ timeout: the bound on connecting and on each read, in seconds; ``None``+ uses the ``KORNIA_DOWNLOAD_TIMEOUT`` environment variable, or 30 s. It+ bounds each wait, not the whole transfer.++ Raises:+ TimeoutError: if the server went *timeout* seconds without answering.+ http.client.IncompleteRead: if the body ended before its ``Content-Length``.+ RuntimeError: if the download does not match *hash_prefix*.+ """+ timeout = _resolve_timeout(timeout)+ dst = os.path.expanduser(dst)+ for _ in range(tempfile.TMP_MAX):+ partial = f"{dst}.{uuid.uuid4().hex}.partial"+ try:+ f = open(partial, "xb")+ except FileExistsError:+ continue+ break+ else: # pragma: no cover - every uuid4 name already taken+ raise FileExistsError(errno.EEXIST, "No usable temporary file name found")++ sha256 = hashlib.sha256() if hash_prefix is not None else None+ bar_type = getattr(torch.hub, "tqdm", None) # tqdm, or torch's stand-in when it is absent+ try:+ with f:+ # ``file://`` is deliberately accepted, as torch accepts it.+ request = Request(url, headers={"User-Agent": "torch.hub"}) # noqa: S310+ with urlopen(request, timeout=timeout) as response: # noqa: S310+ # The length http.client frames the body by: None for a chunked body and for+ # a Content-Length that is missing, negative or not an integer, 0 for a+ # bodiless status. A ``file://`` response has no such attribute.+ framed = getattr(response, "length", None)+ lengths = response.info().get_all("Content-Length")+ total = int(lengths[0]) if lengths else None+ bar = (+ bar_type(total=total, disable=not progress, unit="B", unit_scale=True, unit_divisor=1024)+ if bar_type is not None+ else contextlib.nullcontext()+ )+ received = 0+ with bar:+ while chunk := response.read(_READ_CHUNK_BYTES):+ f.write(chunk)+ received += len(chunk)+ if sha256 is not None:+ sha256.update(chunk)+ if bar_type is not None:+ bar.update(len(chunk))+ # Checked only when Content-Length framed the body, as torch has no check at all+ # elsewhere; http.client clips a longer body there, so only a short one can occur.+ # urllib does not decode a Content-Encoding, so the raw byte count is what it counts.+ if isinstance(framed, int) and received < framed:+ raise _TruncatedTransfer(received, framed)+ if sha256 is not None and hash_prefix is not None:+ digest = sha256.hexdigest()+ if digest[: len(hash_prefix)] != hash_prefix:+ raise RuntimeError(f'invalid hash value (expected "{hash_prefix}", got "{digest}")')+ os.replace(partial, dst)+ except (TimeoutError, URLError) as e:+ if not _is_timeout(e):+ raise+ raise TimeoutError(+ f"the server went {timeout:g} s without answering (the download timeout, which bounds connecting "+ f"and each read). If the link is slow rather than stalled, pass a larger timeout= to "+ f"load_state_dict_from_url, download_file_from_url or download_hf_file, or set the "+ f"{_DOWNLOAD_TIMEOUT_ENV_VAR} environment variable (in seconds), which also reaches callers "+ f"that take no timeout, such as pretrained model constructors"+ ) from e+ finally:+ if os.path.exists(partial):+ os.remove(partial)+++def _prefetch_to_cache(url: str, kwargs: dict[str, Any], timeout: float) -> bool:"""Download *url* into the torch hub cache if it is not already there.Doing the fetch here rather than letting :func:`torch.hub.load_state_dict_from_url`@@ -352,11 +740,17 @@ def _prefetch_to_cache(url: str, kwargs: dict[str, Any]) -> bool:kwargs: the keyword arguments destined for the torch function;``model_dir``, ``file_name``, ``check_hash`` and ``progress`` arehonoured so the cache entry is identical to torch's.+ timeout: the bound on connecting and on each read, in seconds, already+ resolved by :func:`_resolve_timeout`.Returns:Whether a transfer happened. A cache hit returns ``False``, which is how:func:`load_state_dict_from_url` tells a source that was really fetchedfrom one that was handed the file already on disk.++ Raises:+ TimeoutError: if the server stalled for *timeout* seconds; see+ :func:`_download_url_to_file`, which leaves nothing at the cache path."""cached_file = _cached_file_path(url, kwargs)if os.path.exists(cached_file):@@ -371,7 +765,7 @@ def _prefetch_to_cache(url: str, kwargs: dict[str, Any]) -> bool:# torch writes this to stdout; status output belongs on stderr.sys.stderr.write(f'Downloading: "{url}" to {cached_file}\n')- torch.hub.download_url_to_file(url, cached_file, hash_prefix, progress=kwargs.get("progress", True))+ _download_url_to_file(url, cached_file, hash_prefix, progress=kwargs.get("progress", True), timeout=timeout)return True@@ -454,10 +848,9 @@ def _discard_cache_entry(url: str, kwargs: dict[str, Any]) -> str | None:# A read-only cache, or a Windows reader holding the file open. Renaming# it again would fail the same way, so the ledger is marked either way,# but a fallback that can never be reached is worth saying out loud.- warnings.warn(+ _warn(f"Could not discard the cache entry at {path}: {e}. If that file is corrupt, "- f"the fallback sources cannot take effect until it is deleted by hand.",- stacklevel=3,+ f"the fallback sources cannot take effect until it is deleted by hand.")# The entry is still there and still unloadable. Marking the ledger stops# a rename that can only fail the same way from being tried again, and a@@ -505,16 +898,15 @@ def _settle_quarantine(path: str, quarantine: str, *, loaded: bool, downloaded:try:os.remove(quarantine)except OSError as e: # pragma: no cover - a cache that cannot be written to- warnings.warn(f"Could not remove the discarded cache entry at {quarantine}: {e}.", stacklevel=3)+ _warn(f"Could not remove the discarded cache entry at {quarantine}: {e}.")returntry:os.replace(quarantine, path) # atomically overwrites whatever a source left thereexcept OSError as e: # pragma: no cover - a cache that cannot be written to- warnings.warn(+ _warn(f"Could not restore the cache entry at {path} from {quarantine}: {e}. "- f"Move it back by hand to avoid re-downloading the checkpoint.",- stacklevel=3,+ f"Move it back by hand to avoid re-downloading the checkpoint.")returnif not downloaded:@@ -548,14 +940,13 @@ def _drop_failed_download(path: str) -> None:except FileNotFoundError: # pragma: no cover - torch removed it itselfpassexcept OSError as e: # pragma: no cover - a cache that cannot be written to- warnings.warn(+ _warn(f"Could not remove the failed download at {path}: {e}. "- f"Delete it by hand if the fallback sources stop taking effect.",- stacklevel=3,+ f"Delete it by hand if the fallback sources stop taking effect.")-def _prefetch_with_retry(url: str, kwargs: dict[str, Any], budget: _SleepBudget) -> bool:+def _prefetch_with_retry(url: str, kwargs: dict[str, Any], budget: _SleepBudget, timeout: float) -> bool:"""Run :func:`_prefetch_to_cache`, retrying transient failures with backoff.Args:@@ -563,6 +954,7 @@ def _prefetch_with_retry(url: str, kwargs: dict[str, Any], budget: _SleepBudget)kwargs: the keyword arguments destined for the torch function.budget: the waiting time the whole call has left; a retry that wouldexceed it is not taken.+ timeout: forwarded to :func:`_prefetch_to_cache`.Returns:Whether a transfer happened; see :func:`_prefetch_to_cache`.@@ -573,25 +965,22 @@ def _prefetch_with_retry(url: str, kwargs: dict[str, Any], budget: _SleepBudget)"""for attempt in range(1, _MAX_ATTEMPTS + 1):try:- return _prefetch_to_cache(url, kwargs)+ return _prefetch_to_cache(url, kwargs, timeout)except Exception as e:if attempt == _MAX_ATTEMPTS or not _is_transient(e):raisedelay = _retry_delay(e, attempt)if delay > budget.remaining:raise- warnings.warn(+ _warn(f"Transient failure fetching {url!r}: {e}. Retrying in {delay:.0f}s "- f"(attempt {attempt + 1} of {_MAX_ATTEMPTS}).",- # 1 = here, 2 = load_state_dict_from_url, 3 = its caller, which is- # the frame the sibling warning below also points at.- stacklevel=3,+ f"(attempt {attempt + 1} of {_MAX_ATTEMPTS}).")budget.sleep(delay)raise AssertionError("unreachable: the loop above always returns or raises") # pragma: no cover-def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Any]:+def load_state_dict_from_url(url: str | list[str], *, timeout: float | None = None, **kwargs: Any) -> dict[str, Any]:"""Load a state dict from a URL, trying fallback URLs on failure.Replacement for :func:`torch.hub.load_state_dict_from_url` that also accepts@@ -680,10 +1069,25 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Aresponse that names its own delay in ``Retry-After`` -- or, on a rate-limitresponse, ``X-RateLimit-Reset`` -- is honoured instead of the guess, clampedto :data:`_MAX_BACKOFF_SECONDS`, and the call as a whole never waits longer- than :data:`_MAX_CALL_SLEEP_SECONDS`.+ than :data:`_MAX_CALL_SLEEP_SECONDS`. A server that stalls -- accepts the+ connection and then sends nothing -- fails the attempt after ``timeout``+ seconds and counts as transient too.++ The arguments are checked before the cache is consulted or a request made:+ ``file_name`` must be a bare file name, as it names an entry in the flat cache+ directory, and without it the first URL's path must end in one; a keyword+ the torch function does not take raises :class:`TypeError` there and then,+ rather than being mistaken for a corrupt cache entry. A leading ``~`` in+ ``model_dir`` is expanded.Args:url: a URL string, or a list of URL strings tried left-to-right.+ timeout: seconds a connection attempt or a single read may stall before the+ attempt fails; it bounds each wait, not the whole transfer. ``None``+ uses the ``KORNIA_DOWNLOAD_TIMEOUT`` environment variable, read at+ each call, or 30 s when it is unset. The variable is how to raise the+ bound for callers that take no ``timeout``, such as ``pretrained=True``+ model constructors.**kwargs: forwarded to :func:`torch.hub.load_state_dict_from_url`(``map_location``, ``check_hash``, ``file_name``, β¦), with``weights_only`` set to ``True`` unless it is passed as ``False``.@@ -692,6 +1096,13 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, AThe loaded state dict.Raises:+ TypeError: if ``url`` is not a URL string or a list of them, ``timeout``+ is not a number, or a keyword is not one the torch function takes.+ ValueError: if ``url`` is empty; if ``timeout`` is not greater than 0 and+ at most ``threading.TIMEOUT_MAX``, or it is omitted and+ ``KORNIA_DOWNLOAD_TIMEOUT`` holds such a value or no number (the message+ names which); if ``file_name`` is not a bare file name, or it is omitted+ and the first URL does not end in one.RuntimeError: if every URL fails. The message carries the failingexception's type and text, the source it came from and the cache path in play, and theexception itself is chained; without them a rate limit is@@ -708,7 +1119,14 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, A... "pretrained/pretrained_all_datasets/HardNet%2B%2B.pth", # fallback... ])"""- urls = [url] if isinstance(url, str) else list(url)+ urls = _url_list(url)+ timeout = _resolve_timeout(timeout)+ _check_torch_keywords(kwargs)+ file_name = _check_cache_file_name(urls, kwargs.get("file_name"))+ if file_name is not None:+ kwargs["file_name"] = file_name+ if kwargs.get("model_dir") is not None:+ kwargs["model_dir"] = _expand_model_dir(kwargs["model_dir"])# The one torch call below loads from every source, the fallbacks and the# refetch after a quarantine alike, so setting this once covers them all.@@ -743,7 +1161,7 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Amore_sources = i < len(sources) - 1try:# Populate the cache ourselves so torch's stdout line is never reached.- fetched = _prefetch_with_retry(u, kwargs, budget)+ fetched = _prefetch_with_retry(u, kwargs, budget, timeout)downloaded |= fetchedstate_dict = torch.hub.load_state_dict_from_url(u, **kwargs)except Exception as e: # noqa: BLE001@@ -765,10 +1183,7 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Aif moved is not None:quarantine, discarded_url, discard_exc = moved, u, eif more_sources:- warnings.warn(- f"Failed to load weights from {u!r}: {e}. Trying next source.",- stacklevel=2,- )+ _warn(f"Failed to load weights from {u!r}: {e}. Trying next source.")continueif quarantine is not None:_settle_quarantine(cache_path, quarantine, loaded=True, downloaded=downloaded)@@ -801,14 +1216,14 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Aif re_attempted and not downloaded and discard_exc is not None:refetch_note = (f" (the cache entry was set aside and refetching it from that same source "- f"failed too: {type(last_exc).__name__}: {last_exc})"+ f"failed too: {_describe(last_exc)})")last_exc, last_url = discard_exc, discarded_urlraise RuntimeError(f"Failed to load weights from all {len(urls)} source(s). "f"Last URL tried: {last_url!r}. "- f"Last error: {type(last_exc).__name__}: {last_exc}{refetch_note}. "+ f"Last error: {_describe(last_exc)}{refetch_note}. "# Unquoted: the point of naming the path is that it can be pasted into# ``rm``/``del``, and ``repr`` doubles every backslash of a Windows path.f"Cache path: {cache_path} -- delete it if it is corrupt and this repeats."@@ -822,6 +1237,7 @@ def download_file_from_url(model_dir: str | None = None,progress: bool = True,validate: Callable[[str], None] | None = None,+ timeout: float | None = None,) -> str:"""Download a file into the torch hub cache and return its path, without loading it.@@ -829,7 +1245,8 @@ def download_file_from_url(cannot unpickle -- a ``.safetensors`` file, read afterwards with:func:`kornia.core.load_safetensors`. It shares that function's cache, itsfallback-URL handling, its retry-with-backoff on transient failures and rate- limits (see :data:`_MAX_ATTEMPTS` and :func:`_retry_delay`), and its habit of+ limits (see :data:`_MAX_ATTEMPTS` and :func:`_retry_delay`), its bound on a+ stalled server (see ``timeout``), and its habit ofannouncing a transfer on :data:`sys.stderr` rather than stdout. A filealready in the cache is returned as it is, with no request made.@@ -873,20 +1290,33 @@ def download_file_from_url(the second model would silently load the first one's weights (see:func:`_hf_cache_file_name`). Must be a bare filename: the cache isone flat directory, so a value carrying a path separator or naming- ``.``/``..`` would write outside it.+ ``.``/``..`` would write outside it. Without it, the first URL's path+ must end in a file name.model_dir: directory to cache the file in. Defaults to torch's- ``<hub dir>/checkpoints``, which is the cache CI restores.+ ``<hub dir>/checkpoints``, which is the cache CI restores. A leading+ ``~`` is expanded.progress: whether to display a progress bar during a transfer.validate: called with the cache path after each attempt, to decidewhether what is there is usable. Raising rejects the entry. Keep itcheap -- a header parse, not a full read -- since it runs on cachehits too.+ timeout: seconds a connection attempt or a single read may stall before the+ attempt fails, which then counts as transient; it bounds each wait, not+ the whole transfer. ``None`` uses the ``KORNIA_DOWNLOAD_TIMEOUT``+ environment variable, read at each call, or 30 s when it is unset.Returns:The path of the cached file.Raises:- ValueError: if ``file_name`` is not a single path component.+ TypeError: if ``url`` is not a URL string or a list of them, or ``timeout``+ is not a number.+ ValueError: if ``file_name`` is not a single path component, or it is+ omitted and the first URL's path does not end in a file name; if+ ``url`` is empty; or if ``timeout`` is not greater than 0 and at most+ ``threading.TIMEOUT_MAX``, or it is omitted and+ ``KORNIA_DOWNLOAD_TIMEOUT`` holds such a value or no number (the message+ names which).RuntimeError: if every URL fails. The message carries the last failure'stype and text, the source it came from and the cache path in play,and the exception itself is chained.@@ -897,9 +1327,10 @@ def download_file_from_url(... file_name="kornia--kimi-vl-a3b-instruct-vision--model.safetensors",... )"""- if file_name is not None and (file_name in {"", ".", ".."} or os.path.basename(file_name) != file_name):- raise ValueError(f"file_name must be a bare filename inside the cache directory, got {file_name!r}.")- urls = [url] if isinstance(url, str) else list(url)+ urls = _url_list(url)+ file_name = _check_cache_file_name(urls, file_name)+ timeout = _resolve_timeout(timeout)+ model_dir = _expand_model_dir(model_dir)# Pin the cache filename to the primary URL's basename so that all attempts# share one cache slot, exactly as :func:`load_state_dict_from_url` does.@@ -924,7 +1355,7 @@ def download_file_from_url(fetched = Falsemore_sources = i < len(sources) - 1try:- fetched = _prefetch_with_retry(u, kwargs, budget)+ fetched = _prefetch_with_retry(u, kwargs, budget, timeout)downloaded |= fetchedif validate is not None:validate(cache_path)@@ -957,7 +1388,7 @@ def download_file_from_url(if moved is not None:quarantine, discarded_url, discard_exc = moved, u, eif more_sources:- warnings.warn(f"Failed to download {u!r}: {e}. Trying next source.", stacklevel=2)+ _warn(f"Failed to download {u!r}: {e}. Trying next source.")continueif quarantine is not None:_settle_quarantine(cache_path, quarantine, loaded=True, downloaded=downloaded)@@ -985,14 +1416,14 @@ def download_file_from_url(if re_attempted and not downloaded and discard_exc is not None:refetch_note = (f" (the cache entry was set aside and refetching it from that same source "- f"failed too: {type(last_exc).__name__}: {last_exc})"+ f"failed too: {_describe(last_exc)})")last_exc, last_url = discard_exc, discarded_urlraise RuntimeError(f"Failed to download the file from all {len(urls)} source(s). "f"Last URL tried: {last_url!r}. "- f"Last error: {type(last_exc).__name__}: {last_exc}{refetch_note}. "+ f"Last error: {_describe(last_exc)}{refetch_note}. "# Unquoted: the point of naming the path is that it can be pasted into# ``rm``/``del``, and ``repr`` doubles every backslash of a Windows path.f"Cache path: {cache_path} -- delete it if it is corrupt and this repeats."@@ -1006,6 +1437,7 @@ def download_hf_file(model_dir: str | None = None,progress: bool = True,validate: Callable[[str], None] | None = None,+ timeout: float | None = None,) -> str:"""Download one file from a HuggingFace repo and return the path it is cached at.@@ -1027,14 +1459,23 @@ def download_hf_file(it. Pass :func:`kornia.core.check_safetensors` for a checkpoint, sothat a truncated cache entry is re-fetched rather than handed backon every later call.+ timeout: seconds a connection attempt or a single read may stall before the+ attempt fails; it bounds each wait, not the whole transfer. ``None``+ uses the ``KORNIA_DOWNLOAD_TIMEOUT`` environment variable, read at+ each call, or 30 s when it is unset. Forwarded to+ :func:`download_file_from_url`.Returns:The path of the cached file. Read a ``.safetensors`` one with:func:`kornia.core.load_safetensors`.Raises:+ TypeError: if ``timeout`` is not a number.ValueError: if ``filename`` carries a path separator; only files at therepository root are supported, because the cache is one flat directory.+ Also if ``timeout`` is not greater than 0 and at most+ ``threading.TIMEOUT_MAX``, or it is omitted and ``KORNIA_DOWNLOAD_TIMEOUT``+ holds such a value or no number (the message names which).RuntimeError: if the download fails; see :func:`download_file_from_url`.Example:@@ -1048,4 +1489,5 @@ def download_hf_file(model_dir=model_dir,progress=progress,validate=validate,+ timeout=timeout,)diff --git a/testing/doctest_downloads.py b/testing/doctest_downloads.pyindex a3557d40d..87daddb33 100644--- a/testing/doctest_downloads.py+++ b/testing/doctest_downloads.py@@ -44,6 +44,9 @@ DOWNLOAD_ENV_VAR = "KORNIA_DOCTEST_DOWNLOAD"# ``kornia.feature.lightglue_onnx.utils.download`` binds ``download_url_to_file``# at import time, so patching ``torch.hub`` alone would not cover it._DOWNLOAD_PRIMITIVES: tuple[tuple[str, str], ...] = (+ # kornia.core.download runs its own transfer (torch's has no timeout), so every+ # load_state_dict_from_url / download_file_from_url cache miss reaches the network here.+ ("kornia.core.download", "_download_url_to_file"),("torch.hub", "download_url_to_file"),("kornia.feature.lightglue_onnx.utils.download", "download_url_to_file"),# kornia.onnx.download.CachedDownloader.download reaches the network here.diff --git a/tests/core/test_download.py b/tests/core/test_download.pyindex 64e4eac49..52ae5b505 100644--- a/tests/core/test_download.py+++ b/tests/core/test_download.py@@ -18,11 +18,15 @@from __future__ import annotationsimport collections+import copy+import hashlibimport http.clientimport http.serverimport io+import ntpathimport osimport pickle+import socketimport sysimport threadingimport time@@ -57,6 +61,12 @@ def _clear_discard_ledger():download_mod._DISCARDED_CACHE_PATHS.clear()[email protected](autouse=True)+def _no_timeout_from_the_environment(monkeypatch):+ """A ``KORNIA_DOWNLOAD_TIMEOUT`` in the developer's shell must not change these tests."""+ monkeypatch.delenv("KORNIA_DOWNLOAD_TIMEOUT", raising=False)++class TestHfUrl:def test_format(self) -> None:assert hf_url("hardnet", "HardNetPP.pth") == (@@ -106,8 +116,8 @@ class TestLoadStateDictFromUrl:"""Keep the wrapper's prefetch step off the network and out of weights/."""monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))monkeypatch.setattr(- torch.hub,- "download_url_to_file",+ download_mod,+ "_download_url_to_file",lambda url, dst, *a, **k: torch.save({"weight": torch.zeros(1)}, dst),)@@ -212,13 +222,13 @@ class TestProgressGoesToStderr:transfers: list[str] = []monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))- def fake_download(url, dst, hash_prefix=None, progress=True):+ def fake_download(url, dst, hash_prefix=None, progress=True, timeout=None):transfers.append(url)if on_download is not None:on_download()torch.save({"weight": torch.zeros(1)}, dst)- monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ monkeypatch.setattr(download_mod, "_download_url_to_file", fake_download)return transfersdef test_cold_cache_writes_nothing_to_stdout(self, capsys, monkeypatch, tmp_path) -> None:@@ -272,11 +282,11 @@ class TestConcurrentLoadsDoNotDisturbStdout:def _stub_transfer(monkeypatch, tmp_path, hook):monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))- def fake_download(url, dst, hash_prefix=None, progress=True):+ def fake_download(url, dst, hash_prefix=None, progress=True, timeout=None):hook(url)torch.save({"weight": torch.zeros(1)}, dst)- monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ monkeypatch.setattr(download_mod, "_download_url_to_file", fake_download)def test_overlapping_calls_leave_stdout_intact(self, monkeypatch, tmp_path) -> None:barrier = threading.Barrier(2)@@ -381,7 +391,7 @@ class TestPoisonedCacheEntry:transfers: list[str] = []monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))- def fake_download(url, dst, hash_prefix=None, progress=True):+ def fake_download(url, dst, hash_prefix=None, progress=True, timeout=None):transfers.append(url)if url in bad_urls:# A rate-limit page served with a 200, or a truncated transfer.@@ -390,7 +400,7 @@ class TestPoisonedCacheEntry:else:torch.save(TestPoisonedCacheEntry._GOOD, dst)- monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ monkeypatch.setattr(download_mod, "_download_url_to_file", fake_download)return transfersdef test_fallback_recovers_from_bad_primary_download(self, monkeypatch, tmp_path) -> None:@@ -546,11 +556,11 @@ class TestPoisonedCacheEntry:monkeypatch.setattr(download_mod, "time", _FakeTime())transfers: list[str] = []- def offline(url, dst, hash_prefix=None, progress=True):+ def offline(url, dst, hash_prefix=None, progress=True, timeout=None):transfers.append(url)raise URLError("network is unreachable")- monkeypatch.setattr(torch.hub, "download_url_to_file", offline)+ monkeypatch.setattr(download_mod, "_download_url_to_file", offline)cached = tmp_path / "checkpoints" / "model.pth"cached.parent.mkdir(parents=True, exist_ok=True)@@ -586,10 +596,10 @@ class TestPoisonedCacheEntry:monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))monkeypatch.setattr(download_mod, "time", _FakeTime())- def offline(url, dst, hash_prefix=None, progress=True):+ def offline(url, dst, hash_prefix=None, progress=True, timeout=None):raise URLError("network is unreachable")- monkeypatch.setattr(torch.hub, "download_url_to_file", offline)+ monkeypatch.setattr(download_mod, "_download_url_to_file", offline)cached = tmp_path / "checkpoints" / "model.pth"cached.parent.mkdir(parents=True, exist_ok=True)@@ -624,13 +634,13 @@ class TestPoisonedCacheEntry:offline = Truetransfers: list[str] = []- def fake_download(url, dst, hash_prefix=None, progress=True):+ def fake_download(url, dst, hash_prefix=None, progress=True, timeout=None):transfers.append(url)if offline:raise URLError("network is unreachable")torch.save(self._GOOD, dst)- monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ monkeypatch.setattr(download_mod, "_download_url_to_file", fake_download)cached = tmp_path / "checkpoints" / "model.pth"cached.parent.mkdir(parents=True, exist_ok=True)@@ -699,13 +709,13 @@ class TestPoisonedCacheEntry:cached.parent.mkdir(parents=True, exist_ok=True)cached.write_bytes(b"<html>429 Too Many Requests</html>")- def fake_download(url, dst, hash_prefix=None, progress=True):+ def fake_download(url, dst, hash_prefix=None, progress=True, timeout=None):transfers.append(url)if url == self._FALLBACK:raise HTTPError(url, 404, "Not Found", None, None)torch.save(self._GOOD, dst)- monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ monkeypatch.setattr(download_mod, "_download_url_to_file", fake_download)with warnings.catch_warnings(record=True):warnings.simplefilter("always")@@ -733,7 +743,7 @@ class TestPoisonedCacheEntry:monkeypatch.setattr(download_mod, "time", _FakeTime())healthy = False- def fake_download(url, dst, hash_prefix=None, progress=True):+ def fake_download(url, dst, hash_prefix=None, progress=True, timeout=None):if url == self._FALLBACK:raise URLError("network is unreachable")if healthy:@@ -742,7 +752,7 @@ class TestPoisonedCacheEntry:with open(dst, "wb") as f:f.write(b"<html>429 Too Many Requests</html>")- monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ monkeypatch.setattr(download_mod, "_download_url_to_file", fake_download)cached = tmp_path / "checkpoints" / "model.pth"with warnings.catch_warnings(record=True):@@ -802,7 +812,7 @@ class TestPoisonedCacheEntry:healthy = Falsetransfers: list[str] = []- def fake_download(url, dst, hash_prefix=None, progress=True):+ def fake_download(url, dst, hash_prefix=None, progress=True, timeout=None):transfers.append(url)if healthy:torch.save(self._GOOD, dst)@@ -810,7 +820,7 @@ class TestPoisonedCacheEntry:with open(dst, "wb") as f:f.write(b"<html>429 Too Many Requests</html>")- monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ monkeypatch.setattr(download_mod, "_download_url_to_file", fake_download)cached = tmp_path / "checkpoints" / "model.pth"with warnings.catch_warnings(record=True):@@ -889,14 +899,14 @@ class TestTransientRetry:attempts: list[str] = []monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))- def fake_download(url, dst, hash_prefix=None, progress=True):+ def fake_download(url, dst, hash_prefix=None, progress=True, timeout=None):attempts.append(url)outcome = side_effects.pop(0)if outcome is not None:raise outcometorch.save({"weight": torch.zeros(1)}, dst)- monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ monkeypatch.setattr(download_mod, "_download_url_to_file", fake_download)return attempts@pytest.mark.parametrize("code", [408, 425, 429, 500, 502, 503, 504])@@ -1143,8 +1153,8 @@ class TestFailureMessageCarriesCause:def test_message_names_the_underlying_error(self, monkeypatch, tmp_path) -> None:monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))monkeypatch.setattr(- torch.hub,- "download_url_to_file",+ download_mod,+ "_download_url_to_file",lambda url, dst, *a, **k: (_ for _ in ()).throw(_http_error(url, 429)),)monkeypatch.setattr(download_mod, "time", _FakeTime())@@ -1169,7 +1179,7 @@ class TestFailureMessageCarriesCause:def local_server(monkeypatch):"""Serve in-memory files over HTTP from a thread bound to 127.0.0.1.- The transfer runs through ``torch.hub.download_url_to_file`` for real -- nothing is+ The transfer runs through ``kornia.core.download._download_url_to_file`` for real -- nothing isstubbed between the socket and ``torch.load`` -- and nothing leaves the host. Yields``(files, url, hits)``: ``files`` maps a path such as ``"/model.pth"`` to the bytesserved for it (any other path answers 404), ``url(path)`` builds the URL, and ``hits``@@ -1308,7 +1318,7 @@ class TestDownloadFileFromUrl:"""The path for checkpoints torch cannot unpickle -- a ``.safetensors`` file.The transfers here are real: a ``file://`` URL goes through the same- ``torch.hub.download_url_to_file`` a remote one does, so the cache path, the+ ``_download_url_to_file`` a remote one does, so the cache path, thebytes on disk and the cache hit are all exercised end to end without anetwork or a stub standing in for the transfer."""@@ -1327,20 +1337,20 @@ class TestDownloadFileFromUrl:path = download_file_from_url(url, model_dir=str(model_dir), progress=False)- assert path == str(model_dir / "model.safetensors")+ assert Path(path) == model_dir / "model.safetensors"assert Path(path).read_bytes() == payloaddef test_second_call_is_a_cache_hit(self, monkeypatch, tmp_path) -> None:url, _ = self._serve(tmp_path)model_dir = tmp_path / "cache"transfers: list[str] = []- real = torch.hub.download_url_to_file+ real = download_mod._download_url_to_filedef counted(url_, dst, *args, **kwargs):transfers.append(url_)return real(url_, dst, *args, **kwargs)- monkeypatch.setattr(torch.hub, "download_url_to_file", counted)+ monkeypatch.setattr(download_mod, "_download_url_to_file", counted)first = download_file_from_url(url, model_dir=str(model_dir), progress=False)second = download_file_from_url(url, model_dir=str(model_dir), progress=False)@@ -1354,7 +1364,7 @@ class TestDownloadFileFromUrl:path = download_file_from_url(url, progress=False)- assert path == str(tmp_path / "hub" / "checkpoints" / "model.safetensors")+ assert Path(path) == tmp_path / "hub" / "checkpoints" / "model.safetensors"def test_file_name_overrides_the_basename(self, tmp_path) -> None:"""Two repositories publish a ``model.safetensors`` each; one cache slot is not enough."""@@ -1382,15 +1392,15 @@ class TestDownloadFileFromUrl:path = download_file_from_url([dead, url], model_dir=str(model_dir), progress=False)# The cache name is pinned to the *first* URL, as in load_state_dict_from_url.- assert path == str(model_dir / "missing.safetensors")+ assert Path(path) == model_dir / "missing.safetensors"assert Path(path).read_bytes() == payloadassert any("Trying next source" in str(warning.message) for warning in caught)def test_all_sources_failing_names_the_cause_and_the_path(self, monkeypatch, tmp_path) -> None:monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))monkeypatch.setattr(- torch.hub,- "download_url_to_file",+ download_mod,+ "_download_url_to_file",lambda url, dst, *a, **k: (_ for _ in ()).throw(_http_error(url, 404)),)@@ -1416,7 +1426,7 @@ class TestDownloadFileFromUrl:raise _http_error(url, 429)Path(dst).write_bytes(b"weights")- monkeypatch.setattr(torch.hub, "download_url_to_file", flaky)+ monkeypatch.setattr(download_mod, "_download_url_to_file", flaky)with warnings.catch_warnings(record=True):warnings.simplefilter("always")@@ -1435,7 +1445,7 @@ class TestDownloadFileFromUrl:raise OSError("connection reset")Path(dst).write_bytes(b"complete")- monkeypatch.setattr(torch.hub, "download_url_to_file", half_written)+ monkeypatch.setattr(download_mod, "_download_url_to_file", half_written)with warnings.catch_warnings(record=True):warnings.simplefilter("always")@@ -1591,13 +1601,13 @@ class TestDownloadValidate:url = self._serve(tmp_path, payload)model_dir = tmp_path / "cache"transfers: list[str] = []- real = torch.hub.download_url_to_file+ real = download_mod._download_url_to_filedef counted(url_, dst, *args, **kwargs):transfers.append(url_)return real(url_, dst, *args, **kwargs)- monkeypatch.setattr(torch.hub, "download_url_to_file", counted)+ monkeypatch.setattr(download_mod, "_download_url_to_file", counted)validate = self._reject_truncated(len(payload))first = download_file_from_url(url, model_dir=str(model_dir), progress=False, validate=validate)@@ -1701,3 +1711,872 @@ class TestDownloadValidate:truncated.write_bytes(whole[:-4])with pytest.raises(ValueError):check_safetensors(truncated)+++class _Chunked:+ """A ``scripted_server`` response sent with ``Transfer-Encoding: chunked``.++ ``content_length``, when given, adds a ``Content-Length`` header as well, which HTTP+ says the chunked framing overrides.+ """++ def __init__(self, body: bytes, content_length: int | None = None) -> None:+ self.body = body+ self.content_length = content_length+++def _bypass_proxies(monkeypatch) -> None:+ """Send requests for 127.0.0.1 straight to the test server, whatever proxy the shell sets.++ A lowercase ``http_proxy`` pointing at a closed port -- one way to block the internet+ for a test run -- would otherwise take the request and fail it with ``URLError``.+ """+ for var in ("http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY"):+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("no_proxy", "127.0.0.1")+ monkeypatch.setenv("NO_PROXY", "127.0.0.1")+++def scripted_server(monkeypatch):+ """Serve scripted responses over HTTP from a thread bound to 127.0.0.1.++ Like :func:`local_server`, and it shuts down in a tenth of the time, which the many+ short tests below add up. ``responses`` maps a path to a response, or to a list of+ them consumed one per request with the last one repeating: ``bytes`` is a 200 with+ that body, an ``int`` is that status with an empty body and ``Retry-After: 0``, an+ ``(announced, body)`` tuple is a 200 whose ``Content-Length`` header says ``announced``+ (omitted when ``None``) while ``body`` is sent and the connection closes, and a+ :class:`_Chunked` is a 200 with a chunked body. Yields ``(responses, url, hits)``;+ any other path answers 404.+ """+ _bypass_proxies(monkeypatch)++ responses: dict[str, object] = {}+ hits: collections.Counter[str] = collections.Counter()++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ hits[self.path] += 1+ script = responses.get(self.path, 404)+ if not isinstance(script, list):+ script = [script]+ outcome = script[min(hits[self.path], len(script)) - 1]+ if isinstance(outcome, int):+ self.send_response(outcome)+ self.send_header("Retry-After", "0")+ self.send_header("Content-Length", "0")+ self.end_headers()+ return+ if isinstance(outcome, _Chunked):+ self.send_response(200)+ self.send_header("Transfer-Encoding", "chunked")+ if outcome.content_length is not None:+ self.send_header("Content-Length", str(outcome.content_length))+ self.end_headers()+ for start in range(0, len(outcome.body), 1000):+ piece = outcome.body[start : start + 1000]+ self.wfile.write(f"{len(piece):x}\r\n".encode() + piece + b"\r\n")+ self.wfile.write(b"0\r\n\r\n")+ return+ announced, body = outcome if isinstance(outcome, tuple) else (len(outcome), outcome)+ self.send_response(200)+ if announced is not None:+ self.send_header("Content-Length", str(announced))+ self.end_headers()+ self.wfile.write(body) # HTTP/1.0: the connection closes when the handler returns++ def log_message(self, *args: object) -> None:+ pass++ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)+ thread.start()+ port = server.server_address[1]+ try:+ yield responses, (lambda path: f"http://127.0.0.1:{port}{path}"), hits+ finally:+ server.shutdown()+ server.server_close()+ thread.join()+++class _StalledServer:+ """A 127.0.0.1 listener that never finishes a response.++ ``mode="silent"`` accepts each connection and never sends a byte; ``mode="mid_body"``+ reads the request, sends the status line, the headers and the first 100 of 1000+ announced body bytes, then goes quiet. Every connection is held open until+ :meth:`close`, so the only thing that can end a client's wait is its own timeout.+ """++ def __init__(self, mode: str) -> None:+ self.mode = mode+ self.connections: list[socket.socket] = []+ self._stop = threading.Event()+ self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ self._listener.bind(("127.0.0.1", 0))+ self._listener.listen()+ # Closing a listener does not wake a thread blocked in ``accept`` on Linux, so the+ # thread polls a stop flag instead and :meth:`close` never waits on it.+ self._listener.settimeout(0.05)+ self._thread = threading.Thread(target=self._serve, daemon=True)+ self._thread.start()++ def url(self, path: str) -> str:+ return f"http://127.0.0.1:{self._listener.getsockname()[1]}{path}"++ def _serve(self) -> None:+ while not self._stop.is_set():+ try:+ conn, _ = self._listener.accept()+ except TimeoutError: # nobody connected in this poll interval+ continue+ except OSError: # the listener was closed+ return+ self.connections.append(conn)+ if self.mode == "mid_body":+ conn.settimeout(5)+ request = b""+ while b"\r\n\r\n" not in request:+ chunk = conn.recv(4096)+ if not chunk:+ break+ request += chunk+ conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 1000\r\n\r\n" + b"x" * 100)++ def close(self) -> None:+ self._stop.set()+ self._thread.join(timeout=5)+ self._listener.close()+ for conn in self.connections:+ conn.close()++[email protected](params=["silent", "mid_body"])+def stalled_server(request, monkeypatch):+ _bypass_proxies(monkeypatch)+ server = _StalledServer(request.param)+ try:+ yield server+ finally:+ server.close()+++def _outcome_within(fn, seconds: float) -> BaseException | object:+ """Run *fn* in a daemon thread; return what it returned or raised, failing if it is still running."""+ outcome: list[object] = []++ def target() -> None:+ try:+ outcome.append(fn())+ except BaseException as e:+ outcome.append(e)++ worker = threading.Thread(target=target, daemon=True)+ worker.start()+ worker.join(seconds)+ assert not worker.is_alive(), f"still waiting after {seconds} s: the transfer has no timeout"+ return outcome[0]+++def hub_dir_in_tmp(monkeypatch, tmp_path):+ """Point the default cache at *tmp_path* and prove it, before anything is fetched."""+ hub = tmp_path / "hub"+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(hub))+ assert Path(torch.hub.get_dir()).is_relative_to(tmp_path)+ return hub++[email protected]("hub_dir_in_tmp")+class TestTransferTimeout:+ """A stalled server must end a download, not hang it (#5216).++ kornia used to fetch through ``torch.hub.download_url_to_file``, which opens the URL+ with no timeout, and set none either, so a server that accepted the connection and then+ went quiet held the call forever: the retry and fallback logic never got control,+ because nothing raised.+ """++ _TIMEOUT = 0.25+ _DEADLINE = 10.0++ @pytest.mark.parametrize("entry", ["load_state_dict_from_url", "download_file_from_url"])+ def test_a_stalled_server_fails_within_the_timeout(self, stalled_server, monkeypatch, tmp_path, entry) -> None:+ monkeypatch.setattr(download_mod, "time", _FakeTime())+ cache = tmp_path / "cache"+ fn = {"load_state_dict_from_url": load_state_dict_from_url, "download_file_from_url": download_file_from_url}+ url = stalled_server.url("/w.pth")++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ outcome = _outcome_within(+ lambda: fn[entry](url, model_dir=str(cache), progress=False, timeout=self._TIMEOUT), self._DEADLINE+ )++ assert isinstance(outcome, RuntimeError), f"expected the documented RuntimeError, got {outcome!r}"+ assert isinstance(outcome.__cause__, TimeoutError)+ message = str(outcome)+ assert "TimeoutError" in message and f"{self._TIMEOUT:g} s" in message+ assert str(cache / "w.pth") in message+ # Where the bound can be raised, including for callers such as pretrained constructors that take no timeout=.+ assert "timeout=" in message and "KORNIA_DOWNLOAD_TIMEOUT" in message+ assert "_DOWNLOAD_TIMEOUT_SECONDS" not in message+ # A timeout is transient, so the retry logic got control on every attempt.+ assert len(stalled_server.connections) == download_mod._MAX_ATTEMPTS+ # And nothing partial is left behind, under the cache name or a temporary one.+ assert not cache.exists() or list(cache.iterdir()) == []++ def test_the_environment_bounds_a_call_that_passes_no_timeout(self, stalled_server, monkeypatch, tmp_path):+ monkeypatch.setattr(download_mod, "time", _FakeTime())+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", str(self._TIMEOUT))+ monkeypatch.setattr(download_mod, "_HF_BASE", stalled_server.url(""))+ cache = tmp_path / "cache"++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ outcome = _outcome_within(+ lambda: download_hf_file("r", "w.safetensors", model_dir=str(cache), progress=False), self._DEADLINE+ )++ assert isinstance(outcome, RuntimeError), f"expected the documented RuntimeError, got {outcome!r}"+ assert isinstance(outcome.__cause__, TimeoutError)+ assert f"{self._TIMEOUT:g} s" in str(outcome)+ assert not cache.exists() or list(cache.iterdir()) == []++ def test_a_timed_out_primary_falls_back_to_the_mirror(self, stalled_server, scripted_server, monkeypatch, tmp_path):+ monkeypatch.setattr(download_mod, "time", _FakeTime())+ files, url, hits = scripted_server+ files["/w.pth"] = _checkpoint_bytes({"w": torch.arange(3.0)})++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ outcome = _outcome_within(+ lambda: load_state_dict_from_url(+ [stalled_server.url("/w.pth"), url("/w.pth")],+ model_dir=str(tmp_path / "cache"),+ progress=False,+ timeout=self._TIMEOUT,+ ),+ self._DEADLINE,+ )++ assert isinstance(outcome, dict), f"expected the mirror's state dict, got {outcome!r}"+ assert torch.equal(outcome["w"], torch.arange(3.0))+ assert hits["/w.pth"] == 1+ assert any("Trying next source" in str(w.message) for w in caught)++ @pytest.mark.parametrize(+ ("timeout", "error"),+ [+ (0, ValueError),+ (-1.0, ValueError),+ (float("nan"), ValueError),+ (float("inf"), ValueError),+ # Finite but beyond threading.TIMEOUT_MAX: an OverflowError inside the socket otherwise (ruling C16).+ pytest.param(1e300, ValueError, id="1e300"),+ pytest.param(threading.TIMEOUT_MAX * 2, ValueError, id="twice_TIMEOUT_MAX"),+ # More digits than the 4300 that ``repr`` of an int allows by default, so the message cannot print it.+ pytest.param(10**5000, ValueError, id="int_beyond_float"),+ ("30", TypeError),+ ],+ )+ def test_an_unusable_timeout_is_rejected_before_any_request(self, scripted_server, tmp_path, timeout, error):+ files, url, hits = scripted_server+ files["/w.pth"] = _checkpoint_bytes({"w": torch.zeros(1)})++ for fn in (load_state_dict_from_url, download_file_from_url):+ with pytest.raises(error, match="timeout"):+ fn(url("/w.pth"), model_dir=str(tmp_path / "cache"), progress=False, timeout=timeout)++ assert sum(hits.values()) == 0+ assert not (tmp_path / "cache").exists()++ def test_torch_hub_itself_is_left_without_a_timeout(self, scripted_server, tmp_path) -> None:+ """kornia bounds its own transfers only: the socket default and a direct ``torch.hub`` call are unchanged."""+ files, url, _ = scripted_server+ files["/w.pth"] = _checkpoint_bytes({"w": torch.zeros(1)})+ load_state_dict_from_url(url("/w.pth"), model_dir=str(tmp_path / "cache"), progress=False, timeout=5.0)++ assert socket.getdefaulttimeout() is None+ server = _StalledServer("silent")++ ended: list[Exception] = []++ def direct_torch_call() -> None:+ try:+ torch.hub.download_url_to_file(server.url("/x.pth"), str(tmp_path / "direct.pth"), progress=False)+ except Exception as e: # the server hanging up below is what ends it+ ended.append(e)++ worker = threading.Thread(target=direct_torch_call, daemon=True)+ try:+ worker.start()+ worker.join(4 * self._TIMEOUT)+ assert worker.is_alive(), f"a direct torch.hub call picked up kornia's timeout: {ended}"+ finally:+ server.close()+ worker.join(5)+ assert not [e for e in ended if isinstance(e, TimeoutError)]+++class TestLoadStateDictFromUrlFileName:+ """``file_name`` names a cache entry; nothing may escape the cache through it (#5217).++ torch joins it onto ``model_dir`` with ``os.path.join``, so an absolute name or one with+ ``../`` pointed outside the cache, and kornia's cache repair then moved the file there+ aside, downloaded the checkpoint over it and deleted the original.+ """++ _VICTIM = b"precious user data, not a checkpoint"++ def test_an_absolute_file_name_is_rejected_and_the_file_is_untouched(self, scripted_server, tmp_path) -> None:+ files, url, hits = scripted_server+ files["/w.pth"] = _checkpoint_bytes({"w": torch.zeros(2)})+ victims = tmp_path / "user_files"+ victims.mkdir()+ victim = victims / "precious.txt"+ victim.write_bytes(self._VICTIM)++ with pytest.raises(ValueError, match="bare filename"):+ load_state_dict_from_url(+ url("/w.pth"), model_dir=str(tmp_path / "cache"), progress=False, file_name=str(victim)+ )++ assert victim.read_bytes() == self._VICTIM+ assert [p.name for p in victims.iterdir()] == ["precious.txt"]+ assert sum(hits.values()) == 0+ assert not (tmp_path / "cache").exists()++ @pytest.mark.parametrize("file_name", ["../escape.pth", "sub/w.pth", "", ".", ".."])+ @pytest.mark.parametrize("sources", [1, 2], ids=["one_url", "two_urls"])+ def test_file_name_must_be_a_bare_filename(self, scripted_server, tmp_path, file_name, sources) -> None:+ files, url, hits = scripted_server+ files["/w.pth"] = _checkpoint_bytes({"w": torch.zeros(2)})+ model_dir = tmp_path / "cache"++ with pytest.raises(ValueError, match="bare filename"):+ load_state_dict_from_url(+ [url("/w.pth")] * sources, model_dir=str(model_dir), progress=False, file_name=file_name+ )++ assert sum(hits.values()) == 0+ assert not (tmp_path / "escape.pth").exists()+ assert not model_dir.exists(), "nothing was written"+++_ENTRY_POINTS = {"load_state_dict_from_url": load_state_dict_from_url, "download_file_from_url": download_file_from_url}+++class TestUrlArguments:+ """A URL that names no file, or a value that is not a URL, is refused up front (#5219)."""++ @pytest.mark.parametrize("tail", ["/dir/..", "/dir/.", "/dir/"])+ @pytest.mark.parametrize("entry", list(_ENTRY_POINTS))+ @pytest.mark.parametrize("as_list", [False, True], ids=["str", "list"])+ def test_a_url_without_a_file_name_is_rejected(self, scripted_server, tmp_path, tail, entry, as_list) -> None:+ """The derived cache path would be the cache directory or its parent."""+ files, url, hits = scripted_server+ files["/w.pth"] = _checkpoint_bytes({"w": torch.zeros(2)})+ model_dir = tmp_path / "parent" / "cache"+ model_dir.mkdir(parents=True)+ source = [url(tail), url("/w.pth")] if as_list else url(tail)++ with pytest.raises(ValueError, match="file_name="):+ _ENTRY_POINTS[entry](source, model_dir=str(model_dir), progress=False)++ assert sum(hits.values()) == 0+ assert list(model_dir.iterdir()) == []+ assert [p.name for p in model_dir.parent.iterdir()] == ["cache"]++ @pytest.mark.parametrize("entry", list(_ENTRY_POINTS))+ def test_an_explicit_file_name_makes_such_a_url_usable(self, scripted_server, tmp_path, entry) -> None:+ """The error says to pass ``file_name=``; doing so must work."""+ files, url, _ = scripted_server+ files["/dir/"] = _checkpoint_bytes({"w": torch.zeros(2)})++ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ _ENTRY_POINTS[entry](url("/dir/"), model_dir=str(tmp_path / "cache"), progress=False, file_name="w.pth")++ assert (tmp_path / "cache" / "w.pth").is_file()++ @pytest.mark.parametrize(+ ("url", "error", "match"),+ [+ ([], ValueError, "at least one URL"),+ ("", ValueError, "empty"),+ (["http://127.0.0.1:9/w.pth", ""], ValueError, "empty"),+ (Path("w.pth"), TypeError, "as_uri"),+ ([Path("w.pth")], TypeError, "as_uri"),+ (None, TypeError, "URL string"),+ (b"http://127.0.0.1:9/w.pth", TypeError, "URL string"),+ ([b"http://127.0.0.1:9/w.pth"], TypeError, "URL string"),+ ],+ ids=["empty_list", "empty_str", "empty_str_in_list", "path", "path_in_list", "none", "bytes", "bytes_in_list"],+ )+ @pytest.mark.parametrize("entry", list(_ENTRY_POINTS))+ def test_a_value_that_is_not_a_url_is_refused(self, hub_dir_in_tmp, url, error, match, entry) -> None:+ with pytest.raises(error, match=match):+ _ENTRY_POINTS[entry](url, progress=False)++ assert not hub_dir_in_tmp.exists()+++class TestHfUrlEscaping:+ """``hf_url`` builds a URL, so its arguments are path segments, not URL syntax (#5219)."""++ @pytest.mark.parametrize(+ ("filename", "tail"),+ [("a#b.pth", "a%23b.pth"), ("a?b.pth", "a%3Fb.pth"), ("my model.pth", "my%20model.pth"), ("a%b", "a%25b")],+ )+ def test_a_reserved_character_is_percent_encoded(self, filename, tail) -> None:+ assert hf_url("r", filename) == f"https://huggingface.co/kornia/r/resolve/main/{tail}"++ def test_a_subdirectory_keeps_its_slashes(self) -> None:+ assert hf_url("loftr", "weights/outdoor.ckpt") == (+ "https://huggingface.co/kornia/loftr/resolve/main/weights/outdoor.ckpt"+ )++ def test_the_repo_id_is_encoded_too(self) -> None:+ assert hf_url("owner/my repo", "f.pth") == "https://huggingface.co/owner/my%20repo/resolve/main/f.pth"++ def test_download_hf_file_fetches_the_file_it_names(self, scripted_server, monkeypatch, tmp_path) -> None:+ """Unescaped, ``#b.pth`` was a fragment: the file ``a`` was fetched and cached as ``a#b.pth``."""+ files, url, hits = scripted_server+ files["/kornia/r/resolve/main/a%23b.pth"] = b"the file a#b.pth"+ files["/kornia/r/resolve/main/a"] = b"the file a"+ monkeypatch.setattr(download_mod, "_HF_BASE", url(""))++ path = download_hf_file("r", "a#b.pth", model_dir=str(tmp_path / "cache"), progress=False)++ assert Path(path).name == "kornia--r--a#b.pth"+ assert Path(path).read_bytes() == b"the file a#b.pth"+ assert hits == {"/kornia/r/resolve/main/a%23b.pth": 1}+++class TestWarningAttribution:+ """A warning names the caller's line through every public entry point (#5219)."""++ @pytest.mark.parametrize("entry", ["load_state_dict_from_url", "download_file_from_url", "download_hf_file"])+ def test_a_retry_warning_points_at_the_caller(self, scripted_server, monkeypatch, tmp_path, entry) -> None:+ responses, url, _ = scripted_server+ body = _checkpoint_bytes({"w": torch.zeros(1)})+ responses["/flaky/w.pth"] = [503, body]+ responses["/kornia/flaky/resolve/main/w.pth"] = [503, body]+ monkeypatch.setattr(download_mod, "time", _FakeTime())+ monkeypatch.setattr(download_mod, "_HF_BASE", url(""))+ cache = str(tmp_path / "cache")+ calls = {+ "load_state_dict_from_url": lambda: load_state_dict_from_url(+ url("/flaky/w.pth"), model_dir=cache, progress=False+ ),+ "download_file_from_url": lambda: download_file_from_url(+ url("/flaky/w.pth"), model_dir=cache, progress=False+ ),+ "download_hf_file": lambda: download_hf_file("flaky", "w.pth", model_dir=cache, progress=False),+ }++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ calls[entry]()++ retries = [w for w in caught if "Transient failure" in str(w.message)]+ assert len(retries) == 1+ assert Path(retries[0].filename).resolve() == Path(__file__).resolve(), retries[0].filename+++class TestKeywordArguments:+ """A keyword torch does not accept is a caller error, not a corrupt cache entry (#5219)."""++ def test_a_mistyped_keyword_on_a_warm_cache_raises_at_once(self, scripted_server, tmp_path) -> None:+ """It used to quarantine the entry, download it again and raise ``RuntimeError``."""+ files, url, hits = scripted_server+ body = _checkpoint_bytes({"w": torch.zeros(2)})+ files["/w.pth"] = body+ cache = tmp_path / "cache"+ load_state_dict_from_url(url("/w.pth"), model_dir=str(cache), progress=False)+ assert hits["/w.pth"] == 1++ with pytest.raises(TypeError, match="map_locaton"):+ load_state_dict_from_url(url("/w.pth"), model_dir=str(cache), progress=False, map_locaton="cpu")++ assert hits["/w.pth"] == 1, "the checkpoint was downloaded again"+ assert [p.name for p in cache.iterdir()] == ["w.pth"]+ assert (cache / "w.pth").read_bytes() == body++ def test_a_mistyped_keyword_on_a_cold_cache_makes_no_request(self, scripted_server, tmp_path) -> None:+ files, url, hits = scripted_server+ files["/w.pth"] = _checkpoint_bytes({"w": torch.zeros(2)})++ with pytest.raises(TypeError, match="map_locaton"):+ load_state_dict_from_url(url("/w.pth"), model_dir=str(tmp_path / "cache"), map_locaton="cpu")++ assert sum(hits.values()) == 0+ assert not (tmp_path / "cache").exists()++ def test_every_keyword_torch_accepts_is_still_forwarded(self, scripted_server, tmp_path) -> None:+ files, url, _ = scripted_server+ files["/w.pth"] = _checkpoint_bytes({"w": torch.zeros(2)})++ result = load_state_dict_from_url(+ url("/w.pth"),+ model_dir=str(tmp_path / "cache"),+ map_location="cpu",+ progress=False,+ check_hash=False,+ file_name="w.pth",+ weights_only=True,+ )++ assert torch.equal(result["w"], torch.zeros(2))+++class TestModelDirExpandsUser:+ """``model_dir="~/..."`` means the home directory, as it does everywhere else (#5219)."""++ @pytest.fixture+ def home(self, monkeypatch, tmp_path):+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("HOME", str(home))+ monkeypatch.setenv("USERPROFILE", str(home))+ cwd = tmp_path / "cwd"+ cwd.mkdir()+ monkeypatch.chdir(cwd)+ # ``~`` must resolve inside the temporary directory before anything is fetched. Compared as paths: on+ # Windows ``expanduser("~/kc")`` keeps the ``/`` and gives ``...\home/kc``, the same directory.+ assert Path(os.path.expanduser("~/kc")) == home / "kc"+ return home, cwd++ def test_download_file_from_url(self, scripted_server, home) -> None:+ home_dir, cwd = home+ files, url, _ = scripted_server+ files["/t.bin"] = b"payload"++ path = download_file_from_url(url("/t.bin"), model_dir="~/kc", progress=False)++ assert Path(path) == home_dir / "kc" / "t.bin"+ assert Path(path).read_bytes() == b"payload"+ assert list(cwd.iterdir()) == [], "a literal '~' directory was created"++ def test_load_state_dict_from_url(self, scripted_server, home) -> None:+ home_dir, cwd = home+ files, url, _ = scripted_server+ files["/w.pth"] = _checkpoint_bytes({"w": torch.ones(2)})++ result = load_state_dict_from_url(url("/w.pth"), model_dir="~/kc", progress=False)++ assert torch.equal(result["w"], torch.ones(2))+ assert (home_dir / "kc" / "w.pth").is_file()+ assert list(cwd.iterdir()) == [], "a literal '~' directory was created"+++class TestKorniaTransfer:+ """``_download_url_to_file`` stands in for ``torch.hub.download_url_to_file``; it keeps torch's contract."""++ def test_check_hash_accepts_the_right_prefix_and_rejects_a_wrong_one(self, scripted_server, tmp_path) -> None:+ responses, url, _ = scripted_server+ body = _checkpoint_bytes({"w": torch.ones(3)})+ prefix = hashlib.sha256(body).hexdigest()[:8]+ responses[f"/w-{prefix}.pth"] = body+ responses["/w-deadbeef.pth"] = body+ cache = tmp_path / "cache"++ result = load_state_dict_from_url(+ url(f"/w-{prefix}.pth"), model_dir=str(cache), progress=False, check_hash=True+ )+ assert torch.equal(result["w"], torch.ones(3))++ with pytest.raises(RuntimeError, match="invalid hash value") as excinfo:+ load_state_dict_from_url(url("/w-deadbeef.pth"), model_dir=str(cache), progress=False, check_hash=True)+ assert f'got "{prefix}' in str(excinfo.value)+ # Nothing of the rejected transfer is kept, under its name or a temporary one.+ assert [p.name for p in cache.iterdir()] == [f"w-{prefix}.pth"]++ def test_the_progress_bar_stays_off_stdout(self, scripted_server, tmp_path, capsys) -> None:+ responses, url, _ = scripted_server+ responses["/t.bin"] = b"x" * 300_000++ path = download_file_from_url(url("/t.bin"), model_dir=str(tmp_path / "cache"), progress=True)++ assert Path(path).read_bytes() == b"x" * 300_000+ captured = capsys.readouterr()+ assert captured.out == ""+ assert 'Downloading: "' in captured.err++ def test_an_existing_file_is_replaced_only_by_a_complete_transfer(self, scripted_server, tmp_path) -> None:+ """The transfer writes beside the destination and swaps it in only once complete."""+ responses, url, _ = scripted_server+ responses["/t.bin"] = 503+ dst = tmp_path / "t.bin"+ dst.write_bytes(b"previous")++ with pytest.raises(HTTPError):+ download_mod._download_url_to_file(url("/t.bin"), str(dst), progress=False, timeout=5.0)+ assert dst.read_bytes() == b"previous"+ assert [p.name for p in tmp_path.iterdir()] == ["t.bin"]++ responses["/t.bin"] = b"complete"+ download_mod._download_url_to_file(url("/t.bin"), str(dst), progress=False, timeout=5.0)+ assert dst.read_bytes() == b"complete"+ assert [p.name for p in tmp_path.iterdir()] == ["t.bin"]+++class TestTruncatedTransfer:+ """A body shorter than its ``Content-Length`` is a failed transfer, not a file (#5216).++ urllib ends a ``read(n)`` loop on the early close without an error, so a server that+ announced 1577 bytes and sent 50 left a 50-byte file in the cache, which every later+ call returned as a hit.+ """++ @pytest.fixture(autouse=True)+ def _no_backoff(self, monkeypatch, hub_dir_in_tmp):+ monkeypatch.setattr(download_mod, "time", _FakeTime())++ def test_a_short_body_is_retried_and_never_cached(self, scripted_server, tmp_path) -> None:+ responses, url, hits = scripted_server+ body = _checkpoint_bytes({"w": torch.ones(4)})+ responses["/t.bin"] = (len(body), body[:50])+ cache = tmp_path / "cache"++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError) as excinfo:+ download_file_from_url(url("/t.bin"), model_dir=str(cache), progress=False)++ assert isinstance(excinfo.value.__cause__, http.client.IncompleteRead)+ message = str(excinfo.value)+ assert f"Last error: transfer truncated: the server sent 50 of the {len(body)} bytes" in message+ assert "_TruncatedTransfer" not in message+ assert hits["/t.bin"] == download_mod._MAX_ATTEMPTS # retried as the transient failure it is+ assert not cache.exists() or list(cache.iterdir()) == []++ @pytest.mark.parametrize("entry", ["load_state_dict_from_url", "download_file_from_url"])+ def test_a_short_primary_hands_over_to_the_mirror(self, scripted_server, tmp_path, entry) -> None:+ responses, url, _ = scripted_server+ body = _checkpoint_bytes({"w": torch.ones(4)})+ responses["/primary/w.pth"] = (len(body), body[:50])+ responses["/mirror/w.pth"] = body+ cache = tmp_path / "cache"+ fn = {"load_state_dict_from_url": load_state_dict_from_url, "download_file_from_url": download_file_from_url}++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ fn[entry]([url("/primary/w.pth"), url("/mirror/w.pth")], model_dir=str(cache), progress=False)++ assert [p.name for p in cache.iterdir()] == ["w.pth"]+ assert (cache / "w.pth").read_bytes() == body++ def test_a_retry_after_a_short_body_completes_the_file(self, scripted_server, tmp_path) -> None:+ responses, url, hits = scripted_server+ body = b"y" * 5000+ responses["/t.bin"] = [(len(body), body[:50]), body]++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ path = download_file_from_url(url("/t.bin"), model_dir=str(tmp_path / "cache"), progress=False)++ assert Path(path).read_bytes() == body+ assert hits["/t.bin"] == 2++ def test_a_short_body_leaves_an_existing_destination_untouched(self, scripted_server, tmp_path) -> None:+ responses, url, _ = scripted_server+ responses["/t.bin"] = (1000, b"z" * 10)+ dst = tmp_path / "t.bin"+ dst.write_bytes(b"previous")++ with pytest.raises(http.client.IncompleteRead):+ download_mod._download_url_to_file(url("/t.bin"), str(dst), progress=False, timeout=5.0)++ assert dst.read_bytes() == b"previous"+ assert [p.name for p in tmp_path.iterdir()] == ["t.bin"]+++class TestCacheNameEdgeCases:+ """Review follow-ups on the cache-name checks (#5217, #5219)."""++ @pytest.mark.parametrize("entry", list(_ENTRY_POINTS))+ def test_a_drive_relative_url_name_is_rejected_under_windows_path_rules(+ self, monkeypatch, hub_dir_in_tmp, entry+ ) -> None:+ """``d:x.pth`` is one segment of a URL path, but a drive-relative path to ``ntpath.join``."""+ monkeypatch.setattr(download_mod, "time", _FakeTime())+ monkeypatch.setattr(download_mod.os.path, "basename", ntpath.basename)+ # A closed local port: if the name were accepted, the call would fail on the transfer instead.+ with pytest.raises(ValueError, match="file_name="):+ _ENTRY_POINTS[entry]("http://127.0.0.1:9/d:x.pth", progress=False)++ @pytest.mark.parametrize("entry", list(_ENTRY_POINTS))+ def test_a_path_file_name_is_accepted(self, scripted_server, tmp_path, entry) -> None:+ """``file_name=Path("w.pth")`` worked before the check existed; it is a bare name."""+ responses, url, _ = scripted_server+ body = _checkpoint_bytes({"w": torch.ones(2)})+ responses["/other.pth"] = body+ cache = tmp_path / "cache"++ _ENTRY_POINTS[entry](url("/other.pth"), model_dir=str(cache), progress=False, file_name=Path("w.pth"))++ assert [p.name for p in cache.iterdir()] == ["w.pth"]+ assert (cache / "w.pth").read_bytes() == body+++class TestTruncatedTransferFraming:+ """The short-read check follows the framing http.client used, and the error travels (#5216 review)."""++ @pytest.fixture(autouse=True)+ def _no_backoff(self, monkeypatch, hub_dir_in_tmp):+ monkeypatch.setattr(download_mod, "time", _FakeTime())++ @pytest.mark.parametrize(+ "response",+ [(None, b"q" * 5000), _Chunked(b"q" * 5000), _Chunked(b"q" * 5000, content_length=10), (-5, b"q" * 5000)],+ ids=["close_delimited", "chunked", "chunked_with_a_mismatched_content_length", "negative_content_length"],+ )+ def test_a_body_not_framed_by_content_length_downloads_completely(self, scripted_server, tmp_path, response):+ """Without a valid ``Content-Length`` framing the body there is nothing to count against, as in torch."""+ responses, url, hits = scripted_server+ responses["/t.bin"] = response++ path = download_file_from_url(url("/t.bin"), model_dir=str(tmp_path / "cache"), progress=False)++ assert Path(path).read_bytes() == b"q" * 5000+ assert hits["/t.bin"] == 1++ def test_the_truncation_error_pickles_and_copies(self) -> None:+ error = download_mod._TruncatedTransfer(50, 1577)+ for clone in (pickle.loads(pickle.dumps(error)), copy.copy(error)): # noqa: S301 - our own bytes+ assert isinstance(clone, http.client.IncompleteRead)+ assert str(clone) == str(error)+ assert (clone.received, clone.announced) == (50, 1577)+ assert str(error) == "transfer truncated: the server sent 50 of the 1577 bytes its Content-Length announced"+++class TestDownloadTimeoutEnvironment:+ """``KORNIA_DOWNLOAD_TIMEOUT`` sets the default for calls that pass no ``timeout=`` (ruling C14).++ Pretrained model constructors take no ``timeout=``, so the variable is how their users+ raise the bound on a slow link.+ """++ @pytest.fixture(autouse=True)+ def _no_backoff(self, monkeypatch, hub_dir_in_tmp):+ monkeypatch.setattr(download_mod, "time", _FakeTime())++ @pytest.fixture(autouse=True)+ def _no_proxy(self, monkeypatch):+ """Three tests below build a ``_StalledServer`` without the ``stalled_server`` fixture and its proxy scrub."""+ _bypass_proxies(monkeypatch)++ @pytest.mark.parametrize("entry", list(_ENTRY_POINTS))+ def test_the_variable_bounds_a_call_without_timeout(self, monkeypatch, tmp_path, entry) -> None:+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", "0.25")+ server = _StalledServer("silent")+ try:+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ outcome = _outcome_within(+ lambda: _ENTRY_POINTS[entry](server.url("/w.pth"), model_dir=str(tmp_path / "c"), progress=False),+ 10.0,+ )+ finally:+ server.close()++ assert isinstance(outcome, RuntimeError), f"expected the documented RuntimeError, got {outcome!r}"+ assert isinstance(outcome.__cause__, TimeoutError)+ assert "0.25 s" in str(outcome)++ def test_an_explicit_timeout_wins_over_the_variable(self, monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", "600")+ server = _StalledServer("silent")+ try:+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ outcome = _outcome_within(+ lambda: download_file_from_url(+ server.url("/w.pth"), model_dir=str(tmp_path / "c"), progress=False, timeout=0.25+ ),+ 10.0,+ )+ finally:+ server.close()++ assert isinstance(outcome, RuntimeError) and isinstance(outcome.__cause__, TimeoutError)+ assert "0.25 s" in str(outcome)++ def test_an_explicit_timeout_does_not_read_the_variable(self, scripted_server, monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", "abc")+ responses, url, _ = scripted_server+ responses["/t.bin"] = b"payload"++ path = download_file_from_url(url("/t.bin"), model_dir=str(tmp_path / "c"), progress=False, timeout=5.0)++ assert Path(path).read_bytes() == b"payload"++ @pytest.mark.parametrize(+ "value",+ ["0", "-1", "abc", "inf", "nan", "1e300", pytest.param(str(threading.TIMEOUT_MAX * 2), id="twice_TIMEOUT_MAX")],+ )+ @pytest.mark.parametrize("entry", list(_ENTRY_POINTS))+ def test_an_invalid_value_is_named_before_any_request(self, scripted_server, monkeypatch, tmp_path, value, entry):+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", value)+ responses, url, hits = scripted_server+ responses["/t.bin"] = b"payload"++ with pytest.raises(ValueError, match="KORNIA_DOWNLOAD_TIMEOUT"):+ _ENTRY_POINTS[entry](url("/t.bin"), model_dir=str(tmp_path / "c"), progress=False)++ assert sum(hits.values()) == 0+ assert not (tmp_path / "c").exists()++ @pytest.mark.parametrize("value", [None, "", " "], ids=["unset", "empty", "blank"])+ def test_unset_gives_the_default(self, monkeypatch, value) -> None:+ if value is None:+ monkeypatch.delenv("KORNIA_DOWNLOAD_TIMEOUT", raising=False)+ else:+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", value)++ assert download_mod._resolve_timeout(None) == download_mod._DOWNLOAD_TIMEOUT_SECONDS == 30.0++ def test_a_valid_value_is_read_at_call_time(self, monkeypatch) -> None:+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", " 12.5 ")+ assert download_mod._resolve_timeout(None) == 12.5+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", "3")+ assert download_mod._resolve_timeout(None) == 3.0++ def test_the_stdlib_ceiling_itself_is_accepted(self, monkeypatch) -> None:+ """``threading.TIMEOUT_MAX`` is the largest blocking timeout the stdlib takes; validation lets it through."""+ assert download_mod._resolve_timeout(threading.TIMEOUT_MAX) == threading.TIMEOUT_MAX+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", repr(threading.TIMEOUT_MAX))+ assert download_mod._resolve_timeout(None) == threading.TIMEOUT_MAX++ def test_the_message_states_the_bound_exactly(self, monkeypatch) -> None:+ """``:g`` printed 9223372036.0 as 9.22337e+09, and Windows' 4294967.0 as 4.29497e+06, above the bound."""+ bound = f"at most {threading.TIMEOUT_MAX!r} (threading.TIMEOUT_MAX)"+ with pytest.raises(ValueError, match="timeout") as caught:+ download_mod._resolve_timeout(threading.TIMEOUT_MAX * 2)+ assert bound in str(caught.value)+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", "1e300")+ with pytest.raises(ValueError, match="KORNIA_DOWNLOAD_TIMEOUT") as caught:+ download_mod._resolve_timeout(None)+ assert bound in str(caught.value)++ @pytest.mark.parametrize("entry", list(_ENTRY_POINTS))+ def test_a_warm_cache_call_still_checks_the_variable(self, scripted_server, monkeypatch, tmp_path, entry) -> None:+ """The variable is checked when the function is called, before the cache; ``timeout=`` skips it."""+ responses, url, hits = scripted_server+ body = _checkpoint_bytes({"w": torch.ones(2)})+ responses["/w.pth"] = body+ cache = str(tmp_path / "c")+ _ENTRY_POINTS[entry](url("/w.pth"), model_dir=cache, progress=False)+ assert hits["/w.pth"] == 1++ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", "abc")+ with pytest.raises(ValueError, match="KORNIA_DOWNLOAD_TIMEOUT"):+ _ENTRY_POINTS[entry](url("/w.pth"), model_dir=cache, progress=False)+ _ENTRY_POINTS[entry](url("/w.pth"), model_dir=cache, progress=False, timeout=5)++ assert hits["/w.pth"] == 1, "the cached file was fetched again"+ assert (tmp_path / "c" / "w.pth").read_bytes() == bodydiff --git a/tests/test_doctest_downloads.py b/tests/test_doctest_downloads.pyindex 5cbc16d64..4b3a2947c 100644--- a/tests/test_doctest_downloads.py+++ b/tests/test_doctest_downloads.py@@ -127,6 +127,23 @@ class TestPrimitivesStillExist:assert seen == ["http://example.com/model.onnx"]+ def test_guard_covers_kornia_core_downloader(self, monkeypatch, tmp_path) -> None:+ # kornia.core.download runs its own transfer rather than torch.hub's, so+ # patching torch.hub alone would leave every pretrained model downloading.+ # The URL points at a closed local port, so even an unguarded call stays on the host.+ from kornia.core.download import download_file_from_url, load_state_dict_from_url++ url = "http://127.0.0.1:9/w.pth"+ seen: list[str] = []+ with monkeypatch.context() as m:+ install_download_guard(m.setattr, _record_and_raise(seen))+ for fn in (load_state_dict_from_url, download_file_from_url):+ with pytest.raises(RuntimeError) as excinfo:+ fn(url, model_dir=str(tmp_path / "cache"), progress=False)+ assert isinstance(excinfo.value.__cause__, _Blocked)++ assert seen == [url, url]+def test_guard_covers_onnx_cached_downloader(self, monkeypatch, tmp_path) -> None:from kornia.onnx.download import CachedDownloader