Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(cache): confine cluster downloads to their destination

svonava47133d241b4e
diff --git a/packages/sie_sdk/src/sie_sdk/cache.py b/packages/sie_sdk/src/sie_sdk/cache.py
index ae400d113..53bb81f1f 100644
--- a/packages/sie_sdk/src/sie_sdk/cache.py
+++ b/packages/sie_sdk/src/sie_sdk/cache.py
@@ -14,7 +14,8 @@ from __future__ import annotations
import logging
import os
from dataclasses import dataclass
-from pathlib import Path
+from pathlib import Path, PureWindowsPath
+from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING
from sie_sdk.exceptions import GatedModelError
@@ -240,7 +241,8 @@ def _download_from_cluster_cache(model_id: str, config: CacheConfig) -> bool:
return False
# Create local cache directory
- local_model_path = config.local_cache / model_folder
+ cache_root = config.local_cache.resolve()
+ local_model_path = _cache_destination(cache_root, cache_root, model_folder, directory=True)
local_model_path.mkdir(parents=True, exist_ok=True)
# Download the entire model directory structure
@@ -252,23 +254,59 @@ def _download_from_cluster_cache(model_id: str, config: CacheConfig) -> bool:
def _download_directory(backend: StorageBackend, src_path: str, dst_path: Path) -> None:
"""Recursively download a directory from cloud storage.
+ The explicitly selected root may be a symlink. Descendant directories must
+ not be symlinks, and file links must remain within that root. Downloads are
+ staged privately and replaced atomically, preserving existing files on a
+ failed transfer and never writing through an existing hardlink.
+
Args:
backend: Storage backend instance.
src_path: Source path in cloud storage.
dst_path: Destination local path.
"""
- # Download files in current directory
+ root = dst_path.resolve()
+ _download_cache_directory(backend, src_path, root, root)
+
+
+def _cache_destination(root: Path, parent: Path, name: str, *, directory: bool) -> Path:
+ """Validate an immediate backend child and its local destination."""
+ if (
+ not isinstance(name, str)
+ or name in {"", ".", ".."}
+ or any(character in name for character in ("/", "\\", "\x00"))
+ or PureWindowsPath(name).drive
+ ):
+ raise ValueError("Invalid cluster cache child name")
+ path = parent / name
+ if not path.resolve().is_relative_to(root):
+ raise ValueError("Cluster cache destination escapes its repository")
+ # Do not let directory aliases redirect a repository or create cycles.
+ directory_path = path if directory else parent
+ for ancestor in (directory_path, *directory_path.parents):
+ if ancestor == root:
+ break
+ if ancestor.is_symlink():
+ raise ValueError("Cluster cache descendant directories cannot be symlinks")
+ return path
+
+
+def _download_cache_directory(backend: StorageBackend, src_path: str, dst_path: Path, root: Path) -> None:
+ """Walk beneath one admitted root without rebasing through child links."""
for filename in backend.list_files(src_path):
+ dst_file = _cache_destination(root, dst_path, filename, directory=False)
src_file = join_path(src_path, filename)
- dst_file = dst_path / filename
- backend.download_file(src_file, dst_file)
+ with TemporaryDirectory(prefix=".sie-cache-", dir=root) as temporary:
+ staged_file = Path(temporary) / "download"
+ backend.download_file(src_file, staged_file)
+ _cache_destination(root, dst_path, filename, directory=False)
+ staged_file.replace(dst_file)
# Recursively download subdirectories
for dirname in backend.list_dirs(src_path):
- src_subdir = join_path(src_path, dirname)
- dst_subdir = dst_path / dirname
+ dst_subdir = _cache_destination(root, dst_path, dirname, directory=True)
dst_subdir.mkdir(parents=True, exist_ok=True)
- _download_directory(backend, src_subdir, dst_subdir)
+ src_subdir = join_path(src_path, dirname)
+ _download_cache_directory(backend, src_subdir, dst_subdir, root)
def _get_hf_ignore_patterns(
diff --git a/packages/sie_sdk/tests/test_cache.py b/packages/sie_sdk/tests/test_cache.py
index 512e882ad..582bc90ca 100644
--- a/packages/sie_sdk/tests/test_cache.py
+++ b/packages/sie_sdk/tests/test_cache.py
@@ -12,6 +12,7 @@ from huggingface_hub.errors import (
)
from sie_sdk.cache import (
CacheConfig,
+ _download_directory,
ensure_model_cached,
get_cache_config,
is_model_cached,
@@ -62,6 +63,232 @@ class FakeOSSCacheBucket:
Path(filename).write_bytes(self.objects[key])
+class TestDownloadContainment:
+ @pytest.mark.parametrize("kind", ["file", "directory"])
+ @pytest.mark.parametrize(
+ "name", ["", ".", "..", "../escape", "nested/file", "nested\\file", "C:escape", "bad\x00name"]
+ )
+ def test_backend_child_must_be_a_basename(self, tmp_path: Path, kind: str, name: str) -> None:
+ destination = tmp_path / "repository"
+ destination.mkdir()
+ backend = MagicMock()
+ backend.list_files.side_effect = [[name] if kind == "file" else [], []]
+ backend.list_dirs.side_effect = [[name] if kind == "directory" else [], []]
+
+ with pytest.raises(ValueError, match="cache"):
+ _download_directory(backend, "source", destination)
+
+ backend.download_file.assert_not_called()
+ assert list(destination.iterdir()) == []
+
+ @pytest.mark.parametrize("kind", ["file", "directory"])
+ def test_absolute_backend_child_is_refused(self, tmp_path: Path, kind: str) -> None:
+ destination = tmp_path / "repository"
+ destination.mkdir()
+ outside = tmp_path / "outside"
+ outside.write_bytes(b"protected")
+ backend = MagicMock()
+ backend.list_files.return_value = [str(outside)] if kind == "file" else []
+ backend.list_dirs.return_value = [str(outside)] if kind == "directory" else []
+
+ with pytest.raises(ValueError, match="cache"):
+ _download_directory(backend, "source", destination)
+
+ backend.download_file.assert_not_called()
+ assert outside.read_bytes() == b"protected"
+
+ def test_existing_file_link_cannot_write_outside_repository(self, tmp_path: Path) -> None:
+ destination = tmp_path / "repository"
+ destination.mkdir()
+ outside = tmp_path / "outside"
+ outside.write_bytes(b"protected")
+ (destination / "weights").symlink_to(outside)
+ backend = MagicMock()
+ backend.list_files.return_value = ["weights"]
+ backend.list_dirs.return_value = []
+ backend.download_file.side_effect = lambda _source, target: target.write_bytes(b"replacement")
+
+ with pytest.raises(ValueError, match="cache"):
+ _download_directory(backend, "source", destination)
+
+ backend.download_file.assert_not_called()
+ assert outside.read_bytes() == b"protected"
+
+ @pytest.mark.parametrize("outside_root", [True, False])
+ def test_descendant_directory_links_are_refused(self, tmp_path: Path, outside_root: bool) -> None:
+ destination = tmp_path / "repository"
+ destination.mkdir()
+ target = (tmp_path if outside_root else destination) / "target"
+ target.mkdir()
+ (target / "weights").write_bytes(b"protected")
+ (destination / "snapshot").symlink_to(target, target_is_directory=True)
+ backend = MagicMock()
+ backend.list_files.side_effect = lambda path: ["weights"] if path == "source/snapshot" else []
+ backend.list_dirs.side_effect = lambda path: ["snapshot"] if path == "source" else []
+ backend.download_file.side_effect = lambda _source, path: path.write_bytes(b"replacement")
+
+ with pytest.raises(ValueError, match="cache"):
+ _download_directory(backend, "source", destination)
+
+ backend.download_file.assert_not_called()
+ assert (target / "weights").read_bytes() == b"protected"
+
+ def test_explicit_directory_root_may_be_a_symlink(self, tmp_path: Path) -> None:
+ actual = tmp_path / "actual"
+ actual.mkdir()
+ destination = tmp_path / "selected-root"
+ destination.symlink_to(actual, target_is_directory=True)
+ backend = MagicMock()
+ backend.list_files.return_value = ["weights"]
+ backend.list_dirs.return_value = []
+ backend.download_file.side_effect = lambda _source, path: path.write_bytes(b"new")
+
+ _download_directory(backend, "source", destination)
+
+ assert destination.is_symlink()
+ assert (actual / "weights").read_bytes() == b"new"
+
+ def test_atomic_file_replacement_does_not_overwrite_an_existing_hardlink(self, tmp_path: Path) -> None:
+ destination = tmp_path / "repository"
+ destination.mkdir()
+ outside = tmp_path / "outside"
+ outside.write_bytes(b"protected")
+ (destination / "weights").hardlink_to(outside)
+ backend = MagicMock()
+ backend.list_files.return_value = ["weights"]
+ backend.list_dirs.return_value = []
+ backend.download_file.side_effect = lambda _source, path: path.write_bytes(b"new")
+
+ _download_directory(backend, "source", destination)
+
+ assert outside.read_bytes() == b"protected"
+ assert (destination / "weights").read_bytes() == b"new"
+ assert not (destination / "weights").samefile(outside)
+
+ def test_contained_huggingface_file_link_is_replaced_without_changing_blob(self, tmp_path: Path) -> None:
+ destination = tmp_path / "repository"
+ snapshot = destination / "snapshots" / "commit"
+ snapshot.mkdir(parents=True)
+ blob = destination / "blobs" / "digest"
+ blob.parent.mkdir()
+ blob.write_bytes(b"old")
+ (snapshot / "weights").symlink_to("../../blobs/digest")
+ backend = MagicMock()
+ backend.list_dirs.side_effect = lambda path: {"source": ["snapshots"], "source/snapshots": ["commit"]}.get(
+ path, []
+ )
+ backend.list_files.side_effect = lambda path: ["weights"] if path == "source/snapshots/commit" else []
+ backend.download_file.side_effect = lambda _source, path: path.write_bytes(b"new")
+
+ _download_directory(backend, "source", destination)
+
+ assert blob.read_bytes() == b"old"
+ assert (snapshot / "weights").read_bytes() == b"new"
+ assert not (snapshot / "weights").is_symlink()
+
+ def test_failed_download_preserves_existing_file_and_cleans_temporary_data(self, tmp_path: Path) -> None:
+ destination = tmp_path / "repository"
+ destination.mkdir()
+ (destination / "weights").write_bytes(b"old")
+ backend = MagicMock()
+ backend.list_files.return_value = ["weights"]
+ backend.list_dirs.return_value = []
+
+ def fail(_source: str, path: Path) -> None:
+ path.write_bytes(b"partial")
+ raise OSError("controlled download failure")
+
+ backend.download_file.side_effect = fail
+ with pytest.raises(OSError, match="controlled download failure"):
+ _download_directory(backend, "source", destination)
+
+ assert (destination / "weights").read_bytes() == b"old"
+ assert [path.name for path in destination.iterdir()] == ["weights"]
+
+ def test_destination_is_rechecked_after_download(self, tmp_path: Path) -> None:
+ destination = tmp_path / "repository"
+ destination.mkdir()
+ outside = tmp_path / "outside"
+ outside.write_bytes(b"protected")
+ backend = MagicMock()
+ backend.list_files.return_value = ["weights"]
+ backend.list_dirs.return_value = []
+
+ def substitute_destination(_source: str, staged: Path) -> None:
+ (destination / "weights").symlink_to(outside)
+ staged.write_bytes(b"replacement")
+
+ backend.download_file.side_effect = substitute_destination
+ with pytest.raises(ValueError, match="cache"):
+ _download_directory(backend, "source", destination)
+
+ assert outside.read_bytes() == b"protected"
+ assert [path.name for path in destination.iterdir()] == ["weights"]
+
+ def test_parent_directory_is_rechecked_after_download(self, tmp_path: Path) -> None:
+ destination = tmp_path / "repository"
+ snapshot = destination / "snapshot"
+ snapshot.mkdir(parents=True)
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "weights").write_bytes(b"protected")
+ backend = MagicMock()
+ backend.list_dirs.side_effect = lambda path: ["snapshot"] if path == "source" else []
+ backend.list_files.side_effect = lambda path: ["weights"] if path == "source/snapshot" else []
+
+ def substitute_parent(_source: str, staged: Path) -> None:
+ snapshot.rmdir()
+ snapshot.symlink_to(outside, target_is_directory=True)
+ staged.write_bytes(b"replacement")
+
+ backend.download_file.side_effect = substitute_parent
+ with pytest.raises(ValueError, match="cache"):
+ _download_directory(backend, "source", destination)
+
+ assert (outside / "weights").read_bytes() == b"protected"
+ assert [path.name for path in destination.iterdir()] == ["snapshot"]
+
+ def test_derived_repository_root_cannot_alias_another_repository(self, tmp_path: Path) -> None:
+ local = tmp_path / "local"
+ local.mkdir()
+ other = local / "models--tenant-b--adapter"
+ other.mkdir()
+ (local / "models--tenant-a--adapter").symlink_to(other, target_is_directory=True)
+ backend = MagicMock()
+ backend.has_children.return_value = True
+ backend.list_files.return_value = ["injected"]
+ backend.list_dirs.return_value = []
+ backend.download_file.side_effect = lambda _source, path: path.write_bytes(b"injected")
+ config = CacheConfig(local_cache=local, cluster_cache="s3://bucket/cache", hf_fallback=False)
+
+ with (
+ patch("sie_sdk.cache.get_storage_backend", return_value=backend),
+ pytest.raises(ValueError, match="cache"),
+ ):
+ ensure_model_cached("tenant-a/adapter", config)
+
+ backend.download_file.assert_not_called()
+ assert list(other.iterdir()) == []
+
+ def test_configured_cache_root_symlink_supports_cluster_download(self, tmp_path: Path) -> None:
+ actual = tmp_path / "actual"
+ actual.mkdir()
+ selected = tmp_path / "selected"
+ selected.symlink_to(actual, target_is_directory=True)
+ config = CacheConfig(local_cache=selected, cluster_cache="oss://bucket/cache", hf_fallback=False)
+ backend = OSSBackend.__new__(OSSBackend)
+ backend._buckets = {
+ "bucket": FakeOSSCacheBucket({"cache/models--org--model/snapshots/commit/weights": b"cached"})
+ }
+
+ with patch("sie_sdk.cache.get_storage_backend", return_value=backend):
+ result = ensure_model_cached("org/model", config, revision="commit")
+
+ assert result == selected / "models--org--model"
+ assert (actual / "models--org--model/snapshots/commit/weights").read_bytes() == b"cached"
+ assert selected.is_symlink()
+
+
class TestGetCacheConfig:
"""Tests for get_cache_config()."""