From 37139866fa742f84f9960bd8d35d1c51f817531a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:15:34 -0500 Subject: [PATCH 01/20] [GA-9681] Add reusable Pixi validation hooks Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .pre-commit-hooks.yaml | 16 ++ README.rst | 18 ++ mirageoscience/hooks/check_pixi_lock.py | 318 ++++++++++++++++++++++++ mirageoscience/hooks/check_recipe.py | 303 ++++++++++++++++++++++ poetry.lock | 87 ++++++- pyproject.toml | 4 + tests/pixi_hooks_test.py | 144 +++++++++++ 7 files changed, 889 insertions(+), 1 deletion(-) create mode 100644 mirageoscience/hooks/check_pixi_lock.py create mode 100644 mirageoscience/hooks/check_recipe.py create mode 100644 tests/pixi_hooks_test.py diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 66955d0..1c09ebc 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -5,6 +5,22 @@ language: python types: [text] +- id: check-pixi-lock + name: check Pixi lock package sources + description: check locked Conda and PyPI sources against Pixi workspace features + entry: check_pixi_lock + language: python + additional_dependencies: [packaging>=25, PyYAML>=6] + pass_filenames: false + +- id: check-recipe + name: check recipe constraints + description: check recipe security constraints and optional PyTorch backend policy + entry: check_recipe + language: python + additional_dependencies: [packaging>=25, PyYAML>=6] + pass_filenames: false + - id: prepare-commit-msg name: prepare commit message description: add the JIRA ID found in the branch name in case it is missing from the commit message diff --git a/README.rst b/README.rst index 5a323f2..a215132 100644 --- a/README.rst +++ b/README.rst @@ -11,6 +11,13 @@ Included Hooks ^^^^^^^^^^^^^^ - ``check-copyright``: Checks for valid copyright statements in files. +- ``check-pixi-lock``: Checks locked Conda and PyPI sources against Pixi workspace + features. ``--strict-pypi`` requires the lock to contain exactly the packages + declared by the selected PyPI feature; otherwise transitive PyPI dependencies + are allowed while the feature packages are still checked. +- ``check-recipe``: Checks recipe ``run_constraints`` against Pixi constraints, + verifies constrained packages remain transitive, and optionally checks that + the recipe leaves PyTorch backend selection to the installer. - ``prepare-commit-msg``: Adds the JIRA ID found in the branch name in case it is missing from the commit message. - ``check-commit-message``: Checks that the branch name or the commit @@ -34,9 +41,20 @@ Example of ``.pre-commit-config.yamnl``: types: [text] files: (^LICENSE|^README(|-dev).rst|\.py|\.pyi)$ exclude: (^\.|^docs/) + - id: check-pixi-lock + args: [--pypi-feature=mira-pypi, --strict-pypi] + - id: check-recipe + args: [--check-pytorch] - id: prepare-commit-msg - id: check-commit-msg +The Pixi hooks read ``pixi.toml``, ``pixi.lock``, ``recipe.yaml``, and +``pyproject.toml`` from the repository root by default. Configure differing +feature names with ``--pypi-feature`` and ``--conda-feature``. For recipe +workspaces with additional Pixi dependency features, ``--constraints-feature`` +can be repeated; use ``--security-floor`` and ``--require-feature-dependency`` +to define package-specific security requirements. + License ^^^^^^^ diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py new file mode 100644 index 0000000..08dd243 --- /dev/null +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -0,0 +1,318 @@ +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Copyright (c) 2024-2026 Mira Geoscience Ltd. ' +# ' +# This file is part of mirageoscience.pre-commit-hooks package. ' +# ' +# mirageoscience.pre-commit-hooks is distributed under the terms and conditions ' +# of the MIT License (see LICENSE file at the root of this source code package). ' +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + +from __future__ import annotations + +import argparse +import sys +import tomllib +from dataclasses import dataclass +from pathlib import Path +from urllib.parse import unquote, urlsplit + +import yaml +from packaging.utils import canonicalize_name + + +@dataclass(frozen=True) +class LockOptions: + pypi_feature: str + conda_feature: str | None = None + strict_pypi: bool = False + pypi_index_feature: str | None = None + validate_pypi_sources: bool = False + git_url_prefixes: tuple[str, ...] = () + + +@dataclass(frozen=True) +class LockExpectations: + pypi_packages: set[str] + conda_packages: set[str] + index_urls: set[str] + source_roots: set[str] + + +@dataclass(frozen=True) +class LockContext: + options: LockOptions + expectations: LockExpectations + packages_by_url: dict[str, str] + + +def _feature_dependencies( + pixi: dict, feature_name: str, dependency_type: str +) -> set[str]: + try: + dependencies = pixi["feature"][feature_name][dependency_type] + except KeyError as error: + raise ValueError( + f"Pixi feature {feature_name!r} has no {dependency_type!r} table" + ) from error + return {canonicalize_name(name) for name in dependencies} + + +def _environment_features(environment: object) -> set[str]: + if isinstance(environment, dict): + features = environment.get("features", []) + else: + features = environment + if not isinstance(features, list): + raise ValueError(f"Invalid Pixi environment feature list: {features!r}") + return set(features) + + +def _locked_names( + entries: list[dict], packages_by_url: dict[str, str], source: str +) -> set[str]: + names = set() + for entry in entries: + url = entry.get(source) + if url is None: + continue + if source == "pypi": + name = packages_by_url.get(url) + if name is None: + raise ValueError(f"Pixi lock package URL is not defined: {url}") + else: + filename = unquote(urlsplit(url).path.rsplit("/", 1)[-1]) + for suffix in (".tar.bz2", ".conda"): + if filename.endswith(suffix): + filename = filename[: -len(suffix)] + break + package_parts = filename.rsplit("-", 2) + if len(package_parts) != 3: + raise ValueError(f"Cannot determine Conda package name from {url}") + name = package_parts[0] + names.add(canonicalize_name(name)) + return names + + +def _index_urls(pixi: dict, feature_name: str) -> set[str]: + options = pixi["feature"][feature_name].get("pypi-options", {}) + urls = set() + for key in ("index-url",): + if url := options.get(key): + urls.add(url.rstrip("/")) + urls.update(url.rstrip("/") for url in options.get("extra-index-urls", [])) + return urls + + +def _expectations(pixi: dict, options: LockOptions) -> LockExpectations: + pypi_packages = _feature_dependencies( + pixi, options.pypi_feature, "pypi-dependencies" + ) + conda_packages = ( + _feature_dependencies(pixi, options.conda_feature, "dependencies") + if options.conda_feature + else set() + ) + index_feature = options.pypi_index_feature or options.pypi_feature + index_urls = ( + _index_urls(pixi, index_feature) if options.validate_pypi_sources else set() + ) + source_roots = { + f"{url.removesuffix('/simple').rstrip('/')}/" for url in index_urls + } + return LockExpectations(pypi_packages, conda_packages, index_urls, source_roots) + + +def _source_errors( + label: str, + entries: list[dict], + environment_lock: dict, + expected_pypi: set[str], + context: LockContext, +) -> list[str]: + options = context.options + expectations = context.expectations + if not options.validate_pypi_sources or not expected_pypi: + return [] + + errors = [] + missing_indexes = expectations.index_urls - set(environment_lock.get("indexes", [])) + if missing_indexes: + errors.append(f"{label}: missing configured PyPI indexes {sorted(missing_indexes)}") + for entry in entries: + url = entry.get("pypi") + if url is None: + continue + if url.startswith("git+"): + if not any(url.startswith(prefix) for prefix in options.git_url_prefixes): + errors.append(f"{label}: unexpected Git source {url}") + elif not any(url.startswith(root) for root in expectations.source_roots): + errors.append(f"{label}: unexpected PyPI source {url}") + return errors + + +def _pypi_errors( + label: str, + entries: list[dict], + environment_lock: dict, + features: set[str], + context: LockContext, +) -> list[str]: + options = context.options + expectations = context.expectations + pypi_names = _locked_names(entries, context.packages_by_url, "pypi") + expected_pypi = ( + expectations.pypi_packages if options.pypi_feature in features else set() + ) + errors = [] + if options.strict_pypi: + if pypi_names != expected_pypi: + errors.append( + f"{label}: expected exactly PyPI packages {sorted(expected_pypi)}, " + f"found {sorted(pypi_names)}" + ) + else: + missing_pypi = expected_pypi - pypi_names + if missing_pypi: + errors.append(f"{label}: missing PyPI packages {sorted(missing_pypi)}") + if options.pypi_feature not in features and pypi_names: + errors.append( + f"{label}: PyPI packages are locked without the " + f"{options.pypi_feature!r} feature: {sorted(pypi_names)}" + ) + errors.extend(_source_errors(label, entries, environment_lock, expected_pypi, context)) + return errors + + +def _conda_errors( + label: str, + pypi_names: set[str], + conda_names: set[str], + features: set[str], + context: LockContext, +) -> list[str]: + options = context.options + expected_conda = ( + context.expectations.conda_packages + if options.conda_feature and options.conda_feature in features + else set() + ) + expected_pypi = ( + context.expectations.pypi_packages + if options.pypi_feature in features + else set() + ) + errors = [] + missing_conda = expected_conda - conda_names + if missing_conda: + errors.append(f"{label}: missing Conda packages {sorted(missing_conda)}") + wrong_pypi_source = expected_conda & pypi_names + if wrong_pypi_source: + errors.append( + f"{label}: Conda feature packages locked from PyPI " + f"{sorted(wrong_pypi_source)}" + ) + wrong_conda_source = expected_pypi & conda_names + if wrong_conda_source: + errors.append( + f"{label}: PyPI feature packages locked from Conda " + f"{sorted(wrong_conda_source)}" + ) + return errors + + +def _validate_platform( + label: str, + entries: list[dict], + environment_lock: dict, + features: set[str], + context: LockContext, +) -> list[str]: + pypi_names = _locked_names(entries, context.packages_by_url, "pypi") + conda_names = _locked_names(entries, context.packages_by_url, "conda") + return _pypi_errors( + label, entries, environment_lock, features, context + ) + _conda_errors(label, pypi_names, conda_names, features, context) + + +def _validate_environment( + pixi: dict, + environment_name: str, + environment_lock: dict, + context: LockContext, +) -> list[str]: + environment_config = pixi["environments"].get(environment_name) + if environment_config is None: + return [f"{environment_name}: missing Pixi environment definition"] + features = _environment_features(environment_config) + errors = [] + for platform, entries in environment_lock["packages"].items(): + label = f"{environment_name}/{platform}" + errors.extend( + _validate_platform( + label, + entries, + environment_lock, + features, + context, + ) + ) + return errors + + +def validate_lock(pixi: dict, lock: dict, options: LockOptions) -> list[str]: + packages_by_url = { + package["pypi"]: package["name"] + for package in lock["packages"] + if "pypi" in package + } + context = LockContext(options, _expectations(pixi, options), packages_by_url) + errors = [] + for environment_name, environment_lock in lock["environments"].items(): + errors.extend( + _validate_environment( + pixi, + environment_name, + environment_lock, + context, + ) + ) + return errors + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--pixi-file", type=Path, default=Path("pixi.toml")) + parser.add_argument("--lock-file", type=Path, default=Path("pixi.lock")) + parser.add_argument("--pypi-feature", default="mira-pypi") + parser.add_argument("--conda-feature") + parser.add_argument("--strict-pypi", action="store_true") + parser.add_argument("--pypi-index-feature") + parser.add_argument("--validate-pypi-sources", action="store_true") + parser.add_argument("--git-url-prefix", action="append", default=[]) + args = parser.parse_args() + + with args.pixi_file.open("rb") as file: + pixi = tomllib.load(file) + with args.lock_file.open(encoding="utf-8") as file: + lock = yaml.safe_load(file) + errors = validate_lock( + pixi, + lock, + LockOptions( + pypi_feature=args.pypi_feature, + conda_feature=args.conda_feature, + strict_pypi=args.strict_pypi, + pypi_index_feature=args.pypi_index_feature, + validate_pypi_sources=args.validate_pypi_sources, + git_url_prefixes=tuple(args.git_url_prefix), + ), + ) + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + print("Pixi lock package sources match the configured features.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py new file mode 100644 index 0000000..2777c4d --- /dev/null +++ b/mirageoscience/hooks/check_recipe.py @@ -0,0 +1,303 @@ +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Copyright (c) 2024-2026 Mira Geoscience Ltd. ' +# ' +# This file is part of mirageoscience.pre-commit-hooks package. ' +# ' +# mirageoscience.pre-commit-hooks is distributed under the terms and conditions ' +# of the MIT License (see LICENSE file at the root of this source code package). ' +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + +from __future__ import annotations + +import argparse +import re +import sys +import tomllib +from dataclasses import dataclass +from pathlib import Path + +import yaml +from packaging.requirements import Requirement +from packaging.specifiers import SpecifierSet +from packaging.utils import canonicalize_name +from packaging.version import Version + + +@dataclass(frozen=True) +class RecipeOptions: + constraints_features: tuple[str, ...] = () + security_floors: tuple[str, ...] = () + allowed_direct_pixi: tuple[str, ...] = () + required_feature_dependencies: tuple[str, ...] = () + package_aliases: tuple[str, ...] = () + check_pytorch: bool = False + + +def _parse_constraint(value: str) -> tuple[str, str]: + name, separator, specifier = value.strip().partition(" ") + if not separator or not specifier.strip(): + raise ValueError(f"Invalid recipe run constraint: {value!r}") + return canonicalize_name(name), specifier.strip() + + +def _parse_floor(value: str) -> tuple[str, Version]: + match = re.fullmatch(r"([A-Za-z0-9_.-]+)>=([A-Za-z0-9_.+-]+)", value) + if match is None: + raise ValueError(f"Invalid security floor {value!r}; expected package>=version") + return canonicalize_name(match.group(1)), Version(match.group(2)) + + +def _as_specifier_set(value: str) -> SpecifierSet: + specifiers = [] + for specifier in value.split(","): + specifier = specifier.strip() + if not any(operator in specifier for operator in "<>=!~"): + specifier = f"=={specifier}" + specifiers.append(specifier) + return SpecifierSet(",".join(specifiers)) + + +def _project_dependency_names(project: dict) -> set[str]: + project_data = project.get("project", {}) + dependencies = list(project_data.get("dependencies", [])) + for optional_dependencies in project_data.get("optional-dependencies", {}).values(): + dependencies.extend(optional_dependencies) + return { + canonicalize_name(Requirement(dependency).name) for dependency in dependencies + } + + +def _pixi_direct_dependencies(pixi: dict) -> set[str]: + direct_dependencies = set() + for section in (pixi, *pixi.get("feature", {}).values()): + for dependency_type in ("dependencies", "pypi-dependencies"): + direct_dependencies.update( + canonicalize_name(name) + for name in section.get(dependency_type, {}) + ) + return direct_dependencies + + +def _package_aliases(values: tuple[str, ...]) -> dict[str, str]: + aliases = {} + for value in values: + alias, separator, package = value.partition("=") + if not separator or not alias or not package: + raise ValueError(f"Invalid package alias {value!r}; expected alias=package") + aliases[canonicalize_name(alias)] = canonicalize_name(package) + return aliases + + +def _feature_dependency(pixi: dict, feature: str, package: str) -> str | None: + feature_data = pixi.get("feature", {}).get(feature, {}) + for dependency_type in ("dependencies", "pypi-dependencies", "constraints"): + dependencies = feature_data.get(dependency_type, {}) + for name, specifier in dependencies.items(): + if canonicalize_name(name) == package: + return str(specifier) + return None + + +def _pixi_constraints( + pixi: dict, recipe_constraints: dict[str, str], features: tuple[str, ...] +) -> dict[str, str]: + constraints = { + canonicalize_name(name): str(specifier) + for name, specifier in pixi.get("constraints", {}).items() + } + for feature in features: + for package in recipe_constraints: + if package not in constraints: + specifier = _feature_dependency(pixi, feature, package) + if specifier is not None: + constraints[package] = specifier + return constraints + + +def _constraint_errors( + recipe_constraints: dict[str, str], + pixi_constraints: dict[str, str], + options: RecipeOptions, +) -> list[str]: + errors = [] + floors = dict(_parse_floor(value) for value in options.security_floors) + if recipe_constraints.keys() != pixi_constraints.keys(): + errors.append( + "recipe.yaml run_constraints must match Pixi constraints; " + f"recipe={sorted(recipe_constraints)}, Pixi={sorted(pixi_constraints)}" + ) + for package, recipe_specifier in recipe_constraints.items(): + pixi_specifier = pixi_constraints.get(package) + if pixi_specifier is None: + continue + if recipe_specifier == pixi_specifier: + continue + floor = floors.get(package) + if floor is None: + errors.append( + f"{package}: recipe constraint {recipe_specifier!r} does not match " + f"Pixi constraint {pixi_specifier!r}" + ) + continue + if ( + floor not in _as_specifier_set(recipe_specifier) + or floor not in _as_specifier_set(pixi_specifier) + ): + errors.append( + f"{package}: recipe and Pixi constraints must both include " + f"security floor {floor}" + ) + for package, floor in floors.items(): + recipe_specifier = recipe_constraints.get(package) + pixi_specifier = pixi_constraints.get(package) + if recipe_specifier is None or floor not in _as_specifier_set(recipe_specifier): + errors.append( + f"{package}: recipe run_constraints must include security floor {floor}" + ) + if pixi_specifier is None or floor not in _as_specifier_set(pixi_specifier): + errors.append( + f"{package}: Pixi constraints must include security floor {floor}" + ) + return errors + + +def _required_feature_errors(pixi: dict, required: tuple[str, ...]) -> list[str]: + errors = [] + required_dependencies = set() + for value in required: + feature, separator, package = value.partition(":") + if not separator or not feature or not package: + raise ValueError( + f"Invalid required feature dependency {value!r}; " + "expected feature:package" + ) + required_dependencies.add((feature, canonicalize_name(package))) + for feature, package in required_dependencies: + if _feature_dependency(pixi, feature, package) is None: + errors.append( + f"Pixi feature {feature!r} must include dependency {package!r}" + ) + return errors + + +def _transitivity_errors( + pixi: dict, + recipe: dict, + project: dict, + recipe_constraints: dict[str, str], + options: RecipeOptions, +) -> list[str]: + aliases = _package_aliases(options.package_aliases) + security_packages = { + aliases.get(package, package) for package in recipe_constraints + } + project_and_recipe_dependencies = _project_dependency_names(project) + project_and_recipe_dependencies.update( + canonicalize_name( + value.split(maxsplit=1)[0].rsplit("::", 1)[-1] + ) + for value in recipe["requirements"].get("run", []) + ) + project_and_recipe_dependencies = { + aliases.get(package, package) for package in project_and_recipe_dependencies + } + direct_security_dependencies = security_packages & project_and_recipe_dependencies + errors = [] + if direct_security_dependencies: + errors.append( + "Security-floor packages must remain transitive in the published recipe " + f"and project dependencies: {sorted(direct_security_dependencies)}" + ) + allowed_pixi = { + canonicalize_name(name) for name in options.allowed_direct_pixi + } + pixi_direct_dependencies = { + aliases.get(package, package) for package in _pixi_direct_dependencies(pixi) + } + pixi_direct = security_packages & pixi_direct_dependencies + disallowed_direct_pixi = pixi_direct - allowed_pixi + if disallowed_direct_pixi: + errors.append( + "Security-floor packages must remain transitive Pixi dependencies: " + f"{sorted(disallowed_direct_pixi)}" + ) + return errors + + +def _pytorch_errors(recipe: dict) -> list[str]: + packages = { + canonicalize_name(value.split(maxsplit=1)[0].rsplit("::", 1)[-1]) + for value in recipe["requirements"].get("run", []) + } + pytorch_packages = sorted( + package for package in packages if package.startswith("pytorch") + ) + if not pytorch_packages: + return [] + return [ + "recipe.yaml requirements.run must leave PyTorch backend selection " + f"to the installer; found: {pytorch_packages}" + ] + + +def validate_recipe( + pixi: dict, recipe: dict, project: dict, options: RecipeOptions +) -> list[str]: + recipe_constraints = dict( + _parse_constraint(value) + for value in recipe["requirements"].get("run_constraints", []) + ) + pixi_constraints = _pixi_constraints( + pixi, recipe_constraints, options.constraints_features + ) + errors = _constraint_errors(recipe_constraints, pixi_constraints, options) + errors.extend(_required_feature_errors(pixi, options.required_feature_dependencies)) + errors.extend( + _transitivity_errors(pixi, recipe, project, recipe_constraints, options) + ) + if options.check_pytorch: + errors.extend(_pytorch_errors(recipe)) + return errors + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--pixi-file", type=Path, default=Path("pixi.toml")) + parser.add_argument("--recipe-file", type=Path, default=Path("recipe.yaml")) + parser.add_argument("--project-file", type=Path, default=Path("pyproject.toml")) + parser.add_argument("--constraints-feature", action="append", default=[]) + parser.add_argument("--security-floor", action="append", default=[]) + parser.add_argument("--allow-direct-pixi", action="append", default=[]) + parser.add_argument("--require-feature-dependency", action="append", default=[]) + parser.add_argument("--package-alias", action="append", default=[]) + parser.add_argument("--check-pytorch", action="store_true") + args = parser.parse_args() + + with args.pixi_file.open("rb") as file: + pixi = tomllib.load(file) + with args.recipe_file.open(encoding="utf-8") as file: + recipe = yaml.safe_load(file) + with args.project_file.open("rb") as file: + project = tomllib.load(file) + errors = validate_recipe( + pixi, + recipe, + project, + RecipeOptions( + constraints_features=tuple(args.constraints_feature), + security_floors=tuple(args.security_floor), + allowed_direct_pixi=tuple(args.allow_direct_pixi), + required_feature_dependencies=tuple(args.require_feature_dependency), + package_aliases=tuple(args.package_alias), + check_pytorch=args.check_pytorch, + ), + ) + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + print("Recipe constraints match Pixi constraints and remain transitive.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/poetry.lock b/poetry.lock index fc77b16..a5feab7 100644 --- a/poetry.lock +++ b/poetry.lock @@ -395,6 +395,91 @@ pytest = ">=6.2.5" [package.extras] dev = ["pre-commit", "pytest-asyncio", "tox"] +[[package]] +name = "pyyaml" +version = "6.0.4" +description = "YAML parser and emitter for Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "pyyaml-6.0.4-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:78be5a1b05a5d1fd46d0290393e5deeb581fa617585462c1b84f7c6b0cb1e489"}, + {file = "pyyaml-6.0.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e39017e1cef43d03b2ba427f60213e4b36dbc6fb092235fa3de3a510ce064d3c"}, + {file = "pyyaml-6.0.4-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:54c23934cf166bb2090d73d82b1388aadb1cead5e73885223dcfa4a459a22d43"}, + {file = "pyyaml-6.0.4-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d58fe9fa2056fed24f055b74d5dc808fa1f5d084c22e4118f0a08253fe677ffd"}, + {file = "pyyaml-6.0.4-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:88a089e6424a8a256321270620d5a4328ad5227fb2061b07d33f596894336914"}, + {file = "pyyaml-6.0.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:52460c6dd874b22d49fda228fac59da74d7a7b06175ffcc80bfa3ba5389d7f73"}, + {file = "pyyaml-6.0.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:c24097c0462f66358c99dc83d3e1850e005f6293cfa1df1edb243428da1668bf"}, + {file = "pyyaml-6.0.4-cp310-cp310-win32.whl", hash = "sha256:34edca7ab64b705ee7c80bf3f9ac609240677db11e83d9317191f483a4b5a433"}, + {file = "pyyaml-6.0.4-cp310-cp310-win_amd64.whl", hash = "sha256:5246a0feaaac497b09c9462aa926280ae02fc8791b0099c0a925ebd7c7f249a6"}, + {file = "pyyaml-6.0.4-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:180ac792c958c2173f6e4467c55ae5f73ab1a9a624ee29fc7095c56d5e3a4055"}, + {file = "pyyaml-6.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:730788375056c43d3ac15bd894c9cd2fb7a931a38b302f408620c64b3ef176ed"}, + {file = "pyyaml-6.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71bb5b87465d88d1dfc577115af6d435bff9b26f2512936f610c26aa55966028"}, + {file = "pyyaml-6.0.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b9fe0b8c65a1611053eb7fcaa7c022f655b7eebeb0ea034572615453cae6b843"}, + {file = "pyyaml-6.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:622aa875fa6533f25fedcffe23079357d65a690d462200afed5d8e9d0e01ebee"}, + {file = "pyyaml-6.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:49e38a95e24738908ea852e61df0abc58d1e4d4f974ccdb2386eaee412bedc67"}, + {file = "pyyaml-6.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4d3bbc5e8a84a5a6775adecac786f489510a7159b1c343d6f31426d888cfdd6e"}, + {file = "pyyaml-6.0.4-cp311-cp311-win32.whl", hash = "sha256:c0d68d972f6f6417b4e85e9522f3d57bb4fbc924379766ccd87254a31009c1cd"}, + {file = "pyyaml-6.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:0db75f402e99c25239003a499c214a61947b4ef5312af34711d4c63e5c179318"}, + {file = "pyyaml-6.0.4-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:1088ad740f50c13178dad16fbc2fa1f634c791d42c7009fdb390e38e5b90b788"}, + {file = "pyyaml-6.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4d30c2f186612bd2f9f07c08a4c96721af59cfc8da3ec7cb27dfa2834e8bb019"}, + {file = "pyyaml-6.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45e37dd647db9d67b757444c74060c064ace5fdaa08f42bf4fda3812275d423e"}, + {file = "pyyaml-6.0.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9e7ec9dc75cadd392fd687cc9b8ccf7dd59ada0a991e0d14ae0fad9ecdba00c3"}, + {file = "pyyaml-6.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:93bfb2459195406a518e2f487a9bbf01df240175f31e06f5a252ac6734c7bbf0"}, + {file = "pyyaml-6.0.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:84e97378010f3da8daf673b82d39ed638098d236a1b760d61c0c1348a642bd70"}, + {file = "pyyaml-6.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f5c410f9e2ffc9286279a46f2e8c107edaf3b1123510af59c828a9c15b23c9db"}, + {file = "pyyaml-6.0.4-cp312-cp312-win32.whl", hash = "sha256:60e9da2772e259307650e03c24f50e3bc2d9fa5ed1ba44c47582e13b0e7708d1"}, + {file = "pyyaml-6.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:131d11bd9b60d705a6388366d77ed67850995a4d2be85fe149785a257c17e531"}, + {file = "pyyaml-6.0.4-cp312-cp312-win_arm64.whl", hash = "sha256:69380d4bae12aab2a2c9532deff6a2841bc9fda47c333691bd2368b696301768"}, + {file = "pyyaml-6.0.4-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:61eef2f08e977b725f37a8d1663f5a222c6f09207ac0794030d5fca062e7c96e"}, + {file = "pyyaml-6.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9d4211f080920629a90c9e31c51e326fb70cfae38f18d4128b9913c23642bace"}, + {file = "pyyaml-6.0.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:41b4669c3a8fd5750e594dff59d3e62d40e321fec467b50449603710ed0a68f3"}, + {file = "pyyaml-6.0.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:efe68ed09903cca9ab4117c2b9ea6ee8d369818808945bb5a7fa8009b5630b45"}, + {file = "pyyaml-6.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50588147ab2c6a59b5f990a4905db80899a6c2bd197e046a6201f1e67587e794"}, + {file = "pyyaml-6.0.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4d1e8d6e345b4b4424a05a11e699e999e65a88f422f73636f8a0b354bf219ffa"}, + {file = "pyyaml-6.0.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a56491babf0d976625807953bd192dd9de973fccb3270e77b1a795b152a26175"}, + {file = "pyyaml-6.0.4-cp313-cp313-win32.whl", hash = "sha256:1631d566655f3af7d6c4a4485267830f6b680d3dc9704b659b3c3f4541b5a3fe"}, + {file = "pyyaml-6.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:0a3a351f04dc124f9357512bdb80ac37cd1750cf1371da33e7cbb96d80ac865f"}, + {file = "pyyaml-6.0.4-cp313-cp313-win_arm64.whl", hash = "sha256:f617e4e5c619fef5284335b24e3af3a77ce08dc5c389ff4b25033bb2749032b7"}, + {file = "pyyaml-6.0.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4a329472db6c8858ebd94f2214a54c8bff8f035a6cc7af1ab39cc1b33a5f0e56"}, + {file = "pyyaml-6.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7335809813ec838d9cd334b1744cda33deb141c9ef23a9c0df371c37980d3851"}, + {file = "pyyaml-6.0.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ed9b957abb12f6ffcd92d5db32fa3ffd4e4a8423d80ddd51b4efa63b42f6a76b"}, + {file = "pyyaml-6.0.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b525488d5addf5d59ff4610cd8b1deab9dc97fe0fb3fb74533d7f65e9792bd92"}, + {file = "pyyaml-6.0.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c604dc2613c417130479cdd6e55c2faa691b6365aa82b3dafddfcecc2eaf1ac7"}, + {file = "pyyaml-6.0.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:f1a4a85b419f5cb6470dd4be5f766bc59532f11b9c22c076b58a0348f05dca5f"}, + {file = "pyyaml-6.0.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:132c3c7c37a8e6f334921b05cfea5d26e241d792dcbb4db0462129d25ca53b43"}, + {file = "pyyaml-6.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:1d2f08c122727c86f8303bb1dd45159ca1de1f2d68798e671ec46974e321008e"}, + {file = "pyyaml-6.0.4-cp314-cp314-win_arm64.whl", hash = "sha256:33506a2620f0e7c49858f09cb44e99f144878d03af3d9c10aa136e9a1d103bcd"}, + {file = "pyyaml-6.0.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:1db4d51d3c2c9545dd44c614febc4594240754f74b30d8e501415b118347f0d1"}, + {file = "pyyaml-6.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:93da48af92c84c4236578e330a514ca324362c0bb62894d8d2343363ed57ff03"}, + {file = "pyyaml-6.0.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c7129bcee5c88c1450802cc6a95b690ee7c51bfcc7a9b60bbd9549a7a4fcbe6"}, + {file = "pyyaml-6.0.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2018fda285d1289527a389e1b4ace1e2d3af410930f949136b55ecb0747744d1"}, + {file = "pyyaml-6.0.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:15c52bb238a15bb4fd7e6342a5ac71d594507667c7fe0e5a5abbc0f6875d1e91"}, + {file = "pyyaml-6.0.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ab874ebcc5c12c31c859a9e9fe159d688df1f7a099818ef8a35906264a8f5d6b"}, + {file = "pyyaml-6.0.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:62c5b5669b05dabf991a705f3a3601f57b65e95121a1d3e3a4ae4446c8632865"}, + {file = "pyyaml-6.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:609e8efaffa5662da16b7d53eef76fc4eedbbe56fce5829b67ba808a6e35d399"}, + {file = "pyyaml-6.0.4-cp314-cp314t-win_arm64.whl", hash = "sha256:a266cf55ee5cf63c1803432a61c6386e750e0012ca49d12d26ccb0ffd80b343a"}, + {file = "pyyaml-6.0.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:12a155bc41509d71a2eb73e2191d9e400c1345ea99ac3d9946c31f40a4c840f8"}, + {file = "pyyaml-6.0.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:070c22b6f490d6cc30912be9fb9ab1af9c752769b39b53616f6510c3f038ee6a"}, + {file = "pyyaml-6.0.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:872d2a592289061c1b987e335b3568a2616b474be02bd0608d8f551a385441cd"}, + {file = "pyyaml-6.0.4-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:914b19e17814315fbcca52031bf79b68237f3d87a948c584a667b18b468e4df7"}, + {file = "pyyaml-6.0.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c57e40928738c4a202852759f9e1ee2c7063429a9469ee1ac15651bbf7d69963"}, + {file = "pyyaml-6.0.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8e0cd755ce5e9009fd95f9c553e5942478feb8f7dffa19435641fcdc3c20e8ca"}, + {file = "pyyaml-6.0.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2c11be5ab4d9f603a598b5ce93a2064ae38087bdf1b384c5397170054cda4e36"}, + {file = "pyyaml-6.0.4-cp315-cp315-win_amd64.whl", hash = "sha256:67da066ca12eb60114ea87f2ecbcca622fff0c205c743cc900437127564fabf6"}, + {file = "pyyaml-6.0.4-cp315-cp315-win_arm64.whl", hash = "sha256:573debb9fe3075423d4f823795a678580e597218c25baef178d532b124a25a25"}, + {file = "pyyaml-6.0.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c680622f85979f2ff59b4ae44c1ecb5566b2f0f0ffe5d0dc8b4bb6a0e916dabb"}, + {file = "pyyaml-6.0.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:18ea9bda247857fc0de05181675dc116b54c1b04ca3db71de5d2108c882823b7"}, + {file = "pyyaml-6.0.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6ac167ebebc0c387290406a337b9b5c8c343fa5f7928d5941e45a94b8ba3aa39"}, + {file = "pyyaml-6.0.4-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4a2a8f27d24d4cdc05aa11df5f4c08e13f30d9e6674809b6a5ddcfcba49a653a"}, + {file = "pyyaml-6.0.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e956541cc7a3fff2bb5b17aeb6c5bb42c86c8e6dafb5ebdd41a05e72e702076b"}, + {file = "pyyaml-6.0.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8708f6ab9c2581ffa05f66dae3206bb0385949650537d7295fc7ab0d6454dd70"}, + {file = "pyyaml-6.0.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a65339c24f2fb8d4419e06ceec1bda98bdcff727b3b533a81d5af6bb2dd34520"}, + {file = "pyyaml-6.0.4-cp315-cp315t-win_amd64.whl", hash = "sha256:a3cc63af3d639d1609143711837b926183418260aae89ed95193c07b25b99d33"}, + {file = "pyyaml-6.0.4-cp315-cp315t-win_arm64.whl", hash = "sha256:d276f23e2371deb5ee68dd252cc9c2402b806b54d8d2cc7efbb6c34c3a78d886"}, + {file = "pyyaml-6.0.4.tar.gz", hash = "sha256:e24bf71af8a432d7808fabff134d38dfe16d3cbb41f2873bb4b1e42422de0a1a"}, +] + [[package]] name = "tomli" version = "2.5.0" @@ -485,4 +570,4 @@ files = [ [metadata] lock-version = "2.1" python-versions = ">=3.12,<4.0" -content-hash = "28a91daf92bd41969e2786767d8820b6d0db39f6f852db16f523fe5689a56e8c" +content-hash = "7ab6de70ad651976ded5825dc73529e994ddfcfd05f844e0795d526a0662afc7" diff --git a/pyproject.toml b/pyproject.toml index a51e01f..15bedb9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,14 +21,18 @@ Repository = "https://github.com/MiraGeoscience/pre-commit-hooks" [project.scripts] check_copyright = "mirageoscience.hooks.check_copyright:main" git_message_hook = "mirageoscience.hooks.git_message_hook:main" +check_pixi_lock = "mirageoscience.hooks.check_pixi_lock:main" +check_recipe = "mirageoscience.hooks.check_recipe:main" [dependency-groups] dev = [ "Pygments", + "packaging", "pylint", "pytest", "pytest-mock", "pytest-cov", + "PyYAML", "tomli", ] diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py new file mode 100644 index 0000000..b18c92f --- /dev/null +++ b/tests/pixi_hooks_test.py @@ -0,0 +1,144 @@ +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Copyright (c) 2024-2026 Mira Geoscience Ltd. ' +# ' +# This file is part of mirageoscience.pre-commit-hooks package. ' +# ' +# mirageoscience.pre-commit-hooks is distributed under the terms and conditions ' +# of the MIT License (see LICENSE file at the root of this source code package). ' +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + +from __future__ import annotations + +from mirageoscience.hooks.check_pixi_lock import LockOptions, validate_lock +from mirageoscience.hooks.check_recipe import RecipeOptions, validate_recipe + + +def _lock_fixture( + *, + features: list[str], + pypi_names: tuple[str, ...] = (), +) -> tuple[dict, dict]: + pixi = { + "feature": { + "mira-pypi": { + "pypi-dependencies": {"mira-package": "*"}, + }, + }, + "environments": {"default": {"features": features}}, + } + packages = [ + {"pypi": f"https://pypi.org/simple/{name}/", "name": name} + for name in pypi_names + ] + entries = [{"pypi": package["pypi"]} for package in packages] + lock = { + "packages": packages, + "environments": {"default": {"packages": {"win-64": entries}}}, + } + return pixi, lock + + +def test_pypi_packages_are_forbidden_without_feature(): + pixi, lock = _lock_fixture(features=[], pypi_names=("mira-package",)) + + errors = validate_lock(pixi, lock, LockOptions(pypi_feature="mira-pypi")) + + assert any("without the 'mira-pypi' feature" in error for error in errors) + + +def test_strict_pypi_rejects_transitive_packages_for_standalone_packages(): + pixi, lock = _lock_fixture( + features=["mira-pypi"], + pypi_names=("mira-package", "transitive-dependency"), + ) + + errors = validate_lock( + pixi, + lock, + LockOptions(pypi_feature="mira-pypi", strict_pypi=True), + ) + + assert any("expected exactly PyPI packages" in error for error in errors) + + +def test_non_strict_pypi_allows_transitive_packages_for_meta_packages(): + pixi, lock = _lock_fixture( + features=["mira-pypi"], + pypi_names=("mira-package", "transitive-dependency"), + ) + + errors = validate_lock(pixi, lock, LockOptions(pypi_feature="mira-pypi")) + + assert not errors + + +def test_recipe_checks_constraints_and_optional_pytorch(): + pixi = { + "constraints": {"filelock": ">=4.2.1"}, + "feature": {}, + } + recipe = { + "requirements": { + "run": ["python >=3.12"], + "run_constraints": ["filelock >=4.2.1"], + } + } + + options = RecipeOptions(check_pytorch=True) + errors = validate_recipe(pixi, recipe, {}, options) + + assert not errors + recipe["requirements"]["run"].append("pytorch-cpu >=2.0") + errors = validate_recipe(pixi, recipe, {}, options) + assert any("PyTorch backend selection" in error for error in errors) + assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) + + +def test_recipe_supports_feature_constraint_sources_and_explicit_floors(): + pixi = { + "constraints": {"filelock": ">=4.2.1", "setuptools": ">=84.1.0"}, + "feature": { + "conda-rt": { + "dependencies": { + "pillow": "13.*", + "defusedxml": ">=0.7.1", + "h5py": "3.15.*", + "psutil": ">=7.2.2", + } + } + }, + } + recipe = { + "requirements": { + "run": ["python >=3.12"], + "run_constraints": [ + "filelock >=4.2.1", + "pillow >=13.0.0", + "setuptools >=84.1.0", + ], + } + } + + options = RecipeOptions( + constraints_features=("conda-rt",), + security_floors=( + "pillow>=13.0.0", + "filelock>=4.2.1", + "setuptools>=84.1.0", + ), + allowed_direct_pixi=("pillow",), + required_feature_dependencies=( + "conda-rt:defusedxml", + "conda-rt:h5py", + "conda-rt:pillow", + "conda-rt:psutil", + ), + ) + errors = validate_recipe( + pixi, + recipe, + {}, + options, + ) + + assert not errors From 696de92d4dbe50b5a5384da95d92cc6d21120f56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:58:49 -0500 Subject: [PATCH 02/20] [GA-9681] Infer recipe constraints from workspace files Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.rst | 12 +- mirageoscience/hooks/check_pixi_lock.py | 12 +- mirageoscience/hooks/check_recipe.py | 253 +++++++++++------------- tests/pixi_hooks_test.py | 33 +--- 4 files changed, 133 insertions(+), 177 deletions(-) diff --git a/README.rst b/README.rst index a215132..de10459 100644 --- a/README.rst +++ b/README.rst @@ -16,8 +16,9 @@ Included Hooks declared by the selected PyPI feature; otherwise transitive PyPI dependencies are allowed while the feature packages are still checked. - ``check-recipe``: Checks recipe ``run_constraints`` against Pixi constraints, - verifies constrained packages remain transitive, and optionally checks that - the recipe leaves PyTorch backend selection to the installer. + discovers matching feature constraints from ``pixi.toml``, verifies constrained + packages remain transitive in published dependencies, and optionally checks + that the recipe leaves PyTorch backend selection to the installer. - ``prepare-commit-msg``: Adds the JIRA ID found in the branch name in case it is missing from the commit message. - ``check-commit-message``: Checks that the branch name or the commit @@ -50,10 +51,9 @@ Example of ``.pre-commit-config.yamnl``: The Pixi hooks read ``pixi.toml``, ``pixi.lock``, ``recipe.yaml``, and ``pyproject.toml`` from the repository root by default. Configure differing -feature names with ``--pypi-feature`` and ``--conda-feature``. For recipe -workspaces with additional Pixi dependency features, ``--constraints-feature`` -can be repeated; use ``--security-floor`` and ``--require-feature-dependency`` -to define package-specific security requirements. +feature names with ``--pypi-feature`` and ``--conda-feature``. Recipe security +floors and their Pixi source are inferred from ``recipe.yaml`` and ``pixi.toml``; +only enable the optional PyTorch check with ``--check-pytorch`` when required. License ^^^^^^^ diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py index 08dd243..94d90b5 100644 --- a/mirageoscience/hooks/check_pixi_lock.py +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -116,9 +116,7 @@ def _expectations(pixi: dict, options: LockOptions) -> LockExpectations: index_urls = ( _index_urls(pixi, index_feature) if options.validate_pypi_sources else set() ) - source_roots = { - f"{url.removesuffix('/simple').rstrip('/')}/" for url in index_urls - } + source_roots = {f"{url.removesuffix('/simple').rstrip('/')}/" for url in index_urls} return LockExpectations(pypi_packages, conda_packages, index_urls, source_roots) @@ -137,7 +135,9 @@ def _source_errors( errors = [] missing_indexes = expectations.index_urls - set(environment_lock.get("indexes", [])) if missing_indexes: - errors.append(f"{label}: missing configured PyPI indexes {sorted(missing_indexes)}") + errors.append( + f"{label}: missing configured PyPI indexes {sorted(missing_indexes)}" + ) for entry in entries: url = entry.get("pypi") if url is None: @@ -179,7 +179,9 @@ def _pypi_errors( f"{label}: PyPI packages are locked without the " f"{options.pypi_feature!r} feature: {sorted(pypi_names)}" ) - errors.extend(_source_errors(label, entries, environment_lock, expected_pypi, context)) + errors.extend( + _source_errors(label, entries, environment_lock, expected_pypi, context) + ) return errors diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index 2777c4d..7db93ec 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -10,7 +10,6 @@ from __future__ import annotations import argparse -import re import sys import tomllib from dataclasses import dataclass @@ -25,10 +24,6 @@ @dataclass(frozen=True) class RecipeOptions: - constraints_features: tuple[str, ...] = () - security_floors: tuple[str, ...] = () - allowed_direct_pixi: tuple[str, ...] = () - required_feature_dependencies: tuple[str, ...] = () package_aliases: tuple[str, ...] = () check_pytorch: bool = False @@ -40,13 +35,6 @@ def _parse_constraint(value: str) -> tuple[str, str]: return canonicalize_name(name), specifier.strip() -def _parse_floor(value: str) -> tuple[str, Version]: - match = re.fullmatch(r"([A-Za-z0-9_.-]+)>=([A-Za-z0-9_.+-]+)", value) - if match is None: - raise ValueError(f"Invalid security floor {value!r}; expected package>=version") - return canonicalize_name(match.group(1)), Version(match.group(2)) - - def _as_specifier_set(value: str) -> SpecifierSet: specifiers = [] for specifier in value.split(","): @@ -67,17 +55,6 @@ def _project_dependency_names(project: dict) -> set[str]: } -def _pixi_direct_dependencies(pixi: dict) -> set[str]: - direct_dependencies = set() - for section in (pixi, *pixi.get("feature", {}).values()): - for dependency_type in ("dependencies", "pypi-dependencies"): - direct_dependencies.update( - canonicalize_name(name) - for name in section.get(dependency_type, {}) - ) - return direct_dependencies - - def _package_aliases(values: tuple[str, ...]) -> dict[str, str]: aliases = {} for value in values: @@ -88,96 +65,131 @@ def _package_aliases(values: tuple[str, ...]) -> dict[str, str]: return aliases -def _feature_dependency(pixi: dict, feature: str, package: str) -> str | None: - feature_data = pixi.get("feature", {}).get(feature, {}) - for dependency_type in ("dependencies", "pypi-dependencies", "constraints"): - dependencies = feature_data.get(dependency_type, {}) - for name, specifier in dependencies.items(): - if canonicalize_name(name) == package: - return str(specifier) - return None - +def _pixi_constraint_sources(pixi: dict, recipe_packages: set[str]) -> dict: + sources: dict[str, list[tuple[str, str]]] = {} + for package, specifier in pixi.get("constraints", {}).items(): + sources.setdefault(canonicalize_name(package), []).append( + (str(specifier), "workspace constraint") + ) -def _pixi_constraints( - pixi: dict, recipe_constraints: dict[str, str], features: tuple[str, ...] -) -> dict[str, str]: - constraints = { - canonicalize_name(name): str(specifier) - for name, specifier in pixi.get("constraints", {}).items() - } - for feature in features: - for package in recipe_constraints: - if package not in constraints: - specifier = _feature_dependency(pixi, feature, package) - if specifier is not None: - constraints[package] = specifier - return constraints + top_level_packages = set(sources) + for feature_name, feature in pixi.get("feature", {}).items(): + for section in ("dependencies", "pypi-dependencies", "constraints"): + for package, specifier in feature.get(section, {}).items(): + normalized = canonicalize_name(package) + if ( + normalized in recipe_packages + and normalized not in top_level_packages + ): + sources.setdefault(normalized, []).append( + (str(specifier), f"feature {feature_name!r} {section}") + ) + return sources + + +def _minimum_version(specifier: str) -> Version | None: + versions = [] + for item in _as_specifier_set(specifier): + if item.operator in (">=", ">", "~="): + versions.append(Version(item.version)) + elif item.operator == "==": + versions.append(Version(item.version.removesuffix(".*"))) + return max(versions, default=None) + + +def _constraint_matches(recipe_specifier: str, pixi_specifier: str) -> bool: + recipe_set = _as_specifier_set(recipe_specifier) + pixi_set = _as_specifier_set(pixi_specifier) + if recipe_set == pixi_set: + return True + if any(item.operator not in (">=", ">") for item in recipe_set): + return False + recipe_floor = _minimum_version(recipe_specifier) + pixi_floor = _minimum_version(pixi_specifier) + return ( + recipe_floor is not None + and recipe_floor == pixi_floor + and recipe_floor in pixi_set + ) def _constraint_errors( - recipe_constraints: dict[str, str], - pixi_constraints: dict[str, str], - options: RecipeOptions, + recipe_constraints: dict[str, str], pixi_sources: dict[str, list[tuple[str, str]]] ) -> list[str]: errors = [] - floors = dict(_parse_floor(value) for value in options.security_floors) - if recipe_constraints.keys() != pixi_constraints.keys(): + if recipe_constraints.keys() != pixi_sources.keys(): errors.append( "recipe.yaml run_constraints must match Pixi constraints; " - f"recipe={sorted(recipe_constraints)}, Pixi={sorted(pixi_constraints)}" + f"recipe={sorted(recipe_constraints)}, Pixi={sorted(pixi_sources)}" ) for package, recipe_specifier in recipe_constraints.items(): - pixi_specifier = pixi_constraints.get(package) - if pixi_specifier is None: - continue - if recipe_specifier == pixi_specifier: - continue - floor = floors.get(package) - if floor is None: - errors.append( - f"{package}: recipe constraint {recipe_specifier!r} does not match " - f"Pixi constraint {pixi_specifier!r}" - ) + sources = pixi_sources.get(package) + if not sources: continue - if ( - floor not in _as_specifier_set(recipe_specifier) - or floor not in _as_specifier_set(pixi_specifier) - ): - errors.append( - f"{package}: recipe and Pixi constraints must both include " - f"security floor {floor}" - ) - for package, floor in floors.items(): - recipe_specifier = recipe_constraints.get(package) - pixi_specifier = pixi_constraints.get(package) - if recipe_specifier is None or floor not in _as_specifier_set(recipe_specifier): + for pixi_specifier, source in sources: + if _constraint_matches(recipe_specifier, pixi_specifier): + continue errors.append( - f"{package}: recipe run_constraints must include security floor {floor}" - ) - if pixi_specifier is None or floor not in _as_specifier_set(pixi_specifier): - errors.append( - f"{package}: Pixi constraints must include security floor {floor}" + f"{package}: recipe constraint {recipe_specifier!r} is not " + f"consistent with {source} {pixi_specifier!r}" ) return errors -def _required_feature_errors(pixi: dict, required: tuple[str, ...]) -> list[str]: - errors = [] - required_dependencies = set() - for value in required: - feature, separator, package = value.partition(":") - if not separator or not feature or not package: - raise ValueError( - f"Invalid required feature dependency {value!r}; " - "expected feature:package" - ) - required_dependencies.add((feature, canonicalize_name(package))) - for feature, package in required_dependencies: - if _feature_dependency(pixi, feature, package) is None: - errors.append( - f"Pixi feature {feature!r} must include dependency {package!r}" +def _pixi_direct_dependencies(pixi: dict) -> tuple[set[str], dict[str, set[str]]]: + root: set[str] = set() + features: dict[str, set[str]] = {} + for dependency_type in ("dependencies", "pypi-dependencies"): + root.update(canonicalize_name(name) for name in pixi.get(dependency_type, {})) + for feature_name, feature in pixi.get("feature", {}).items(): + for dependency_type in ("dependencies", "pypi-dependencies"): + features.setdefault(feature_name, set()).update( + canonicalize_name(name) for name in feature.get(dependency_type, {}) ) - return errors + return root, features + + +def _published_transitivity_errors( + recipe: dict, + project: dict, + security_packages: set[str], + aliases: dict[str, str], +) -> list[str]: + dependencies = _project_dependency_names(project) + dependencies.update( + canonicalize_name(value.split(maxsplit=1)[0].rsplit("::", 1)[-1]) + for value in recipe["requirements"].get("run", []) + ) + dependencies = {aliases.get(package, package) for package in dependencies} + direct_dependencies = security_packages & dependencies + if not direct_dependencies: + return [] + return [ + "Security-floor packages must remain transitive in the published recipe " + f"and project dependencies: {sorted(direct_dependencies)}" + ] + + +def _pixi_transitivity_errors( + pixi: dict, security_packages: set[str], aliases: dict[str, str] +) -> list[str]: + root_dependencies, feature_dependencies = _pixi_direct_dependencies(pixi) + root_dependencies = {aliases.get(package, package) for package in root_dependencies} + top_level_constraints = { + aliases.get(canonicalize_name(package), canonicalize_name(package)) + for package in pixi.get("constraints", {}) + } + direct_root_security = security_packages & root_dependencies + direct_feature_dependencies = set().union(*feature_dependencies.values()) + direct_feature_security = security_packages & direct_feature_dependencies + invalid_feature_security = direct_feature_security & top_level_constraints + invalid_pixi_security = direct_root_security | invalid_feature_security + if not invalid_pixi_security: + return [] + return [ + "Security-floor packages must remain Pixi constraints, not direct " + f"dependencies: {sorted(invalid_pixi_security)}" + ] def _transitivity_errors( @@ -191,37 +203,9 @@ def _transitivity_errors( security_packages = { aliases.get(package, package) for package in recipe_constraints } - project_and_recipe_dependencies = _project_dependency_names(project) - project_and_recipe_dependencies.update( - canonicalize_name( - value.split(maxsplit=1)[0].rsplit("::", 1)[-1] - ) - for value in recipe["requirements"].get("run", []) - ) - project_and_recipe_dependencies = { - aliases.get(package, package) for package in project_and_recipe_dependencies - } - direct_security_dependencies = security_packages & project_and_recipe_dependencies - errors = [] - if direct_security_dependencies: - errors.append( - "Security-floor packages must remain transitive in the published recipe " - f"and project dependencies: {sorted(direct_security_dependencies)}" - ) - allowed_pixi = { - canonicalize_name(name) for name in options.allowed_direct_pixi - } - pixi_direct_dependencies = { - aliases.get(package, package) for package in _pixi_direct_dependencies(pixi) - } - pixi_direct = security_packages & pixi_direct_dependencies - disallowed_direct_pixi = pixi_direct - allowed_pixi - if disallowed_direct_pixi: - errors.append( - "Security-floor packages must remain transitive Pixi dependencies: " - f"{sorted(disallowed_direct_pixi)}" - ) - return errors + return _published_transitivity_errors( + recipe, project, security_packages, aliases + ) + _pixi_transitivity_errors(pixi, security_packages, aliases) def _pytorch_errors(recipe: dict) -> list[str]: @@ -247,11 +231,8 @@ def validate_recipe( _parse_constraint(value) for value in recipe["requirements"].get("run_constraints", []) ) - pixi_constraints = _pixi_constraints( - pixi, recipe_constraints, options.constraints_features - ) - errors = _constraint_errors(recipe_constraints, pixi_constraints, options) - errors.extend(_required_feature_errors(pixi, options.required_feature_dependencies)) + pixi_sources = _pixi_constraint_sources(pixi, set(recipe_constraints)) + errors = _constraint_errors(recipe_constraints, pixi_sources) errors.extend( _transitivity_errors(pixi, recipe, project, recipe_constraints, options) ) @@ -265,10 +246,6 @@ def main() -> int: parser.add_argument("--pixi-file", type=Path, default=Path("pixi.toml")) parser.add_argument("--recipe-file", type=Path, default=Path("recipe.yaml")) parser.add_argument("--project-file", type=Path, default=Path("pyproject.toml")) - parser.add_argument("--constraints-feature", action="append", default=[]) - parser.add_argument("--security-floor", action="append", default=[]) - parser.add_argument("--allow-direct-pixi", action="append", default=[]) - parser.add_argument("--require-feature-dependency", action="append", default=[]) parser.add_argument("--package-alias", action="append", default=[]) parser.add_argument("--check-pytorch", action="store_true") args = parser.parse_args() @@ -284,10 +261,6 @@ def main() -> int: recipe, project, RecipeOptions( - constraints_features=tuple(args.constraints_feature), - security_floors=tuple(args.security_floor), - allowed_direct_pixi=tuple(args.allow_direct_pixi), - required_feature_dependencies=tuple(args.require_feature_dependency), package_aliases=tuple(args.package_alias), check_pytorch=args.check_pytorch, ), diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index b18c92f..1b8e9ba 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -94,16 +94,13 @@ def test_recipe_checks_constraints_and_optional_pytorch(): assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) -def test_recipe_supports_feature_constraint_sources_and_explicit_floors(): - pixi = { +def test_recipe_infers_feature_constraint_source_and_floor(): + pixi: dict = { "constraints": {"filelock": ">=4.2.1", "setuptools": ">=84.1.0"}, "feature": { "conda-rt": { "dependencies": { "pillow": "13.*", - "defusedxml": ">=0.7.1", - "h5py": "3.15.*", - "psutil": ">=7.2.2", } } }, @@ -119,26 +116,10 @@ def test_recipe_supports_feature_constraint_sources_and_explicit_floors(): } } - options = RecipeOptions( - constraints_features=("conda-rt",), - security_floors=( - "pillow>=13.0.0", - "filelock>=4.2.1", - "setuptools>=84.1.0", - ), - allowed_direct_pixi=("pillow",), - required_feature_dependencies=( - "conda-rt:defusedxml", - "conda-rt:h5py", - "conda-rt:pillow", - "conda-rt:psutil", - ), - ) - errors = validate_recipe( - pixi, - recipe, - {}, - options, - ) + errors = validate_recipe(pixi, recipe, {}, RecipeOptions()) assert not errors + + pixi["feature"]["conda-rt"]["dependencies"]["pillow"] = "12.*" + errors = validate_recipe(pixi, recipe, {}, RecipeOptions()) + assert any("pillow" in error for error in errors) From 596280d3fb1656addc18eda4a28d67a90c8d9c9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:11:22 -0500 Subject: [PATCH 03/20] [GA-9681] Default Pixi hook sources and files Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .pre-commit-hooks.yaml | 2 ++ README.rst | 12 ++++++---- mirageoscience/hooks/check_pixi_lock.py | 13 ++++++++--- tests/pixi_hooks_test.py | 29 +++++++++++++++++++++++++ 4 files changed, 49 insertions(+), 7 deletions(-) diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 1c09ebc..cf14cf4 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -12,6 +12,7 @@ language: python additional_dependencies: [packaging>=25, PyYAML>=6] pass_filenames: false + files: ^(pixi\.toml|pixi\.lock|\.pre-commit-config\.yaml|prek\.toml)$ - id: check-recipe name: check recipe constraints @@ -20,6 +21,7 @@ language: python additional_dependencies: [packaging>=25, PyYAML>=6] pass_filenames: false + files: ^(recipe\.yaml|pixi\.toml|pyproject\.toml|\.pre-commit-config\.yaml|prek\.toml)$ - id: prepare-commit-msg name: prepare commit message diff --git a/README.rst b/README.rst index de10459..43155ee 100644 --- a/README.rst +++ b/README.rst @@ -50,10 +50,14 @@ Example of ``.pre-commit-config.yamnl``: - id: check-commit-msg The Pixi hooks read ``pixi.toml``, ``pixi.lock``, ``recipe.yaml``, and -``pyproject.toml`` from the repository root by default. Configure differing -feature names with ``--pypi-feature`` and ``--conda-feature``. Recipe security -floors and their Pixi source are inferred from ``recipe.yaml`` and ``pixi.toml``; -only enable the optional PyTorch check with ``--check-pytorch`` when required. +``pyproject.toml`` from the repository root by default. They also provide default +file filters for these workspace files and the pre-commit configuration, so +consumer configs do not need to repeat ``files``. Configure differing feature +names with ``--pypi-feature`` and ``--conda-feature``. Recipe security floors and +their Pixi source are inferred from ``recipe.yaml`` and ``pixi.toml``; Git sources +from ``git+https://github.com/MiraGeoscience/`` are allowed by default and can be +overridden with ``--git-url-prefix``. Only enable the optional PyTorch check with +``--check-pytorch`` when required. License ^^^^^^^ diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py index 94d90b5..e3369a5 100644 --- a/mirageoscience/hooks/check_pixi_lock.py +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -20,6 +20,9 @@ from packaging.utils import canonicalize_name +DEFAULT_GIT_URL_PREFIXES = ("git+https://github.com/MiraGeoscience/",) + + @dataclass(frozen=True) class LockOptions: pypi_feature: str @@ -27,7 +30,7 @@ class LockOptions: strict_pypi: bool = False pypi_index_feature: str | None = None validate_pypi_sources: bool = False - git_url_prefixes: tuple[str, ...] = () + git_url_prefixes: tuple[str, ...] = DEFAULT_GIT_URL_PREFIXES @dataclass(frozen=True) @@ -290,7 +293,7 @@ def main() -> int: parser.add_argument("--strict-pypi", action="store_true") parser.add_argument("--pypi-index-feature") parser.add_argument("--validate-pypi-sources", action="store_true") - parser.add_argument("--git-url-prefix", action="append", default=[]) + parser.add_argument("--git-url-prefix", action="append") args = parser.parse_args() with args.pixi_file.open("rb") as file: @@ -306,7 +309,11 @@ def main() -> int: strict_pypi=args.strict_pypi, pypi_index_feature=args.pypi_index_feature, validate_pypi_sources=args.validate_pypi_sources, - git_url_prefixes=tuple(args.git_url_prefix), + git_url_prefixes=( + tuple(args.git_url_prefix) + if args.git_url_prefix is not None + else DEFAULT_GIT_URL_PREFIXES + ), ), ) if errors: diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index 1b8e9ba..2c439ff 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -72,6 +72,35 @@ def test_non_strict_pypi_allows_transitive_packages_for_meta_packages(): assert not errors +def test_pypi_source_validation_defaults_to_mira_git_urls(): + index = "https://packages.example.org/simple" + git_url = "git+https://github.com/MiraGeoscience/mira-package.git" + pixi, lock = _lock_fixture( + features=["mira-pypi"], + pypi_names=("mira-package", "mira-git-package"), + ) + pixi["feature"]["mira-pypi"]["pypi-options"] = {"index-url": index} + pixi["feature"]["mira-pypi"]["pypi-dependencies"]["mira-git-package"] = "*" + lock["packages"][0]["pypi"] = f"{index.removesuffix('/simple')}/mira-package.whl" + lock["packages"][1]["pypi"] = git_url + lock["environments"]["default"]["indexes"] = [index] + lock["environments"]["default"]["packages"]["win-64"] = [ + {"pypi": package["pypi"]} for package in lock["packages"] + ] + + errors = validate_lock( + pixi, + lock, + LockOptions( + pypi_feature="mira-pypi", + strict_pypi=True, + validate_pypi_sources=True, + ), + ) + + assert not errors + + def test_recipe_checks_constraints_and_optional_pytorch(): pixi = { "constraints": {"filelock": ">=4.2.1"}, From 345a57568cc9a9b7b42147732212dd9a80849f48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:42:27 -0500 Subject: [PATCH 04/20] [GA-9681] Address Pixi hook review findings Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .pre-commit-hooks.yaml | 2 - README.rst | 4 +- mirageoscience/hooks/check_pixi_lock.py | 82 ++++++++++---- mirageoscience/hooks/check_recipe.py | 39 +++++-- poetry.lock | 6 +- pyproject.toml | 3 +- tests/pixi_hooks_test.py | 142 ++++++++++++++++++++++++ 7 files changed, 242 insertions(+), 36 deletions(-) diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index cf14cf4..f0cf023 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -10,7 +10,6 @@ description: check locked Conda and PyPI sources against Pixi workspace features entry: check_pixi_lock language: python - additional_dependencies: [packaging>=25, PyYAML>=6] pass_filenames: false files: ^(pixi\.toml|pixi\.lock|\.pre-commit-config\.yaml|prek\.toml)$ @@ -19,7 +18,6 @@ description: check recipe security constraints and optional PyTorch backend policy entry: check_recipe language: python - additional_dependencies: [packaging>=25, PyYAML>=6] pass_filenames: false files: ^(recipe\.yaml|pixi\.toml|pyproject\.toml|\.pre-commit-config\.yaml|prek\.toml)$ diff --git a/README.rst b/README.rst index 43155ee..2168bd8 100644 --- a/README.rst +++ b/README.rst @@ -57,7 +57,9 @@ names with ``--pypi-feature`` and ``--conda-feature``. Recipe security floors an their Pixi source are inferred from ``recipe.yaml`` and ``pixi.toml``; Git sources from ``git+https://github.com/MiraGeoscience/`` are allowed by default and can be overridden with ``--git-url-prefix``. Only enable the optional PyTorch check with -``--check-pytorch`` when required. +``--check-pytorch`` when required. For source validation, use the repeatable +``--artifact-source-root`` option to permit download locations outside an +index's URL; PyPI's standard artifact host is allowed automatically. License ^^^^^^^ diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py index e3369a5..1705cfe 100644 --- a/mirageoscience/hooks/check_pixi_lock.py +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -10,6 +10,7 @@ from __future__ import annotations import argparse +import re import sys import tomllib from dataclasses import dataclass @@ -21,6 +22,7 @@ DEFAULT_GIT_URL_PREFIXES = ("git+https://github.com/MiraGeoscience/",) +PYPI_INDEX = "https://pypi.org/simple" @dataclass(frozen=True) @@ -31,6 +33,7 @@ class LockOptions: pypi_index_feature: str | None = None validate_pypi_sources: bool = False git_url_prefixes: tuple[str, ...] = DEFAULT_GIT_URL_PREFIXES + artifact_source_roots: tuple[str, ...] = () @dataclass(frozen=True) @@ -49,14 +52,34 @@ class LockContext: def _feature_dependencies( - pixi: dict, feature_name: str, dependency_type: str + pixi: dict, feature_name: str, dependency_type: str, platform: str ) -> set[str]: try: - dependencies = pixi["feature"][feature_name][dependency_type] + feature = pixi["feature"][feature_name] except KeyError as error: + raise ValueError(f"Pixi feature {feature_name!r} is not defined") from error + targets = feature.get("target", {}) + if dependency_type not in feature and not any( + dependency_type in target for target in targets.values() + ): raise ValueError( f"Pixi feature {feature_name!r} has no {dependency_type!r} table" - ) from error + ) + dependencies = dict(feature.get(dependency_type, {})) + subdir = platform + for candidate in pixi.get("workspace", {}).get("platforms", []): + if isinstance(candidate, dict) and candidate.get("name") == platform: + subdir = candidate.get("platform", platform) + break + family = subdir.split("-", 1)[0] + for selector, target in targets.items(): + pattern = re.escape(selector).replace(r"\*", ".*") + if ( + re.fullmatch(pattern, platform) + or selector == family + or (selector == "unix" and family in {"linux", "osx"}) + ): + dependencies.update(target.get(dependency_type, {})) return {canonicalize_name(name) for name in dependencies} @@ -99,19 +122,18 @@ def _locked_names( def _index_urls(pixi: dict, feature_name: str) -> set[str]: options = pixi["feature"][feature_name].get("pypi-options", {}) urls = set() - for key in ("index-url",): - if url := options.get(key): - urls.add(url.rstrip("/")) + if url := options.get("index-url"): + urls.add(url.rstrip("/")) urls.update(url.rstrip("/") for url in options.get("extra-index-urls", [])) return urls -def _expectations(pixi: dict, options: LockOptions) -> LockExpectations: +def _expectations(pixi: dict, options: LockOptions, platform: str) -> LockExpectations: pypi_packages = _feature_dependencies( - pixi, options.pypi_feature, "pypi-dependencies" + pixi, options.pypi_feature, "pypi-dependencies", platform ) conda_packages = ( - _feature_dependencies(pixi, options.conda_feature, "dependencies") + _feature_dependencies(pixi, options.conda_feature, "dependencies", platform) if options.conda_feature else set() ) @@ -119,7 +141,19 @@ def _expectations(pixi: dict, options: LockOptions) -> LockExpectations: index_urls = ( _index_urls(pixi, index_feature) if options.validate_pypi_sources else set() ) - source_roots = {f"{url.removesuffix('/simple').rstrip('/')}/" for url in index_urls} + source_indexes = set(index_urls) + if options.validate_pypi_sources and not pixi["feature"][index_feature].get( + "pypi-options", {} + ).get("index-url"): + source_indexes.add(PYPI_INDEX) + source_roots = { + f"{url.removesuffix('/simple').rstrip('/')}/" for url in source_indexes + } + if PYPI_INDEX in source_indexes: + source_roots.add("https://files.pythonhosted.org/") + source_roots.update( + f"{root.rstrip('/')}/" for root in options.artifact_source_roots + ) return LockExpectations(pypi_packages, conda_packages, index_urls, source_roots) @@ -127,12 +161,12 @@ def _source_errors( label: str, entries: list[dict], environment_lock: dict, - expected_pypi: set[str], + pypi_feature_enabled: bool, context: LockContext, ) -> list[str]: options = context.options expectations = context.expectations - if not options.validate_pypi_sources or not expected_pypi: + if not options.validate_pypi_sources or not pypi_feature_enabled: return [] errors = [] @@ -183,7 +217,9 @@ def _pypi_errors( f"{options.pypi_feature!r} feature: {sorted(pypi_names)}" ) errors.extend( - _source_errors(label, entries, environment_lock, expected_pypi, context) + _source_errors( + label, entries, environment_lock, options.pypi_feature in features, context + ) ) return errors @@ -243,22 +279,28 @@ def _validate_environment( pixi: dict, environment_name: str, environment_lock: dict, - context: LockContext, + options: LockOptions, + packages_by_url: dict[str, str], ) -> list[str]: - environment_config = pixi["environments"].get(environment_name) + environment_config = pixi.get("environments", {}).get(environment_name) if environment_config is None: - return [f"{environment_name}: missing Pixi environment definition"] + if environment_name != "default": + return [f"{environment_name}: missing Pixi environment definition"] + environment_config = [] features = _environment_features(environment_config) errors = [] for platform, entries in environment_lock["packages"].items(): label = f"{environment_name}/{platform}" + platform_context = LockContext( + options, _expectations(pixi, options, platform), packages_by_url + ) errors.extend( _validate_platform( label, entries, environment_lock, features, - context, + platform_context, ) ) return errors @@ -270,7 +312,6 @@ def validate_lock(pixi: dict, lock: dict, options: LockOptions) -> list[str]: for package in lock["packages"] if "pypi" in package } - context = LockContext(options, _expectations(pixi, options), packages_by_url) errors = [] for environment_name, environment_lock in lock["environments"].items(): errors.extend( @@ -278,7 +319,8 @@ def validate_lock(pixi: dict, lock: dict, options: LockOptions) -> list[str]: pixi, environment_name, environment_lock, - context, + options, + packages_by_url, ) ) return errors @@ -294,6 +336,7 @@ def main() -> int: parser.add_argument("--pypi-index-feature") parser.add_argument("--validate-pypi-sources", action="store_true") parser.add_argument("--git-url-prefix", action="append") + parser.add_argument("--artifact-source-root", action="append", default=[]) args = parser.parse_args() with args.pixi_file.open("rb") as file: @@ -309,6 +352,7 @@ def main() -> int: strict_pypi=args.strict_pypi, pypi_index_feature=args.pypi_index_feature, validate_pypi_sources=args.validate_pypi_sources, + artifact_source_roots=tuple(args.artifact_source_root), git_url_prefixes=( tuple(args.git_url_prefix) if args.git_url_prefix is not None diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index 7db93ec..22a5a6b 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -36,6 +36,8 @@ def _parse_constraint(value: str) -> tuple[str, str]: def _as_specifier_set(value: str) -> SpecifierSet: + if value in ("", "*"): + return SpecifierSet() specifiers = [] for specifier in value.split(","): specifier = specifier.strip() @@ -69,7 +71,7 @@ def _pixi_constraint_sources(pixi: dict, recipe_packages: set[str]) -> dict: sources: dict[str, list[tuple[str, str]]] = {} for package, specifier in pixi.get("constraints", {}).items(): sources.setdefault(canonicalize_name(package), []).append( - (str(specifier), "workspace constraint") + (_pixi_version(specifier), "workspace constraint") ) top_level_packages = set(sources) @@ -82,11 +84,20 @@ def _pixi_constraint_sources(pixi: dict, recipe_packages: set[str]) -> dict: and normalized not in top_level_packages ): sources.setdefault(normalized, []).append( - (str(specifier), f"feature {feature_name!r} {section}") + ( + _pixi_version(specifier), + f"feature {feature_name!r} {section}", + ) ) return sources +def _pixi_version(specifier: object) -> str: + if isinstance(specifier, dict): + return str(specifier.get("version", "")) + return str(specifier) + + def _minimum_version(specifier: str) -> Version | None: versions = [] for item in _as_specifier_set(specifier): @@ -139,13 +150,19 @@ def _constraint_errors( def _pixi_direct_dependencies(pixi: dict) -> tuple[set[str], dict[str, set[str]]]: root: set[str] = set() features: dict[str, set[str]] = {} - for dependency_type in ("dependencies", "pypi-dependencies"): - root.update(canonicalize_name(name) for name in pixi.get(dependency_type, {})) + + def dependencies(section: dict) -> set[str]: + tables = [section, *section.get("target", {}).values()] + return { + canonicalize_name(name) + for table in tables + for dependency_type in ("dependencies", "pypi-dependencies") + for name in table.get(dependency_type, {}) + } + + root.update(dependencies(pixi)) for feature_name, feature in pixi.get("feature", {}).items(): - for dependency_type in ("dependencies", "pypi-dependencies"): - features.setdefault(feature_name, set()).update( - canonicalize_name(name) for name in feature.get(dependency_type, {}) - ) + features[feature_name] = dependencies(feature) return root, features @@ -180,7 +197,11 @@ def _pixi_transitivity_errors( for package in pixi.get("constraints", {}) } direct_root_security = security_packages & root_dependencies - direct_feature_dependencies = set().union(*feature_dependencies.values()) + direct_feature_dependencies = { + aliases.get(package, package) + for packages in feature_dependencies.values() + for package in packages + } direct_feature_security = security_packages & direct_feature_dependencies invalid_feature_security = direct_feature_security & top_level_constraints invalid_pixi_security = direct_root_security | invalid_feature_security diff --git a/poetry.lock b/poetry.lock index a5feab7..9af64b5 100644 --- a/poetry.lock +++ b/poetry.lock @@ -265,7 +265,7 @@ version = "26.3" description = "Core utilities for Python packages" optional = false python-versions = ">=3.9" -groups = ["dev"] +groups = ["main", "dev"] files = [ {file = "packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c"}, {file = "packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79"}, @@ -401,7 +401,7 @@ version = "6.0.4" description = "YAML parser and emitter for Python" optional = false python-versions = ">=3.10" -groups = ["dev"] +groups = ["main"] files = [ {file = "pyyaml-6.0.4-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:78be5a1b05a5d1fd46d0290393e5deeb581fa617585462c1b84f7c6b0cb1e489"}, {file = "pyyaml-6.0.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e39017e1cef43d03b2ba427f60213e4b36dbc6fb092235fa3de3a510ce064d3c"}, @@ -570,4 +570,4 @@ files = [ [metadata] lock-version = "2.1" python-versions = ">=3.12,<4.0" -content-hash = "7ab6de70ad651976ded5825dc73529e994ddfcfd05f844e0795d526a0662afc7" +content-hash = "f03009e6dc1ed4172f4522feba900d3c29ed8eafbcc57e451991977eedb49614" diff --git a/pyproject.toml b/pyproject.toml index 15bedb9..d37b1cf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,6 +9,7 @@ build-backend = "poetry_dynamic_versioning.backend" name = "mirageoscience.pre-commit-hooks" requires-python = ">=3.12,<4.0" dynamic = ["version"] +dependencies = ["packaging>=25", "PyYAML>=6"] description = "" readme = "README.rst" @@ -27,12 +28,10 @@ check_recipe = "mirageoscience.hooks.check_recipe:main" [dependency-groups] dev = [ "Pygments", - "packaging", "pylint", "pytest", "pytest-mock", "pytest-cov", - "PyYAML", "tomli", ] diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index 2c439ff..562d9df 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -9,6 +9,8 @@ from __future__ import annotations +import pytest + from mirageoscience.hooks.check_pixi_lock import LockOptions, validate_lock from mirageoscience.hooks.check_recipe import RecipeOptions, validate_recipe @@ -101,6 +103,98 @@ def test_pypi_source_validation_defaults_to_mira_git_urls(): assert not errors +def test_target_specific_feature_dependencies_are_checked_per_platform(): + pixi, lock = _lock_fixture(features=["mira-pypi", "conda-rt"]) + pixi["feature"]["mira-pypi"] = { + "target": { + "win-64": {"pypi-dependencies": {"win-package": "*"}}, + "linux": {"pypi-dependencies": {"linux-package": "*"}}, + } + } + pixi["feature"]["conda-rt"] = { + "dependencies": {"base-package": "*"}, + "target": {"win-64": {"dependencies": {"win-conda": "*"}}}, + } + win_url = "https://example.org/win.whl" + linux_url = "https://example.org/linux.whl" + lock["packages"] = [ + {"pypi": win_url, "name": "win-package"}, + {"pypi": linux_url, "name": "linux-package"}, + ] + base = {"conda": "https://example.org/base-package-1-0.conda"} + win = {"conda": "https://example.org/win-conda-1-0.conda"} + lock["environments"]["default"]["packages"] = { + "win-64": [{"pypi": win_url}, base, win], + "linux-64": [{"pypi": linux_url}, base], + } + options = LockOptions("mira-pypi", conda_feature="conda-rt", strict_pypi=True) + + assert not validate_lock(pixi, lock, options) + lock["environments"]["default"]["packages"]["win-64"].remove(win) + assert any("win-conda" in error for error in validate_lock(pixi, lock, options)) + + +@pytest.mark.parametrize("configured", [True, False]) +def test_pypi_source_validation_accepts_public_pypi_artifact_host(configured): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + if configured: + pixi["feature"]["mira-pypi"]["pypi-options"] = { + "index-url": "https://pypi.org/simple" + } + url = "https://files.pythonhosted.org/packages/mira-package.whl" + lock["packages"][0]["pypi"] = url + if configured: + lock["environments"]["default"]["indexes"] = ["https://pypi.org/simple"] + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + options = LockOptions("mira-pypi", validate_pypi_sources=True) + + assert not validate_lock(pixi, lock, options) + url = "https://files.pythonhosted.org.evil.example/package.whl" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + assert any( + "unexpected PyPI source" in error + for error in validate_lock(pixi, lock, options) + ) + + +def test_pypi_source_validation_accepts_configured_artifact_root(): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + pixi["feature"]["mira-pypi"]["pypi-options"] = { + "index-url": "https://index.example/simple" + } + url = "https://artifacts.example/packages/mira-package.whl" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["indexes"] = ["https://index.example/simple"] + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + options = LockOptions("mira-pypi", validate_pypi_sources=True) + assert any( + "unexpected PyPI source" in error + for error in validate_lock(pixi, lock, options) + ) + options = LockOptions( + "mira-pypi", + validate_pypi_sources=True, + artifact_source_roots=("https://artifacts.example/packages",), + ) + assert not validate_lock(pixi, lock, options) + + +@pytest.mark.parametrize("environments", [None, {"other": []}]) +def test_implicit_default_environment_and_unknown_named_environment(environments): + pixi, lock = _lock_fixture(features=[]) + if environments is None: + del pixi["environments"] + else: + pixi["environments"] = environments + assert not validate_lock(pixi, lock, LockOptions("mira-pypi")) + lock["environments"]["unknown"] = lock["environments"]["default"] + assert any( + "unknown: missing" in error + for error in validate_lock(pixi, lock, LockOptions("mira-pypi")) + ) + + def test_recipe_checks_constraints_and_optional_pytorch(): pixi = { "constraints": {"filelock": ">=4.2.1"}, @@ -152,3 +246,51 @@ def test_recipe_infers_feature_constraint_source_and_floor(): pixi["feature"]["conda-rt"]["dependencies"]["pillow"] = "12.*" errors = validate_recipe(pixi, recipe, {}, RecipeOptions()) assert any("pillow" in error for error in errors) + + +def test_recipe_accepts_inline_versions_but_rejects_versionless_dependencies(): + pixi = { + "feature": { + "conda-rt": { + "dependencies": { + "pillow": {"version": "13.*", "channel": "conda-forge"} + } + } + } + } + recipe = {"requirements": {"run_constraints": ["pillow >=13.0.0"]}} + assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) + pixi["feature"]["conda-rt"]["dependencies"]["pillow"] = {"path": "../pillow"} + assert any( + "pillow" in error + for error in validate_recipe(pixi, recipe, {}, RecipeOptions()) + ) + + +@pytest.mark.parametrize("section", ["root", "feature"]) +def test_recipe_rejects_target_specific_direct_security_dependencies(section): + pixi: dict = {"constraints": {"filelock": ">=4.2.1"}} + target = {"win-64": {"dependencies": {"filelock": "*"}}} + if section == "root": + pixi["target"] = target + else: + pixi["feature"] = {"extra": {"target": target}} + recipe = {"requirements": {"run_constraints": ["filelock >=4.2.1"]}} + assert any( + "not direct dependencies" in error + for error in validate_recipe(pixi, recipe, {}, RecipeOptions()) + ) + + +def test_recipe_applies_aliases_to_feature_dependencies(): + pixi = { + "constraints": {"pytorch": ">=2.0"}, + "feature": {"extra": {"pypi-dependencies": {"torch": "*"}}}, + } + recipe = {"requirements": {"run_constraints": ["pytorch >=2.0"]}} + assert any( + "not direct dependencies" in error + for error in validate_recipe( + pixi, recipe, {}, RecipeOptions(package_aliases=("torch=pytorch",)) + ) + ) From 23def6449800542fbad755b17c633d9f33a2002a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:36:29 -0500 Subject: [PATCH 05/20] [GA-9681] Reject unsafe Git source URLs Validate Git URL authorities and reject ambiguous paths to prevent allowlist bypass via traversal or host spoofing. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- mirageoscience/hooks/check_pixi_lock.py | 31 ++++++++++++++++- tests/pixi_hooks_test.py | 45 +++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py index 1705cfe..d5a50e4 100644 --- a/mirageoscience/hooks/check_pixi_lock.py +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -157,6 +157,35 @@ def _expectations(pixi: dict, options: LockOptions, platform: str) -> LockExpect return LockExpectations(pypi_packages, conda_packages, index_urls, source_roots) +def _allowed_git_source(url: str, prefixes: tuple[str, ...]) -> bool: + if any(ord(char) < 32 or ord(char) == 127 for char in url): + return False + try: + parsed = urlsplit(url) + path = parsed.path + while True: + decoded = unquote(path) + if decoded == path: + break + if decoded.count("/") != path.count("/"): + return False + path = decoded + if ( + "\\" in path + or any(ord(char) < 32 or ord(char) == 127 for char in path) + or any(segment in {".", ".."} for segment in path.split("/")) + ): + return False + return any( + url.startswith(prefix) + and parsed.scheme == urlsplit(prefix).scheme + and parsed.netloc == urlsplit(prefix).netloc + for prefix in prefixes + ) + except ValueError: + return False + + def _source_errors( label: str, entries: list[dict], @@ -180,7 +209,7 @@ def _source_errors( if url is None: continue if url.startswith("git+"): - if not any(url.startswith(prefix) for prefix in options.git_url_prefixes): + if not _allowed_git_source(url, options.git_url_prefixes): errors.append(f"{label}: unexpected Git source {url}") elif not any(url.startswith(root) for root in expectations.source_roots): errors.append(f"{label}: unexpected PyPI source {url}") diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index 562d9df..8ef6c36 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -103,6 +103,51 @@ def test_pypi_source_validation_defaults_to_mira_git_urls(): assert not errors +@pytest.mark.parametrize( + "git_url", + [ + "git+https://github.com/MiraGeoscience/../attacker/package.git", + "git+https://github.com/MiraGeoscience/%2e%2e/attacker/package.git", + "git+https://github.com/MiraGeoscience/%252e%252e/attacker/package.git", + "git+https://github.com/MiraGeoscience/%2f..%2fattacker/package.git", + "git+https://github.com/MiraGeoscience/%252f..%252fattacker/package.git", + "git+https://github.com/MiraGeoscience/%5c..%5cattacker/package.git", + "git+https://github.com/MiraGeoscience/package%0a.git", + "git+https://github.com/MiraGeoscience/..\\attacker/package.git", + ], +) +def test_pypi_source_validation_rejects_git_path_traversal(git_url): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + lock["packages"][0]["pypi"] = git_url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": git_url}] + + errors = validate_lock( + pixi, lock, LockOptions("mira-pypi", validate_pypi_sources=True) + ) + + assert any("unexpected Git source" in error for error in errors) + + +def test_pypi_source_validation_matches_git_host_for_custom_prefix(): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + url = "git+https://github.com.evil.example/MiraGeoscience/package.git" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + options = LockOptions( + "mira-pypi", + validate_pypi_sources=True, + git_url_prefixes=("git+https://github.com",), + ) + assert any( + "unexpected Git source" in error for error in validate_lock(pixi, lock, options) + ) + + url = "git+https://github.com/other/package%2dname.git@v1.0#subdirectory=python" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + assert not validate_lock(pixi, lock, options) + + def test_target_specific_feature_dependencies_are_checked_per_platform(): pixi, lock = _lock_fixture(features=["mira-pypi", "conda-rt"]) pixi["feature"]["mira-pypi"] = { From e1727d837565e7cd89a535a07675fa4af31667bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:47:04 -0500 Subject: [PATCH 06/20] exclude pytorch backend from recipe, not pytorch itself --- mirageoscience/hooks/check_recipe.py | 27 +++++++++++------- tests/pixi_hooks_test.py | 41 ++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index 22a5a6b..f612c14 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -10,6 +10,7 @@ from __future__ import annotations import argparse +import re import sys import tomllib from dataclasses import dataclass @@ -230,18 +231,24 @@ def _transitivity_errors( def _pytorch_errors(recipe: dict) -> list[str]: - packages = { - canonicalize_name(value.split(maxsplit=1)[0].rsplit("::", 1)[-1]) - for value in recipe["requirements"].get("run", []) - } - pytorch_packages = sorted( - package for package in packages if package.startswith("pytorch") - ) - if not pytorch_packages: + backend_specs = [] + for section in ("run", "run_constraints"): + for value in recipe["requirements"].get(section, []): + match = re.match(r"^(?:[^\s:]+::)?([a-zA-Z0-9_.-]+)(.*)$", value.strip()) + if not match: + continue + package = canonicalize_name(match.group(1)) + specifier = match.group(2) + if package in {"pytorch-cpu", "pytorch-gpu", "pytorch-cuda", "cpuonly"} or ( + package in {"pytorch", "pytorch-mutex"} + and re.search(r"cpu|cuda|gpu", specifier, re.IGNORECASE) + ): + backend_specs.append(f"{section}: {value}") + if not backend_specs: return [] return [ - "recipe.yaml requirements.run must leave PyTorch backend selection " - f"to the installer; found: {pytorch_packages}" + "recipe.yaml requirements must leave PyTorch backend selection " + f"to the installer; found: {backend_specs}" ] diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index 8ef6c36..6931c92 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -262,6 +262,47 @@ def test_recipe_checks_constraints_and_optional_pytorch(): assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) +@pytest.mark.parametrize( + "dependency", + [ + "pytorch", + "pytorch >=2.13.0,<2.15.0", + "conda-forge::pytorch >=2.13.0, <2.15.0", + "pytorch=2.14", + "pytorch-lightning >=2.0", + ], +) +def test_recipe_allows_backend_neutral_pytorch(dependency): + recipe = {"requirements": {"run": [dependency]}} + assert not validate_recipe({}, recipe, {}, RecipeOptions(check_pytorch=True)) + + +@pytest.mark.parametrize( + "dependency", + [ + "pytorch-cpu >=2.0", + "conda-forge::pytorch_gpu >=2.0", + "pytorch-cuda >=12", + "cpuonly", + "pytorch >=2.0 cpu*", + "pytorch=2.14=*cuda*", + "pytorch[version='>=2.0',build='cuda*']", + "pytorch-mutex 1.0 cuda", + ], +) +def test_recipe_rejects_pytorch_backend_selection(dependency): + recipe = {"requirements": {"run": [dependency]}} + errors = validate_recipe({}, recipe, {}, RecipeOptions(check_pytorch=True)) + assert any("PyTorch backend selection" in error for error in errors) + assert not validate_recipe({}, recipe, {}, RecipeOptions()) + + +def test_recipe_rejects_pytorch_backend_run_constraint(): + recipe = {"requirements": {"run_constraints": ["pytorch >=2.0 cpu*"]}} + errors = validate_recipe({}, recipe, {}, RecipeOptions(check_pytorch=True)) + assert any("PyTorch backend selection" in error for error in errors) + + def test_recipe_infers_feature_constraint_source_and_floor(): pixi: dict = { "constraints": {"filelock": ">=4.2.1", "setuptools": ">=84.1.0"}, From 943012770670ee8e202f91aa748da100146f7a66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:39:14 -0500 Subject: [PATCH 07/20] support multi-line inline table in toml --- mirageoscience/hooks/check_pixi_lock.py | 4 +- mirageoscience/hooks/check_recipe.py | 6 +- poetry.lock | 79 +--------------------- pyproject.toml | 3 +- tests/pixi_hooks_test.py | 87 ++++++++++++++++++++++++- 5 files changed, 93 insertions(+), 86 deletions(-) diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py index d5a50e4..2be2623 100644 --- a/mirageoscience/hooks/check_pixi_lock.py +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -12,11 +12,11 @@ import argparse import re import sys -import tomllib from dataclasses import dataclass from pathlib import Path from urllib.parse import unquote, urlsplit +import tomlkit import yaml from packaging.utils import canonicalize_name @@ -369,7 +369,7 @@ def main() -> int: args = parser.parse_args() with args.pixi_file.open("rb") as file: - pixi = tomllib.load(file) + pixi = tomlkit.load(file).unwrap() with args.lock_file.open(encoding="utf-8") as file: lock = yaml.safe_load(file) errors = validate_lock( diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index f612c14..4203ef6 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -12,10 +12,10 @@ import argparse import re import sys -import tomllib from dataclasses import dataclass from pathlib import Path +import tomlkit import yaml from packaging.requirements import Requirement from packaging.specifiers import SpecifierSet @@ -279,11 +279,11 @@ def main() -> int: args = parser.parse_args() with args.pixi_file.open("rb") as file: - pixi = tomllib.load(file) + pixi = tomlkit.load(file).unwrap() with args.recipe_file.open(encoding="utf-8") as file: recipe = yaml.safe_load(file) with args.project_file.open("rb") as file: - project = tomllib.load(file) + project = tomlkit.load(file).unwrap() errors = validate_recipe( pixi, recipe, diff --git a/poetry.lock b/poetry.lock index 9af64b5..a9710f3 100644 --- a/poetry.lock +++ b/poetry.lock @@ -480,88 +480,13 @@ files = [ {file = "pyyaml-6.0.4.tar.gz", hash = "sha256:e24bf71af8a432d7808fabff134d38dfe16d3cbb41f2873bb4b1e42422de0a1a"}, ] -[[package]] -name = "tomli" -version = "2.5.0" -description = "A lil' TOML parser" -optional = false -python-versions = ">=3.8" -groups = ["dev"] -files = [ - {file = "tomli-2.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c4dc1c1781f2f716de763d1e9a7b34c6a894e167e291c7c5d16c72f7a9538545"}, - {file = "tomli-2.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:eff8babca5a7999bc137acbc7482a8b7e17ffca5075ab41f5d770ab408c7bfef"}, - {file = "tomli-2.5.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:86665cee9c4835b7a7f1e8ec2c719b5258d4dc782887aded5a8ae7352a96843b"}, - {file = "tomli-2.5.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7e369fd63331746182360977b1892bfc215476a30d61612d732425311639f56"}, - {file = "tomli-2.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7ad1ea345759240d6463efa0ed1c704402752e49aa21476620738d74d72d8aa1"}, - {file = "tomli-2.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96243987194634bd411066ce40c952e108f86af04db533ecd8ac3ff2a85b1885"}, - {file = "tomli-2.5.0-cp311-cp311-win32.whl", hash = "sha256:610b27d99f28ec5f191c7064a48f3ddb179a1fe6ca73d571483ae859f57b605e"}, - {file = "tomli-2.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:c804ae44fe7b4bab5da295e4f980a1ff04670bca9d23fe0a4e887e08ebd741a8"}, - {file = "tomli-2.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:cfac177ebd6236003846ea339981f71457cb6eb748f23381eb257e45092e3980"}, - {file = "tomli-2.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1f4a40d03fb9f63424f0979855bdeaf44dd7696b8d59501822c10ed30ba532df"}, - {file = "tomli-2.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9ebf8d19b17bd0daeb7b7dec81a946a439b753942fd0210d6e96c532249eea6b"}, - {file = "tomli-2.5.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf0b5e8e0f68ebb494356e577c06c139161efd8d3b9050f93b39b7c26cc54ff0"}, - {file = "tomli-2.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6cf74416bdc94ae458b14e37286c1073081850ac8459a00d0c5efef5d44294c6"}, - {file = "tomli-2.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:61ea1ebe1e55a34ea8199cc8dbff398d35027b82271c8ac4802fd3a1fd5b1bcc"}, - {file = "tomli-2.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ed53f7e89bb04f6d9e8e7799112360b0c4d5cbff067de0814c98c37c39b920f7"}, - {file = "tomli-2.5.0-cp312-cp312-win32.whl", hash = "sha256:e7ad033e27a516a233bea839cdb77b80146facb3b4f40bf02cd0cac165cdd5c2"}, - {file = "tomli-2.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:bd05de8c1698f8413dd7d869492693a0bf2211543b787ac78cd5e7536af1a6d7"}, - {file = "tomli-2.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:069435bd5480429b98c5e5afb02ab21c219b6f0064680671c6dc0d46817346ea"}, - {file = "tomli-2.5.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:943276cf269e0071948d9ff697159c1735e623c1151d88abb09b74659ef0cbea"}, - {file = "tomli-2.5.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:463b16086865b97facd8d0b3fb4cb7c544e3f58d2a69dc3113d6db9653fdb043"}, - {file = "tomli-2.5.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1245a6638fc4bb0a60af38a7d45413db34a13842027c77597c712c998c62fdf0"}, - {file = "tomli-2.5.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5d8bac3d603c97e6854424e5b2b5b741bdbde387e09f162fb0446812b4a8362b"}, - {file = "tomli-2.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:21e4cae4114aba25aa0d4f85cdf486d290fb35c0954d7bba536248da64d43066"}, - {file = "tomli-2.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:bbaefc84548d754be821bba7c4141c4787dda182f9e77f2f87b71213529efa7b"}, - {file = "tomli-2.5.0-cp313-cp313-win32.whl", hash = "sha256:abdbf6313b8d9efe157edeb7ab6eae4de064b1300ad31abf73755154b30abe68"}, - {file = "tomli-2.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:fd4dc129784e0c5335bd4e61dfcc4487499a013419e655cf2da1d091b7e0efdc"}, - {file = "tomli-2.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:69491c143d2fe063046e0301e62a810bed338fa4d1ce0fd870c27dc1e09b0d84"}, - {file = "tomli-2.5.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d3182ee2d887e507bd67319a0a61105d1dd33facc111329559a233b772c1a105"}, - {file = "tomli-2.5.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:521345fd1f19d45b8df87657aaa38b6f2ca3800059fadf428e7ebf479a383646"}, - {file = "tomli-2.5.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6e95c7614e705bfe2b04b27aa124adec59752d15813df37e2156747cab3a006b"}, - {file = "tomli-2.5.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7ac2027d37c3afbdf4bdd377f2676f6f1d2122a5be1f1137b49dced590b37e75"}, - {file = "tomli-2.5.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c414be4ed9d3cac80c42e348fa5a956117d1a48227f48026e31f59cb4a7671eb"}, - {file = "tomli-2.5.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9b03d7dc168353b4132965bde20feceabaa470e570c6f59660dfae59b1f9eeb3"}, - {file = "tomli-2.5.0-cp314-cp314-win32.whl", hash = "sha256:6f041843c4d3a37245c0c056fd955b186bf8b1fb85690cbe40b81230891dc34b"}, - {file = "tomli-2.5.0-cp314-cp314-win_amd64.whl", hash = "sha256:f4b653094e18f9031102d3a1da5c729c8f222d85225b18037dac621695e46e1a"}, - {file = "tomli-2.5.0-cp314-cp314-win_arm64.whl", hash = "sha256:3f89d10c1ff6a38d992c27fc8a4816af71a909e08a40ec66934240b1e74347c3"}, - {file = "tomli-2.5.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:e9e15b4a6c7dd6b85b5fbab29488a73f1f70de516942308daa266bf0e0aeb0d4"}, - {file = "tomli-2.5.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e12bbcd32897272fb05929110362ae9ff4c1b9bb26bd9e971e71dcd3275b4c3d"}, - {file = "tomli-2.5.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20aa36de8f2cf87237143bc1fa1aae8d6612c09118f4da21c6a684db5dd1f6f9"}, - {file = "tomli-2.5.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22185fad8a1e622f064e78008018a0dd3323550dcb479cb7a1d296888d74024f"}, - {file = "tomli-2.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:984012f71908165449a951de2050d52f276bfe3aa5d5f570f63ddad814370374"}, - {file = "tomli-2.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f79203b3965b4000e91808aaa7c040206093f2b8bf86f455982f2274c9ccf442"}, - {file = "tomli-2.5.0-cp314-cp314t-win32.whl", hash = "sha256:91294a9fb94a75542f6e46e4a2ae709bd8d9b51134098cae5cf3bea5478b6d03"}, - {file = "tomli-2.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:f15e3e0b835a6d68b10c86bf80a3149780498d6911c93c3ffd1861d19f9200f1"}, - {file = "tomli-2.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:6664b7ae7af7294256c53960a6103077f4914cec8ff98479c352f622c6f6b2f0"}, - {file = "tomli-2.5.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:a525685c2f97da40762b8695eb7aa0af4c8344ca1905c73e4e29cb04d34607dc"}, - {file = "tomli-2.5.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:9dbb18c1cfb2f6517942fc9314437f66aa06d94436ffb1f06102ef3572f35276"}, - {file = "tomli-2.5.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:752e8b1aa6a4367ef8bf6a1a1e005540f7ed055ba36d7193796812ca5404eb52"}, - {file = "tomli-2.5.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c47300f9bf791808f77d82747691c4bb09cb14bdf3060cca99b42cdc4361d5a7"}, - {file = "tomli-2.5.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:19b0dd8749f4ea2f112c5fcfb3c5248390c899d7e2e173f1d91abee1fa0ff391"}, - {file = "tomli-2.5.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:57b1c3b01fab802e2899bc3d168dca320e14165e2fd9fd584760fb4ca5826859"}, - {file = "tomli-2.5.0-cp315-cp315-win32.whl", hash = "sha256:667e521b37a6c5ccaa044202c235b530f90177ffe2cd4a64ecc213c7dd535feb"}, - {file = "tomli-2.5.0-cp315-cp315-win_amd64.whl", hash = "sha256:d747252933c8a65ef6bd8da0fbb7ce28a90eb6119d8cd00772cd528aa07b68d5"}, - {file = "tomli-2.5.0-cp315-cp315-win_arm64.whl", hash = "sha256:75dbcde8751b0a960aa3de173aa5e894d590755c6d7758b7e774c06f1dc3cbdd"}, - {file = "tomli-2.5.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:2419c2a189551987b59d80e63ec355671283336f41c6b9b89462df679c7d0c57"}, - {file = "tomli-2.5.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:0dc598040da8d42cf20f0be588ed7004f46db12a0ac6c32e03a59dccedaaadcd"}, - {file = "tomli-2.5.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49096930c8d886c9bbdab62d2d0d17ce823ddeea522309a190b36245d5b49e01"}, - {file = "tomli-2.5.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8ade5023067f99fe72b88accd30d0ea05a158e9e32a11f124e731ea9695313f"}, - {file = "tomli-2.5.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b69564772b5c8f22ea5f498dff08cfa825045b4d4c4400529000bdf818aa3b2a"}, - {file = "tomli-2.5.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:8ff3a2ca028c7eee0c777f9a092038d0a594a9fa04e215f929a22c329e2cb142"}, - {file = "tomli-2.5.0-cp315-cp315t-win32.whl", hash = "sha256:62fc1bc8eb03e3a9cadfca713d65614ed8e09d974a283295ffe3a831976b4dc5"}, - {file = "tomli-2.5.0-cp315-cp315t-win_amd64.whl", hash = "sha256:f3fcbc57b1791fa6cbe5d8434179d51de12be1a4811469529f47f6e7487a2571"}, - {file = "tomli-2.5.0-cp315-cp315t-win_arm64.whl", hash = "sha256:d2ba24db8a9376921b5e87b4762b9adb0f3f1deaea68f2b8b0bb2c11efb9c3e7"}, - {file = "tomli-2.5.0-py3-none-any.whl", hash = "sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b"}, - {file = "tomli-2.5.0.tar.gz", hash = "sha256:264507556cd8b8c8e7c6ee037cdf443a463f03f4c958e57195e3d369711b8ff6"}, -] - [[package]] name = "tomlkit" version = "0.15.2" description = "Style preserving TOML library" optional = false python-versions = ">=3.9" -groups = ["dev"] +groups = ["main", "dev"] files = [ {file = "tomlkit-0.15.2-py3-none-any.whl", hash = "sha256:05562412163a3037b94497385fb7f9204c637bc605af7a48199e41cf2272f437"}, {file = "tomlkit-0.15.2.tar.gz", hash = "sha256:83e32755ba1d20d9340bd069ee97e9f6232ba2346b63ffcba425de01f7e327a6"}, @@ -570,4 +495,4 @@ files = [ [metadata] lock-version = "2.1" python-versions = ">=3.12,<4.0" -content-hash = "f03009e6dc1ed4172f4522feba900d3c29ed8eafbcc57e451991977eedb49614" +content-hash = "041646e4eb66e16fb812e3cc5b87d582a4cac76f7c9d5ca75a363813cdb41e21" diff --git a/pyproject.toml b/pyproject.toml index d37b1cf..aa17671 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ build-backend = "poetry_dynamic_versioning.backend" name = "mirageoscience.pre-commit-hooks" requires-python = ">=3.12,<4.0" dynamic = ["version"] -dependencies = ["packaging>=25", "PyYAML>=6"] +dependencies = ["packaging>=25", "PyYAML>=6", "tomlkit>=0.15.2"] description = "" readme = "README.rst" @@ -32,7 +32,6 @@ dev = [ "pytest", "pytest-mock", "pytest-cov", - "tomli", ] [tool.poetry] diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index 6931c92..77f4e97 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -9,10 +9,20 @@ from __future__ import annotations +import sys + import pytest -from mirageoscience.hooks.check_pixi_lock import LockOptions, validate_lock -from mirageoscience.hooks.check_recipe import RecipeOptions, validate_recipe +from mirageoscience.hooks.check_pixi_lock import ( + LockOptions, + main as check_pixi_lock_main, + validate_lock, +) +from mirageoscience.hooks.check_recipe import ( + RecipeOptions, + main as check_recipe_main, + validate_recipe, +) def _lock_fixture( @@ -40,6 +50,79 @@ def _lock_fixture( return pixi, lock +def _multiline_pixi_manifest() -> str: + return """\ +[workspace.conda-pypi-map] +"https://example.org/conda" = { + mapping-mode = "overlay", + mapping = { + gempy = "gempy", + gempy-engine = "gempy-engine", + }, +} + +[constraints] +filelock = ">=4.2.1" + +[feature.mira-pypi] +pypi-dependencies = {} +""" + + +def test_recipe_main_parses_toml_11_inline_tables(tmp_path, monkeypatch, capsys): + pixi_file = tmp_path / "pixi.toml" + recipe_file = tmp_path / "recipe.yaml" + project_file = tmp_path / "pyproject.toml" + pixi_file.write_text(_multiline_pixi_manifest(), encoding="utf-8") + recipe_file.write_text( + "requirements:\n run_constraints:\n - filelock >=4.2.1\n", + encoding="utf-8", + ) + project_file.write_text("[project]\ndependencies = []\n", encoding="utf-8") + monkeypatch.setattr( + sys, + "argv", + [ + "check-recipe", + "--pixi-file", + str(pixi_file), + "--recipe-file", + str(recipe_file), + "--project-file", + str(project_file), + ], + ) + + assert check_recipe_main() == 0 + assert "Recipe constraints match" in capsys.readouterr().out + + +def test_pixi_lock_main_parses_toml_11_inline_tables(tmp_path, monkeypatch, capsys): + pixi_file = tmp_path / "pixi.toml" + lock_file = tmp_path / "pixi.lock" + pixi_file.write_text(_multiline_pixi_manifest(), encoding="utf-8") + lock_file.write_text( + "packages: []\nenvironments:\n default:\n packages:\n win-64: []\n", + encoding="utf-8", + ) + monkeypatch.setattr( + sys, + "argv", + [ + "check-pixi-lock", + "--pixi-file", + str(pixi_file), + "--lock-file", + str(lock_file), + "--pypi-feature", + "mira-pypi", + ], + ) + + assert check_pixi_lock_main() == 0 + assert "Pixi lock package sources match" in capsys.readouterr().out + + def test_pypi_packages_are_forbidden_without_feature(): pixi, lock = _lock_fixture(features=[], pypi_names=("mira-package",)) From 5c14b171c8a0da3719af6507486cb9aba1ba5278 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:39:38 +0000 Subject: [PATCH 08/20] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- tests/pixi_hooks_test.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index 77f4e97..abbf59a 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -15,14 +15,18 @@ from mirageoscience.hooks.check_pixi_lock import ( LockOptions, - main as check_pixi_lock_main, validate_lock, ) +from mirageoscience.hooks.check_pixi_lock import ( + main as check_pixi_lock_main, +) from mirageoscience.hooks.check_recipe import ( RecipeOptions, - main as check_recipe_main, validate_recipe, ) +from mirageoscience.hooks.check_recipe import ( + main as check_recipe_main, +) def _lock_fixture( From e9732c1d1aa0f0709e275fec31f11f7d068900b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:12:05 -0500 Subject: [PATCH 09/20] [GA-9681] Address Pixi hook review comments Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.rst | 10 ++- mirageoscience/hooks/check_pixi_lock.py | 79 ++++++++++++++-------- mirageoscience/hooks/check_recipe.py | 46 +++++++++++-- tests/pixi_hooks_test.py | 88 +++++++++++++++++++++++++ 4 files changed, 185 insertions(+), 38 deletions(-) diff --git a/README.rst b/README.rst index 2168bd8..18df424 100644 --- a/README.rst +++ b/README.rst @@ -57,9 +57,13 @@ names with ``--pypi-feature`` and ``--conda-feature``. Recipe security floors an their Pixi source are inferred from ``recipe.yaml`` and ``pixi.toml``; Git sources from ``git+https://github.com/MiraGeoscience/`` are allowed by default and can be overridden with ``--git-url-prefix``. Only enable the optional PyTorch check with -``--check-pytorch`` when required. For source validation, use the repeatable -``--artifact-source-root`` option to permit download locations outside an -index's URL; PyPI's standard artifact host is allowed automatically. +``--check-pytorch`` when required. For source validation, enable +``--validate-pypi-sources``; the repeatable ``--artifact-source-root`` option is +only used with this flag, to permit download locations outside an index's URL. +PyPI's standard artifact host is allowed automatically. If index configuration +lives in a separate feature, ``--pypi-index-feature`` selects that feature's +``pypi-options``; the feature must be enabled in the environment to apply its +indexes. Otherwise, workspace-level options or the default PyPI index are used. License ^^^^^^^ diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py index 2be2623..05c3902 100644 --- a/mirageoscience/hooks/check_pixi_lock.py +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -119,8 +119,18 @@ def _locked_names( return names -def _index_urls(pixi: dict, feature_name: str) -> set[str]: - options = pixi["feature"][feature_name].get("pypi-options", {}) +def _pypi_options(pixi: dict, feature_name: str | None) -> dict: + options = dict(pixi.get("pypi-options", {})) + options.update(pixi.get("workspace", {}).get("pypi-options", {})) + if feature_name is not None: + options.update( + pixi.get("feature", {}).get(feature_name, {}).get("pypi-options", {}) + ) + return options + + +def _index_urls(pixi: dict, feature_name: str | None) -> set[str]: + options = _pypi_options(pixi, feature_name) urls = set() if url := options.get("index-url"): urls.add(url.rstrip("/")) @@ -128,7 +138,9 @@ def _index_urls(pixi: dict, feature_name: str) -> set[str]: return urls -def _expectations(pixi: dict, options: LockOptions, platform: str) -> LockExpectations: +def _expectations( + pixi: dict, options: LockOptions, platform: str, features: set[str] +) -> LockExpectations: pypi_packages = _feature_dependencies( pixi, options.pypi_feature, "pypi-dependencies", platform ) @@ -137,14 +149,15 @@ def _expectations(pixi: dict, options: LockOptions, platform: str) -> LockExpect if options.conda_feature else set() ) - index_feature = options.pypi_index_feature or options.pypi_feature + index_feature: str | None = options.pypi_index_feature or options.pypi_feature + if index_feature not in features: + index_feature = None index_urls = ( _index_urls(pixi, index_feature) if options.validate_pypi_sources else set() ) source_indexes = set(index_urls) - if options.validate_pypi_sources and not pixi["feature"][index_feature].get( - "pypi-options", {} - ).get("index-url"): + index_options = _pypi_options(pixi, index_feature) + if options.validate_pypi_sources and not index_options.get("index-url"): source_indexes.add(PYPI_INDEX) source_roots = { f"{url.removesuffix('/simple').rstrip('/')}/" for url in source_indexes @@ -321,7 +334,7 @@ def _validate_environment( for platform, entries in environment_lock["packages"].items(): label = f"{environment_name}/{platform}" platform_context = LockContext( - options, _expectations(pixi, options, platform), packages_by_url + options, _expectations(pixi, options, platform, features), packages_by_url ) errors.extend( _validate_platform( @@ -368,27 +381,37 @@ def main() -> int: parser.add_argument("--artifact-source-root", action="append", default=[]) args = parser.parse_args() - with args.pixi_file.open("rb") as file: - pixi = tomlkit.load(file).unwrap() - with args.lock_file.open(encoding="utf-8") as file: - lock = yaml.safe_load(file) - errors = validate_lock( - pixi, - lock, - LockOptions( - pypi_feature=args.pypi_feature, - conda_feature=args.conda_feature, - strict_pypi=args.strict_pypi, - pypi_index_feature=args.pypi_index_feature, - validate_pypi_sources=args.validate_pypi_sources, - artifact_source_roots=tuple(args.artifact_source_root), - git_url_prefixes=( - tuple(args.git_url_prefix) - if args.git_url_prefix is not None - else DEFAULT_GIT_URL_PREFIXES + try: + with args.pixi_file.open("rb") as file: + pixi = tomlkit.load(file).unwrap() + with args.lock_file.open(encoding="utf-8") as file: + lock = yaml.safe_load(file) + errors = validate_lock( + pixi, + lock, + LockOptions( + pypi_feature=args.pypi_feature, + conda_feature=args.conda_feature, + strict_pypi=args.strict_pypi, + pypi_index_feature=args.pypi_index_feature, + validate_pypi_sources=args.validate_pypi_sources, + artifact_source_roots=tuple(args.artifact_source_root), + git_url_prefixes=( + tuple(args.git_url_prefix) + if args.git_url_prefix is not None + else DEFAULT_GIT_URL_PREFIXES + ), ), - ), - ) + ) + except ( + ValueError, + KeyError, + TypeError, + tomlkit.exceptions.ParseError, + yaml.YAMLError, + ) as error: + print(f"Invalid Pixi lock configuration: {error}", file=sys.stderr) + return 1 if errors: print("\n".join(errors), file=sys.stderr) return 1 diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index 4203ef6..c0c6029 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -30,10 +30,11 @@ class RecipeOptions: def _parse_constraint(value: str) -> tuple[str, str]: - name, separator, specifier = value.strip().partition(" ") - if not separator or not specifier.strip(): + match = re.match(r"^\s*([^\s<>=!~]+)\s*(.*?)\s*$", value) + if not match or not match.group(2): raise ValueError(f"Invalid recipe run constraint: {value!r}") - return canonicalize_name(name), specifier.strip() + name = match.group(1).rsplit("::", 1)[-1] + return canonicalize_name(name), match.group(2) def _as_specifier_set(value: str) -> SpecifierSet: @@ -42,12 +43,41 @@ def _as_specifier_set(value: str) -> SpecifierSet: specifiers = [] for specifier in value.split(","): specifier = specifier.strip() + conda_equality = re.fullmatch(r"=(\d[0-9A-Za-z.!+_-]*)", specifier) + if conda_equality: + version = conda_equality.group(1) + specifier = f"=={version if version.endswith('.*') else f'{version}.*'}" if not any(operator in specifier for operator in "<>=!~"): specifier = f"=={specifier}" specifiers.append(specifier) return SpecifierSet(",".join(specifiers)) +def _requirement_strings(values: object): + if values is None: + return + if isinstance(values, str): + yield values + return + if isinstance(values, list): + for value in values: + yield from _requirement_strings(value) + return + if isinstance(values, dict) and "then" in values: + yield from _requirement_strings(values["then"]) + if "else" in values: + yield from _requirement_strings(values["else"]) + return + raise ValueError(f"Invalid recipe requirement entry: {values!r}") + + +def _requirement_package(value: str) -> str: + match = re.match(r"^(?:[^\s:]+::)?([a-zA-Z0-9_.-]+)", value.strip()) + if not match: + raise ValueError(f"Invalid recipe run requirement: {value!r}") + return canonicalize_name(match.group(1)) + + def _project_dependency_names(project: dict) -> set[str]: project_data = project.get("project", {}) dependencies = list(project_data.get("dependencies", [])) @@ -175,8 +205,8 @@ def _published_transitivity_errors( ) -> list[str]: dependencies = _project_dependency_names(project) dependencies.update( - canonicalize_name(value.split(maxsplit=1)[0].rsplit("::", 1)[-1]) - for value in recipe["requirements"].get("run", []) + _requirement_package(value) + for value in _requirement_strings(recipe["requirements"].get("run", [])) ) dependencies = {aliases.get(package, package) for package in dependencies} direct_dependencies = security_packages & dependencies @@ -233,7 +263,7 @@ def _transitivity_errors( def _pytorch_errors(recipe: dict) -> list[str]: backend_specs = [] for section in ("run", "run_constraints"): - for value in recipe["requirements"].get(section, []): + for value in _requirement_strings(recipe["requirements"].get(section, [])): match = re.match(r"^(?:[^\s:]+::)?([a-zA-Z0-9_.-]+)(.*)$", value.strip()) if not match: continue @@ -257,7 +287,9 @@ def validate_recipe( ) -> list[str]: recipe_constraints = dict( _parse_constraint(value) - for value in recipe["requirements"].get("run_constraints", []) + for value in _requirement_strings( + recipe["requirements"].get("run_constraints", []) + ) ) pixi_sources = _pixi_constraint_sources(pixi, set(recipe_constraints)) errors = _constraint_errors(recipe_constraints, pixi_sources) diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index abbf59a..feab8a1 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -290,6 +290,43 @@ def test_pypi_source_validation_accepts_public_pypi_artifact_host(configured): ) +def test_pypi_source_validation_inherits_workspace_index_options(): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + index = "https://packages.example.org/simple" + url = "https://packages.example.org/packages/mira-package.whl" + pixi["pypi-options"] = {"index-url": index} + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["indexes"] = [index] + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + options = LockOptions("mira-pypi", validate_pypi_sources=True) + + assert not validate_lock(pixi, lock, options) + url = "https://files.pythonhosted.org/packages/mira-package.whl" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + assert any( + "unexpected PyPI source" in error + for error in validate_lock(pixi, lock, options) + ) + + +def test_pypi_source_validation_ignores_inactive_index_feature(): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + pixi["feature"]["mira-pypi-index"] = { + "pypi-options": {"index-url": "https://packages.example.org/simple"} + } + url = "https://files.pythonhosted.org/packages/mira-package.whl" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + options = LockOptions( + "mira-pypi", + pypi_index_feature="mira-pypi-index", + validate_pypi_sources=True, + ) + + assert not validate_lock(pixi, lock, options) + + def test_pypi_source_validation_accepts_configured_artifact_root(): pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) pixi["feature"]["mira-pypi"]["pypi-options"] = { @@ -327,6 +364,32 @@ def test_implicit_default_environment_and_unknown_named_environment(environments ) +def test_pixi_lock_main_reports_validation_errors(tmp_path, monkeypatch, capsys): + pixi_file = tmp_path / "pixi.toml" + lock_file = tmp_path / "pixi.lock" + pixi_file.write_text(_multiline_pixi_manifest(), encoding="utf-8") + lock_file.write_text( + "packages: []\nenvironments:\n default:\n packages:\n win-64: []\n", + encoding="utf-8", + ) + monkeypatch.setattr( + sys, + "argv", + [ + "check-pixi-lock", + "--pixi-file", + str(pixi_file), + "--lock-file", + str(lock_file), + "--pypi-feature", + "missing-feature", + ], + ) + + assert check_pixi_lock_main() == 1 + assert "Pixi feature 'missing-feature' is not defined" in capsys.readouterr().err + + def test_recipe_checks_constraints_and_optional_pytorch(): pixi = { "constraints": {"filelock": ">=4.2.1"}, @@ -421,6 +484,31 @@ def test_recipe_infers_feature_constraint_source_and_floor(): assert any("pillow" in error for error in errors) +@pytest.mark.parametrize( + ("recipe_constraint", "pixi_constraint"), + [("urllib3>=2.5", ">=2.5"), ("urllib3=2.5", "=2.5")], +) +def test_recipe_parses_conda_constraints_without_spaces( + recipe_constraint, pixi_constraint +): + pixi = {"constraints": {"urllib3": pixi_constraint}} + recipe = {"requirements": {"run_constraints": [recipe_constraint]}} + + assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) + + +def test_recipe_reads_conditional_run_constraints(): + pixi = {"constraints": {"filelock": ">=4.2.1"}} + recipe = { + "requirements": { + "run": ["python >=3.12"], + "run_constraints": [{"if": "win", "then": "filelock >=4.2.1"}], + } + } + + assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) + + def test_recipe_accepts_inline_versions_but_rejects_versionless_dependencies(): pixi = { "feature": { From 9c90cd2f9386e19ea0167262c83a5f2649677287 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:25:38 -0500 Subject: [PATCH 10/20] option to skip check on constraints if using unsupport conditionals reject conditional run constraints with clear message and doc to skip the check As that is too much code to match constrains with condition beteween pixi.toml and the conda recipe Also change README from rst to md (simpler, and built-in preview in IDE) --- README.md | 64 +++++++++++++++++++ README.rst | 95 ---------------------------- mirageoscience/hooks/check_recipe.py | 58 ++++++++++++----- pyproject.toml | 2 +- tests/pixi_hooks_test.py | 21 +++++- 5 files changed, 127 insertions(+), 113 deletions(-) create mode 100644 README.md delete mode 100644 README.rst diff --git a/README.md b/README.md new file mode 100644 index 0000000..6806035 --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# MiraGeoscience.Pre-Commit Hooks + +This repository provides a collection of pre-commit hooks to automate essential checks and streamline your development workflow. By utilizing these hooks, you can maintain code quality and consistency across your projects, fostering a more efficient and collaborative development environment. + +## Included Hooks + +### `check-copyright` +Checks for valid copyright statements in files. + +### `check-pixi-lock` +Checks locked Conda and PyPI sources against Pixi workspace features. +`--strict-pypi` requires the lock to contain exactly the packages declared by the selected PyPI feature; otherwise transitive PyPI dependencies are allowed while the feature packages are still checked. + +The default workspace detection reads `pixi.toml`, `pixi.lock`, and `pyproject.toml` from the repository root. Configure differing feature names with `--pypi-feature` and `--conda-feature`. + +### `check-recipe` +Checks recipe `run_constraints` against Pixi constraints, discovers matching feature constraints from `pixi.toml`, verifies constrained packages remain transitive in published dependencies, and optionally checks that the recipe leaves PyTorch backend selection to the installer. + +Conditional `run_constraints` are not supported by the recipe validation; use unconditional constraints or pass `--ignore-constraints` to skip this specific constraint comparison. + +Recipe security floors and their Pixi source are inferred from `recipe.yaml` and `pixi.toml`. Git sources from `git+https://github.com/MiraGeoscience/` are allowed by default and can be overridden with `--git-url-prefix`. + +Only enable the optional PyTorch check with `--check-pytorch` when required. + +For source validation, enable `--validate-pypi-sources`. The repeatable `--artifact-source-root` option is only used with this flag to permit download locations outside an index's URL. PyPI's standard artifact host is allowed automatically. If index configuration lives in a separate feature, `--pypi-index-feature` selects that feature's `pypi-options`; the feature must be enabled in the environment to apply its indexes. Otherwise, workspace-level options or the default PyPI index are used. + +### `prepare-commit-msg` +Adds the JIRA ID found in the branch name in case it is missing from the commit message. + +### `check-commit-message` +Checks that the branch name or the commit message starts with a reference to JIRA, and if the message meets the minimum required length for the summary line. Also checks that the JIRA ID in the commit message is consistent with the one extracted from the branch name (if any). + +## Usage + +Example of `.pre-commit-config.yamnl`: + +```yaml +repos: +- repo: http://github.com/MiraGeoscience/pre-commit-hooks + rev: + hooks: + - id: check-copyright + types: [text] + files: (^LICENSE|^README(|-dev).rst|\.py|\.pyi)$ + exclude: (^\.|^docs/) + - id: check-pixi-lock + args: [--pypi-feature=mira-pypi, --strict-pypi] + - id: check-recipe + args: [--check-pytorch] + - id: prepare-commit-msg + - id: check-commit-msg +``` + +## License + +MIT License + +Copyright (c) 2024-2026 Mira Geoscience Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.rst b/README.rst deleted file mode 100644 index 18df424..0000000 --- a/README.rst +++ /dev/null @@ -1,95 +0,0 @@ -MiraGeoscience.Pre-Commit Hooks -=============================== - -This repository provides a collection of pre-commit hooks to automate -essential checks and streamline your development workflow. By utilizing -these hooks, you can maintain code quality and consistency across your -projects, fostering a more efficient and collaborative development -environment. - -Included Hooks -^^^^^^^^^^^^^^ - -- ``check-copyright``: Checks for valid copyright statements in files. -- ``check-pixi-lock``: Checks locked Conda and PyPI sources against Pixi workspace - features. ``--strict-pypi`` requires the lock to contain exactly the packages - declared by the selected PyPI feature; otherwise transitive PyPI dependencies - are allowed while the feature packages are still checked. -- ``check-recipe``: Checks recipe ``run_constraints`` against Pixi constraints, - discovers matching feature constraints from ``pixi.toml``, verifies constrained - packages remain transitive in published dependencies, and optionally checks - that the recipe leaves PyTorch backend selection to the installer. -- ``prepare-commit-msg``: Adds the JIRA ID found in the branch name - in case it is missing from the commit message. -- ``check-commit-message``: Checks that the branch name or the commit - message starts with a reference to JIRA, and if the message meets the - minimum required length for the summary line. Also checks that the JIRA ID in - the commit message is consistEnt with the one extracted from the - branch name (if any). - -Usage -^^^^^ - -Example of ``.pre-commit-config.yamnl``: - -.. code:: yaml - - repos: - - repo: http://github.com/MiraGeoscience/pre-commit-hooks - rev: - hooks: - - id: check-copyright - types: [text] - files: (^LICENSE|^README(|-dev).rst|\.py|\.pyi)$ - exclude: (^\.|^docs/) - - id: check-pixi-lock - args: [--pypi-feature=mira-pypi, --strict-pypi] - - id: check-recipe - args: [--check-pytorch] - - id: prepare-commit-msg - - id: check-commit-msg - -The Pixi hooks read ``pixi.toml``, ``pixi.lock``, ``recipe.yaml``, and -``pyproject.toml`` from the repository root by default. They also provide default -file filters for these workspace files and the pre-commit configuration, so -consumer configs do not need to repeat ``files``. Configure differing feature -names with ``--pypi-feature`` and ``--conda-feature``. Recipe security floors and -their Pixi source are inferred from ``recipe.yaml`` and ``pixi.toml``; Git sources -from ``git+https://github.com/MiraGeoscience/`` are allowed by default and can be -overridden with ``--git-url-prefix``. Only enable the optional PyTorch check with -``--check-pytorch`` when required. For source validation, enable -``--validate-pypi-sources``; the repeatable ``--artifact-source-root`` option is -only used with this flag, to permit download locations outside an index's URL. -PyPI's standard artifact host is allowed automatically. If index configuration -lives in a separate feature, ``--pypi-index-feature`` selects that feature's -``pypi-options``; the feature must be enabled in the environment to apply its -indexes. Otherwise, workspace-level options or the default PyPI index are used. - -License -^^^^^^^ - -MIT License - -Copyright (c) 2024-2026 Mira Geoscience Ltd. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -Copyright -^^^^^^^^^ -Copyright (c) 2024-2026 Mira Geoscience Ltd. diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index c0c6029..3fb1628 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -7,6 +7,14 @@ # of the MIT License (see LICENSE file at the root of this source code package). ' # ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +"""Validate conda recipe constraints against the Pixi workspace. + +Conditional ``run_constraints`` entries are not supported by the Conda recipe +comparison because they are flattened to a single effective constraint rather than +one unconditional value. Use unconditional constraints or pass +``--ignore-constraints`` to skip this specific comparison. +""" + from __future__ import annotations import argparse @@ -27,6 +35,7 @@ class RecipeOptions: package_aliases: tuple[str, ...] = () check_pytorch: bool = False + ignore_constraints: bool = False def _parse_constraint(value: str) -> tuple[str, str]: @@ -63,11 +72,14 @@ def _requirement_strings(values: object): for value in values: yield from _requirement_strings(value) return - if isinstance(values, dict) and "then" in values: - yield from _requirement_strings(values["then"]) - if "else" in values: - yield from _requirement_strings(values["else"]) - return + if isinstance(values, dict): + if "if" in values or "then" in values or "else" in values: + raise ValueError( + "Conditional recipe requirements are not supported by " + "check-conda-recipe; pass --ignore-constraints to skip this check " + "for conditional constraints, or use unconditional constraints." + ) + raise ValueError(f"Invalid recipe requirement entry: {values!r}") raise ValueError(f"Invalid recipe requirement entry: {values!r}") @@ -285,17 +297,31 @@ def _pytorch_errors(recipe: dict) -> list[str]: def validate_recipe( pixi: dict, recipe: dict, project: dict, options: RecipeOptions ) -> list[str]: - recipe_constraints = dict( - _parse_constraint(value) - for value in _requirement_strings( - recipe["requirements"].get("run_constraints", []) + errors = [] + run_constraints = recipe.get("requirements", {}).get("run_constraints", []) + conditional_run_constraints = [ + value + for value in run_constraints + if isinstance(value, dict) and any(key in value for key in ("if", "then", "else")) + ] + if conditional_run_constraints and not options.ignore_constraints: + errors.append( + "Conditional run_constraints are not supported by check-conda-recipe; " + "use unconditional constraints or exclude this validation. Pass " + "--ignore-constraints to skip this check for conditional constraints." + ) + return errors + + if not conditional_run_constraints: + recipe_constraints = dict( + _parse_constraint(value) + for value in _requirement_strings(run_constraints) + ) + pixi_sources = _pixi_constraint_sources(pixi, set(recipe_constraints)) + errors.extend(_constraint_errors(recipe_constraints, pixi_sources)) + errors.extend( + _transitivity_errors(pixi, recipe, project, recipe_constraints, options) ) - ) - pixi_sources = _pixi_constraint_sources(pixi, set(recipe_constraints)) - errors = _constraint_errors(recipe_constraints, pixi_sources) - errors.extend( - _transitivity_errors(pixi, recipe, project, recipe_constraints, options) - ) if options.check_pytorch: errors.extend(_pytorch_errors(recipe)) return errors @@ -308,6 +334,7 @@ def main() -> int: parser.add_argument("--project-file", type=Path, default=Path("pyproject.toml")) parser.add_argument("--package-alias", action="append", default=[]) parser.add_argument("--check-pytorch", action="store_true") + parser.add_argument("--ignore-constraints", action="store_true") args = parser.parse_args() with args.pixi_file.open("rb") as file: @@ -323,6 +350,7 @@ def main() -> int: RecipeOptions( package_aliases=tuple(args.package_alias), check_pytorch=args.check_pytorch, + ignore_constraints=args.ignore_constraints, ), ) if errors: diff --git a/pyproject.toml b/pyproject.toml index aa17671..59317ee 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ dynamic = ["version"] dependencies = ["packaging>=25", "PyYAML>=6", "tomlkit>=0.15.2"] description = "" -readme = "README.rst" +readme = "README.md" license = "MIT" authors = [{ name = "Mira Geoscience", email = "support@mirageoscience.com" }] diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index feab8a1..9dcce76 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -497,7 +497,7 @@ def test_recipe_parses_conda_constraints_without_spaces( assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) -def test_recipe_reads_conditional_run_constraints(): +def test_recipe_rejects_conditional_run_constraints(): pixi = {"constraints": {"filelock": ">=4.2.1"}} recipe = { "requirements": { @@ -506,7 +506,24 @@ def test_recipe_reads_conditional_run_constraints(): } } - assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) + errors = validate_recipe(pixi, recipe, {}, RecipeOptions()) + assert any( + "Conditional run_constraints are not supported" in error for error in errors + ) + assert any("--ignore-constraints" in error for error in errors) + + +def test_recipe_ignores_conditional_constraint_validation_when_requested(): + pixi = {"constraints": {"filelock": ">=4.2.1"}} + recipe = { + "requirements": { + "run": ["python >=3.12"], + "run_constraints": [{"if": "win", "then": "filelock >=4.2.1"}], + } + } + + errors = validate_recipe(pixi, recipe, {}, RecipeOptions(ignore_constraints=True)) + assert not errors def test_recipe_accepts_inline_versions_but_rejects_versionless_dependencies(): From 4dc82560a99ce0ab0297f15f60ad250c61956193 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:26:03 +0000 Subject: [PATCH 11/20] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- mirageoscience/hooks/check_recipe.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index 3fb1628..74d5699 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -302,7 +302,8 @@ def validate_recipe( conditional_run_constraints = [ value for value in run_constraints - if isinstance(value, dict) and any(key in value for key in ("if", "then", "else")) + if isinstance(value, dict) + and any(key in value for key in ("if", "then", "else")) ] if conditional_run_constraints and not options.ignore_constraints: errors.append( @@ -314,8 +315,7 @@ def validate_recipe( if not conditional_run_constraints: recipe_constraints = dict( - _parse_constraint(value) - for value in _requirement_strings(run_constraints) + _parse_constraint(value) for value in _requirement_strings(run_constraints) ) pixi_sources = _pixi_constraint_sources(pixi, set(recipe_constraints)) errors.extend(_constraint_errors(recipe_constraints, pixi_sources)) From ce87defe32ce403388388ec1ea9abe5a7f35e53d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:37:15 -0500 Subject: [PATCH 12/20] readme file inclusion is at project level: no need for tool.pooetry --- pyproject.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 59317ee..aedea55 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,7 +39,6 @@ requires-poetry = ">=2.2.0" include = [ "LICENSE", - "README.rst", { path = "mirageoscience/hooks/_version.py", format = ["sdist", "wheel"] }, ] From e4bc6e821bd887ec0febd9c3e6b380d3404366fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:55:48 -0500 Subject: [PATCH 13/20] correct scope and implementation --- README.md | 8 +- mirageoscience/hooks/check_pixi_lock.py | 14 ++ mirageoscience/hooks/check_recipe.py | 179 ++++++++++-------------- tests/pixi_hooks_test.py | 122 +++++++++------- 4 files changed, 165 insertions(+), 158 deletions(-) diff --git a/README.md b/README.md index 6806035..886d76b 100644 --- a/README.md +++ b/README.md @@ -11,10 +11,14 @@ Checks for valid copyright statements in files. Checks locked Conda and PyPI sources against Pixi workspace features. `--strict-pypi` requires the lock to contain exactly the packages declared by the selected PyPI feature; otherwise transitive PyPI dependencies are allowed while the feature packages are still checked. -The default workspace detection reads `pixi.toml`, `pixi.lock`, and `pyproject.toml` from the repository root. Configure differing feature names with `--pypi-feature` and `--conda-feature`. +By default, this hook reads `pixi.toml` and `pixi.lock` from the repository root. Configure differing feature names with `--pypi-feature` and `--conda-feature`. ### `check-recipe` -Checks recipe `run_constraints` against Pixi constraints, discovers matching feature constraints from `pixi.toml`, verifies constrained packages remain transitive in published dependencies, and optionally checks that the recipe leaves PyTorch backend selection to the installer. +Checks recipe `run_constraints` against Pixi constraints, discovers matching feature constraints from `pixi.toml`, verifies constrained packages are not also direct dependencies in recipe `run`, and optionally checks that the recipe leaves PyTorch backend selection to the installer. + +By default, this hook reads `recipe.yaml` and `pixi.toml` from the repository root. + +Dependency consistency is checked by `pip check` during recipe builds; this hook focuses on ensuring recipe and Pixi constraints agree. Conditional `run_constraints` are not supported by the recipe validation; use unconditional constraints or pass `--ignore-constraints` to skip this specific constraint comparison. diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py index 05c3902..b878420 100644 --- a/mirageoscience/hooks/check_pixi_lock.py +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -54,6 +54,7 @@ class LockContext: def _feature_dependencies( pixi: dict, feature_name: str, dependency_type: str, platform: str ) -> set[str]: + """Resolve feature dependencies, including matching platform-target overrides.""" try: feature = pixi["feature"][feature_name] except KeyError as error: @@ -84,6 +85,7 @@ def _feature_dependencies( def _environment_features(environment: object) -> set[str]: + """Normalize a Pixi environment definition to its feature-name set.""" if isinstance(environment, dict): features = environment.get("features", []) else: @@ -96,6 +98,7 @@ def _environment_features(environment: object) -> set[str]: def _locked_names( entries: list[dict], packages_by_url: dict[str, str], source: str ) -> set[str]: + """Extract canonical package names from PyPI or Conda lock entries.""" names = set() for entry in entries: url = entry.get(source) @@ -120,6 +123,7 @@ def _locked_names( def _pypi_options(pixi: dict, feature_name: str | None) -> dict: + """Merge PyPI options in top-level, workspace, then feature precedence.""" options = dict(pixi.get("pypi-options", {})) options.update(pixi.get("workspace", {}).get("pypi-options", {})) if feature_name is not None: @@ -130,6 +134,7 @@ def _pypi_options(pixi: dict, feature_name: str | None) -> dict: def _index_urls(pixi: dict, feature_name: str | None) -> set[str]: + """Return configured PyPI index URLs without trailing slashes.""" options = _pypi_options(pixi, feature_name) urls = set() if url := options.get("index-url"): @@ -141,6 +146,7 @@ def _index_urls(pixi: dict, feature_name: str | None) -> set[str]: def _expectations( pixi: dict, options: LockOptions, platform: str, features: set[str] ) -> LockExpectations: + """Build platform-specific package and artifact-source expectations.""" pypi_packages = _feature_dependencies( pixi, options.pypi_feature, "pypi-dependencies", platform ) @@ -171,6 +177,7 @@ def _expectations( def _allowed_git_source(url: str, prefixes: tuple[str, ...]) -> bool: + """Check an allowed Git URL prefix and reject unsafe path segments.""" if any(ord(char) < 32 or ord(char) == 127 for char in url): return False try: @@ -206,6 +213,7 @@ def _source_errors( pypi_feature_enabled: bool, context: LockContext, ) -> list[str]: + """Report missing indexes and PyPI or Git sources outside allowed roots.""" options = context.options expectations = context.expectations if not options.validate_pypi_sources or not pypi_feature_enabled: @@ -236,6 +244,7 @@ def _pypi_errors( features: set[str], context: LockContext, ) -> list[str]: + """Check locked PyPI packages, using exact or minimum membership policy.""" options = context.options expectations = context.expectations pypi_names = _locked_names(entries, context.packages_by_url, "pypi") @@ -273,6 +282,7 @@ def _conda_errors( features: set[str], context: LockContext, ) -> list[str]: + """Check expected packages are locked from their configured package source.""" options = context.options expected_conda = ( context.expectations.conda_packages @@ -310,6 +320,7 @@ def _validate_platform( features: set[str], context: LockContext, ) -> list[str]: + """Validate locked package names and sources for one platform.""" pypi_names = _locked_names(entries, context.packages_by_url, "pypi") conda_names = _locked_names(entries, context.packages_by_url, "conda") return _pypi_errors( @@ -324,6 +335,7 @@ def _validate_environment( options: LockOptions, packages_by_url: dict[str, str], ) -> list[str]: + """Validate every locked platform for one Pixi environment.""" environment_config = pixi.get("environments", {}).get(environment_name) if environment_config is None: if environment_name != "default": @@ -349,6 +361,7 @@ def _validate_environment( def validate_lock(pixi: dict, lock: dict, options: LockOptions) -> list[str]: + """Validate all lock environments against the Pixi feature configuration.""" packages_by_url = { package["pypi"]: package["name"] for package in lock["packages"] @@ -369,6 +382,7 @@ def validate_lock(pixi: dict, lock: dict, options: LockOptions) -> list[str]: def main() -> int: + """Load CLI inputs, validate the lock, and return the process status.""" parser = argparse.ArgumentParser() parser.add_argument("--pixi-file", type=Path, default=Path("pixi.toml")) parser.add_argument("--lock-file", type=Path, default=Path("pixi.lock")) diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index 74d5699..be64966 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -25,7 +25,6 @@ import tomlkit import yaml -from packaging.requirements import Requirement from packaging.specifiers import SpecifierSet from packaging.utils import canonicalize_name from packaging.version import Version @@ -39,6 +38,7 @@ class RecipeOptions: def _parse_constraint(value: str) -> tuple[str, str]: + """Split a Conda requirement into its canonical package name and specifier.""" match = re.match(r"^\s*([^\s<>=!~]+)\s*(.*?)\s*$", value) if not match or not match.group(2): raise ValueError(f"Invalid recipe run constraint: {value!r}") @@ -47,6 +47,7 @@ def _parse_constraint(value: str) -> tuple[str, str]: def _as_specifier_set(value: str) -> SpecifierSet: + """Convert Conda-style version syntax to a packaging specifier set.""" if value in ("", "*"): return SpecifierSet() specifiers = [] @@ -63,6 +64,7 @@ def _as_specifier_set(value: str) -> SpecifierSet: def _requirement_strings(values: object): + """Yield unconditional requirement strings; reject conditional entries.""" if values is None: return if isinstance(values, str): @@ -83,24 +85,36 @@ def _requirement_strings(values: object): raise ValueError(f"Invalid recipe requirement entry: {values!r}") +def _flatten_requirement_strings(values: object): + """Yield requirement strings, including both branches of conditional entries.""" + if values is None: + return + if isinstance(values, str): + yield values + return + if isinstance(values, list): + for value in values: + yield from _flatten_requirement_strings(value) + return + if isinstance(values, dict): + if any(key in values for key in ("if", "then", "else")): + for branch in ("then", "else"): + yield from _flatten_requirement_strings(values.get(branch)) + return + raise ValueError(f"Invalid recipe requirement entry: {values!r}") + raise ValueError(f"Invalid recipe requirement entry: {values!r}") + + def _requirement_package(value: str) -> str: + """Return a canonical package name, ignoring any Conda channel prefix.""" match = re.match(r"^(?:[^\s:]+::)?([a-zA-Z0-9_.-]+)", value.strip()) if not match: raise ValueError(f"Invalid recipe run requirement: {value!r}") return canonicalize_name(match.group(1)) -def _project_dependency_names(project: dict) -> set[str]: - project_data = project.get("project", {}) - dependencies = list(project_data.get("dependencies", [])) - for optional_dependencies in project_data.get("optional-dependencies", {}).values(): - dependencies.extend(optional_dependencies) - return { - canonicalize_name(Requirement(dependency).name) for dependency in dependencies - } - - def _package_aliases(values: tuple[str, ...]) -> dict[str, str]: + """Parse package alias mappings and canonicalize both sides.""" aliases = {} for value in values: alias, separator, package = value.partition("=") @@ -110,7 +124,8 @@ def _package_aliases(values: tuple[str, ...]) -> dict[str, str]: return aliases -def _pixi_constraint_sources(pixi: dict, recipe_packages: set[str]) -> dict: +def _pixi_constraint_sources(pixi: dict, constrained_packages: set[str]) -> dict: + """Collect Pixi constraint and feature sources for recipe-constrained packages.""" sources: dict[str, list[tuple[str, str]]] = {} for package, specifier in pixi.get("constraints", {}).items(): sources.setdefault(canonicalize_name(package), []).append( @@ -123,7 +138,7 @@ def _pixi_constraint_sources(pixi: dict, recipe_packages: set[str]) -> dict: for package, specifier in feature.get(section, {}).items(): normalized = canonicalize_name(package) if ( - normalized in recipe_packages + normalized in constrained_packages and normalized not in top_level_packages ): sources.setdefault(normalized, []).append( @@ -136,12 +151,14 @@ def _pixi_constraint_sources(pixi: dict, recipe_packages: set[str]) -> dict: def _pixi_version(specifier: object) -> str: + """Extract the version from a Pixi inline dependency table or scalar.""" if isinstance(specifier, dict): return str(specifier.get("version", "")) return str(specifier) def _minimum_version(specifier: str) -> Version | None: + """Return the strongest lower bound represented by a specifier.""" versions = [] for item in _as_specifier_set(specifier): if item.operator in (">=", ">", "~="): @@ -152,6 +169,7 @@ def _minimum_version(specifier: str) -> Version | None: def _constraint_matches(recipe_specifier: str, pixi_specifier: str) -> bool: + """Match exact specifiers or lower bounds with the same effective floor.""" recipe_set = _as_specifier_set(recipe_specifier) pixi_set = _as_specifier_set(pixi_specifier) if recipe_set == pixi_set: @@ -170,6 +188,7 @@ def _constraint_matches(recipe_specifier: str, pixi_specifier: str) -> bool: def _constraint_errors( recipe_constraints: dict[str, str], pixi_sources: dict[str, list[tuple[str, str]]] ) -> list[str]: + """Report package-set differences and incompatible Pixi constraint sources.""" errors = [] if recipe_constraints.keys() != pixi_sources.keys(): errors.append( @@ -190,92 +209,35 @@ def _constraint_errors( return errors -def _pixi_direct_dependencies(pixi: dict) -> tuple[set[str], dict[str, set[str]]]: - root: set[str] = set() - features: dict[str, set[str]] = {} - - def dependencies(section: dict) -> set[str]: - tables = [section, *section.get("target", {}).values()] - return { - canonicalize_name(name) - for table in tables - for dependency_type in ("dependencies", "pypi-dependencies") - for name in table.get(dependency_type, {}) - } - - root.update(dependencies(pixi)) - for feature_name, feature in pixi.get("feature", {}).items(): - features[feature_name] = dependencies(feature) - return root, features - - -def _published_transitivity_errors( - recipe: dict, - project: dict, - security_packages: set[str], - aliases: dict[str, str], +def _recipe_transitivity_errors( + run_requirement_entries: object, + constrained_packages: set[str], + options: RecipeOptions, ) -> list[str]: - dependencies = _project_dependency_names(project) - dependencies.update( + """Report constrained packages declared directly in the recipe's run section.""" + aliases = _package_aliases(options.package_aliases) + security_packages = { + aliases.get(package, package) for package in constrained_packages + } + dependencies = { _requirement_package(value) - for value in _requirement_strings(recipe["requirements"].get("run", [])) - ) + for value in _requirement_strings(run_requirement_entries) + } dependencies = {aliases.get(package, package) for package in dependencies} direct_dependencies = security_packages & dependencies if not direct_dependencies: return [] return [ - "Security-floor packages must remain transitive in the published recipe " - f"and project dependencies: {sorted(direct_dependencies)}" - ] - - -def _pixi_transitivity_errors( - pixi: dict, security_packages: set[str], aliases: dict[str, str] -) -> list[str]: - root_dependencies, feature_dependencies = _pixi_direct_dependencies(pixi) - root_dependencies = {aliases.get(package, package) for package in root_dependencies} - top_level_constraints = { - aliases.get(canonicalize_name(package), canonicalize_name(package)) - for package in pixi.get("constraints", {}) - } - direct_root_security = security_packages & root_dependencies - direct_feature_dependencies = { - aliases.get(package, package) - for packages in feature_dependencies.values() - for package in packages - } - direct_feature_security = security_packages & direct_feature_dependencies - invalid_feature_security = direct_feature_security & top_level_constraints - invalid_pixi_security = direct_root_security | invalid_feature_security - if not invalid_pixi_security: - return [] - return [ - "Security-floor packages must remain Pixi constraints, not direct " - f"dependencies: {sorted(invalid_pixi_security)}" + "Security-floor packages must remain transitive in recipe requirements: " + f"{sorted(direct_dependencies)}" ] -def _transitivity_errors( - pixi: dict, - recipe: dict, - project: dict, - recipe_constraints: dict[str, str], - options: RecipeOptions, -) -> list[str]: - aliases = _package_aliases(options.package_aliases) - security_packages = { - aliases.get(package, package) for package in recipe_constraints - } - return _published_transitivity_errors( - recipe, project, security_packages, aliases - ) + _pixi_transitivity_errors(pixi, security_packages, aliases) - - -def _pytorch_errors(recipe: dict) -> list[str]: +def _pytorch_errors(requirements: dict) -> list[str]: + """Report explicit PyTorch backend selection in run or run_constraints entries.""" backend_specs = [] for section in ("run", "run_constraints"): - for value in _requirement_strings(recipe["requirements"].get(section, [])): + for value in _flatten_requirement_strings(requirements.get(section, [])): match = re.match(r"^(?:[^\s:]+::)?([a-zA-Z0-9_.-]+)(.*)$", value.strip()) if not match: continue @@ -294,36 +256,41 @@ def _pytorch_errors(recipe: dict) -> list[str]: ] -def validate_recipe( - pixi: dict, recipe: dict, project: dict, options: RecipeOptions -) -> list[str]: +def validate_recipe(pixi: dict, recipe: dict, options: RecipeOptions) -> list[str]: + """Validate recipe constraints, transitivity, and optional PyTorch policy.""" errors = [] - run_constraints = recipe.get("requirements", {}).get("run_constraints", []) - conditional_run_constraints = [ - value - for value in run_constraints - if isinstance(value, dict) - and any(key in value for key in ("if", "then", "else")) - ] - if conditional_run_constraints and not options.ignore_constraints: + requirements = recipe.get("requirements", {}) + run_requirement_entries = requirements.get("run", []) + run_constraint_requirement_entries = requirements.get("run_constraints", []) + has_conditional_constraints = any( + isinstance(value, dict) and any(key in value for key in ("if", "then", "else")) + for value in run_constraint_requirement_entries + ) + if has_conditional_constraints and not options.ignore_constraints: errors.append( "Conditional run_constraints are not supported by check-conda-recipe; " "use unconditional constraints or exclude this validation. Pass " "--ignore-constraints to skip this check for conditional constraints." ) - return errors - if not conditional_run_constraints: + constrained_packages = { + _requirement_package(value) + for value in _flatten_requirement_strings(run_constraint_requirement_entries) + } + if not has_conditional_constraints: recipe_constraints = dict( - _parse_constraint(value) for value in _requirement_strings(run_constraints) + _parse_constraint(value) + for value in _requirement_strings(run_constraint_requirement_entries) ) pixi_sources = _pixi_constraint_sources(pixi, set(recipe_constraints)) errors.extend(_constraint_errors(recipe_constraints, pixi_sources)) - errors.extend( - _transitivity_errors(pixi, recipe, project, recipe_constraints, options) + errors.extend( + _recipe_transitivity_errors( + run_requirement_entries, constrained_packages, options ) + ) if options.check_pytorch: - errors.extend(_pytorch_errors(recipe)) + errors.extend(_pytorch_errors(requirements)) return errors @@ -331,7 +298,6 @@ def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--pixi-file", type=Path, default=Path("pixi.toml")) parser.add_argument("--recipe-file", type=Path, default=Path("recipe.yaml")) - parser.add_argument("--project-file", type=Path, default=Path("pyproject.toml")) parser.add_argument("--package-alias", action="append", default=[]) parser.add_argument("--check-pytorch", action="store_true") parser.add_argument("--ignore-constraints", action="store_true") @@ -341,12 +307,9 @@ def main() -> int: pixi = tomlkit.load(file).unwrap() with args.recipe_file.open(encoding="utf-8") as file: recipe = yaml.safe_load(file) - with args.project_file.open("rb") as file: - project = tomlkit.load(file).unwrap() errors = validate_recipe( pixi, recipe, - project, RecipeOptions( package_aliases=tuple(args.package_alias), check_pytorch=args.check_pytorch, diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index 9dcce76..9e004eb 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -76,13 +76,11 @@ def _multiline_pixi_manifest() -> str: def test_recipe_main_parses_toml_11_inline_tables(tmp_path, monkeypatch, capsys): pixi_file = tmp_path / "pixi.toml" recipe_file = tmp_path / "recipe.yaml" - project_file = tmp_path / "pyproject.toml" pixi_file.write_text(_multiline_pixi_manifest(), encoding="utf-8") recipe_file.write_text( "requirements:\n run_constraints:\n - filelock >=4.2.1\n", encoding="utf-8", ) - project_file.write_text("[project]\ndependencies = []\n", encoding="utf-8") monkeypatch.setattr( sys, "argv", @@ -92,8 +90,6 @@ def test_recipe_main_parses_toml_11_inline_tables(tmp_path, monkeypatch, capsys) str(pixi_file), "--recipe-file", str(recipe_file), - "--project-file", - str(project_file), ], ) @@ -403,13 +399,13 @@ def test_recipe_checks_constraints_and_optional_pytorch(): } options = RecipeOptions(check_pytorch=True) - errors = validate_recipe(pixi, recipe, {}, options) + errors = validate_recipe(pixi, recipe, options) assert not errors recipe["requirements"]["run"].append("pytorch-cpu >=2.0") - errors = validate_recipe(pixi, recipe, {}, options) + errors = validate_recipe(pixi, recipe, options) assert any("PyTorch backend selection" in error for error in errors) - assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) + assert not validate_recipe(pixi, recipe, RecipeOptions()) @pytest.mark.parametrize( @@ -424,7 +420,7 @@ def test_recipe_checks_constraints_and_optional_pytorch(): ) def test_recipe_allows_backend_neutral_pytorch(dependency): recipe = {"requirements": {"run": [dependency]}} - assert not validate_recipe({}, recipe, {}, RecipeOptions(check_pytorch=True)) + assert not validate_recipe({}, recipe, RecipeOptions(check_pytorch=True)) @pytest.mark.parametrize( @@ -442,14 +438,14 @@ def test_recipe_allows_backend_neutral_pytorch(dependency): ) def test_recipe_rejects_pytorch_backend_selection(dependency): recipe = {"requirements": {"run": [dependency]}} - errors = validate_recipe({}, recipe, {}, RecipeOptions(check_pytorch=True)) + errors = validate_recipe({}, recipe, RecipeOptions(check_pytorch=True)) assert any("PyTorch backend selection" in error for error in errors) - assert not validate_recipe({}, recipe, {}, RecipeOptions()) + assert not validate_recipe({}, recipe, RecipeOptions()) def test_recipe_rejects_pytorch_backend_run_constraint(): recipe = {"requirements": {"run_constraints": ["pytorch >=2.0 cpu*"]}} - errors = validate_recipe({}, recipe, {}, RecipeOptions(check_pytorch=True)) + errors = validate_recipe({}, recipe, RecipeOptions(check_pytorch=True)) assert any("PyTorch backend selection" in error for error in errors) @@ -475,12 +471,12 @@ def test_recipe_infers_feature_constraint_source_and_floor(): } } - errors = validate_recipe(pixi, recipe, {}, RecipeOptions()) + errors = validate_recipe(pixi, recipe, RecipeOptions()) assert not errors pixi["feature"]["conda-rt"]["dependencies"]["pillow"] = "12.*" - errors = validate_recipe(pixi, recipe, {}, RecipeOptions()) + errors = validate_recipe(pixi, recipe, RecipeOptions()) assert any("pillow" in error for error in errors) @@ -494,7 +490,7 @@ def test_recipe_parses_conda_constraints_without_spaces( pixi = {"constraints": {"urllib3": pixi_constraint}} recipe = {"requirements": {"run_constraints": [recipe_constraint]}} - assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) + assert not validate_recipe(pixi, recipe, RecipeOptions()) def test_recipe_rejects_conditional_run_constraints(): @@ -506,13 +502,36 @@ def test_recipe_rejects_conditional_run_constraints(): } } - errors = validate_recipe(pixi, recipe, {}, RecipeOptions()) + errors = validate_recipe(pixi, recipe, RecipeOptions()) assert any( "Conditional run_constraints are not supported" in error for error in errors ) assert any("--ignore-constraints" in error for error in errors) +def test_recipe_checks_pytorch_in_run_and_conditional_run_constraints(): + recipe = { + "requirements": { + "run": ["pytorch-cpu >=2.0"], + "run_constraints": [ + {"if": "win", "then": "pytorch-cuda >=12"}, + "pytorch-mutex 1.0 cuda", + ], + } + } + + errors = validate_recipe({}, recipe, RecipeOptions(check_pytorch=True)) + + assert any( + "Conditional run_constraints are not supported" in error for error in errors + ) + pytorch_errors = [error for error in errors if "PyTorch backend selection" in error] + assert len(pytorch_errors) == 1 + assert "run: pytorch-cpu" in pytorch_errors[0] + assert "run_constraints: pytorch-cuda" in pytorch_errors[0] + assert "run_constraints: pytorch-mutex 1.0 cuda" in pytorch_errors[0] + + def test_recipe_ignores_conditional_constraint_validation_when_requested(): pixi = {"constraints": {"filelock": ">=4.2.1"}} recipe = { @@ -522,10 +541,47 @@ def test_recipe_ignores_conditional_constraint_validation_when_requested(): } } - errors = validate_recipe(pixi, recipe, {}, RecipeOptions(ignore_constraints=True)) + errors = validate_recipe(pixi, recipe, RecipeOptions(ignore_constraints=True)) assert not errors +def test_recipe_checks_transitivity_for_ignored_conditional_constraints(): + pixi = { + "constraints": { + "filelock": ">=4.2.1", + "setuptools": ">=84.1.0", + } + } + recipe = { + "requirements": { + "run": ["filelock >=4.2.1", "setuptools >=84.1.0"], + "run_constraints": [ + {"if": "win", "then": "filelock >=4.2.1"}, + "setuptools >=84.1.0", + ], + } + } + + errors = validate_recipe(pixi, recipe, RecipeOptions(ignore_constraints=True)) + transitivity_errors = [error for error in errors if "must remain" in error] + assert len(transitivity_errors) == 1 + assert "['filelock', 'setuptools']" in transitivity_errors[0] + + +def test_recipe_checks_pytorch_in_ignored_conditional_constraints(): + recipe = { + "requirements": { + "run_constraints": [{"if": "win", "then": "pytorch-cpu >=2.0"}] + } + } + + errors = validate_recipe( + {}, recipe, RecipeOptions(check_pytorch=True, ignore_constraints=True) + ) + + assert any("PyTorch backend selection" in error for error in errors) + + def test_recipe_accepts_inline_versions_but_rejects_versionless_dependencies(): pixi = { "feature": { @@ -537,38 +593,8 @@ def test_recipe_accepts_inline_versions_but_rejects_versionless_dependencies(): } } recipe = {"requirements": {"run_constraints": ["pillow >=13.0.0"]}} - assert not validate_recipe(pixi, recipe, {}, RecipeOptions()) + assert not validate_recipe(pixi, recipe, RecipeOptions()) pixi["feature"]["conda-rt"]["dependencies"]["pillow"] = {"path": "../pillow"} assert any( - "pillow" in error - for error in validate_recipe(pixi, recipe, {}, RecipeOptions()) - ) - - -@pytest.mark.parametrize("section", ["root", "feature"]) -def test_recipe_rejects_target_specific_direct_security_dependencies(section): - pixi: dict = {"constraints": {"filelock": ">=4.2.1"}} - target = {"win-64": {"dependencies": {"filelock": "*"}}} - if section == "root": - pixi["target"] = target - else: - pixi["feature"] = {"extra": {"target": target}} - recipe = {"requirements": {"run_constraints": ["filelock >=4.2.1"]}} - assert any( - "not direct dependencies" in error - for error in validate_recipe(pixi, recipe, {}, RecipeOptions()) - ) - - -def test_recipe_applies_aliases_to_feature_dependencies(): - pixi = { - "constraints": {"pytorch": ">=2.0"}, - "feature": {"extra": {"pypi-dependencies": {"torch": "*"}}}, - } - recipe = {"requirements": {"run_constraints": ["pytorch >=2.0"]}} - assert any( - "not direct dependencies" in error - for error in validate_recipe( - pixi, recipe, {}, RecipeOptions(package_aliases=("torch=pytorch",)) - ) + "pillow" in error for error in validate_recipe(pixi, recipe, RecipeOptions()) ) From 4c602cd7760033c1acbd306cba90dd53c49c4d58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:17:46 -0500 Subject: [PATCH 14/20] add note or known limitation --- README.md | 2 ++ mirageoscience/hooks/check_recipe.py | 3 +++ 2 files changed, 5 insertions(+) diff --git a/README.md b/README.md index 886d76b..6ebf4a9 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ Only enable the optional PyTorch check with `--check-pytorch` when required. For source validation, enable `--validate-pypi-sources`. The repeatable `--artifact-source-root` option is only used with this flag to permit download locations outside an index's URL. PyPI's standard artifact host is allowed automatically. If index configuration lives in a separate feature, `--pypi-index-feature` selects that feature's `pypi-options`; the feature must be enabled in the environment to apply its indexes. Otherwise, workspace-level options or the default PyPI index are used. +**Known limitation:** unconditional dependency traversal can reject valid recipes with conditional runtime dependencies. The check aims at covering simple use-cases for now. + ### `prepare-commit-msg` Adds the JIRA ID found in the branch name in case it is missing from the commit message. diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index be64966..058b77e 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -9,6 +9,9 @@ """Validate conda recipe constraints against the Pixi workspace. +**Known limitation:** unconditional dependency traversal can reject valid recipes with +conditional runtime dependencies. The check aims at covering simple use cases for now. + Conditional ``run_constraints`` entries are not supported by the Conda recipe comparison because they are flattened to a single effective constraint rather than one unconditional value. Use unconditional constraints or pass From 4488f7058884b72fa168fa7d20a17751a646d164 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:17:57 -0500 Subject: [PATCH 15/20] reflow readme file --- README.md | 65 ++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 50 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 6ebf4a9..6eca833 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ # MiraGeoscience.Pre-Commit Hooks -This repository provides a collection of pre-commit hooks to automate essential checks and streamline your development workflow. By utilizing these hooks, you can maintain code quality and consistency across your projects, fostering a more efficient and collaborative development environment. +This repository provides a collection of pre-commit hooks to automate essential +checks and streamline your development workflow. By utilizing these hooks, you +can maintain code quality and consistency across your projects, fostering a more +efficient and collaborative development environment. ## Included Hooks @@ -9,32 +12,52 @@ Checks for valid copyright statements in files. ### `check-pixi-lock` Checks locked Conda and PyPI sources against Pixi workspace features. -`--strict-pypi` requires the lock to contain exactly the packages declared by the selected PyPI feature; otherwise transitive PyPI dependencies are allowed while the feature packages are still checked. +`--strict-pypi` requires the lock to contain exactly the packages declared by +the selected PyPI feature; otherwise transitive PyPI dependencies are allowed +while the feature packages are still checked. -By default, this hook reads `pixi.toml` and `pixi.lock` from the repository root. Configure differing feature names with `--pypi-feature` and `--conda-feature`. +By default, this hook reads `pixi.toml` and `pixi.lock` from the repository root. +Configure differing feature names with `--pypi-feature` and `--conda-feature`. ### `check-recipe` -Checks recipe `run_constraints` against Pixi constraints, discovers matching feature constraints from `pixi.toml`, verifies constrained packages are not also direct dependencies in recipe `run`, and optionally checks that the recipe leaves PyTorch backend selection to the installer. +Checks recipe `run_constraints` against Pixi constraints, discovers matching +feature constraints from `pixi.toml`, verifies constrained packages are not +also direct dependencies in recipe `run`, and optionally checks that the recipe +leaves PyTorch backend selection to the installer. By default, this hook reads `recipe.yaml` and `pixi.toml` from the repository root. -Dependency consistency is checked by `pip check` during recipe builds; this hook focuses on ensuring recipe and Pixi constraints agree. +Dependency consistency is checked by `pip check` during recipe builds; this hook +focuses on ensuring recipe and Pixi constraints agree. -Conditional `run_constraints` are not supported by the recipe validation; use unconditional constraints or pass `--ignore-constraints` to skip this specific constraint comparison. +Conditional `run_constraints` are not supported by the recipe validation; use +unconditional constraints or pass `--ignore-constraints` to skip this specific +constraint comparison. -Recipe security floors and their Pixi source are inferred from `recipe.yaml` and `pixi.toml`. Git sources from `git+https://github.com/MiraGeoscience/` are allowed by default and can be overridden with `--git-url-prefix`. +Recipe security floors and their Pixi source are inferred from `recipe.yaml` and +`pixi.toml`. Git sources from `git+https://github.com/MiraGeoscience/` are allowed +by default and can be overridden with `--git-url-prefix`. Only enable the optional PyTorch check with `--check-pytorch` when required. -For source validation, enable `--validate-pypi-sources`. The repeatable `--artifact-source-root` option is only used with this flag to permit download locations outside an index's URL. PyPI's standard artifact host is allowed automatically. If index configuration lives in a separate feature, `--pypi-index-feature` selects that feature's `pypi-options`; the feature must be enabled in the environment to apply its indexes. Otherwise, workspace-level options or the default PyPI index are used. +For source validation, enable `--validate-pypi-sources`. The repeatable +`--artifact-source-root` option is only used with this flag to permit download +locations outside an index's URL. PyPI's standard artifact host is allowed automatically. +If index configuration lives in a separate feature, `--pypi-index-feature` selects that +feature's `pypi-options`; the feature must be enabled in the environment to apply its +indexes. Otherwise, workspace-level options or the default PyPI index are used. -**Known limitation:** unconditional dependency traversal can reject valid recipes with conditional runtime dependencies. The check aims at covering simple use-cases for now. +**Known limitation:** unconditional dependency traversal can reject valid recipes with +conditional runtime dependencies. The check aims at covering simple use-cases for now. ### `prepare-commit-msg` Adds the JIRA ID found in the branch name in case it is missing from the commit message. ### `check-commit-message` -Checks that the branch name or the commit message starts with a reference to JIRA, and if the message meets the minimum required length for the summary line. Also checks that the JIRA ID in the commit message is consistent with the one extracted from the branch name (if any). +Checks that the branch name or the commit message starts with a reference to JIRA, +and if the message meets the minimum required length for the summary line. Also checks +that the JIRA ID in the commit message is consistent with the one extracted from the +branch name (if any). ## Usage @@ -63,8 +86,20 @@ MIT License Copyright (c) 2024-2026 Mira Geoscience Ltd. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 6f279c29604f5a5e911876d16edbb57c1dffa0b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:44:12 -0500 Subject: [PATCH 16/20] check-pixi-lock: support repeatable pypi-feature and conda-feature also clarify doc in README --- README.md | 18 +++- mirageoscience/hooks/check_pixi_lock.py | 119 +++++++++++++++--------- tests/pixi_hooks_test.py | 67 +++++++++++++ 3 files changed, 159 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 6eca833..98fb447 100644 --- a/README.md +++ b/README.md @@ -13,11 +13,25 @@ Checks for valid copyright statements in files. ### `check-pixi-lock` Checks locked Conda and PyPI sources against Pixi workspace features. `--strict-pypi` requires the lock to contain exactly the packages declared by -the selected PyPI feature; otherwise transitive PyPI dependencies are allowed +the selected PyPI features; otherwise transitive PyPI dependencies are allowed while the feature packages are still checked. By default, this hook reads `pixi.toml` and `pixi.lock` from the repository root. -Configure differing feature names with `--pypi-feature` and `--conda-feature`. +Use `--pypi-feature` for each feature that declares packages under +`[feature..pypi-dependencies]`; the default is `mira-pypi`. Repeat the +option when PyPI dependencies are split across features, for example +`--pypi-feature=mira-pypi --pypi-feature=vendor-pypi`. + +Repeat the optional `--conda-feature` for each feature whose packages under +`[feature..dependencies]` must stay Conda-sourced, for example +`--conda-feature=conda-base --conda-feature=conda-runtime`. This enables a +source-separation check: in environments where the selected features are +enabled, those packages must be present in the Conda lock and not the PyPI +lock, while packages from the selected PyPI features must be present in the +PyPI lock and not the Conda lock. Do not select the same package in both +categories; this check rejects that overlap, even though Pixi itself resolves +such a conflict in favour of Conda. If omitted, the hook does not check the +source of feature-declared Conda dependencies. ### `check-recipe` Checks recipe `run_constraints` against Pixi constraints, discovers matching diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py index b878420..f9a0136 100644 --- a/mirageoscience/hooks/check_pixi_lock.py +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -27,8 +27,8 @@ @dataclass(frozen=True) class LockOptions: - pypi_feature: str - conda_feature: str | None = None + pypi_feature: str | tuple[str, ...] + conda_feature: str | tuple[str, ...] | None = None strict_pypi: bool = False pypi_index_feature: str | None = None validate_pypi_sources: bool = False @@ -84,6 +84,22 @@ def _feature_dependencies( return {canonicalize_name(name) for name in dependencies} +def _pypi_features(options: LockOptions) -> tuple[str, ...]: + """Normalize configured PyPI features to a tuple.""" + if isinstance(options.pypi_feature, str): + return (options.pypi_feature,) + return options.pypi_feature + + +def _conda_features(options: LockOptions) -> tuple[str, ...]: + """Normalize configured Conda features to a tuple.""" + if options.conda_feature is None: + return () + if isinstance(options.conda_feature, str): + return (options.conda_feature,) + return options.conda_feature + + def _environment_features(environment: object) -> set[str]: """Normalize a Pixi environment definition to its feature-name set.""" if isinstance(environment, dict): @@ -147,23 +163,47 @@ def _expectations( pixi: dict, options: LockOptions, platform: str, features: set[str] ) -> LockExpectations: """Build platform-specific package and artifact-source expectations.""" - pypi_packages = _feature_dependencies( - pixi, options.pypi_feature, "pypi-dependencies", platform - ) - conda_packages = ( - _feature_dependencies(pixi, options.conda_feature, "dependencies", platform) - if options.conda_feature - else set() - ) - index_feature: str | None = options.pypi_index_feature or options.pypi_feature - if index_feature not in features: - index_feature = None - index_urls = ( - _index_urls(pixi, index_feature) if options.validate_pypi_sources else set() + pypi_features = _pypi_features(options) + pypi_packages = set() + for feature_name in pypi_features: + feature_packages = _feature_dependencies( + pixi, feature_name, "pypi-dependencies", platform + ) + if feature_name in features: + pypi_packages.update(feature_packages) + conda_packages = set() + for feature_name in _conda_features(options): + feature_packages = _feature_dependencies( + pixi, feature_name, "dependencies", platform + ) + if feature_name in features: + conda_packages.update(feature_packages) + index_features = ( + ( + (options.pypi_index_feature,) + if options.pypi_index_feature in features + else () + ) + if options.pypi_index_feature + else tuple( + feature_name for feature_name in pypi_features if feature_name in features + ) ) + index_urls = set() + if options.validate_pypi_sources: + if index_features: + for feature_name in index_features: + index_urls.update(_index_urls(pixi, feature_name)) + else: + index_urls = _index_urls(pixi, None) source_indexes = set(index_urls) - index_options = _pypi_options(pixi, index_feature) - if options.validate_pypi_sources and not index_options.get("index-url"): + has_default_index = ( + not index_features and not _pypi_options(pixi, None).get("index-url") + ) or any( + not _pypi_options(pixi, feature_name).get("index-url") + for feature_name in index_features + ) + if options.validate_pypi_sources and has_default_index: source_indexes.add(PYPI_INDEX) source_roots = { f"{url.removesuffix('/simple').rstrip('/')}/" for url in source_indexes @@ -247,10 +287,10 @@ def _pypi_errors( """Check locked PyPI packages, using exact or minimum membership policy.""" options = context.options expectations = context.expectations + pypi_features = _pypi_features(options) + pypi_feature_enabled = any(feature in features for feature in pypi_features) pypi_names = _locked_names(entries, context.packages_by_url, "pypi") - expected_pypi = ( - expectations.pypi_packages if options.pypi_feature in features else set() - ) + expected_pypi = expectations.pypi_packages errors = [] if options.strict_pypi: if pypi_names != expected_pypi: @@ -262,15 +302,18 @@ def _pypi_errors( missing_pypi = expected_pypi - pypi_names if missing_pypi: errors.append(f"{label}: missing PyPI packages {sorted(missing_pypi)}") - if options.pypi_feature not in features and pypi_names: + if not pypi_feature_enabled and pypi_names: + feature_label = ( + f"the {pypi_features[0]!r} feature" + if len(pypi_features) == 1 + else f"any of the {pypi_features!r} features" + ) errors.append( - f"{label}: PyPI packages are locked without the " - f"{options.pypi_feature!r} feature: {sorted(pypi_names)}" + f"{label}: PyPI packages are locked without {feature_label}: " + f"{sorted(pypi_names)}" ) errors.extend( - _source_errors( - label, entries, environment_lock, options.pypi_feature in features, context - ) + _source_errors(label, entries, environment_lock, pypi_feature_enabled, context) ) return errors @@ -279,21 +322,11 @@ def _conda_errors( label: str, pypi_names: set[str], conda_names: set[str], - features: set[str], context: LockContext, ) -> list[str]: """Check expected packages are locked from their configured package source.""" - options = context.options - expected_conda = ( - context.expectations.conda_packages - if options.conda_feature and options.conda_feature in features - else set() - ) - expected_pypi = ( - context.expectations.pypi_packages - if options.pypi_feature in features - else set() - ) + expected_conda = context.expectations.conda_packages + expected_pypi = context.expectations.pypi_packages errors = [] missing_conda = expected_conda - conda_names if missing_conda: @@ -325,7 +358,7 @@ def _validate_platform( conda_names = _locked_names(entries, context.packages_by_url, "conda") return _pypi_errors( label, entries, environment_lock, features, context - ) + _conda_errors(label, pypi_names, conda_names, features, context) + ) + _conda_errors(label, pypi_names, conda_names, context) def _validate_environment( @@ -386,8 +419,8 @@ def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--pixi-file", type=Path, default=Path("pixi.toml")) parser.add_argument("--lock-file", type=Path, default=Path("pixi.lock")) - parser.add_argument("--pypi-feature", default="mira-pypi") - parser.add_argument("--conda-feature") + parser.add_argument("--pypi-feature", action="append") + parser.add_argument("--conda-feature", action="append") parser.add_argument("--strict-pypi", action="store_true") parser.add_argument("--pypi-index-feature") parser.add_argument("--validate-pypi-sources", action="store_true") @@ -404,8 +437,8 @@ def main() -> int: pixi, lock, LockOptions( - pypi_feature=args.pypi_feature, - conda_feature=args.conda_feature, + pypi_feature=tuple(args.pypi_feature or ["mira-pypi"]), + conda_feature=tuple(args.conda_feature or []), strict_pypi=args.strict_pypi, pypi_index_feature=args.pypi_index_feature, validate_pypi_sources=args.validate_pypi_sources, diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index 9e004eb..ec37184 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -70,6 +70,15 @@ def _multiline_pixi_manifest() -> str: [feature.mira-pypi] pypi-dependencies = {} + +[feature.vendor-pypi] +pypi-dependencies = {} + +[feature.conda-base] +dependencies = {} + +[feature.conda-extra] +dependencies = {} """ @@ -116,6 +125,12 @@ def test_pixi_lock_main_parses_toml_11_inline_tables(tmp_path, monkeypatch, caps str(lock_file), "--pypi-feature", "mira-pypi", + "--pypi-feature", + "vendor-pypi", + "--conda-feature", + "conda-base", + "--conda-feature", + "conda-extra", ], ) @@ -157,6 +172,58 @@ def test_non_strict_pypi_allows_transitive_packages_for_meta_packages(): assert not errors +def test_multiple_pypi_features_check_packages_and_indexes_together(): + pixi, lock = _lock_fixture( + features=["mira-pypi", "vendor-pypi"], + pypi_names=("mira-package", "vendor-package"), + ) + pixi["feature"]["mira-pypi"]["pypi-options"] = { + "extra-index-urls": ["https://packages.example.org/simple"] + } + pixi["feature"]["vendor-pypi"] = {"pypi-dependencies": {"vendor-package": "*"}} + lock["packages"][1]["pypi"] = ( + "https://files.pythonhosted.org/packages/vendor-package.whl" + ) + lock["environments"]["default"]["indexes"] = ["https://packages.example.org/simple"] + lock["environments"]["default"]["packages"]["win-64"] = [ + {"pypi": package["pypi"]} for package in lock["packages"] + ] + + errors = validate_lock( + pixi, + lock, + LockOptions( + pypi_feature=("mira-pypi", "vendor-pypi"), + strict_pypi=True, + validate_pypi_sources=True, + ), + ) + + assert not errors + + +def test_multiple_conda_features_check_packages_together(): + pixi, lock = _lock_fixture( + features=["mira-pypi", "conda-base", "conda-extra"], + pypi_names=("mira-package",), + ) + pixi["feature"]["conda-base"] = {"dependencies": {"base-package": "*"}} + pixi["feature"]["conda-extra"] = {"dependencies": {"extra-package": "*"}} + base_url = "https://example.org/base-package-1-0.conda" + extra_url = "https://example.org/extra-package-1-0.conda" + entries = lock["environments"]["default"]["packages"]["win-64"] + entries.extend([{"conda": base_url}, {"conda": extra_url}]) + options = LockOptions( + pypi_feature="mira-pypi", + conda_feature=("conda-base", "conda-extra"), + ) + + assert not validate_lock(pixi, lock, options) + entries.remove({"conda": extra_url}) + errors = validate_lock(pixi, lock, options) + assert any("missing Conda packages ['extra-package']" in error for error in errors) + + def test_pypi_source_validation_defaults_to_mira_git_urls(): index = "https://packages.example.org/simple" git_url = "git+https://github.com/MiraGeoscience/mira-package.git" From d93123a112cb572f4ad55dcd54729c9ec27f193e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:44:50 -0500 Subject: [PATCH 17/20] clarify and some mix-up in the documentation --- README.md | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 98fb447..8de8f6e 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,30 @@ categories; this check rejects that overlap, even though Pixi itself resolves such a conflict in favour of Conda. If omitted, the hook does not check the source of feature-declared Conda dependencies. +By default, the hook checks expected package membership and Conda-versus-PyPI +lock placement, but does not validate PyPI index URLs or package download +origins. Enable `--validate-pypi-sources` for those checks. The repeatable +`--artifact-source-root` option is only used with this flag to permit download +locations outside an index's URL. For example, if a locked wheel is downloaded from +`https://artifacts.example.com/python-wheels/package-1.0.whl`, allow that artifact +location with: + +```yaml +args: + - --validate-pypi-sources + - --artifact-source-root=https://artifacts.example.com/python-wheels +``` + +The root is the allowed artifact URL prefix, not the PyPI index URL; repeat the option +for additional artifact locations. + +PyPI's standard artifact host is allowed automatically. +If index configuration lives in a separate feature, `--pypi-index-feature` selects that +feature's `pypi-options`; the feature must be enabled in the environment to apply its +indexes. Otherwise, workspace-level options or the default PyPI index are used. Git +sources from `git+https://github.com/MiraGeoscience/` are allowed by default; repeat +`--git-url-prefix` to configure allowed Git URL prefixes. + ### `check-recipe` Checks recipe `run_constraints` against Pixi constraints, discovers matching feature constraints from `pixi.toml`, verifies constrained packages are not @@ -49,18 +73,10 @@ unconditional constraints or pass `--ignore-constraints` to skip this specific constraint comparison. Recipe security floors and their Pixi source are inferred from `recipe.yaml` and -`pixi.toml`. Git sources from `git+https://github.com/MiraGeoscience/` are allowed -by default and can be overridden with `--git-url-prefix`. +`pixi.toml`. Only enable the optional PyTorch check with `--check-pytorch` when required. -For source validation, enable `--validate-pypi-sources`. The repeatable -`--artifact-source-root` option is only used with this flag to permit download -locations outside an index's URL. PyPI's standard artifact host is allowed automatically. -If index configuration lives in a separate feature, `--pypi-index-feature` selects that -feature's `pypi-options`; the feature must be enabled in the environment to apply its -indexes. Otherwise, workspace-level options or the default PyPI index are used. - **Known limitation:** unconditional dependency traversal can reject valid recipes with conditional runtime dependencies. The check aims at covering simple use-cases for now. From e27b9dac51dba7d7c6ec05cec58c29b3861e6101 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:33:15 -0500 Subject: [PATCH 18/20] Fix recipe validation feedback Apply the PR review feedback for conditional recipe constraints, invalid-config handling, and regression coverage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 4 +- mirageoscience/hooks/check_recipe.py | 50 ++++++++++++--------- tests/pixi_hooks_test.py | 65 +++++++++++++++++++++++++++- 3 files changed, 96 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 8de8f6e..9c1d794 100644 --- a/README.md +++ b/README.md @@ -77,8 +77,8 @@ Recipe security floors and their Pixi source are inferred from `recipe.yaml` and Only enable the optional PyTorch check with `--check-pytorch` when required. -**Known limitation:** unconditional dependency traversal can reject valid recipes with -conditional runtime dependencies. The check aims at covering simple use-cases for now. +**Known limitation:** both branches of conditional runtime dependencies are checked, +which can reject recipes whose constraints apply to a different platform. ### `prepare-commit-msg` Adds the JIRA ID found in the branch name in case it is missing from the commit message. diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index 058b77e..5879244 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -9,8 +9,8 @@ """Validate conda recipe constraints against the Pixi workspace. -**Known limitation:** unconditional dependency traversal can reject valid recipes with -conditional runtime dependencies. The check aims at covering simple use cases for now. +**Known limitation:** both branches of conditional runtime dependencies are checked, +which can reject recipes whose constraints apply to a different platform. Conditional ``run_constraints`` entries are not supported by the Conda recipe comparison because they are flattened to a single effective constraint rather than @@ -80,9 +80,9 @@ def _requirement_strings(values: object): if isinstance(values, dict): if "if" in values or "then" in values or "else" in values: raise ValueError( - "Conditional recipe requirements are not supported by " - "check-conda-recipe; pass --ignore-constraints to skip this check " - "for conditional constraints, or use unconditional constraints." + "Conditional run_constraints are not supported by check-recipe; " + "pass --ignore-constraints to skip this check for conditional " + "constraints, or use unconditional constraints." ) raise ValueError(f"Invalid recipe requirement entry: {values!r}") raise ValueError(f"Invalid recipe requirement entry: {values!r}") @@ -224,7 +224,7 @@ def _recipe_transitivity_errors( } dependencies = { _requirement_package(value) - for value in _requirement_strings(run_requirement_entries) + for value in _flatten_requirement_strings(run_requirement_entries) } dependencies = {aliases.get(package, package) for package in dependencies} direct_dependencies = security_packages & dependencies @@ -271,7 +271,7 @@ def validate_recipe(pixi: dict, recipe: dict, options: RecipeOptions) -> list[st ) if has_conditional_constraints and not options.ignore_constraints: errors.append( - "Conditional run_constraints are not supported by check-conda-recipe; " + "Conditional run_constraints are not supported by check-recipe; " "use unconditional constraints or exclude this validation. Pass " "--ignore-constraints to skip this check for conditional constraints." ) @@ -306,19 +306,29 @@ def main() -> int: parser.add_argument("--ignore-constraints", action="store_true") args = parser.parse_args() - with args.pixi_file.open("rb") as file: - pixi = tomlkit.load(file).unwrap() - with args.recipe_file.open(encoding="utf-8") as file: - recipe = yaml.safe_load(file) - errors = validate_recipe( - pixi, - recipe, - RecipeOptions( - package_aliases=tuple(args.package_alias), - check_pytorch=args.check_pytorch, - ignore_constraints=args.ignore_constraints, - ), - ) + try: + with args.pixi_file.open("rb") as file: + pixi = tomlkit.load(file).unwrap() + with args.recipe_file.open(encoding="utf-8") as file: + recipe = yaml.safe_load(file) + errors = validate_recipe( + pixi, + recipe, + RecipeOptions( + package_aliases=tuple(args.package_alias), + check_pytorch=args.check_pytorch, + ignore_constraints=args.ignore_constraints, + ), + ) + except ( + ValueError, + KeyError, + TypeError, + tomlkit.exceptions.ParseError, + yaml.YAMLError, + ) as error: + print(f"Invalid recipe configuration: {error}", file=sys.stderr) + return 1 if errors: print("\n".join(errors), file=sys.stderr) return 1 diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py index ec37184..58d2f71 100644 --- a/tests/pixi_hooks_test.py +++ b/tests/pixi_hooks_test.py @@ -106,6 +106,37 @@ def test_recipe_main_parses_toml_11_inline_tables(tmp_path, monkeypatch, capsys) assert "Recipe constraints match" in capsys.readouterr().out +@pytest.mark.parametrize( + "case", + [ + ("invalid = [", "requirements: {}", []), + ("", "requirements: [", []), + ("", "requirements: {}", ["--package-alias", "invalid"]), + ], +) +def test_recipe_main_reports_invalid_configuration(tmp_path, monkeypatch, capsys, case): + pixi_content, recipe_content, extra_args = case + pixi_file = tmp_path / "pixi.toml" + recipe_file = tmp_path / "recipe.yaml" + pixi_file.write_text(pixi_content, encoding="utf-8") + recipe_file.write_text(recipe_content, encoding="utf-8") + monkeypatch.setattr( + sys, + "argv", + [ + "check-recipe", + "--pixi-file", + str(pixi_file), + "--recipe-file", + str(recipe_file), + *extra_args, + ], + ) + + assert check_recipe_main() == 1 + assert "Invalid recipe configuration:" in capsys.readouterr().err + + def test_pixi_lock_main_parses_toml_11_inline_tables(tmp_path, monkeypatch, capsys): pixi_file = tmp_path / "pixi.toml" lock_file = tmp_path / "pixi.lock" @@ -560,6 +591,37 @@ def test_recipe_parses_conda_constraints_without_spaces( assert not validate_recipe(pixi, recipe, RecipeOptions()) +@pytest.mark.parametrize("branch", ["then", "else"]) +def test_recipe_checks_conditional_run_requirements_for_transitivity(branch): + recipe = { + "requirements": { + "run": [{"if": "win", branch: ["python", "urllib3 >=2.5"]}], + "run_constraints": ["urllib3 >=2.5"], + } + } + + errors = validate_recipe( + {"constraints": {"urllib3": ">=2.5"}}, recipe, RecipeOptions() + ) + + assert len(errors) == 1 + assert "must remain transitive" in errors[0] + assert "urllib3" in errors[0] + + +def test_recipe_accepts_unconstrained_conditional_run_requirements(): + recipe = { + "requirements": { + "run": ["numpy", {"if": "win", "then": "pywin32", "else": "posix"}], + "run_constraints": ["urllib3 >=2.5"], + } + } + + assert not validate_recipe( + {"constraints": {"urllib3": ">=2.5"}}, recipe, RecipeOptions() + ) + + def test_recipe_rejects_conditional_run_constraints(): pixi = {"constraints": {"filelock": ">=4.2.1"}} recipe = { @@ -571,7 +633,8 @@ def test_recipe_rejects_conditional_run_constraints(): errors = validate_recipe(pixi, recipe, RecipeOptions()) assert any( - "Conditional run_constraints are not supported" in error for error in errors + "Conditional run_constraints are not supported by check-recipe" in error + for error in errors ) assert any("--ignore-constraints" in error for error in errors) From f1ed3319398d2074805b76ae315a5d3fe1964506 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:14:12 -0500 Subject: [PATCH 19/20] add checks: recipe and requirements must be a dict --- mirageoscience/hooks/check_recipe.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index 5879244..df0cbf3 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -262,7 +262,11 @@ def _pytorch_errors(requirements: dict) -> list[str]: def validate_recipe(pixi: dict, recipe: dict, options: RecipeOptions) -> list[str]: """Validate recipe constraints, transitivity, and optional PyTorch policy.""" errors = [] + if not isinstance(recipe, dict): + raise ValueError("recipe.yaml must contain a mapping") requirements = recipe.get("requirements", {}) + if not isinstance(requirements, dict): + raise ValueError("recipe.yaml 'requirements' must be a mapping") run_requirement_entries = requirements.get("run", []) run_constraint_requirement_entries = requirements.get("run_constraints", []) has_conditional_constraints = any( From 3df0e5e91841ac1f00e5d07ea4a9de7351602456 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Hensgen?= <24550538+sebhmg@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:45:03 -0500 Subject: [PATCH 20/20] DRY: use a manifest_error context --- mirageoscience/hooks/_cli_utils.py | 51 +++++++++++++++++++++++++ mirageoscience/hooks/check_pixi_lock.py | 23 ++++------- mirageoscience/hooks/check_recipe.py | 23 ++++------- 3 files changed, 65 insertions(+), 32 deletions(-) create mode 100644 mirageoscience/hooks/_cli_utils.py diff --git a/mirageoscience/hooks/_cli_utils.py b/mirageoscience/hooks/_cli_utils.py new file mode 100644 index 0000000..8ab5790 --- /dev/null +++ b/mirageoscience/hooks/_cli_utils.py @@ -0,0 +1,51 @@ +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Copyright (c) 2024-2026 Mira Geoscience Ltd. ' +# ' +# This file is part of mirageoscience.pre-commit-hooks package. ' +# ' +# mirageoscience.pre-commit-hooks is distributed under the terms and conditions ' +# of the MIT License (see LICENSE file at the root of this source code package). ' +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + +from __future__ import annotations + +import sys +from collections.abc import Iterator +from contextlib import contextmanager + +import tomlkit +import yaml + + +def print_invalid_configuration(kind: str, error: Exception) -> None: + """Print a consistent CLI error for invalid hook configuration.""" + print(f"Invalid {kind} configuration: {error}", file=sys.stderr) + + +def report_validation_result(errors: list[str] | None, success_message: str) -> int: + """Report manifest validation results and return the CLI status.""" + if errors is None: + # Manifest parsing/validation raised an expected error inside manifest_error. + return 1 + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + print(success_message) + return 0 + + +@contextmanager +def manifest_error(kind: str) -> Iterator[list[Exception]]: + """Report expected errors while parsing or validating a manifest.""" + errors: list[Exception] = [] + try: + yield errors + except ( + ValueError, + KeyError, + TypeError, + tomlkit.exceptions.ParseError, + yaml.YAMLError, + ) as error: + errors.append(error) + print_invalid_configuration(kind, error) diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py index f9a0136..d72a116 100644 --- a/mirageoscience/hooks/check_pixi_lock.py +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -11,7 +11,6 @@ import argparse import re -import sys from dataclasses import dataclass from pathlib import Path from urllib.parse import unquote, urlsplit @@ -20,6 +19,8 @@ import yaml from packaging.utils import canonicalize_name +from mirageoscience.hooks._cli_utils import manifest_error, report_validation_result + DEFAULT_GIT_URL_PREFIXES = ("git+https://github.com/MiraGeoscience/",) PYPI_INDEX = "https://pypi.org/simple" @@ -428,7 +429,8 @@ def main() -> int: parser.add_argument("--artifact-source-root", action="append", default=[]) args = parser.parse_args() - try: + errors: list[str] | None = None + with manifest_error("Pixi lock"): with args.pixi_file.open("rb") as file: pixi = tomlkit.load(file).unwrap() with args.lock_file.open(encoding="utf-8") as file: @@ -450,20 +452,9 @@ def main() -> int: ), ), ) - except ( - ValueError, - KeyError, - TypeError, - tomlkit.exceptions.ParseError, - yaml.YAMLError, - ) as error: - print(f"Invalid Pixi lock configuration: {error}", file=sys.stderr) - return 1 - if errors: - print("\n".join(errors), file=sys.stderr) - return 1 - print("Pixi lock package sources match the configured features.") - return 0 + return report_validation_result( + errors, "Pixi lock package sources match the configured features." + ) if __name__ == "__main__": diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py index df0cbf3..50b1420 100644 --- a/mirageoscience/hooks/check_recipe.py +++ b/mirageoscience/hooks/check_recipe.py @@ -22,7 +22,6 @@ import argparse import re -import sys from dataclasses import dataclass from pathlib import Path @@ -32,6 +31,8 @@ from packaging.utils import canonicalize_name from packaging.version import Version +from mirageoscience.hooks._cli_utils import manifest_error, report_validation_result + @dataclass(frozen=True) class RecipeOptions: @@ -310,7 +311,8 @@ def main() -> int: parser.add_argument("--ignore-constraints", action="store_true") args = parser.parse_args() - try: + errors: list[str] | None = None + with manifest_error("recipe"): with args.pixi_file.open("rb") as file: pixi = tomlkit.load(file).unwrap() with args.recipe_file.open(encoding="utf-8") as file: @@ -324,20 +326,9 @@ def main() -> int: ignore_constraints=args.ignore_constraints, ), ) - except ( - ValueError, - KeyError, - TypeError, - tomlkit.exceptions.ParseError, - yaml.YAMLError, - ) as error: - print(f"Invalid recipe configuration: {error}", file=sys.stderr) - return 1 - if errors: - print("\n".join(errors), file=sys.stderr) - return 1 - print("Recipe constraints match Pixi constraints and remain transitive.") - return 0 + return report_validation_result( + errors, "Recipe constraints match Pixi constraints and remain transitive." + ) if __name__ == "__main__":