Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(onnx): honor configured download timeout (#5389)

Karnajeet Gosavib13cd9829d7a
diff --git a/changelog.d/5389.fixed.md b/changelog.d/5389.fixed.md
new file mode 100644
index 000000000..387eba295
--- /dev/null
+++ b/changelog.d/5389.fixed.md
@@ -0,0 +1 @@
+`kornia.onnx.download.CachedDownloader`, which `ONNXLoader`, `kornia.models.small_sr` and `kornia.contrib.super_resolution` download through, now uses `kornia.core.download`'s transfer: a server that stalls fails with `TimeoutError` after `KORNIA_DOWNLOAD_TIMEOUT` seconds (30 s when it is unset) instead of blocking forever, and a leading `~` in the cache directory or file path is expanded instead of creating a literal `~` directory.
diff --git a/kornia/onnx/download.py b/kornia/onnx/download.py
index e6f1a191e..7f379d7dc 100644
--- a/kornia/onnx/download.py
+++ b/kornia/onnx/download.py
@@ -19,12 +19,11 @@ from __future__ import annotations
import logging
import os
-import urllib.request
-import uuid
-from contextlib import suppress
+import urllib.error
from typing import Any, Optional
from kornia.config import kornia_config
+from kornia.core import download as _core_download
__all__ = ["CachedDownloader"]
@@ -51,6 +50,7 @@ class CachedDownloader:
# Determine the local file path
if cache_dir is None:
cache_dir = kornia_config.hub_cache_dir
+ cache_dir = os.path.expanduser(cache_dir)
# The filename is the model name (without directory path)
if suffix is not None and not model_name.endswith(suffix):
@@ -82,6 +82,7 @@ class CachedDownloader:
Raises:
ValueError: If ``url`` is not an HTTP or HTTPS URL, if download is
disabled and the file is missing, or if the server answers with an HTTP error.
+ TimeoutError: If the server goes ``KORNIA_DOWNLOAD_TIMEOUT`` seconds without answering (see ``download``).
urllib.error.URLError: If the server cannot be reached, or ``urllib.error.ContentTooShortError``
if the body is shorter than its ``Content-Length`` (see ``download``).
"""
@@ -109,12 +110,16 @@ class CachedDownloader:
Raises:
ValueError: If the file is missing and ``download_if_not_exists`` is ``False``, if ``url`` is not an
- HTTP or HTTPS URL, or if the server answers with an HTTP error.
+ HTTP or HTTPS URL, if the server answers with an HTTP error, or if ``KORNIA_DOWNLOAD_TIMEOUT`` is
+ set to anything but a positive number of seconds.
+ TimeoutError: If the server goes ``KORNIA_DOWNLOAD_TIMEOUT`` seconds (30 s when it is unset) without
+ answering. Nothing is left at ``file_path``.
urllib.error.ContentTooShortError: If the body is shorter than its ``Content-Length``. Nothing is
left at ``file_path``, so the next call downloads again.
urllib.error.URLError: If the server cannot be reached.
"""
+ file_path = os.path.expanduser(file_path)
if os.path.exists(file_path):
_logger.info(f"Loading `{url}` from `{file_path}`.")
return
@@ -122,22 +127,19 @@ class CachedDownloader:
if not download_if_not_exists:
raise ValueError(f"`{file_path}` not found. You may set `download=True`.")
- os.makedirs(os.path.dirname(file_path), exist_ok=True) # Create the cache directory if it doesn't exist
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
if url.startswith(("http:", "https:")):
- # Keep incomplete transfers out of the cache, including while another caller is checking it: write
- # beside the destination and publish with os.replace. Let urlretrieve create the file, so it gets the
- # permissions of any new file (umask applied); a tempfile would be 0o600 and lock other users out of a
- # shared cache.
- temporary_path = f"{file_path}.{uuid.uuid4().hex}.partial"
try:
_logger.info(f"Downloading `{url}` to `{file_path}`.")
- urllib.request.urlretrieve(url, temporary_path) # noqa: S310
- os.replace(temporary_path, file_path)
- except urllib.error.HTTPError as e:
- raise ValueError(f"Error in resolving `{url}`.") from e
- finally:
- with suppress(FileNotFoundError):
- os.remove(temporary_path)
+ _core_download._download_url_to_file(url, file_path, progress=False)
+ except urllib.error.HTTPError as exc:
+ raise ValueError(f"Error in resolving `{url}`.") from exc
+ except _core_download._TruncatedTransfer as exc:
+ # urlretrieve's type and message for a body shorter than its Content-Length; any other
+ # IncompleteRead (a chunked body cut mid-chunk) propagates unchanged, as it did from urlretrieve
+ raise urllib.error.ContentTooShortError(
+ f"retrieval incomplete: got only {exc.received} out of {exc.announced} bytes", b""
+ ) from exc
else:
raise ValueError("URL must start with 'http:' or 'https:'")
diff --git a/testing/doctest_downloads.py b/testing/doctest_downloads.py
index f2b63d3ee..ac236bce9 100644
--- a/testing/doctest_downloads.py
+++ b/testing/doctest_downloads.py
@@ -42,11 +42,10 @@ DOWNLOAD_ENV_VAR = "KORNIA_DOCTEST_DOWNLOAD"
# ``(module, attribute)`` pairs resolved lazily at patch time.
_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.
+ # load_state_dict_from_url / download_file_from_url cache miss reaches the network here,
+ # and so do download_onnx_from_url and kornia.onnx's CachedDownloader, which call it.
("kornia.core.download", "_download_url_to_file"),
("torch.hub", "download_url_to_file"),
- # kornia.onnx.download.CachedDownloader.download reaches the network here.
- ("urllib.request", "urlretrieve"),
)
diff --git a/tests/onnx/test_download.py b/tests/onnx/test_download.py
index 8752179d5..f32a6b9ff 100644
--- a/tests/onnx/test_download.py
+++ b/tests/onnx/test_download.py
@@ -17,6 +17,7 @@
from __future__ import annotations
+import http.client
import http.server
import os
import sys
@@ -86,6 +87,35 @@ class TestCachedDownloader:
assert (tmp_path / "cache" / "operators" / "model.pth").read_bytes() == b"weights"
assert hits == ["/model"]
+ def test_download_expands_user_directory(self, download_server, monkeypatch, tmp_path):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ monkeypatch.chdir(tmp_path) # without the expansion, a literal "~" directory lands in the working directory
+ responses, base_url, _ = download_server
+ responses["/model"] = (b"weights", 7)
+
+ path = CachedDownloader.download_to_cache(f"{base_url}/model", "model", cache_dir="~/cache", suffix=".onnx")
+
+ assert Path(path) == tmp_path / "cache" / "model.onnx"
+ assert Path(path).read_bytes() == b"weights"
+
+ def test_download_expands_user_file_path(self, download_server, monkeypatch, tmp_path):
+ # the cache check and the directory creation must see the expanded path, or every call downloads again
+ # and a literal "~" directory appears in the working directory
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ (tmp_path / "cwd").mkdir()
+ monkeypatch.chdir(tmp_path / "cwd")
+ responses, base_url, hits = download_server
+ responses["/model"] = (b"weights", 7)
+
+ for _ in range(2):
+ CachedDownloader.download(f"{base_url}/model", "~/cache/model.onnx")
+
+ assert (tmp_path / "cache" / "model.onnx").read_bytes() == b"weights"
+ assert hits == ["/model"]
+ assert list((tmp_path / "cwd").iterdir()) == []
+
def test_short_transfer_is_not_cached(self, download_server, monkeypatch, tmp_path):
monkeypatch.chdir(tmp_path)
responses, base_url, hits = download_server
@@ -93,7 +123,7 @@ class TestCachedDownloader:
responses["/model"] = (payload[: len(payload) // 2], len(payload))
url = f"{base_url}/model"
- with pytest.raises(ContentTooShortError):
+ with pytest.raises(ContentTooShortError, match=r"got only 5120 out of 10240 bytes"):
CachedDownloader.download_to_cache(url, "model", cache_dir="cache", suffix=".pth")
assert list((tmp_path / "cache").iterdir()) == []
@@ -104,6 +134,71 @@ class TestCachedDownloader:
assert hits == ["/model", "/model"]
assert list((tmp_path / "cache").iterdir()) == [tmp_path / "cache" / "model.pth"]
+ def test_other_incomplete_read_propagates(self, tmp_path):
+ # only a body shorter than its Content-Length becomes ContentTooShortError; any other IncompleteRead (a
+ # chunked body cut mid-chunk) propagates unchanged, as it did from urlretrieve
+ path = tmp_path / "cache" / "model.onnx"
+ cut = http.client.IncompleteRead(b"")
+
+ with (
+ mock.patch("kornia.core.download._download_url_to_file", side_effect=cut),
+ pytest.raises(http.client.IncompleteRead) as exc_info,
+ ):
+ CachedDownloader.download("http://127.0.0.1:9/model.onnx", str(path))
+
+ assert exc_info.value is cut
+
+ def test_stalled_transfer_obeys_timeout_environment_variable(self, monkeypatch, tmp_path):
+ for var in ("http_proxy", "HTTP_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")
+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", "0.2")
+ stalled, release = threading.Event(), threading.Event()
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self) -> None:
+ self.send_response(200)
+ self.send_header("Content-Length", "100")
+ self.end_headers()
+ self.wfile.write(b"x" * 10)
+ self.wfile.flush()
+ stalled.set()
+ release.wait(5)
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ server_thread = threading.Thread(target=server.serve_forever, daemon=True)
+ server_thread.start()
+ path = tmp_path / "cache" / "model.onnx"
+ url = f"http://127.0.0.1:{server.server_port}/model.onnx"
+ errors: list[BaseException] = []
+
+ def download() -> None:
+ try:
+ CachedDownloader.download(url, str(path))
+ except BaseException as exc:
+ errors.append(exc)
+
+ worker = threading.Thread(target=download, daemon=True)
+ try:
+ worker.start()
+ assert stalled.wait(5), "the server did not start the transfer"
+ worker.join(5)
+ assert not worker.is_alive(), "download remained blocked past KORNIA_DOWNLOAD_TIMEOUT"
+ finally:
+ release.set()
+ worker.join(5)
+ server.shutdown()
+ server.server_close()
+ server_thread.join(5)
+
+ assert len(errors) == 1 and isinstance(errors[0], TimeoutError), errors
+ assert not path.exists()
+ assert not list(path.parent.glob("*.partial"))
+
def test_http_error_does_not_leave_cache_entry(self, download_server, tmp_path):
_, base_url, _ = download_server
path = tmp_path / "cache" / "missing.pth"
@@ -128,31 +223,29 @@ class TestCachedDownloader:
assert hits == []
def test_interrupted_transfer_leaves_no_file(self, tmp_path):
- # KeyboardInterrupt is a BaseException: the cleanup must not be an `except Exception`
+ # KeyboardInterrupt is a BaseException: the cleanup must not be an `except Exception`. The transfer's
+ # temporary file already exists when the request is opened, so interrupting there must remove it.
path = tmp_path / "cache" / "model.pth"
- def interrupted(url, filename):
- Path(filename).write_bytes(b"partial")
- raise KeyboardInterrupt
-
- with mock.patch("urllib.request.urlretrieve", side_effect=interrupted), pytest.raises(KeyboardInterrupt):
+ with (
+ mock.patch("kornia.core.download.urlopen", side_effect=KeyboardInterrupt),
+ pytest.raises(KeyboardInterrupt),
+ ):
CachedDownloader.download("http://127.0.0.1:9/model.pth", str(path))
assert list(path.parent.iterdir()) == []
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX permission bits")
- def test_cache_file_has_default_permissions(self, tmp_path):
+ def test_cache_file_has_default_permissions(self, download_server, tmp_path):
# a downloaded file gets the permissions of any new file (umask applied), not mkstemp's owner-only 0o600,
# so a cache filled by one user stays readable by another
+ responses, base_url, _ = download_server
+ responses["/model.pth"] = (b"weights", 7)
path = tmp_path / "cache" / "model.pth"
reference = tmp_path / "reference"
reference.write_bytes(b"")
- def write(url, filename):
- Path(filename).write_bytes(b"weights")
-
- with mock.patch("urllib.request.urlretrieve", side_effect=write):
- CachedDownloader.download("http://127.0.0.1:9/model.pth", str(path))
+ CachedDownloader.download(f"{base_url}/model.pth", str(path))
assert path.stat().st_mode == reference.stat().st_mode
@@ -188,7 +281,7 @@ class TestCachedDownloader:
worker.start()
assert half_sent.wait(10)
deadline = time.monotonic() + 10
- while not (path.parent.exists() and any(p.stat().st_size > 0 for p in path.parent.iterdir())):
+ while not (path.parent.exists() and any(p != path for p in path.parent.iterdir())):
assert time.monotonic() < deadline, "the transfer never started writing"
time.sleep(0.01)
assert not path.exists()
diff --git a/tests/onnx/test_utils.py b/tests/onnx/test_utils.py
index af1aa782f..abaef4788 100644
--- a/tests/onnx/test_utils.py
+++ b/tests/onnx/test_utils.py
@@ -103,22 +103,23 @@ class TestONNXLoader:
from unittest import mock
with mock.patch(
- "urllib.request.urlretrieve", side_effect=lambda url, path: Path(path).write_bytes(b"model")
- ) as mock_urlretrieve:
+ "kornia.core.download._download_url_to_file",
+ side_effect=lambda url, path, **kwargs: Path(path).write_bytes(b"model"),
+ ) as mock_download:
url = "https://huggingface.co/some_model.onnx"
file_path = tmp_path / "cache" / "some_model.onnx"
ONNXLoader.download(url, str(file_path))
- mock_urlretrieve.assert_called_once()
- assert mock_urlretrieve.call_args.args[0] == url
+ mock_download.assert_called_once()
+ assert mock_download.call_args.args[0] == url
assert file_path.read_bytes() == b"model"
def test_download_failure(self, tmp_path):
from unittest import mock
with mock.patch(
- "urllib.request.urlretrieve",
+ "kornia.core.download._download_url_to_file",
side_effect=urllib.error.HTTPError(url=None, code=404, msg="Not Found", hdrs=None, fp=None),
) as _:
url = "https://huggingface.co/non_existent_model.onnx"