Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(io): keep a concurrent download's copy when Windows refuses the replace (#5816)

Dmytro Mishkin3a4aba6a62cd
diff --git a/kornia/io/sample.py b/kornia/io/sample.py
index 1635e3943..f8e4b6bf4 100644
--- a/kornia/io/sample.py
+++ b/kornia/io/sample.py
@@ -50,7 +50,10 @@ def download_image(url: str, save_to: str) -> None:
Each call writes the bytes to a temporary file of its own next to ``save_to`` and renames it onto ``save_to`` only
once the write is complete, removing it if the write fails. An interrupted download therefore never leaves a
- partial file at ``save_to``, and concurrent downloads of the same file each replace it with a complete copy.
+ partial file at ``save_to``, and concurrent downloads of the same file each leave a complete copy there. Windows
+ cannot replace a file that is open, for example one that a concurrent call has just put there and is reading; the
+ later call keeps that copy only if its bytes match the download and removes its own temporary file. A refused
+ replacement with a missing, unreadable, or different destination still raises the replacement error.
Args:
url: The URL of the image to download.
@@ -66,7 +69,19 @@ def download_image(url: str, save_to: str) -> None:
try:
with open(part, "xb") as f:
f.write(data)
- os.replace(part, save_to)
+ try:
+ os.replace(part, save_to)
+ except PermissionError:
+ # Windows may refuse to replace an open file. Only accept an identical completed download.
+ matches = False
+ try:
+ with open(save_to, "rb") as existing:
+ matches = existing.read(len(data) + 1) == data
+ except OSError:
+ pass # preserve the replacement error when the destination cannot be verified
+ if not matches:
+ raise
+ os.remove(part)
except BaseException:
with contextlib.suppress(FileNotFoundError):
os.remove(part)
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index a5ac419ec..07e1b54a5 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -666,7 +666,8 @@ class TestSampleImages:
mock_urlopen.assert_not_called()
assert not cache.exists()
- def test_concurrent_downloads_of_the_same_image_both_succeed(self, tmp_path: Path) -> None:
+ @pytest.mark.parametrize("refuse_replacing_a_file", [False, True], ids=["posix_replace", "windows_replace"])
+ def test_concurrent_downloads_of_the_same_image_both_succeed(self, tmp_path: Path, refuse_replacing_a_file) -> None:
import os
import threading
from concurrent.futures import ThreadPoolExecutor
@@ -680,11 +681,16 @@ class TestSampleImages:
payload = source.read_bytes()
cache = tmp_path / "cache"
both_written = threading.Barrier(2, timeout=10)
+ one_replace_at_a_time = threading.Lock()
real_replace = os.replace
def replace_after_both_writes(src, dst):
both_written.wait() # both calls have missed the cache and finished writing before either replaces
- return real_replace(src, dst)
+ with one_replace_at_a_time:
+ if refuse_replacing_a_file and os.path.exists(dst):
+ # Windows refuses to replace a file that the call which put it there is reading
+ raise PermissionError(13, "Access is denied", dst)
+ return real_replace(src, dst)
def fetch():
return get_sample_images(paths=["https://example.invalid/x/same.png"], cache_dir=str(cache))[0]
@@ -752,6 +758,69 @@ class TestDownloadImage:
assert dst.read_bytes() == payload
assert sorted(p.name for p in tmp_path.iterdir()) == ["panda.jpg"] # no temporary file is left behind
+ def test_a_refused_replace_without_a_copy_raises_and_leaves_no_file(self, tmp_path):
+ from unittest import mock
+
+ from kornia.io.sample import download_image
+
+ with (
+ mock.patch("kornia.io.sample.urlopen") as mock_urlopen,
+ mock.patch("kornia.io.sample.os.replace", side_effect=PermissionError(13, "Access is denied")),
+ ):
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = b"payload"
+ with pytest.raises(PermissionError):
+ download_image(self.URL, str(tmp_path / "panda.jpg"))
+ assert list(tmp_path.iterdir()) == [] # neither the destination nor the temporary file
+
+ @pytest.mark.parametrize("existing", [b"payload", b"different", b"payload-extra", b"pay"])
+ def test_a_refused_replace_only_accepts_matching_bytes(self, tmp_path, existing):
+ from unittest import mock
+
+ from kornia.io.sample import download_image
+
+ dst = tmp_path / "panda.jpg"
+ dst.write_bytes(existing)
+ error = PermissionError(13, "Access is denied")
+ with (
+ mock.patch("kornia.io.sample.urlopen") as mock_urlopen,
+ mock.patch("kornia.io.sample.os.replace", side_effect=error),
+ ):
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = b"payload"
+ if existing == b"payload":
+ download_image(self.URL, str(dst))
+ else:
+ with pytest.raises(PermissionError) as exc:
+ download_image(self.URL, str(dst))
+ assert exc.value is error
+ assert dst.read_bytes() == existing
+ assert list(tmp_path.iterdir()) == [dst]
+
+ def test_a_refused_replace_with_an_unreadable_copy_preserves_the_replace_error(self, tmp_path):
+ from unittest import mock
+
+ from kornia.io.sample import download_image
+
+ dst = tmp_path / "panda.jpg"
+ dst.write_bytes(b"payload")
+ error = PermissionError(13, "Replace refused")
+
+ def refusing_read(path, mode="r", *args, **kwargs):
+ if mode == "rb":
+ raise PermissionError(13, "Read refused")
+ return open(path, mode, *args, **kwargs)
+
+ with (
+ mock.patch("kornia.io.sample.urlopen") as mock_urlopen,
+ mock.patch("kornia.io.sample.os.replace", side_effect=error),
+ mock.patch("kornia.io.sample.open", refusing_read, create=True),
+ ):
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = b"payload"
+ with pytest.raises(PermissionError) as exc:
+ download_image(self.URL, str(dst))
+ assert exc.value is error
+ assert dst.read_bytes() == b"payload"
+ assert list(tmp_path.iterdir()) == [dst]
+
def test_the_destination_appears_only_once_the_write_is_complete(self, tmp_path):
from unittest import mock