Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Avoid incomplete files in CachedDownloader cache (#5272)

hoobnn2ae33162fa4f
diff --git a/changelog.d/5272.fixed.md b/changelog.d/5272.fixed.md
new file mode 100644
index 000000000..a16c7f6a2
--- /dev/null
+++ b/changelog.d/5272.fixed.md
@@ -0,0 +1 @@
+`kornia.onnx.download.CachedDownloader` keeps an absolute `cache_dir` absolute and caches only complete downloads, so a transfer that is cut short or interrupted is downloaded again on the next call. It used to store the file under a relative copy of the directory in the current working directory and to keep the partial file forever. A partial file already left in the cache by an earlier version is not detected: delete it once. A model cached under the misplaced relative directory is downloaded again once to the absolute one.
diff --git a/kornia/onnx/download.py b/kornia/onnx/download.py
index 357b42cae..80c57b40a 100644
--- a/kornia/onnx/download.py
+++ b/kornia/onnx/download.py
@@ -20,6 +20,8 @@ from __future__ import annotations
import logging
import os
import urllib.request
+import uuid
+from contextlib import suppress
from typing import Any, Optional
from kornia.config import kornia_config
@@ -56,7 +58,7 @@ class CachedDownloader:
else:
file_name = os.path.split(model_name)[-1]
- return os.path.join(*cache_dir.split(os.sep), *model_name.split(os.sep)[:-1], file_name)
+ return os.path.join(cache_dir, *model_name.split(os.sep)[:-1], file_name)
@classmethod
def download_to_cache(cls, url: str, name: str, download: bool = True, **kwargs: Any) -> str:
@@ -78,8 +80,10 @@ class CachedDownloader:
Local filesystem path to the cached file.
Raises:
- ValueError: If ``url`` is not an HTTP or HTTPS URL, or if download is
- disabled and the file is missing.
+ 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.
+ urllib.error.URLError: If the server cannot be reached, or ``urllib.error.ContentTooShortError``
+ if the body is shorter than its ``Content-Length`` (see ``download``).
"""
if url.startswith(("http:", "https:")):
cache_dir = kwargs.get("cache_dir", None)
@@ -103,6 +107,13 @@ class CachedDownloader:
file_path: The local path where the downloaded model should be saved.
download_if_not_exists: If True, the file will be downloaded if it's not already downloaded.
+ 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.
+ 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.
+
"""
if os.path.exists(file_path):
_logger.info(f"Loading `{url}` from `{file_path}`.")
@@ -114,10 +125,19 @@ class CachedDownloader:
os.makedirs(os.path.dirname(file_path), exist_ok=True) # Create the cache directory if it doesn't exist
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, file_path) # noqa: S310
+ 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)
else:
raise ValueError("URL must start with 'http:' or 'https:'")
diff --git a/tests/onnx/test_download.py b/tests/onnx/test_download.py
new file mode 100644
index 000000000..4ff21c99c
--- /dev/null
+++ b/tests/onnx/test_download.py
@@ -0,0 +1,201 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import http.server
+import os
+import sys
+import threading
+import time
+from pathlib import Path
+from unittest import mock
+from urllib.error import ContentTooShortError, HTTPError
+
+import pytest
+
+from kornia.onnx.download import CachedDownloader
+
+pytestmark = pytest.mark.device_agnostic
+
+
+def download_server(monkeypatch):
+ """Serve bytes with a controllable Content-Length to exercise short transfers."""
+ 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")
+ responses: dict[str, tuple[bytes, int]] = {}
+ hits: list[str] = []
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self) -> None:
+ hits.append(self.path)
+ if self.path not in responses:
+ self.send_error(404)
+ return
+ body, length = responses[self.path]
+ self.send_response(200)
+ self.send_header("Content-Length", str(length))
+ self.send_header("Connection", "close")
+ self.end_headers()
+ self.wfile.write(body)
+
+ 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, daemon=True)
+ thread.start()
+ try:
+ yield responses, f"http://127.0.0.1:{server.server_port}", hits
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+
+class TestCachedDownloader:
+ @pytest.mark.parametrize("absolute", [False, True])
+ def test_download_preserves_cache_directory(self, download_server, monkeypatch, tmp_path, absolute):
+ monkeypatch.chdir(tmp_path)
+ responses, base_url, hits = download_server
+ responses["/model"] = (b"weights", 7)
+ cache_dir = str(tmp_path / "cache") if absolute else "cache"
+
+ path = CachedDownloader.download_to_cache(
+ f"{base_url}/model", os.path.join("operators", "model"), cache_dir=cache_dir, suffix=".pth"
+ )
+
+ assert path == os.path.join(cache_dir, "operators", "model.pth")
+ assert (tmp_path / "cache" / "operators" / "model.pth").read_bytes() == b"weights"
+ assert hits == ["/model"]
+
+ def test_short_transfer_is_not_cached(self, download_server, monkeypatch, tmp_path):
+ monkeypatch.chdir(tmp_path)
+ responses, base_url, hits = download_server
+ payload = bytes(range(256)) * 40
+ responses["/model"] = (payload[: len(payload) // 2], len(payload))
+ url = f"{base_url}/model"
+
+ with pytest.raises(ContentTooShortError):
+ CachedDownloader.download_to_cache(url, "model", cache_dir="cache", suffix=".pth")
+
+ assert list((tmp_path / "cache").iterdir()) == []
+ responses["/model"] = (payload, len(payload))
+ path = CachedDownloader.download_to_cache(url, "model", cache_dir="cache", suffix=".pth")
+ assert Path(path).read_bytes() == payload
+ assert CachedDownloader.download_to_cache(url, "model", cache_dir="cache", suffix=".pth") == path
+ assert hits == ["/model", "/model"]
+ assert list((tmp_path / "cache").iterdir()) == [tmp_path / "cache" / "model.pth"]
+
+ def test_http_error_does_not_leave_cache_entry(self, download_server, tmp_path):
+ _, base_url, _ = download_server
+ path = tmp_path / "cache" / "missing.pth"
+ with pytest.raises(ValueError, match="Error in resolving") as exc:
+ CachedDownloader.download(f"{base_url}/missing", str(path))
+ assert isinstance(exc.value.__cause__, HTTPError)
+ assert list(path.parent.iterdir()) == []
+
+ def test_download_disabled(self, download_server, tmp_path):
+ _, base_url, hits = download_server
+ with pytest.raises(ValueError, match="not found"):
+ CachedDownloader.download(f"{base_url}/model", str(tmp_path / "missing.pth"), False)
+ assert hits == []
+
+ @pytest.mark.parametrize("download", [False, True])
+ def test_existing_cache_entry_is_preserved(self, download_server, tmp_path, download):
+ _, base_url, hits = download_server
+ path = tmp_path / "model.pth"
+ path.write_bytes(b"cached weights")
+ CachedDownloader.download(f"{base_url}/missing", str(path), download)
+ assert path.read_bytes() == b"cached weights"
+ assert hits == []
+
+ def test_interrupted_transfer_leaves_no_file(self, tmp_path):
+ # KeyboardInterrupt is a BaseException: the cleanup must not be an `except Exception`
+ 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):
+ with 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):
+ # 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
+ 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))
+
+ assert path.stat().st_mode == reference.stat().st_mode
+
+ def test_partial_transfer_is_not_visible_at_cache_path(self, monkeypatch, tmp_path):
+ # a second caller checking the cache mid-transfer must not find (and return) a half-written file
+ 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")
+ payload = bytes(range(256)) * 400
+ half_sent, release = threading.Event(), threading.Event()
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self) -> None:
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload[: len(payload) // 2])
+ self.wfile.flush()
+ half_sent.set()
+ release.wait(10)
+ self.wfile.write(payload[len(payload) // 2 :])
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ path = tmp_path / "cache" / "model.pth"
+ url = f"http://127.0.0.1:{server.server_port}/model.pth"
+ worker = threading.Thread(target=CachedDownloader.download, args=(url, str(path)))
+ try:
+ 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())):
+ assert time.monotonic() < deadline, "the transfer never started writing"
+ time.sleep(0.01)
+ assert not path.exists()
+ finally:
+ release.set()
+ worker.join(10)
+ server.shutdown()
+ server.server_close()
+ assert path.read_bytes() == payload
diff --git a/tests/onnx/test_utils.py b/tests/onnx/test_utils.py
index 692cf2680..4f82e8940 100644
--- a/tests/onnx/test_utils.py
+++ b/tests/onnx/test_utils.py
@@ -17,6 +17,7 @@
import os
import urllib
+from pathlib import Path
import pytest
@@ -52,50 +53,68 @@ class TestONNXLoader:
assert model == mock_model
mock_onnx_load.assert_called_once_with(model_name)
- def test_load_model_download(self):
+ def test_load_model_download(self, tmp_path):
from unittest import mock
from onnx import ModelProto
with (
- mock.patch("urllib.request.urlretrieve") as mock_urlretrieve,
- mock.patch("os.path.exists") as mock_exists,
+ mock.patch.object(ONNXLoader, "download") as mock_download,
mock.patch("onnx.load") as mock_onnx_load,
):
model_name = "hf://operators/some_model"
- mock_exists.return_value = False
- mock_urlretrieve.return_value = None # Simulating successful download
-
mock_model = mock.Mock(spec=ModelProto)
mock_onnx_load.return_value = mock_model
- model = ONNXLoader.load_model(model_name)
+ model = ONNXLoader.load_model(model_name, cache_dir=str(tmp_path))
assert model == mock_model
- mock_urlretrieve.assert_called_once_with(
+ mock_download.assert_called_once_with(
"https://huggingface.co/kornia/ONNX_models/resolve/main/operators/some_model.onnx",
- os.path.join(".kornia_hub", "onnx_models", "operators", "some_model.onnx"),
+ str(tmp_path / "some_model.onnx"),
+ download_if_not_exists=True,
)
+ mock_onnx_load.assert_called_once_with(str(tmp_path / "some_model.onnx"))
+
+ @pytest.mark.parametrize("absolute", [False, True])
+ def test_load_model_hf_default_cache_dir(self, absolute, monkeypatch, tmp_path):
+ # without cache_dir, an hf:// model is cached under <hub_onnx_dir>/<folder>/, also for an absolute hub_onnx_dir
+ from unittest import mock
+
+ from kornia.config import kornia_config
+
+ hub_dir = str(tmp_path / "onnx_models") if absolute else os.path.join("rel", "onnx_models")
+ monkeypatch.setattr(kornia_config, "hub_onnx_dir", hub_dir)
+
+ with mock.patch.object(ONNXLoader, "download") as mock_download, mock.patch("onnx.load"):
+ ONNXLoader.load_model("hf://operators/some_model")
+
+ mock_download.assert_called_once_with(
+ "https://huggingface.co/kornia/ONNX_models/resolve/main/operators/some_model.onnx",
+ os.path.join(hub_dir, "operators", "some_model.onnx"),
+ download_if_not_exists=True,
+ )
def test_load_model_not_found(self):
model_name = "non_existent_model.onnx"
with pytest.raises(ValueError, match=f"File {model_name} not found"):
ONNXLoader.load_model(model_name)
- def test_download_success(self):
- import os
+ def test_download_success(self, tmp_path):
from unittest import mock
- with mock.patch("urllib.request.urlretrieve") as mock_urlretrieve, mock.patch("os.makedirs") as mock_makedirs:
+ with mock.patch(
+ "urllib.request.urlretrieve", side_effect=lambda url, path: Path(path).write_bytes(b"model")
+ ) as mock_urlretrieve:
url = "https://huggingface.co/some_model.onnx"
- file_path = os.path.join(".test_cache", "some_model.onnx")
+ file_path = tmp_path / "cache" / "some_model.onnx"
- ONNXLoader.download(url, file_path)
+ ONNXLoader.download(url, str(file_path))
- mock_makedirs.assert_called_once_with(os.path.dirname(file_path), exist_ok=True)
- mock_urlretrieve.assert_called_once_with(url, file_path)
+ mock_urlretrieve.assert_called_once()
+ assert mock_urlretrieve.call_args.args[0] == url
+ assert file_path.read_bytes() == b"model"
- def test_download_failure(self):
- import os
+ def test_download_failure(self, tmp_path):
from unittest import mock
with mock.patch(
@@ -103,7 +122,7 @@ class TestONNXLoader:
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"
- file_path = os.path.join(".test_cache", "non_existent_model.onnx")
+ file_path = str(tmp_path / "non_existent_model.onnx")
with pytest.raises(ValueError, match="Error in resolving"):
ONNXLoader.download(url, file_path)