From a7eb2e27972bf121921e9182a3ba0afd83ed40c6 Mon Sep 17 00:00:00 2001 From: sayakpaul Date: Tue, 2 Jun 2026 12:16:51 +0530 Subject: [PATCH 1/2] refactor validate dependency --- kernels/src/kernels/utils.py | 26 +++++++++++++++++++++--- kernels/tests/test_deps.py | 39 +++++++++++++++++++++++++++++++++++- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/kernels/src/kernels/utils.py b/kernels/src/kernels/utils.py index 8dce35c7a..427da06dc 100644 --- a/kernels/src/kernels/utils.py +++ b/kernels/src/kernels/utils.py @@ -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(): @@ -277,6 +281,17 @@ 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. + 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( @@ -354,7 +369,9 @@ def _resolve_local_variant_path( ) ) ) - return _find_kernel_in_repo_path(repo_path, variant=variant, variant_locks=variant_locks) + variant_path = _find_kernel_in_repo_path(repo_path, variant=variant, variant_locks=variant_locks) + _validate_variant_dependencies(variant_path) + return variant_path def _find_kernel_in_repo_path( @@ -502,12 +519,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}") diff --git a/kernels/tests/test_deps.py b/kernels/tests/test_deps.py index a7536b313..918308792 100644 --- a/kernels/tests/test_deps.py +++ b/kernels/tests/test_deps.py @@ -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 @@ -22,3 +24,38 @@ 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): + """Dependencies are validated *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 optimization 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") + + +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)) From de5f1b1803b725adab7a301115d312bcda26c545 Mon Sep 17 00:00:00 2001 From: sayakpaul Date: Tue, 2 Jun 2026 16:06:17 +0530 Subject: [PATCH 2/2] address review feedback. --- kernels/src/kernels/utils.py | 42 ++++++++++++++++++++---------------- kernels/tests/test_deps.py | 16 ++++++++++---- 2 files changed, 36 insertions(+), 22 deletions(-) diff --git a/kernels/src/kernels/utils.py b/kernels/src/kernels/utils.py index 427da06dc..541b4e565 100644 --- a/kernels/src/kernels/utils.py +++ b/kernels/src/kernels/utils.py @@ -235,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. @@ -255,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. @@ -264,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) @@ -282,15 +290,16 @@ def install_kernel( ) # Validate Python dependencies before downloading the variant. - 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) + 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}/*"] @@ -369,9 +378,7 @@ def _resolve_local_variant_path( ) ) ) - variant_path = _find_kernel_in_repo_path(repo_path, variant=variant, variant_locks=variant_locks) - _validate_variant_dependencies(variant_path) - return variant_path + return _find_kernel_in_repo_path(repo_path, variant=variant, variant_locks=variant_locks) def _find_kernel_in_repo_path( @@ -489,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) @@ -684,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) diff --git a/kernels/tests/test_deps.py b/kernels/tests/test_deps.py index 918308792..3eaa7bce2 100644 --- a/kernels/tests/test_deps.py +++ b/kernels/tests/test_deps.py @@ -27,12 +27,13 @@ def test_illegal_dep(): def test_deps_validated_before_download(monkeypatch): - """Dependencies are validated *before* the build variant is downloaded. + """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 optimization against regressions that move validation back after - the download. + early-bail ordering against regressions that move validation back after the + download. """ class _Downloaded(RuntimeError): @@ -44,7 +45,14 @@ def _fail(*_args, **_kwargs): 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") + 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):