Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): drop a transfer validate refused, and report the rejection (#4367)

Miral Aminbb7b99f2e9c6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fbb45e1f4..dbba7dff4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -479,6 +479,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
constructor stores what it is given, so `scaled.tx = 7` moved the camera `scale()` was called on.
The returned camera's numbers are unchanged. (#4264, #4349)
+* A fresh transfer that `validate` rejects is now removed even when no other source could have used
+ the emptied path -- which is every `download_hf_file` caller, since it passes one URL. Those bytes
+ arrived during the call and were refused, so unlike the ambiguous load failures
+ `load_state_dict_from_url` weighs, keeping them would end the call having added a poisoned entry to
+ a cache that had none. An offline re-fetch also reports the validator's rejection rather than the
+ network error stacked on top of it, so the message names the file rather than an entry that is
+ intact and, by then, restored. (#4367)
+
* `RenderingDeFMO` (used by `DeFMO`) no longer crashes on a half-precision forward pass. Its rendering
time-steps (`times`) were a plain Python attribute, not a registered buffer, so `nn.Module.to()` never
moved it; `forward` re-derived `times`'s device from the input on every call but never its dtype, so
diff --git a/kornia/core/download.py b/kornia/core/download.py
index 99d3dde5b..04fd2639f 100644
--- a/kornia/core/download.py
+++ b/kornia/core/download.py
@@ -533,8 +533,12 @@ def _drop_failed_download(path: str) -> None:
returns the path to the state the call found, which is also the empty path the
next source needs in order to be fetched at all.
- Only called while a later source remains; see :func:`load_state_dict_from_url`
- for why the final source keeps what it wrote.
+ :func:`load_state_dict_from_url` calls this only while a later source remains,
+ because there a load failure does not establish that the bytes are bad -- a
+ ``map_location`` a build cannot satisfy fails an intact checkpoint -- so the
+ final source keeps what it wrote. :func:`download_file_from_url` calls it for
+ every ``validate`` rejection of a fresh transfer, last source or not, because
+ that rejection *is* a verdict on the file.
Args:
path: the cache path this source just wrote.
@@ -804,10 +808,25 @@ def download_file_from_url(
download-only function does not have: without one, nothing here can tell a
truncated cache entry from an intact one, so a bad file is handed back as a
cache hit on every later call and the caller keeps failing until it is
- deleted by hand. ``validate`` supplies the missing step -- it is called with
- the cache path after each attempt, and raising from it is treated exactly as
- a load failure is: the entry is quarantined, the next source is tried, and
- the discarded source is re-fetched once.
+ deleted by hand.
+
+ ``validate`` supplies the missing step: it is called with the cache path
+ after each attempt, and raising from it rejects the file. What follows
+ depends on where the file came from.
+
+ A rejected *cache entry* -- one the call found rather than fetched -- is
+ quarantined as :func:`load_state_dict_from_url` quarantines a checkpoint that
+ fails to load: it is moved aside so the remaining sources see an empty path,
+ the source that was handed it is re-fetched once, and if nothing usable turns
+ up the original is put back.
+
+ A rejected *fresh transfer* is deleted outright, whether or not a later
+ source could have used the emptied path. Those bytes arrived during this call
+ and ``validate`` refused them, which is a verdict on the file itself, unlike
+ the ambiguous load failures that function has to weigh; keeping them would end
+ the call having added a poisoned entry to a cache that had none. Nothing is
+ re-fetched in that case, so a one-URL call -- what :func:`download_hf_file`
+ makes -- raises with the cache left empty rather than poisoned.
Without ``validate`` nothing is quarantined, as before. The path is returned
to the caller and named in the failure message so that a file which turns
@@ -863,6 +882,7 @@ def download_file_from_url(
budget = _SleepBudget(_MAX_CALL_SLEEP_SECONDS)
quarantine: str | None = None
discarded_url: str | None = None
+ discard_exc: Exception | None = None
downloaded = False
last_exc: Exception | None = None
last_url: str | None = None
@@ -883,10 +903,21 @@ def download_file_from_url(
if fetched:
# These bytes are this source's own transfer, not an entry
# the call found, so there is nothing to preserve and the
- # quarantine does not apply. Drop them when a later source
- # can use the emptied path.
- if more_sources:
- _drop_failed_download(cache_path)
+ # quarantine does not apply.
+ #
+ # They go whether or not a later source can use the emptied
+ # path, which is where this differs from
+ # :func:`load_state_dict_from_url`. Reaching here with
+ # ``fetched`` true means the transfer succeeded and
+ # ``validate`` refused what it wrote -- a verdict on the file
+ # itself. The load failures that function has to weigh are
+ # ambiguous, so it keeps the bytes rather than risk deleting
+ # an intact checkpoint behind a bad ``map_location``; a
+ # rejection here is not, and keeping them would end the call
+ # having *added* a poisoned entry to a cache that had none.
+ # ``download_hf_file`` passes a single URL, so this is the
+ # ordinary cold-cache path, not an edge case.
+ _drop_failed_download(cache_path)
else:
# Either nothing transferred, or -- the case this whole
# branch exists for -- a cache hit was handed back and
@@ -894,7 +925,7 @@ def download_file_from_url(
# source really fetches; it comes back below if none does.
moved = _discard_cache_entry(u, kwargs)
if moved is not None:
- quarantine, discarded_url = moved, u
+ quarantine, discarded_url, discard_exc = moved, u, e
if more_sources:
warnings.warn(f"Failed to download {u!r}: {e}. Trying next source.", stacklevel=2)
continue
@@ -914,10 +945,24 @@ def download_file_from_url(
if quarantine is not None:
_settle_quarantine(cache_path, quarantine, loaded=False, downloaded=downloaded)
+ # The re-attempt pass runs only when nothing transferred, so if it also failed
+ # without transferring, ``last_exc`` is a refetch failure sitting on top of the
+ # rejection that fired the discard -- and that rejection is the one thing naming
+ # what is wrong with the file. Reporting the network instead points the caller at
+ # an entry that is intact and, offline, has just been restored by the ``finally``
+ # above. :func:`load_state_dict_from_url` makes the same swap.
+ refetch_note = ""
+ 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})"
+ )
+ last_exc, last_url = discard_exc, discarded_url
+
raise 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}. "
+ f"Last error: {type(last_exc).__name__}: {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."
diff --git a/tests/core/test_download.py b/tests/core/test_download.py
index 6a7ff784a..9d5422b48 100644
--- a/tests/core/test_download.py
+++ b/tests/core/test_download.py
@@ -1479,6 +1479,43 @@ class TestDownloadValidate:
assert Path(path).read_bytes() == payload
+ def test_a_rejected_fresh_transfer_is_not_left_behind(self, tmp_path) -> None:
+ """A cold cache that fails must not end the call poisoned.
+
+ One URL -- which is what ``download_hf_file`` passes -- nothing cached, and
+ the transfer arrives truncated. Those bytes are this call's own and
+ ``validate`` has refused them, so they go rather than waiting for a later
+ call to find them.
+ """
+ url = self._serve(tmp_path, b"trunc")
+ model_dir = tmp_path / "cache"
+
+ with pytest.raises(RuntimeError, match="Failed to download the file"):
+ download_file_from_url(url, model_dir=str(model_dir), progress=False, validate=self._reject_truncated(14))
+
+ assert not (model_dir / "model.safetensors").exists(), "a refused transfer was left cached"
+
+ def test_the_rejection_is_what_the_failure_reports(self, monkeypatch, tmp_path) -> None:
+ """Offline with a poisoned entry: name the file, not the network.
+
+ The re-attempt fails on the network, so the last exception is a
+ ``URLError`` sitting on top of the rejection that actually explains the
+ failure. Reporting the network points the caller at an entry that is
+ intact and has just been restored.
+ """
+ monkeypatch.setattr(download_mod, "time", _FakeTime())
+ model_dir = tmp_path / "cache"
+ model_dir.mkdir()
+ (model_dir / "model.safetensors").write_bytes(b"trunc")
+ dead = (tmp_path / "missing" / "model.safetensors").as_uri()
+
+ with pytest.raises(RuntimeError) as excinfo:
+ download_file_from_url(dead, model_dir=str(model_dir), progress=False, validate=self._reject_truncated(14))
+
+ message = str(excinfo.value)
+ assert "truncated" in message, "the rejection that explains the failure is missing"
+ assert "refetching it from that same source failed too" in message
+
def test_a_file_that_never_validates_raises_and_keeps_the_original(self, tmp_path) -> None:
"""Nothing on disk is known-good, so the pre-call entry is put back.