Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 30 additions & 14 deletions fastembed/common/model_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,10 +262,21 @@ def _verify_files_from_metadata(
if file_path.stat().st_size != meta["size"]:
return False
return True
except (OSError, KeyError) as e:
except (OSError, KeyError, TypeError) as e:
logger.error(f"Error verifying files: {e!s}")
return False

def _load_file_metadata(path: Path) -> dict[str, Any] | None:
try:
loaded = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as e:
logger.warning(f"Ignoring unreadable metadata file {path}: {e!s}")
return None
if not isinstance(loaded, dict):
logger.warning(f"Ignoring malformed metadata file {path}: expected JSON object")
return None
return loaded

def _collect_file_metadata(
model_dir: Path, revision: str, repo_files: list[RepoFile]
) -> dict[str, dict[str, int | str]]:
Expand All @@ -289,7 +300,7 @@ def _save_file_metadata(model_dir: Path, meta: dict[str, dict[str, int | str]])
try:
if not model_dir.exists():
model_dir.mkdir(parents=True, exist_ok=True)
(model_dir / cls.METADATA_FILE).write_text(json.dumps(meta))
(model_dir / cls.METADATA_FILE).write_text(json.dumps(meta), encoding="utf-8")
except (OSError, ValueError) as e:
logger.warning(f"Error saving metadata: {e!s}")

Expand Down Expand Up @@ -330,8 +341,10 @@ def _save_file_metadata(model_dir: Path, meta: dict[str, dict[str, int | str]])
)
metadata_file = snapshot_dir / cls.METADATA_FILE
if metadata_file.exists():
metadata = json.loads(metadata_file.read_text())
if not _verify_files_from_metadata(snapshot_dir, metadata, repo_files=[]):
metadata = _load_file_metadata(metadata_file)
if metadata is not None and not _verify_files_from_metadata(
snapshot_dir, metadata, repo_files=[]
):
# A size mismatch on one of this model's own files (its weights, or
# whatever else its description lists) means loading would later fail
# with a cryptic error, so the snapshot is not offered at all. A
Expand All @@ -341,6 +354,8 @@ def _save_file_metadata(model_dir: Path, meta: dict[str, dict[str, int | str]])
model_file_corrupt = any(
_repo_relative_path(Path(rel_path)) in model_files
and (snapshot_dir / rel_path).is_file()
and isinstance(meta, dict)
and "size" in meta
and (snapshot_dir / rel_path).stat().st_size != meta["size"]
for rel_path, meta in metadata.items()
)
Expand Down Expand Up @@ -407,16 +422,17 @@ def _save_file_metadata(model_dir: Path, meta: dict[str, dict[str, int | str]])

# a forced download re-fetches every file, so show progress and re-collect the metadata
if not kwargs.get("force_download") and snapshot_dir.exists() and metadata_file.exists():
metadata = json.loads(metadata_file.read_text())
# metadata lacking a requested file, e.g. a new model_file, can't vouch for it
requested_files = {f.path for f in repo_files if f.path in allow_patterns}
stored_files = {_repo_relative_path(Path(rel_path)) for rel_path in metadata}
# empty metadata lists no files, so it can't vouch for the cached ones
verified_metadata = (
bool(metadata)
and requested_files.issubset(stored_files)
and _verify_files_from_metadata(snapshot_dir, metadata, repo_files)
)
metadata = _load_file_metadata(metadata_file)
if metadata is not None:
# metadata lacking a requested file, e.g. a new model_file, can't vouch for it
requested_files = {f.path for f in repo_files if f.path in allow_patterns}
stored_files = {_repo_relative_path(Path(rel_path)) for rel_path in metadata}
# empty metadata lists no files, so it can't vouch for the cached ones
verified_metadata = (
bool(metadata)
and requested_files.issubset(stored_files)
and _verify_files_from_metadata(snapshot_dir, metadata, repo_files)
)

if verified_metadata:
disable_progress_bars()
Expand Down
42 changes: 42 additions & 0 deletions tests/test_model_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,45 @@ def test_download_failure_only_sleeps_between_attempts(
assert download.call_count == retries + 1
assert fallback.call_count == (retries if with_url_fallback else 0)
assert sleep.call_args_list == [call(delay) for delay in delays]


@pytest.mark.parametrize("raw_metadata", [b"{truncated", b"null", b"[]", b"\xff"])
def test_corrupt_metadata_json_does_not_block_offline_or_online_loads(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, raw_metadata: bytes
) -> None:
cache = tmp_path / "cache"
snapshot = cache / "models--qdrant--fake-onnx"
model_file = snapshot / "snapshots" / REVISION / "model.onnx"
model_file.parent.mkdir(parents=True)
model_bytes = b"fake-onnx-bytes"
model_file.write_bytes(model_bytes)
metadata_path = snapshot / ModelManagement.METADATA_FILE
metadata_path.write_bytes(raw_metadata)

monkeypatch.setattr(
model_management, "snapshot_download", lambda **kwargs: str(model_file.parent)
)

offline_result = ModelManagement.download_files_from_huggingface(
"qdrant/fake-onnx",
cache_dir=str(cache),
extra_patterns=["model.onnx"],
local_files_only=True,
)
assert offline_result == str(model_file.parent)

hub_file = RepoFile(path="model.onnx", size=len(model_bytes), oid="blob123")
monkeypatch.setattr(model_management, "list_repo_tree", lambda *a, **kw: [hub_file])
monkeypatch.setattr(
model_management, "model_info", lambda *a, **kw: SimpleNamespace(sha=REVISION)
)

online_result = ModelManagement.download_files_from_huggingface(
"qdrant/fake-onnx",
cache_dir=str(cache),
extra_patterns=["model.onnx"],
local_files_only=False,
)
assert online_result == str(model_file.parent)
repaired = json.loads(metadata_path.read_text())
assert list(repaired) == [str(Path("snapshots") / REVISION / "model.onnx")]