Skip to content
Merged
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
42 changes: 34 additions & 8 deletions kernels/src/kernels/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,13 +192,17 @@ def _parse_local_kernel_overrides(local_kernels: str) -> dict[str, Path]:
CACHE_DIR: str | None = _get_cache_dir()


def _validate_variant_dependencies(variant_path: Path) -> None:
metadata = Metadata.read_from_file(variant_path / "metadata.json")
validate_dependencies(metadata.name.python_name, metadata.python_depends, _backend())


def _import_from_path(variant_path: Path, repo_info: RepoInfo | None = None) -> ModuleType:
if (loaded_kernel := _loaded_kernels.get(variant_path)) is not None:
return loaded_kernel.module

metadata = Metadata.read_from_file(variant_path / "metadata.json")
module_name = metadata.name.python_name
validate_dependencies(module_name, metadata.python_depends, _backend())

file_path = variant_path / "__init__.py"
if not file_path.exists():
Expand Down Expand Up @@ -231,6 +235,7 @@ def install_kernel(
backend: str | None = None,
variant_locks: dict[str, VariantLock] | None = None,
user_agent: str | dict | None = None,
validate_dependencies: bool = False,
) -> Path:
"""
Download a kernel for the current environment to the cache.
Expand All @@ -251,6 +256,9 @@ def install_kernel(
Optional dictionary of variant locks for validation.
user_agent (`Union[str, dict]`, *optional*):
The `user_agent` info to pass to `snapshot_download()` for internal telemetry.
validate_dependencies (`bool`, defaults to False):
When set to True, performs dependency validation. Useful for kernels that have
extra Python dependencies.

Returns:
`Path`: The path to the variant directory.
Expand All @@ -260,13 +268,17 @@ def install_kernel(
# Same local-cache resolution path used by `load_kernel`, which is
# always offline. Sharing the helper avoids the network dependency
# that `get_variants` would otherwise introduce.
return _resolve_local_variant_path(
variant_path = _resolve_local_variant_path(
api,
repo_id,
revision=revision,
backend=backend,
variant_locks=variant_locks,
)
# For locally downloaded kernels, we run the validation after resolving the path
if validate_dependencies:
_validate_variant_dependencies(variant_path)
return variant_path

repo_id, revision = resolve_status(api, repo_id, revision)
variants = get_variants(api, repo_id=repo_id, revision=revision)
Expand All @@ -277,6 +289,18 @@ def install_kernel(
f"Cannot find a build variant for this system in {repo_id} (revision: {revision}):\n\n{variants_trace_str(trace)}"
)

# Validate Python dependencies before downloading the variant.
if validate_dependencies:
metadata_path = api.hf_hub_download(
repo_id,
repo_type="kernel",
filename=f"build/{variant.variant_str}/metadata.json",
cache_dir=CACHE_DIR,
revision=revision,
local_files_only=False,
)
_validate_variant_dependencies(Path(metadata_path).parent)

allow_patterns = [f"build/{variant.variant_str}/*"]

repo_path = Path(
Expand Down Expand Up @@ -472,10 +496,7 @@ def get_kernel(
revision=revision,
)
variant_path = install_kernel(
repo_id,
backend=backend,
revision=revision,
user_agent=user_agent,
repo_id, backend=backend, revision=revision, user_agent=user_agent, validate_dependencies=True
)
return _import_from_path(variant_path, repo_info=repo_info)

Expand All @@ -502,12 +523,15 @@ def get_local_kernel(
variant, _ = resolve_variant(variants, backend)

if variant is not None:
return _import_from_path(base_path / variant.variant_str)
variant_path = base_path / variant.variant_str
_validate_variant_dependencies(variant_path)
return _import_from_path(variant_path)

# If we didn't find the package in the repo we may have a explicit
# package path.
variant_path = repo_path
if variant_path.exists():
_validate_variant_dependencies(variant_path)
return _import_from_path(variant_path)

raise FileNotFoundError(f"Could not find kernel in {repo_path}")
Expand Down Expand Up @@ -664,7 +688,9 @@ def get_locked_kernel(repo_id: str, local_files_only: bool = False) -> ModuleTyp
if locked_sha is None:
raise ValueError(f"Kernel `{repo_id}` is not locked")

variant_path = install_kernel(repo_id, revision=locked_sha, local_files_only=local_files_only)
variant_path = install_kernel(
repo_id, revision=locked_sha, local_files_only=local_files_only, validate_dependencies=True
)

return _import_from_path(variant_path)

Expand Down
47 changes: 46 additions & 1 deletion kernels/tests/test_deps.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from importlib.util import find_spec
from pathlib import Path

import pytest
from huggingface_hub import HfApi, snapshot_download

from kernels import get_kernel
from kernels import get_kernel, get_local_kernel, install_kernel


@pytest.mark.cuda_only
Expand All @@ -22,3 +24,46 @@ def test_python_deps(dependency):
def test_illegal_dep():
with pytest.raises(ValueError, match=r"Kernel module `python_invalid_dep` uses.*kepler-22b"):
get_kernel("kernels-test/python-invalid-dep", revision="main")


def test_deps_validated_before_download(monkeypatch):
"""With `validate_dependencies=True`, deps are checked *before* the build
variant is downloaded.

`snapshot_download` (the full-variant download) is patched to fail, so the
dependency error can only surface if validation runs first — guarding the
early-bail ordering against regressions that move validation back after the
download.
"""

class _Downloaded(RuntimeError):
pass

def _fail(*_args, **_kwargs):
raise _Downloaded("build variant was downloaded before dependency validation")

monkeypatch.setattr(HfApi, "snapshot_download", _fail)

with pytest.raises(ValueError, match=r"Kernel module `python_invalid_dep` uses.*kepler-22b"):
install_kernel("kernels-test/python-invalid-dep", revision="main", validate_dependencies=True)


def test_install_kernel_skips_validation_by_default():
"""Validation is opt-in: with the default `validate_dependencies=False`,
`install_kernel` downloads an invalid-dep kernel without raising."""
variant_path = install_kernel("kernels-test/python-invalid-dep", revision="main")
assert (variant_path / "metadata.json").exists()


def test_local_kernel_validates_deps(tmp_path):
"""`get_local_kernel` validates dependencies even though it never goes through
`install_kernel`'s pre-download check, so removing the gate from
`_import_from_path` must not drop validation for local kernels."""
repo_path = snapshot_download(
"kernels-test/python-invalid-dep",
repo_type="kernel",
revision="main",
cache_dir=tmp_path,
)
with pytest.raises(ValueError, match=r"Kernel module `python_invalid_dep` uses.*kepler-22b"):
get_local_kernel(Path(repo_path))
Loading