From 3a18b0d7fe7fe6778082ce078654d43920ec0cdf Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:18 +0000 Subject: [PATCH 01/17] test(parity): add reproducible easybuild parity audit script The new script lives under scripts/. The recipe command gains a hidden parity-audit subcommand that exports JSON for it. An integration test suite writes its own fixtures, and the integration CI job runs it. The script prints the seed it samples with, so a run can be repeated. The sample always takes in the easyblocks that change module naming. The script compares module metadata and the nearest dependencies against EasyBuild at runtime, with no copied corpus. --- .github/workflows/ci_test.yml | 1 + changelog.d/+parity-audit-harness.misc.md | 1 + scripts/parity_audit.py | 653 ++++++++++++++++++++++ src/build_order.rs | 56 ++ src/main.rs | 113 ++++ tests/parity_audit_script.rs | 327 +++++++++++ 6 files changed, 1151 insertions(+) create mode 100644 changelog.d/+parity-audit-harness.misc.md create mode 100755 scripts/parity_audit.py create mode 100644 tests/parity_audit_script.rs diff --git a/.github/workflows/ci_test.yml b/.github/workflows/ci_test.yml index d55b5ec2..d40ee11c 100644 --- a/.github/workflows/ci_test.yml +++ b/.github/workflows/ci_test.yml @@ -228,6 +228,7 @@ jobs: --test module_tree_dump_script \ --test oom_profile \ --test optimisation_criteria \ + --test parity_audit_script \ --test pr_merge_order \ --test pr_overlap \ --test pr_overlap_arch \ diff --git a/changelog.d/+parity-audit-harness.misc.md b/changelog.d/+parity-audit-harness.misc.md new file mode 100644 index 00000000..b34bdaf9 --- /dev/null +++ b/changelog.d/+parity-audit-harness.misc.md @@ -0,0 +1 @@ +Add the reproducible EasyBuild parity audit script under scripts/ together with its generated-fixture integration test and hidden recipe parity-audit export subcommand. diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py new file mode 100755 index 00000000..dd58c121 --- /dev/null +++ b/scripts/parity_audit.py @@ -0,0 +1,653 @@ +#!/usr/bin/env python3 +"""Reproducible parity audit between EasyBuild and ``eb-stack``. + +Selects a deterministic stratified sample across an easyconfigs tree +(seeded via ``--seed``) plus a targeted set of recipes using easyblocks +that touch module naming (``ModuleRC``, ``Toolchain``, ``Bundle``, +``Amber``, ``versionprefix``, ``modaltsoftname``, and any easyblock in +``--easybuild-easyblocks`` overriding ``det_full_module_name`` or using +``modaltsoftname``). + +Compares ``eb-stack recipe parity-audit`` against EasyBuild (or a +pre-generated ``--truth-json`` oracle) across parse status, dropped +``exts_list``, ``module_name``, ``versionsuffix``, ``exts_count``, and +nearest-hierarchy-level dependency resolution. Exits 0 on full parity +and 1 on any mismatch or error. +""" + +from __future__ import annotations + +import argparse +import json +import os +import random +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +TARGETED_EASYBLOCKS = ("ModuleRC", "Toolchain", "Bundle", "Amber") +_ASSIGN_RE = re.compile( + r"^\s*(easyblock|versionprefix|modaltsoftname|exts_list|dependencies|builddependencies)\s*=", + re.MULTILINE, +) +_TOOLCHAIN_RE = re.compile( + r"^\s*toolchain\s*=\s*\{\s*['\"]name['\"]\s*:\s*['\"]([^'\"]+)['\"]", + re.MULTILINE, +) + + +def parse_args(argv: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--easyconfigs", + type=Path, + required=True, + help="Path to the easyconfigs root directory.", + ) + parser.add_argument( + "--seed", + type=int, + default=20261121, + help="PRNG seed for deterministic stratified sampling (default: 20261121).", + ) + parser.add_argument( + "--sample-size", + type=int, + default=200, + help="Target stratified random sample size (default: 200).", + ) + parser.add_argument( + "--no-targeted", + action="store_true", + help="Do not add targeted module-naming easyblock recipes.", + ) + parser.add_argument( + "--easybuild-framework", + type=Path, + default=None, + help="Optional easybuild-framework checkout path to prepend to sys.path.", + ) + parser.add_argument( + "--easybuild-easyblocks", + type=Path, + default=None, + help="Optional easybuild-easyblocks checkout path to scan and add to sys.path.", + ) + parser.add_argument( + "--pythonpath", + action="append", + default=[], + help="Extra directory to prepend to sys.path when importing easybuild.", + ) + parser.add_argument( + "--truth-json", + type=Path, + default=None, + help="Optional JSON oracle file instead of importing EasyBuild.", + ) + parser.add_argument( + "--emit-truth", + type=Path, + default=None, + help="Optional path to write the EasyBuild truth JSON.", + ) + parser.add_argument( + "--eb-stack", + type=Path, + default=None, + help="Path to the eb-stack binary.", + ) + parser.add_argument( + "--eb-stack-json", + type=Path, + default=None, + help="Optional pre-generated JSON from `eb-stack recipe parity-audit`.", + ) + parser.add_argument( + "--out", + type=Path, + default=None, + help="Optional path to write the full parity report JSON.", + ) + return parser.parse_args(argv) + + +def discover_easyblocks_touching_naming(easyblocks_root: Path | None) -> list[str]: + if easyblocks_root is None or not easyblocks_root.is_dir(): + return [] + matched: set[str] = set() + for path in sorted(easyblocks_root.rglob("*.py")): + try: + text = path.read_text(encoding="utf-8", errors="ignore") + except OSError: + continue + if "def det_full_module_name" in text or "modaltsoftname" in text: + for m in re.finditer(r"class\s+(EB_[A-Za-z0-9_]+)\s*\(", text): + cls = m.group(1) + if cls.startswith("EB_"): + matched.add(cls[3:]) + matched.add(cls) + return sorted(matched) + + +def collect_easyconfig_files(root: Path) -> list[tuple[str, str]]: + files: list[tuple[str, str]] = [] + for path in sorted(root.rglob("*.eb")): + rel = path.relative_to(root).as_posix() + if "/__archive__/" in f"/{rel}": + continue + text = path.read_text(encoding="utf-8", errors="ignore") + files.append((rel, text)) + return files + + +def classify_recipe(rel: str, text: str, extra_easyblocks: set[str]) -> tuple[str, bool]: + easyblock_match = re.search( + r"^\s*easyblock\s*=\s*['\"]([^'\"]+)['\"]", text, re.MULTILINE + ) + easyblock = easyblock_match.group(1) if easyblock_match else "" + tc_match = _TOOLCHAIN_RE.search(text) + tc_name = tc_match.group(1) if tc_match else "system" + + is_targeted = ( + easyblock in TARGETED_EASYBLOCKS + or easyblock in extra_easyblocks + or bool(re.search(r"^\s*versionprefix\s*=", text, re.MULTILINE)) + or bool(re.search(r"^\s*modaltsoftname\s*=", text, re.MULTILINE)) + ) + + if easyblock == "Toolchain" or tc_name in ("foss", "intel", "gompi", "gfbf", "NVHPC"): + bucket = f"tc:{tc_name}" + elif "Bundle" in easyblock: + bucket = "bundle" + elif re.search(r"^\s*exts_list\s*=", text, re.MULTILINE): + bucket = "exts_list" + elif re.search(r"^\s*versionprefix\s*=", text, re.MULTILINE): + bucket = "versionprefix" + elif re.search(r"^\s*(dependencies|builddependencies)\s*=", text, re.MULTILINE): + bucket = "deps" + else: + bucket = f"tc:{tc_name}" + return bucket, is_targeted + + +def select_sample( + root: Path, + seed: int, + sample_size: int, + include_targeted: bool, + extra_easyblocks: list[str], +) -> tuple[list[str], dict[str, str]]: + files = collect_easyconfig_files(root) + extra_set = set(extra_easyblocks) + buckets: dict[str, list[str]] = {} + targeted: list[str] = [] + reasons: dict[str, str] = {} + + for rel, text in files: + bucket, is_targeted = classify_recipe(rel, text, extra_set) + buckets.setdefault(bucket, []).append(rel) + if include_targeted and is_targeted: + targeted.append(rel) + reasons[rel] = "targeted" + + rng = random.Random(seed) + chosen: list[str] = [] + chosen_set: set[str] = set() + + if sample_size > 0 and files: + bucket_names = sorted(buckets) + per_bucket = max(1, sample_size // max(1, len(bucket_names))) + remainder_pool: list[tuple[str, str]] = [] + for bname in bucket_names: + items = list(buckets[bname]) + rng.shuffle(items) + take = items[:per_bucket] + for rel in take: + if len(chosen) >= sample_size: + break + if rel not in chosen_set: + chosen.append(rel) + chosen_set.add(rel) + reasons.setdefault(rel, f"sample:{bname}") + for rel in items[per_bucket:]: + remainder_pool.append((bname, rel)) + if len(chosen) < sample_size and remainder_pool: + rng.shuffle(remainder_pool) + for bname, rel in remainder_pool: + if len(chosen) >= sample_size: + break + if rel not in chosen_set: + chosen.append(rel) + chosen_set.add(rel) + reasons.setdefault(rel, f"sample:{bname}") + + for rel in sorted(targeted): + if rel not in chosen_set: + chosen.append(rel) + chosen_set.add(rel) + + return sorted(chosen), reasons + + +def format_eb_dep_module(dep: dict) -> str: + if dep.get("resolved_module"): + return str(dep["resolved_module"]) + name = str(dep["name"]) + version = str(dep.get("version") or dep.get("version_req") or "") + vprefix = str(dep.get("versionprefix") or "") + vsuffix = str(dep.get("versionsuffix") or "") + tc_name = str(dep.get("toolchain_name") or "") + tc_ver = str(dep.get("toolchain_version") or "") + if not tc_name or tc_name.lower() == "system" or tc_ver.lower() == "system": + tc_part = "" + elif tc_ver: + tc_part = f"-{tc_name}-{tc_ver}" + else: + tc_part = f"-{tc_name}" + return f"{name}/{vprefix}{version}{tc_part}{vsuffix}" + + +def extract_easybuild_truth( + root: Path, + rels: list[str], + reasons: dict[str, str], + framework_dir: Path | None, + easyblocks_dir: Path | None, + extra_pythonpath: list[str], +) -> dict: + for entry in reversed(extra_pythonpath): + if entry and entry not in sys.path: + sys.path.insert(0, entry) + for extra_dir in (easyblocks_dir, framework_dir): + if extra_dir is not None: + resolved = str(extra_dir.resolve()) + if resolved not in sys.path: + sys.path.insert(0, resolved) + + try: + from easybuild.framework.easyconfig import easyconfig as eb_easyconfig + from easybuild.framework.easyconfig.easyconfig import EasyConfig + from easybuild.tools import modules as eb_modules + from easybuild.tools.module_naming_scheme.easybuild_mns import EasyBuildMNS + except ImportError as exc: + raise SystemExit( + "EasyBuild is not importable; pass --truth-json or --easybuild-framework. " + f"Import error: {exc}" + ) from exc + + try: + from easybuild.tools.options import set_up_configuration + + set_up_configuration( + args=[f"--robot={root}"], + silent=True, + ) + except Exception: + pass + + if hasattr(eb_modules, "NoModulesTool") and hasattr(eb_easyconfig, "modules_tool"): + orig_modules_tool = eb_easyconfig.modules_tool + + def _safe_modules_tool(*args, **kwargs): + try: + return orig_modules_tool(*args, **kwargs) + except Exception: + return eb_modules.NoModulesTool(testing=True) + + eb_easyconfig.modules_tool = _safe_modules_tool + + mns = EasyBuildMNS() + results = [] + for rel in rels: + path = root / rel + try: + ec = EasyConfig(str(path), validate=False) + full_mod_name = mns.det_full_module_name(ec) + tc = ec.get("toolchain") or {} + tc_name = str(tc.get("name", "system")) + tc_ver = str(tc.get("version", "system")) + all_deps = ( + ec.dependencies() + if callable(getattr(ec, "dependencies", None)) + else ec.get("dependencies", []) + ) + deps = [ + dep_to_dict(dep) + for dep in all_deps + if not (isinstance(dep, dict) and dep.get("build_only")) + ] + bdeps = [] + bdep_raw = ( + ec.builddependencies() + if callable(getattr(ec, "builddependencies", None)) + else ec.get("builddependencies", []) + ) + for dep in bdep_raw: + bdeps.append(dep_to_dict(dep)) + try: + exts = ec.get("exts_list", resolve=False) or [] + except TypeError: + exts = ec.get("exts_list") or [] + results.append( + { + "rel": rel, + "bucket": reasons.get(rel, ""), + "ok": True, + "name": str(ec["name"]), + "version": str(ec["version"]), + "versionprefix": str(ec.get("versionprefix") or ""), + "versionsuffix": str(ec.get("versionsuffix") or ""), + "toolchain_name": tc_name, + "toolchain_version": tc_ver, + "module_name": str(full_mod_name), + "dependencies": deps, + "builddependencies": bdeps, + "exts_list": [ + { + "name": str(e[0]) if isinstance(e, (list, tuple)) else str(e), + "version": str(e[1]) + if isinstance(e, (list, tuple)) and len(e) > 1 + else "", + } + for e in exts + ], + } + ) + except Exception as exc: + results.append( + { + "rel": rel, + "bucket": reasons.get(rel, ""), + "ok": False, + "error": str(exc), + } + ) + return {"results": results} + + +def dep_to_dict(dep) -> dict: + if isinstance(dep, dict): + tc = dep.get("toolchain") or {} + return { + "name": str(dep["name"]), + "version": str(dep.get("version", "")), + "versionprefix": str(dep.get("versionprefix") or ""), + "versionsuffix": str(dep.get("versionsuffix") or ""), + "toolchain_name": str(dep.get("toolchain_name") or tc.get("name") or ""), + "toolchain_version": str(dep.get("toolchain_version") or tc.get("version") or ""), + "external_module": bool(dep.get("external_module", False)), + "hidden": bool(dep.get("hidden", False)), + "resolved_module": dep.get("resolved_module") or dep.get("full_mod_name"), + } + if isinstance(dep, (list, tuple)): + name = str(dep[0]) + version = str(dep[1]) if len(dep) > 1 else "" + vsuffix = str(dep[2]) if len(dep) > 2 and dep[2] is not None else "" + tc = dep[3] if len(dep) > 3 else None + if isinstance(tc, (list, tuple)) and len(tc) >= 2: + tc_name, tc_ver = str(tc[0]), str(tc[1]) + elif isinstance(tc, dict): + tc_name, tc_ver = str(tc.get("name", "")), str(tc.get("version", "")) + elif tc is True: + tc_name, tc_ver = "system", "system" + else: + tc_name, tc_ver = "", "" + return { + "name": name, + "version": version, + "versionprefix": "", + "versionsuffix": vsuffix, + "toolchain_name": tc_name, + "toolchain_version": tc_ver, + "external_module": False, + "hidden": False, + } + return { + "name": str(dep), + "version": "", + "versionprefix": "", + "versionsuffix": "", + "toolchain_name": "", + "toolchain_version": "", + "external_module": False, + "hidden": False, + } + + +def resolve_eb_stack_bin(explicit: Path | None) -> Path: + if explicit is not None: + return explicit + env_bin = os.environ.get("EB_STACK_BIN") + if env_bin: + return Path(env_bin) + repo_root = Path(__file__).resolve().parents[1] + for candidate in ( + repo_root / "target" / "release" / "eb-stack", + repo_root / "target" / "debug" / "eb-stack", + ): + if candidate.is_file(): + return candidate + found = shutil.which("eb-stack") + if found: + return Path(found) + raise SystemExit( + "Could not locate eb-stack binary. Pass --eb-stack or build with cargo build." + ) + + +def run_eb_stack_audit(eb_stack_bin: Path, root: Path, rels: list[str]) -> dict: + with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, encoding="utf-8") as fp: + for rel in rels: + fp.write(f"{rel}\n") + recipes_file = Path(fp.name) + try: + proc = subprocess.run( + [ + str(eb_stack_bin), + "recipe", + "parity-audit", + "--easyconfigs", + str(root), + "--recipes-file", + str(recipes_file), + ], + capture_output=True, + text=True, + check=False, + ) + finally: + recipes_file.unlink(missing_ok=True) + if proc.returncode != 0: + raise SystemExit( + f"eb-stack recipe parity-audit failed ({proc.returncode}): {proc.stderr.strip()}" + ) + return json.loads(proc.stdout) + + +def compare_parity(truth_rows: list[dict], stack_rows: list[dict]) -> dict: + by_rel_stack = {row["rel"]: row for row in stack_rows} + mismatches: list[dict] = [] + checked = 0 + + for truth in truth_rows: + rel = truth["rel"] + checked += 1 + if truth.get("ok") is False: + mismatches.append( + { + "rel": rel, + "field": "easybuild_error", + "easybuild": truth.get("error", "error"), + "eb_stack": None, + } + ) + continue + + stack = by_rel_stack.get(rel) + if stack is None: + mismatches.append( + { + "rel": rel, + "field": "missing_from_eb_stack", + "easybuild": truth.get("module_name"), + "eb_stack": None, + } + ) + continue + + if not stack.get("ok"): + mismatches.append( + { + "rel": rel, + "field": "eb_stack_error", + "easybuild": truth.get("module_name"), + "eb_stack": stack.get("error"), + } + ) + continue + + if stack.get("dropped_exts"): + mismatches.append( + { + "rel": rel, + "field": "dropped_exts", + "easybuild": len(truth.get("exts_list", [])), + "eb_stack": stack.get("skipped_statements", []), + } + ) + + eb_mod = truth.get("module_name", "") + st_mod = stack.get("module_name", "") + if eb_mod != st_mod: + mismatches.append( + { + "rel": rel, + "field": "module_name", + "easybuild": eb_mod, + "eb_stack": st_mod, + } + ) + + eb_vs = truth.get("versionsuffix", "") + st_vs = stack.get("versionsuffix", "") + if eb_vs != st_vs: + mismatches.append( + { + "rel": rel, + "field": "versionsuffix", + "easybuild": eb_vs, + "eb_stack": st_vs, + } + ) + + eb_exts = truth.get("exts_count") + if eb_exts is None: + eb_exts = len(truth.get("exts_list", [])) + st_exts = stack.get("exts_count", 0) + if eb_exts != st_exts: + mismatches.append( + { + "rel": rel, + "field": "exts_count", + "easybuild": eb_exts, + "eb_stack": st_exts, + } + ) + + st_deps_by_key: dict[tuple[str, str], list[str | None]] = {} + for dep in stack.get("deps", []): + key = (dep["kind"], dep["name"]) + st_deps_by_key.setdefault(key, []).append(dep.get("resolved_module")) + + for kind, field in (("runtime", "dependencies"), ("build", "builddependencies")): + for dep in truth.get(field, []): + if dep.get("external_module"): + continue + if not dep.get("toolchain_name") and dep.get("toolchain_name") != "": + continue + expected_mod = format_eb_dep_module(dep) + candidates = st_deps_by_key.get((kind, dep["name"]), []) + if expected_mod not in candidates: + mismatches.append( + { + "rel": rel, + "field": f"{kind}_dep:{dep['name']}", + "easybuild": expected_mod, + "eb_stack": candidates, + } + ) + + return { + "checked": checked, + "mismatch_count": len(mismatches), + "mismatches": mismatches, + } + + +def main(argv: list[str]) -> int: + args = parse_args(argv) + root = args.easyconfigs.resolve() + if not root.is_dir(): + raise SystemExit(f"easyconfigs root is not a directory: {root}") + + extra_easyblocks = discover_easyblocks_touching_naming(args.easybuild_easyblocks) + + if args.truth_json is not None: + truth_doc = json.loads(args.truth_json.read_text(encoding="utf-8")) + truth_rows = truth_doc["results"] + rels = [row["rel"] for row in truth_rows] + reasons = {row["rel"]: row.get("bucket", "truth") for row in truth_rows} + else: + rels, reasons = select_sample( + root=root, + seed=args.seed, + sample_size=args.sample_size, + include_targeted=not args.no_targeted, + extra_easyblocks=extra_easyblocks, + ) + truth_doc = extract_easybuild_truth( + root=root, + rels=rels, + reasons=reasons, + framework_dir=args.easybuild_framework, + easyblocks_dir=args.easybuild_easyblocks, + extra_pythonpath=args.pythonpath, + ) + truth_rows = truth_doc["results"] + if args.emit_truth is not None: + args.emit_truth.write_text(json.dumps(truth_doc, indent=2) + "\n", encoding="utf-8") + + if args.eb_stack_json is not None: + stack_doc = json.loads(args.eb_stack_json.read_text(encoding="utf-8")) + else: + eb_stack_bin = resolve_eb_stack_bin(args.eb_stack) + stack_doc = run_eb_stack_audit(eb_stack_bin, root, rels) + + report = compare_parity(truth_rows, stack_doc.get("recipes", [])) + report["seed"] = args.seed + report["sample_size"] = args.sample_size + report["selected_count"] = len(rels) + report["targeted_count"] = sum(1 for r in reasons.values() if r == "targeted") + + if args.out is not None: + args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + + print( + f"parity_audit: seed={report['seed']} checked={report['checked']} " + f"targeted={report['targeted_count']} " + f"mismatches={report['mismatch_count']}" + ) + for item in report["mismatches"]: + print( + f" MISMATCH {item['rel']} [{item['field']}]: " + f"easybuild={item['easybuild']!r} eb-stack={item['eb_stack']!r}" + ) + return 1 if report["mismatch_count"] > 0 else 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/src/build_order.rs b/src/build_order.rs index f536c027..ef905c78 100644 --- a/src/build_order.rs +++ b/src/build_order.rs @@ -1624,6 +1624,62 @@ pub fn runtime_edges(order: &[Candidate]) -> HashMap> { edges } +/// One dependency resolution record emitted for EasyBuild parity checks. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct ParityDepResolution { + /// Dependency section: `"runtime"` or `"build"`. + pub kind: &'static str, + /// Dependency package name. + pub name: String, + /// Requested version string. + pub version_req: String, + /// Optional versionsuffix constraint. + pub versionsuffix: Option, + /// Selected dependency module name (`Name/full_version`), if found. + pub resolved_module: Option, +} + +/// Pre-indexed candidate table for resolving dependencies across a tree. +pub struct ParityTreeIndex<'a> { + all: &'a [Candidate], + by_name: HashMap<&'a str, Vec<&'a Candidate>>, +} + +impl<'a> ParityTreeIndex<'a> { + /// Index `candidates` by package name once for repeated parity lookups. + pub fn new(candidates: &'a [Candidate]) -> Self { + Self { + all: candidates, + by_name: index_by_name(candidates), + } + } + + /// Resolve every runtime and build dependency of `candidate` at its + /// nearest toolchain hierarchy level. + pub fn resolve_candidate_deps(&self, candidate: &Candidate) -> Vec { + let mut out = + Vec::with_capacity(candidate.dependencies.len() + candidate.builddependencies.len()); + for (kind, deps) in [ + ("runtime", &candidate.dependencies), + ("build", &candidate.builddependencies), + ] { + for dep in deps { + let resolved_module = + resolve_dep(&self.by_name, candidate, dep, Choice::Newest, self.all) + .map(|matched| module_name(&ModuleKey::of(matched))); + out.push(ParityDepResolution { + kind, + name: dep.name.clone(), + version_req: dep.version_req.clone(), + versionsuffix: dep.versionsuffix.clone(), + resolved_module, + }); + } + } + out + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/main.rs b/src/main.rs index 48fee93d..4ea97aaa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1106,6 +1106,16 @@ enum RecipeCommand { #[arg(long)] dry_run: bool, }, + /// Hidden helper: export parsed recipe metadata and nearest-hierarchy deps as JSON. + #[command(hide = true)] + ParityAudit { + /// Easyconfig tree root. + #[arg(long)] + easyconfigs: PathBuf, + /// Optional file of newline-separated recipe paths (relative to `--easyconfigs` or absolute). + #[arg(long)] + recipes_file: Option, + }, } #[derive(clap::Args, Debug)] @@ -3453,6 +3463,109 @@ fn run_recipe(command: RecipeCommand) -> Result<()> { } Ok(()) } + RecipeCommand::ParityAudit { + easyconfigs, + recipes_file, + } => { + let tree = parse_easyconfig_trees(&[easyconfigs.as_path()]) + .map_err(|error| anyhow::Error::msg(error).context("--easyconfigs"))?; + let canon_root = + std::fs::canonicalize(&easyconfigs).unwrap_or_else(|_| easyconfigs.clone()); + let index = eb_stack::build_order::ParityTreeIndex::new(&tree.candidates); + let mut by_canon = std::collections::HashMap::new(); + for candidate in &tree.candidates { + let path = Path::new(&candidate.easyconfig_path); + let canon = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + by_canon.insert(canon, candidate); + } + let targets: Vec = match recipes_file { + Some(file) => { + let body = std::fs::read_to_string(&file) + .with_context(|| format!("--recipes-file {}", file.display()))?; + body.lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .map(|line| { + let p = Path::new(line); + if p.is_absolute() { + p.to_path_buf() + } else { + canon_root.join(p) + } + }) + .collect() + } + None => tree + .candidates + .iter() + .map(|c| PathBuf::from(&c.easyconfig_path)) + .collect(), + }; + let mut recipes = Vec::with_capacity(targets.len()); + for target in &targets { + let canon_target = std::fs::canonicalize(target).unwrap_or_else(|_| target.clone()); + let rel = canon_target + .strip_prefix(&canon_root) + .unwrap_or(&canon_target) + .to_string_lossy() + .into_owned(); + let reporting = eb_stack::resolve_easyconfig_file_reporting(&canon_target); + let (candidate_owned, skipped_statements) = match reporting { + Ok((ec, skipped)) => (Some(ec.to_candidate()), skipped), + Err(err) => { + recipes.push(serde_json::json!({ + "rel": rel, + "ok": false, + "error": err.to_string(), + "dropped_exts": false, + "skipped_statements": [], + })); + continue; + } + }; + let candidate = by_canon + .get(&canon_target) + .copied() + .or(candidate_owned.as_ref()) + .expect("resolved candidate"); + let dropped_exts = skipped_statements.iter().any(|statement| { + statement.text.contains("exts_list") || statement.message.contains("exts_list") + }); + let skipped_strings: Vec = + skipped_statements.iter().map(ToString::to_string).collect(); + let mod_name = eb_stack::build_order::module_name( + &eb_stack::build_order::ModuleKey::of(candidate), + ); + let deps = index.resolve_candidate_deps(candidate); + recipes.push(serde_json::json!({ + "rel": rel, + "ok": true, + "error": serde_json::Value::Null, + "name": candidate.name, + "version": candidate.version, + "versionprefix": candidate.versionprefix.as_deref().unwrap_or(""), + "versionsuffix": candidate.versionsuffix.as_deref().unwrap_or(""), + "toolchain": { + "name": candidate.toolchain.name, + "version": candidate.toolchain.version, + }, + "module_name": mod_name, + "exts_count": candidate.exts_list.len(), + "dropped_exts": dropped_exts, + "skipped_statements": skipped_strings, + "deps": deps, + })); + } + println!( + "{}", + serde_json::to_string_pretty(&serde_json::json!({ + "tree_candidates": tree.candidates.len(), + "tree_skipped_count": tree.skipped.len(), + "recipes": recipes, + }))? + ); + Ok(()) + } } } diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs new file mode 100644 index 00000000..8ca378a9 --- /dev/null +++ b/tests/parity_audit_script.rs @@ -0,0 +1,327 @@ +//! Reproducibility and failure-mode tests for `scripts/parity_audit.py` +//! using generated fixtures only. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn repo_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +fn write_file(path: &Path, body: &str) { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent dirs"); + } + std::fs::write(path, body).expect("write generated fixture"); +} + +fn generate_fixture_tree(root: &Path) { + write_file( + &root.join("g/GCCcore/GCCcore-13.3.0.eb"), + r#"easyblock = 'Toolchain' +name = 'GCCcore' +version = '13.3.0' +homepage = 'https://gcc.gnu.org/' +description = 'GCCcore' +toolchain = SYSTEM +moduleclass = 'compiler' +"#, + ); + write_file( + &root.join("g/GCC/GCC-13.3.0.eb"), + r#"easyblock = 'Toolchain' +name = 'GCC' +version = '13.3.0' +homepage = 'https://gcc.gnu.org/' +description = 'GCC' +toolchain = SYSTEM +dependencies = [('GCCcore', '13.3.0')] +moduleclass = 'toolchain' +"#, + ); + write_file( + &root.join("f/foss/foss-2024a.eb"), + r#"easyblock = 'Toolchain' +name = 'foss' +version = '2024a' +homepage = 'https://easybuild.io' +description = 'foss' +toolchain = SYSTEM +dependencies = [('GCC', '13.3.0')] +moduleclass = 'toolchain' +"#, + ); + write_file( + &root.join("z/zlib/zlib-1.3.1-GCCcore-13.3.0.eb"), + r#"easyblock = 'ConfigureMake' +name = 'zlib' +version = '1.3.1' +homepage = 'https://zlib.net/' +description = 'zlib' +toolchain = {'name': 'GCCcore', 'version': '13.3.0'} +moduleclass = 'lib' +"#, + ); + write_file( + &root.join("c/CMake/CMake-3.29.3-GCCcore-13.3.0.eb"), + r#"easyblock = 'ConfigureMake' +name = 'CMake' +version = '3.29.3' +homepage = 'https://cmake.org/' +description = 'CMake' +toolchain = {'name': 'GCCcore', 'version': '13.3.0'} +moduleclass = 'devel' +"#, + ); + write_file( + &root.join("t/ToolA/ToolA-1.0-foss-2024a-extra.eb"), + r#"easyblock = 'PythonBundle' +name = 'ToolA' +version = '1.0' +versionprefix = 'pre-' +versionsuffix = '-extra' +homepage = 'https://example.org/' +description = 'ToolA' +toolchain = {'name': 'foss', 'version': '2024a'} +builddependencies = [('CMake', '3.29.3')] +dependencies = [('zlib', '1.3.1')] +exts_list = [ + ('extone', '0.1.0'), + ('exttwo', '0.2.0'), +] +moduleclass = 'tools' +"#, + ); + write_file( + &root.join("b/BundleB/BundleB-2.0-foss-2024a.eb"), + r#"easyblock = 'Bundle' +name = 'BundleB' +version = '2.0' +homepage = 'https://example.org/' +description = 'BundleB' +toolchain = {'name': 'foss', 'version': '2024a'} +dependencies = [('zlib', '1.3.1')] +moduleclass = 'tools' +"#, + ); +} + +fn generate_easyblocks_stub(root: &Path) { + write_file( + &root.join("easybuild/easyblocks/t/toola.py"), + r#"class EB_ToolA(object): + def det_full_module_name(self, ec): + return None +"#, + ); +} + +fn generate_easybuild_python_stub(root: &Path) { + for rel in [ + "easybuild/__init__.py", + "easybuild/framework/__init__.py", + "easybuild/framework/easyconfig/__init__.py", + "easybuild/tools/__init__.py", + "easybuild/tools/module_naming_scheme/__init__.py", + ] { + write_file(&root.join(rel), ""); + } + write_file( + &root.join("easybuild/tools/options.py"), + r#"ROBOT_ROOT = None + +def set_up_configuration(args=None, silent=True): + global ROBOT_ROOT + for arg in args or []: + if arg.startswith("--robot="): + ROBOT_ROOT = arg.split("=", 1)[1] +"#, + ); + write_file( + &root.join("easybuild/tools/modules.py"), + r#"class NoModulesTool: + def __init__(self, testing=False): + self.testing = testing +"#, + ); + write_file( + &root.join("easybuild/tools/module_naming_scheme/easybuild_mns.py"), + r#"class EasyBuildMNS: + def det_full_module_name(self, ec): + tc = ec.get("toolchain") or {"name": "system", "version": "system"} + tc_part = "" if tc["name"].lower() == "system" else f"-{tc['name']}-{tc['version']}" + vp = ec.get("versionprefix") or "" + vs = ec.get("versionsuffix") or "" + return f"{ec['name']}/{vp}{ec['version']}{tc_part}{vs}" +"#, + ); + write_file( + &root.join("easybuild/framework/easyconfig/easyconfig.py"), + r#"from pathlib import Path +from easybuild.tools import options +from easybuild.tools.module_naming_scheme.easybuild_mns import EasyBuildMNS + +def _parse_eb(path): + ns = {"SYSTEM": {"name": "system", "version": "system"}} + ns["name"] = "" + ns["version"] = "" + exec(Path(path).read_text(encoding="utf-8"), ns) + return ns + +def _resolve_dep(dep_tuple, robot_root): + name, version = dep_tuple[0], dep_tuple[1] + mns = EasyBuildMNS() + for p in sorted(Path(robot_root).rglob("*.eb")): + ns = _parse_eb(p) + if ns.get("name") == name and ns.get("version") == version: + tc = ns.get("toolchain") or {"name": "system", "version": "system"} + return { + "name": name, + "version": version, + "versionprefix": ns.get("versionprefix") or "", + "versionsuffix": ns.get("versionsuffix") or "", + "toolchain": tc, + "full_mod_name": mns.det_full_module_name(ns), + "external_module": False, + "hidden": False, + "build_only": False, + } + return { + "name": name, + "version": version, + "toolchain": {"name": "system", "version": "system"}, + "external_module": False, + } + +class EasyConfig(dict): + def __init__(self, path, validate=False): + super().__init__(_parse_eb(path)) + self._robot = options.ROBOT_ROOT or str(Path(path).parents[2]) + + def dependencies(self): + return [_resolve_dep(d, self._robot) for d in self.get("dependencies", [])] + + def builddependencies(self): + return [_resolve_dep(d, self._robot) for d in self.get("builddependencies", [])] +"#, + ); +} + +#[test] +fn parity_audit_passes_against_generated_easybuild_stub_and_eb_stack() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + let py_stub = temp.path().join("py_stub"); + let eblocks = temp.path().join("easyblocks"); + let report_a = temp.path().join("report-a.json"); + let report_b = temp.path().join("report-b.json"); + let truth_out = temp.path().join("truth.json"); + + generate_fixture_tree(&ec_root); + generate_easybuild_python_stub(&py_stub); + generate_easyblocks_stub(&eblocks); + + let script = repo_root().join("scripts/parity_audit.py"); + let bin = env!("CARGO_BIN_EXE_eb-stack"); + + for (report, emit_truth) in [(&report_a, Some(&truth_out)), (&report_b, None)] { + let mut cmd = Command::new("python3"); + cmd.arg(&script) + .arg("--easyconfigs") + .arg(&ec_root) + .arg("--seed") + .arg("42") + .arg("--sample-size") + .arg("4") + .arg("--easybuild-easyblocks") + .arg(&eblocks) + .arg("--pythonpath") + .arg(&py_stub) + .arg("--eb-stack") + .arg(bin) + .arg("--out") + .arg(report); + if let Some(truth_path) = emit_truth { + cmd.arg("--emit-truth").arg(truth_path); + } + let output = cmd.output().expect("run parity_audit.py"); + assert!( + output.status.success(), + "stdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + + let doc_a: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report_a).unwrap()).unwrap(); + let doc_b: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report_b).unwrap()).unwrap(); + assert_eq!(doc_a["mismatch_count"], 0); + assert_eq!(doc_a["targeted_count"], 5); + assert!(doc_a["checked"].as_u64().unwrap() >= 5); + assert_eq!(doc_a, doc_b, "seeded parity runs must be deterministic"); + assert!(truth_out.is_file()); +} + +#[test] +fn parity_audit_exits_nonzero_on_mismatch_and_dropped_exts() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + generate_fixture_tree(&ec_root); + + let truth_path = temp.path().join("bad-truth.json"); + let truth = serde_json::json!({ + "results": [ + { + "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", + "bucket": "sample:exts_list", + "ok": true, + "name": "ToolA", + "version": "1.0", + "versionprefix": "pre-", + "versionsuffix": "-wrong", + "toolchain_name": "foss", + "toolchain_version": "2024a", + "module_name": "ToolA/pre-1.0-foss-2024a-extra", + "dependencies": [ + { + "name": "zlib", + "version": "1.3.1", + "versionsuffix": "", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "external_module": false + } + ], + "builddependencies": [], + "exts_list": [ + {"name": "extone", "version": "0.1.0"} + ] + } + ] + }); + write_file(&truth_path, &serde_json::to_string_pretty(&truth).unwrap()); + + let report_path = temp.path().join("bad-report.json"); + let output = Command::new("python3") + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(&ec_root) + .arg("--truth-json") + .arg(&truth_path) + .arg("--eb-stack") + .arg(env!("CARGO_BIN_EXE_eb-stack")) + .arg("--out") + .arg(&report_path) + .output() + .expect("run parity_audit.py mismatch check"); + + assert!( + !output.status.success(), + "parity_audit.py must fail when versionsuffix/exts_count disagree" + ); + let report: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); + assert_eq!(report["mismatch_count"], 2); +} From a54b8c4c2543ba4ece3aa5256b543a1e9b86cbfc Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:19 +0000 Subject: [PATCH 02/17] chore(parity): scale audit to 2000 sample and all hook easyblocks Raise the default sample size in scripts/parity_audit.py to 2000, and keep printing the random seed to stdout. The easyblock scan now parses each file instead of matching substrings. It finds classes that hook module naming, version templates or toolchains, and maps EB_ class names back to software names, so easyconfigs that pick their easyblock implicitly are found too. --- .../+parity-audit-easyblock-hooks.misc.md | 1 + scripts/parity_audit.py | 106 ++++++++++++++++-- tests/parity_audit_script.rs | 92 +++++++++++++++ 3 files changed, 190 insertions(+), 9 deletions(-) create mode 100644 changelog.d/+parity-audit-easyblock-hooks.misc.md diff --git a/changelog.d/+parity-audit-easyblock-hooks.misc.md b/changelog.d/+parity-audit-easyblock-hooks.misc.md new file mode 100644 index 00000000..9ff5a08a --- /dev/null +++ b/changelog.d/+parity-audit-easyblock-hooks.misc.md @@ -0,0 +1 @@ +Raise the default parity audit sample to 2000 seeded recipes, and find the easyblocks that hook module naming, version templates or toolchains by parsing them. diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index dd58c121..3257ba91 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -18,6 +18,7 @@ from __future__ import annotations import argparse +import ast import json import os import random @@ -56,8 +57,8 @@ def parse_args(argv: list[str]) -> argparse.Namespace: parser.add_argument( "--sample-size", type=int, - default=200, - help="Target stratified random sample size (default: 200).", + default=2000, + help="Target stratified random sample size (default: 2000).", ) parser.add_argument( "--no-targeted", @@ -115,6 +116,80 @@ def parse_args(argv: list[str]) -> argparse.Namespace: return parser.parse_args(argv) +_MODULE_NAMING_METHODS = frozenset( + { + "make_module_req_guess", + "det_full_module_name", + "module_name", + "make_module_req", + "make_module_dep", + "make_module_extend_modpath", + "make_module_step", + } +) +_VERSION_TEMPLATE_METHODS = frozenset( + { + "generate_template_values", + "update_config_template_run_step", + "det_template_values", + } +) +_TOOLCHAIN_HOOK_METHODS = frozenset( + { + "comp_family", + "mpi_family", + "toolchain_family", + } +) +_NAMING_TEMPLATE_ATTRS = frozenset( + { + "template_values", + "modaltsoftname", + "env_mod_alt_soft_name", + "versionprefix", + "version_prefix", + "altroot", + "altversion", + } +) + + +def _decode_eb_class_name(cls_name: str) -> str: + raw = cls_name[3:] if cls_name.startswith("EB_") else cls_name + return ( + raw.replace("_minus_", "-") + .replace("_plus_", "+") + .replace("_dot_", ".") + .replace("_underscore_", "_") + ) + + +def _class_touches_naming_or_hooks(cls_node: ast.ClassDef) -> bool: + for base in cls_node.bases: + if isinstance(base, ast.Name) and base.id == "Toolchain": + return True + if isinstance(base, ast.Attribute) and base.attr == "Toolchain": + return True + + for node in ast.walk(cls_node): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + if ( + node.name in _MODULE_NAMING_METHODS + or node.name in _VERSION_TEMPLATE_METHODS + or node.name in _TOOLCHAIN_HOOK_METHODS + or "toolchain" in node.name.lower() + ): + return True + elif isinstance(node, ast.Attribute) and node.attr in _NAMING_TEMPLATE_ATTRS: + return True + elif isinstance(node, ast.Name) and node.id in _NAMING_TEMPLATE_ATTRS: + return True + elif isinstance(node, ast.Constant) and isinstance(node.value, str): + if node.value in _NAMING_TEMPLATE_ATTRS: + return True + return False + + def discover_easyblocks_touching_naming(easyblocks_root: Path | None) -> list[str]: if easyblocks_root is None or not easyblocks_root.is_dir(): return [] @@ -124,12 +199,19 @@ def discover_easyblocks_touching_naming(easyblocks_root: Path | None) -> list[st text = path.read_text(encoding="utf-8", errors="ignore") except OSError: continue - if "def det_full_module_name" in text or "modaltsoftname" in text: - for m in re.finditer(r"class\s+(EB_[A-Za-z0-9_]+)\s*\(", text): - cls = m.group(1) + try: + tree = ast.parse(text, filename=str(path)) + except SyntaxError: + continue + for node in ast.walk(tree): + if not isinstance(node, ast.ClassDef): + continue + if _class_touches_naming_or_hooks(node): + cls = node.name + matched.add(cls) if cls.startswith("EB_"): matched.add(cls[3:]) - matched.add(cls) + matched.add(_decode_eb_class_name(cls)) return sorted(matched) @@ -149,14 +231,19 @@ def classify_recipe(rel: str, text: str, extra_easyblocks: set[str]) -> tuple[st r"^\s*easyblock\s*=\s*['\"]([^'\"]+)['\"]", text, re.MULTILINE ) easyblock = easyblock_match.group(1) if easyblock_match else "" + name_match = re.search( + r"^\s*name\s*=\s*['\"]([^'\"]+)['\"]", text, re.MULTILINE + ) + software_name = name_match.group(1) if name_match else "" tc_match = _TOOLCHAIN_RE.search(text) tc_name = tc_match.group(1) if tc_match else "system" is_targeted = ( easyblock in TARGETED_EASYBLOCKS or easyblock in extra_easyblocks - or bool(re.search(r"^\s*versionprefix\s*=", text, re.MULTILINE)) - or bool(re.search(r"^\s*modaltsoftname\s*=", text, re.MULTILINE)) + or (not easyblock and software_name in extra_easyblocks) + or bool(re.search(r"^\s*version_?prefix\s*=", text, re.MULTILINE)) + or bool(re.search(r"^\s*(?:modaltsoftname|env_mod_alt_soft_name)\s*=", text, re.MULTILINE)) ) if easyblock == "Toolchain" or tc_name in ("foss", "intel", "gompi", "gfbf", "NVHPC"): @@ -637,7 +724,8 @@ def main(argv: list[str]) -> int: args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print( - f"parity_audit: seed={report['seed']} checked={report['checked']} " + f"parity_audit: seed={report['seed']} " + f"checked={report['checked']} " f"targeted={report['targeted_count']} " f"mismatches={report['mismatch_count']}" ) diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index 8ca378a9..7e082902 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -325,3 +325,95 @@ fn parity_audit_exits_nonzero_on_mismatch_and_dropped_exts() { serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); assert_eq!(report["mismatch_count"], 2); } + +#[test] +fn parity_audit_discovers_all_hook_categories_and_prints_seed() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + let py_stub = temp.path().join("py_stub"); + let eblocks = temp.path().join("easyblocks"); + let report = temp.path().join("report.json"); + + generate_fixture_tree(&ec_root); + generate_easybuild_python_stub(&py_stub); + + // Add one easyconfig per hook family beyond det_full_module_name. + for (rel, name, easyblock) in [ + ("m/ModReqApp/ModReqApp-1.0.eb", "ModReqApp", None), + ("n/ModNameApp/ModNameApp-1.0.eb", "ModNameApp", None), + ("v/VerTplApp/VerTplApp-1.0.eb", "VerTplApp", None), + ("t/TcHookApp/TcHookApp-1.0.eb", "TcHookApp", None), + ("f/FooBar/FooBar-1.0.eb", "Foo-Bar", Some("Foo-Bar")), + ] { + let eb_line = match easyblock { + Some(eb) => format!("easyblock = '{eb}'\n"), + None => String::new(), + }; + write_file( + &ec_root.join(rel), + &format!( + "{eb_line}name = '{name}'\nversion = '1.0'\n\ + homepage = 'https://example.org/'\ndescription = '{name}'\n\ + toolchain = SYSTEM\nmoduleclass = 'tools'\n" + ), + ); + } + + write_file( + &eblocks.join("easybuild/easyblocks/m/modreqapp.py"), + "class EB_ModReqApp:\n def make_module_req_guess(self):\n return {}\n", + ); + write_file( + &eblocks.join("easybuild/easyblocks/n/modnameapp.py"), + "class EB_ModNameApp:\n def module_name(self):\n return 'alt'\n", + ); + write_file( + &eblocks.join("easybuild/easyblocks/v/vertplapp.py"), + "class EB_VerTplApp:\n def generate_template_values(self):\n self.cfg.template_values['x'] = '1'\n", + ); + write_file( + &eblocks.join("easybuild/easyblocks/t/tchookapp.py"), + "class EB_TcHookApp:\n def comp_family(self):\n return 'GCC'\n", + ); + write_file( + &eblocks.join("easybuild/easyblocks/f/foo_minus_bar.py"), + "class EB_Foo_minus_Bar:\n def det_full_module_name(self, ec):\n return None\n", + ); + + let output = Command::new("python3") + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(&ec_root) + .arg("--seed") + .arg("20261122") + .arg("--sample-size") + .arg("0") + .arg("--easybuild-easyblocks") + .arg(&eblocks) + .arg("--pythonpath") + .arg(&py_stub) + .arg("--eb-stack") + .arg(env!("CARGO_BIN_EXE_eb-stack")) + .arg("--out") + .arg(&report) + .output() + .expect("run parity_audit.py"); + + assert!( + output.status.success(), + "stdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("seed=20261122"), + "stdout must print seed=20261122, got: {stdout}" + ); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report).unwrap()).unwrap(); + // GCCcore/GCC/foss (Toolchain) + ToolA (versionprefix) + BundleB (Bundle) = 5, + // plus all 5 hook apps = 10 targeted. + assert_eq!(doc["targeted_count"], 10); + assert_eq!(doc["checked"], 10); +} From 230691e3ccb92e50b0ea35a34102ecc1447b95f1 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:20 +0000 Subject: [PATCH 03/17] fix(parity): validate complete audit truth The comparator skipped every EasyBuild dependency without a toolchain name, and never looked for dependencies that only eb-stack resolved. A recipe whose dependency lost its toolchain, or for which eb-stack invented an extra dependency, therefore passed. A dependency without a toolchain name is now reported as _dep::missing_toolchain, and every eb-stack dependency with no EasyBuild counterpart as extra__dep:. The unused assignment regex goes. parity_audit_resolves_with_easybuild_framework installs EasyBuild into a virtual environment of its own and audits the fixtures under fixtures/parity_audit_framework/: an App recipe with a GCCcore zlib dependency, which must match, and MissTc, whose dependency has an empty toolchain and must be reported. The integration CI job sets up Python 3.14 for it. --- .github/workflows/ci_test.yml | 3 + changelog.d/+parity-audit-framework.bugfix.md | 1 + fixtures/parity_audit_framework/LICENSE | 339 ++++++++++++++++++ fixtures/parity_audit_framework/README.md | 12 + .../a/App/App-1.0-GCCcore-13.3.0.eb | 8 + .../easyconfigs/g/GCCcore/GCCcore-13.3.0.eb | 7 + .../easyconfigs/m/MissTc/MissTc-1.0.eb | 8 + .../z/zlib/zlib-1.3.1-GCCcore-13.3.0.eb | 7 + scripts/parity_audit.py | 30 +- tests/parity_audit_script.rs | 169 ++++++++- 10 files changed, 575 insertions(+), 9 deletions(-) create mode 100644 changelog.d/+parity-audit-framework.bugfix.md create mode 100644 fixtures/parity_audit_framework/LICENSE create mode 100644 fixtures/parity_audit_framework/README.md create mode 100644 fixtures/parity_audit_framework/easyconfigs/a/App/App-1.0-GCCcore-13.3.0.eb create mode 100644 fixtures/parity_audit_framework/easyconfigs/g/GCCcore/GCCcore-13.3.0.eb create mode 100644 fixtures/parity_audit_framework/easyconfigs/m/MissTc/MissTc-1.0.eb create mode 100644 fixtures/parity_audit_framework/easyconfigs/z/zlib/zlib-1.3.1-GCCcore-13.3.0.eb diff --git a/.github/workflows/ci_test.yml b/.github/workflows/ci_test.yml index d40ee11c..641304f5 100644 --- a/.github/workflows/ci_test.yml +++ b/.github/workflows/ci_test.yml @@ -176,6 +176,9 @@ jobs: - uses: actions/checkout@v7 - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 + - uses: actions/setup-python@v6 + with: + python-version: '3.14' - name: Every integration test that is not ignore-only run: | cargo test --locked \ diff --git a/changelog.d/+parity-audit-framework.bugfix.md b/changelog.d/+parity-audit-framework.bugfix.md new file mode 100644 index 00000000..e4f448e2 --- /dev/null +++ b/changelog.d/+parity-audit-framework.bugfix.md @@ -0,0 +1 @@ +Parity audits report a dependency whose toolchain is empty and a dependency only eb-stack resolves, instead of skipping them, and a real EasyBuild run covers a GCCcore dependency and an empty toolchain. diff --git a/fixtures/parity_audit_framework/LICENSE b/fixtures/parity_audit_framework/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/fixtures/parity_audit_framework/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/fixtures/parity_audit_framework/README.md b/fixtures/parity_audit_framework/README.md new file mode 100644 index 00000000..ed25a2b9 --- /dev/null +++ b/fixtures/parity_audit_framework/README.md @@ -0,0 +1,12 @@ +# Parity fixture: framework dependency resolution + +Minimal easyconfigs for the real EasyBuild parity audit +(`parity_audit_resolves_with_easybuild_framework`). One recipe builds +against GCCcore and depends on zlib, so dependency resolution runs. +Another names a dependency whose toolchain is empty, so the audit's +missing-toolchain check runs. Excluded from the published `eb_stack` +crate via `Cargo.toml` `exclude = ["fixtures/parity_*/"]`. + +`LICENSE` is the GNU General Public License v2.0 text kept with the +other parity fixtures +(`sha256: 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643`). diff --git a/fixtures/parity_audit_framework/easyconfigs/a/App/App-1.0-GCCcore-13.3.0.eb b/fixtures/parity_audit_framework/easyconfigs/a/App/App-1.0-GCCcore-13.3.0.eb new file mode 100644 index 00000000..0b4d2ea6 --- /dev/null +++ b/fixtures/parity_audit_framework/easyconfigs/a/App/App-1.0-GCCcore-13.3.0.eb @@ -0,0 +1,8 @@ +easyblock = 'ConfigureMake' +name = 'App' +version = '1.0' +homepage = 'https://example.org/' +description = 'App built with GCCcore against zlib' +toolchain = {'name': 'GCCcore', 'version': '13.3.0'} +dependencies = [('zlib', '1.3.1')] +moduleclass = 'tools' diff --git a/fixtures/parity_audit_framework/easyconfigs/g/GCCcore/GCCcore-13.3.0.eb b/fixtures/parity_audit_framework/easyconfigs/g/GCCcore/GCCcore-13.3.0.eb new file mode 100644 index 00000000..860836ee --- /dev/null +++ b/fixtures/parity_audit_framework/easyconfigs/g/GCCcore/GCCcore-13.3.0.eb @@ -0,0 +1,7 @@ +easyblock = 'Toolchain' +name = 'GCCcore' +version = '13.3.0' +homepage = 'https://gcc.gnu.org/' +description = 'GCCcore' +toolchain = SYSTEM +moduleclass = 'compiler' diff --git a/fixtures/parity_audit_framework/easyconfigs/m/MissTc/MissTc-1.0.eb b/fixtures/parity_audit_framework/easyconfigs/m/MissTc/MissTc-1.0.eb new file mode 100644 index 00000000..7108ea62 --- /dev/null +++ b/fixtures/parity_audit_framework/easyconfigs/m/MissTc/MissTc-1.0.eb @@ -0,0 +1,8 @@ +easyblock = 'ConfigureMake' +name = 'MissTc' +version = '1.0' +homepage = 'https://example.org/' +description = 'Dependency with an empty toolchain' +toolchain = SYSTEM +dependencies = [('orphan', '1.0', '', ('', ''))] +moduleclass = 'tools' diff --git a/fixtures/parity_audit_framework/easyconfigs/z/zlib/zlib-1.3.1-GCCcore-13.3.0.eb b/fixtures/parity_audit_framework/easyconfigs/z/zlib/zlib-1.3.1-GCCcore-13.3.0.eb new file mode 100644 index 00000000..2a85ece3 --- /dev/null +++ b/fixtures/parity_audit_framework/easyconfigs/z/zlib/zlib-1.3.1-GCCcore-13.3.0.eb @@ -0,0 +1,7 @@ +easyblock = 'ConfigureMake' +name = 'zlib' +version = '1.3.1' +homepage = 'https://zlib.net/' +description = 'zlib' +toolchain = {'name': 'GCCcore', 'version': '13.3.0'} +moduleclass = 'lib' diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index 3257ba91..e0279f32 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -30,10 +30,6 @@ from pathlib import Path TARGETED_EASYBLOCKS = ("ModuleRC", "Toolchain", "Bundle", "Amber") -_ASSIGN_RE = re.compile( - r"^\s*(easyblock|versionprefix|modaltsoftname|exts_list|dependencies|builddependencies)\s*=", - re.MULTILINE, -) _TOOLCHAIN_RE = re.compile( r"^\s*toolchain\s*=\s*\{\s*['\"]name['\"]\s*:\s*['\"]([^'\"]+)['\"]", re.MULTILINE, @@ -650,14 +646,25 @@ def compare_parity(truth_rows: list[dict], stack_rows: list[dict]) -> dict: key = (dep["kind"], dep["name"]) st_deps_by_key.setdefault(key, []).append(dep.get("resolved_module")) + truth_deps_by_key: dict[tuple[str, str], list[dict]] = {} for kind, field in (("runtime", "dependencies"), ("build", "builddependencies")): for dep in truth.get(field, []): if dep.get("external_module"): continue - if not dep.get("toolchain_name") and dep.get("toolchain_name") != "": + key = (kind, dep["name"]) + truth_deps_by_key.setdefault(key, []).append(dep) + if not dep.get("toolchain_name"): + mismatches.append( + { + "rel": rel, + "field": f"{kind}_dep:{dep['name']}:missing_toolchain", + "easybuild": f"missing toolchain_name in recipe {rel}", + "eb_stack": st_deps_by_key.get(key, []), + } + ) continue expected_mod = format_eb_dep_module(dep) - candidates = st_deps_by_key.get((kind, dep["name"]), []) + candidates = st_deps_by_key.get(key, []) if expected_mod not in candidates: mismatches.append( { @@ -667,6 +674,17 @@ def compare_parity(truth_rows: list[dict], stack_rows: list[dict]) -> dict: "eb_stack": candidates, } ) + for key, candidates in st_deps_by_key.items(): + if key not in truth_deps_by_key: + kind, name = key + mismatches.append( + { + "rel": rel, + "field": f"extra_{kind}_dep:{name}", + "easybuild": [], + "eb_stack": candidates, + } + ) return { "checked": checked, diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index 7e082902..c94fdcb3 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -1,5 +1,4 @@ -//! Reproducibility and failure-mode tests for `scripts/parity_audit.py` -//! using generated fixtures only. +//! Reproducibility and failure-mode tests for `scripts/parity_audit.py`. use std::path::{Path, PathBuf}; use std::process::Command; @@ -8,6 +7,15 @@ fn repo_root() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } +fn mismatch_fields(report: &serde_json::Value) -> Vec { + report["mismatches"] + .as_array() + .unwrap() + .iter() + .map(|mismatch| mismatch["field"].as_str().unwrap().to_string()) + .collect() +} + fn write_file(path: &Path, body: &str) { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).expect("create parent dirs"); @@ -207,6 +215,8 @@ class EasyConfig(dict): ); } +/// The generated Python stub covers offline fixture cases; the real framework +/// resolution path is exercised by `parity_audit_resolves_with_easybuild_framework`. #[test] fn parity_audit_passes_against_generated_easybuild_stub_and_eb_stack() { let temp = tempfile::tempdir().expect("tempdir"); @@ -264,6 +274,90 @@ fn parity_audit_passes_against_generated_easybuild_stub_and_eb_stack() { assert!(truth_out.is_file()); } +/// Resolves a GCCcore dependency and an empty toolchain through the real +/// EasyBuild framework. +#[test] +fn parity_audit_resolves_with_easybuild_framework() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = repo_root().join("fixtures/parity_audit_framework/easyconfigs"); + let report = temp.path().join("report.json"); + let venv = temp.path().join("easybuild-venv"); + let python = venv.join("bin/python"); + + let venv_status = Command::new("python3") + .args(["-m", "venv"]) + .arg(&venv) + .status() + .expect("create EasyBuild virtual environment"); + assert!( + venv_status.success(), + "create EasyBuild virtual environment" + ); + let install_status = Command::new(&python) + .args([ + "-m", + "pip", + "install", + "easybuild-framework", + "easybuild-easyblocks", + ]) + .status() + .expect("install EasyBuild framework"); + assert!(install_status.success(), "install EasyBuild framework"); + + let output = Command::new(&python) + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(&ec_root) + .arg("--seed") + .arg("42") + .arg("--sample-size") + .arg("10") + .arg("--eb-stack") + .arg(env!("CARGO_BIN_EXE_eb-stack")) + .arg("--out") + .arg(&report) + .output() + .expect("run parity_audit.py with easybuild-framework"); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report).unwrap_or_default()) + .unwrap_or(serde_json::Value::Null); + assert!(report.is_file(), "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!( + doc["checked"], 4, + "stdout:\n{stdout}\nstderr:\n{stderr}\n{doc}" + ); + let fields = mismatch_fields(&doc); + assert!( + fields + .iter() + .any(|field| field == "runtime_dep:orphan:missing_toolchain"), + "missing toolchain must be reported, got {fields:?}\n{doc}" + ); + let app_mismatches: Vec<_> = doc["mismatches"] + .as_array() + .unwrap() + .iter() + .filter(|mismatch| { + mismatch["rel"] + .as_str() + .unwrap() + .contains("App-1.0-GCCcore-13.3.0.eb") + }) + .collect(); + assert!( + app_mismatches.is_empty(), + "GCCcore dependency resolution mismatched: {app_mismatches:?}" + ); + assert!( + !output.status.success(), + "stdout:\n{stdout}\nstderr:\n{stderr}" + ); +} + #[test] fn parity_audit_exits_nonzero_on_mismatch_and_dropped_exts() { let temp = tempfile::tempdir().expect("tempdir"); @@ -323,7 +417,76 @@ fn parity_audit_exits_nonzero_on_mismatch_and_dropped_exts() { ); let report: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); - assert_eq!(report["mismatch_count"], 2); + assert_eq!(report["mismatch_count"], 3); +} + +#[test] +fn parity_audit_reports_dropped_extensions_missing_toolchains_and_extra_deps() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + generate_fixture_tree(&ec_root); + + let truth_path = temp.path().join("truth.json"); + let stack_path = temp.path().join("stack.json"); + let truth = serde_json::json!({ + "results": [{ + "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", + "ok": true, + "module_name": "ToolA/pre-1.0-foss-2024a-extra", + "versionsuffix": "-extra", + "exts_list": [], + "dependencies": [{ + "name": "zlib", + "toolchain_name": null, + "external_module": false + }], + "builddependencies": [] + }] + }); + let stack = serde_json::json!({ + "recipes": [{ + "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", + "ok": true, + "module_name": "ToolA/pre-1.0-foss-2024a-extra", + "versionsuffix": "-extra", + "exts_count": 0, + "dropped_exts": true, + "skipped_statements": ["exts_list"], + "deps": [ + {"kind": "runtime", "name": "zlib", "resolved_module": null}, + {"kind": "build", "name": "CMake", "resolved_module": "CMake/3.29.3"} + ] + }] + }); + write_file(&truth_path, &serde_json::to_string_pretty(&truth).unwrap()); + write_file(&stack_path, &serde_json::to_string_pretty(&stack).unwrap()); + + let report_path = temp.path().join("report.json"); + let output = Command::new("python3") + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(&ec_root) + .arg("--truth-json") + .arg(&truth_path) + .arg("--eb-stack-json") + .arg(&stack_path) + .arg("--out") + .arg(&report_path) + .output() + .expect("run parity_audit.py mismatch check"); + + assert!(!output.status.success()); + let report: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); + let fields: Vec<&str> = report["mismatches"] + .as_array() + .unwrap() + .iter() + .map(|mismatch| mismatch["field"].as_str().unwrap()) + .collect(); + assert!(fields.contains(&"dropped_exts")); + assert!(fields.contains(&"runtime_dep:zlib:missing_toolchain")); + assert!(fields.contains(&"extra_build_dep:CMake")); } #[test] From 04e254d44e0061d9a99b3cda46d333c7bb98ab7e Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:21 +0000 Subject: [PATCH 04/17] fix(parity): pin the EasyBuild packages the audit installs The framework test installed whatever easybuild-framework and easybuild-easyblocks PyPI served that day, so its outcome could change without a commit here. scripts/easybuild-requirements.txt pins both at 5.4.2, and the test installs that file into its own virtual environment. --- .../+parity-audit-easybuild-pin.bugfix.md | 1 + scripts/easybuild-requirements.txt | 4 ++ tests/parity_audit_script.rs | 38 +++++++++++++------ 3 files changed, 32 insertions(+), 11 deletions(-) create mode 100644 changelog.d/+parity-audit-easybuild-pin.bugfix.md create mode 100644 scripts/easybuild-requirements.txt diff --git a/changelog.d/+parity-audit-easybuild-pin.bugfix.md b/changelog.d/+parity-audit-easybuild-pin.bugfix.md new file mode 100644 index 00000000..38f82b88 --- /dev/null +++ b/changelog.d/+parity-audit-easybuild-pin.bugfix.md @@ -0,0 +1 @@ +Pin the EasyBuild framework and easyblocks versions the parity audit installs. diff --git a/scripts/easybuild-requirements.txt b/scripts/easybuild-requirements.txt new file mode 100644 index 00000000..a320ef7e --- /dev/null +++ b/scripts/easybuild-requirements.txt @@ -0,0 +1,4 @@ +# Exact EasyBuild pins for the parity audit. tests/parity_audit_script.rs +# installs this file into a virtual environment of its own. +easybuild-framework==5.4.2 +easybuild-easyblocks==5.4.2 diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index c94fdcb3..4f4961d5 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -7,6 +7,26 @@ fn repo_root() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } +fn pinned_easybuild_specs() -> Vec { + let path = repo_root().join("scripts/easybuild-requirements.txt"); + let text = std::fs::read_to_string(&path) + .unwrap_or_else(|err| panic!("read {}: {err}", path.display())); + let specs: Vec = text + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .map(str::to_string) + .collect(); + assert!(!specs.is_empty(), "EasyBuild requirements file is empty"); + for spec in &specs { + assert!( + spec.contains("=="), + "EasyBuild requirement must pin an exact version: {spec}" + ); + } + specs +} + fn mismatch_fields(report: &serde_json::Value) -> Vec { report["mismatches"] .as_array() @@ -275,7 +295,8 @@ fn parity_audit_passes_against_generated_easybuild_stub_and_eb_stack() { } /// Resolves a GCCcore dependency and an empty toolchain through the real -/// EasyBuild framework. +/// EasyBuild framework, at the versions `scripts/easybuild-requirements.txt` +/// pins. #[test] fn parity_audit_resolves_with_easybuild_framework() { let temp = tempfile::tempdir().expect("tempdir"); @@ -293,16 +314,11 @@ fn parity_audit_resolves_with_easybuild_framework() { venv_status.success(), "create EasyBuild virtual environment" ); - let install_status = Command::new(&python) - .args([ - "-m", - "pip", - "install", - "easybuild-framework", - "easybuild-easyblocks", - ]) - .status() - .expect("install EasyBuild framework"); + let mut install = Command::new(&python); + install + .args(["-m", "pip", "install", "--disable-pip-version-check"]) + .args(pinned_easybuild_specs()); + let install_status = install.status().expect("install EasyBuild framework"); assert!(install_status.success(), "install EasyBuild framework"); let output = Command::new(&python) From 03a09c294c92c2ad89cd20c8f2e3df24cdcc354a Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:22 +0000 Subject: [PATCH 05/17] fix(parity): match external modules on both sides The truth side was dropping external-module dependencies before the two-way check, so eb-stack reported those dependencies as extra. The comparator now leaves an external module out on both sides. --- .../+parity-audit-external-deps.bugfix.md | 1 + scripts/parity_audit.py | 12 +- tests/parity_audit_script.rs | 104 ++++++++++++++++++ 3 files changed, 116 insertions(+), 1 deletion(-) create mode 100644 changelog.d/+parity-audit-external-deps.bugfix.md diff --git a/changelog.d/+parity-audit-external-deps.bugfix.md b/changelog.d/+parity-audit-external-deps.bugfix.md new file mode 100644 index 00000000..35135744 --- /dev/null +++ b/changelog.d/+parity-audit-external-deps.bugfix.md @@ -0,0 +1 @@ +Leave external-module dependencies out of both sides of the parity audit. diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index e0279f32..9fd8acba 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -641,9 +641,19 @@ def compare_parity(truth_rows: list[dict], stack_rows: list[dict]) -> dict: } ) + # External modules have no toolchain. Drop them on both sides so an + # eb-stack external dependency is not reported as extra. + external_keys = { + (kind, str(dep.get("name") or "")) + for kind, field in (("runtime", "dependencies"), ("build", "builddependencies")) + for dep in truth.get(field, []) + if dep.get("external_module") + } st_deps_by_key: dict[tuple[str, str], list[str | None]] = {} for dep in stack.get("deps", []): - key = (dep["kind"], dep["name"]) + key = (dep["kind"], str(dep.get("name") or "")) + if dep.get("external_module") or key in external_keys: + continue st_deps_by_key.setdefault(key, []).append(dep.get("resolved_module")) truth_deps_by_key: dict[tuple[str, str], list[dict]] = {} diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index 4f4961d5..f2fd0f17 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -596,3 +596,107 @@ fn parity_audit_discovers_all_hook_categories_and_prints_seed() { assert_eq!(doc["targeted_count"], 10); assert_eq!(doc["checked"], 10); } + +#[test] +fn parity_audit_ignores_external_modules_on_both_sides() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + generate_fixture_tree(&ec_root); + + let truth_path = temp.path().join("truth.json"); + let stack_path = temp.path().join("stack.json"); + let truth = serde_json::json!({ + "results": [{ + "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", + "ok": true, + "module_name": "ToolA/pre-1.0-foss-2024a-extra", + "versionsuffix": "-extra", + "exts_list": [ + {"name": "extone", "version": "0.1.0"}, + {"name": "exttwo", "version": "0.2.0"} + ], + "dependencies": [ + { + "name": "cray-mpich", + "version": "8.1.25", + "external_module": true, + "resolved_module": "cray-mpich/8.1.25", + "toolchain_name": "" + }, + { + "name": "zlib", + "version": "1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "external_module": false, + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + } + ], + "builddependencies": [] + }] + }); + let stack = serde_json::json!({ + "recipes": [{ + "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", + "ok": true, + "module_name": "ToolA/pre-1.0-foss-2024a-extra", + "versionsuffix": "-extra", + "exts_count": 2, + "dropped_exts": false, + "deps": [ + { + "kind": "runtime", + "name": "cray-mpich", + "version_req": "==8.1.25", + "external_module": true, + "resolved_module": "cray-mpich/8.1.25" + }, + { + "kind": "runtime", + "name": "zlib", + "version_req": "==1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + }, + { + "kind": "build", + "name": "Ninja", + "version_req": "==1.11.1", + "resolved_module": "Ninja/1.11.1" + } + ] + }] + }); + write_file(&truth_path, &serde_json::to_string_pretty(&truth).unwrap()); + write_file(&stack_path, &serde_json::to_string_pretty(&stack).unwrap()); + + let report_path = temp.path().join("report.json"); + let output = Command::new("python3") + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(&ec_root) + .arg("--truth-json") + .arg(&truth_path) + .arg("--eb-stack-json") + .arg(&stack_path) + .arg("--out") + .arg(&report_path) + .output() + .expect("run parity_audit.py external-module check"); + + let report: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); + let fields = mismatch_fields(&report); + assert!( + !fields + .iter() + .any(|field| field == "extra_runtime_dep:cray-mpich"), + "external module must not be an extra dependency: {fields:?}" + ); + assert!( + fields.iter().any(|field| field == "extra_build_dep:Ninja"), + "a non-external extra dependency must still be reported: {fields:?}" + ); + assert!(!output.status.success()); +} From f68de50eb85f62ed24f0daa9df2710fb154ab170 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:23 +0000 Subject: [PATCH 06/17] fix(parity): compare name, version and toolchain The comparator matched dependencies on name alone, so eb-stack choosing a different version or toolchain of the right package passed. A dependency now matches on name and version, and on toolchain when both sides record one; a candidate sharing only a name shows as extra. recipe parity-audit records the toolchain of each resolved dependency for this, or the tuple's own toolchain when nothing resolved. --- .../+parity-audit-dep-identity.bugfix.md | 1 + scripts/parity_audit.py | 110 ++++++++++++----- src/build_order.rs | 16 ++- tests/parity_audit_script.rs | 111 ++++++++++++++++++ 4 files changed, 202 insertions(+), 36 deletions(-) create mode 100644 changelog.d/+parity-audit-dep-identity.bugfix.md diff --git a/changelog.d/+parity-audit-dep-identity.bugfix.md b/changelog.d/+parity-audit-dep-identity.bugfix.md new file mode 100644 index 00000000..c5cacbd5 --- /dev/null +++ b/changelog.d/+parity-audit-dep-identity.bugfix.md @@ -0,0 +1 @@ +Compare parity-audit dependencies by name, version, and toolchain. diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index 9fd8acba..51e667e6 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -11,8 +11,10 @@ Compares ``eb-stack recipe parity-audit`` against EasyBuild (or a pre-generated ``--truth-json`` oracle) across parse status, dropped ``exts_list``, ``module_name``, ``versionsuffix``, ``exts_count``, and -nearest-hierarchy-level dependency resolution. Exits 0 on full parity -and 1 on any mismatch or error. +nearest-hierarchy-level dependency resolution. External modules are +left out of both sides. A dependency matches on name and version, and +on toolchain when both sides name one. Exits 0 on full parity and 1 +on any mismatch or error. """ from __future__ import annotations @@ -551,6 +553,47 @@ def run_eb_stack_audit(eb_stack_bin: Path, root: Path, rels: list[str]) -> dict: return json.loads(proc.stdout) +def _is_external(dep: dict) -> bool: + return bool(dep.get("external_module")) + + +def _dep_version(dep: dict) -> str: + raw = dep.get("version") + if raw in (None, ""): + raw = dep.get("version_req") or "" + text = str(raw) + if text.startswith("=="): + return text[2:] + return text + + +def _dep_toolchain(dep: dict) -> tuple[str, str] | None: + name = dep.get("toolchain_name") + version = dep.get("toolchain_version") + if not name: + toolchain = dep.get("toolchain") + if isinstance(toolchain, dict): + name = toolchain.get("name") or "" + version = toolchain.get("version") or "" + else: + return None + name = str(name) + if not name: + return None + return (name, str(version or "")) + + +def _same_dep(left: dict, right: dict) -> bool: + """Name and version, plus toolchain when both sides record one.""" + if str(left.get("name") or "") != str(right.get("name") or ""): + return False + if _dep_version(left) != _dep_version(right): + return False + left_tc = _dep_toolchain(left) + right_tc = _dep_toolchain(right) + return not (left_tc and right_tc and left_tc != right_tc) + + def compare_parity(truth_rows: list[dict], stack_rows: list[dict]) -> dict: by_rel_stack = {row["rel"]: row for row in stack_rows} mismatches: list[dict] = [] @@ -643,38 +686,38 @@ def compare_parity(truth_rows: list[dict], stack_rows: list[dict]) -> dict: # External modules have no toolchain. Drop them on both sides so an # eb-stack external dependency is not reported as extra. - external_keys = { - (kind, str(dep.get("name") or "")) - for kind, field in (("runtime", "dependencies"), ("build", "builddependencies")) - for dep in truth.get(field, []) - if dep.get("external_module") - } - st_deps_by_key: dict[tuple[str, str], list[str | None]] = {} - for dep in stack.get("deps", []): - key = (dep["kind"], str(dep.get("name") or "")) - if dep.get("external_module") or key in external_keys: - continue - st_deps_by_key.setdefault(key, []).append(dep.get("resolved_module")) - - truth_deps_by_key: dict[tuple[str, str], list[dict]] = {} + stack_deps = [dep for dep in stack.get("deps", []) if not _is_external(dep)] + external_truth: list[dict] = [] + truth_by_kind: dict[str, list[dict]] = {"runtime": [], "build": []} for kind, field in (("runtime", "dependencies"), ("build", "builddependencies")): for dep in truth.get(field, []): - if dep.get("external_module"): + if _is_external(dep): + external_truth.append(dep) continue - key = (kind, dep["name"]) - truth_deps_by_key.setdefault(key, []).append(dep) + truth_by_kind[kind].append(dep) + + def _stack_for(kind: str, dep: dict) -> list[dict]: + return [ + other + for other in stack_deps + if other.get("kind") == kind and _same_dep(dep, other) + ] + + for kind, deps in truth_by_kind.items(): + for dep in deps: + matched = _stack_for(kind, dep) if not dep.get("toolchain_name"): mismatches.append( { "rel": rel, "field": f"{kind}_dep:{dep['name']}:missing_toolchain", "easybuild": f"missing toolchain_name in recipe {rel}", - "eb_stack": st_deps_by_key.get(key, []), + "eb_stack": [other.get("resolved_module") for other in matched], } ) continue expected_mod = format_eb_dep_module(dep) - candidates = st_deps_by_key.get(key, []) + candidates = [other.get("resolved_module") for other in matched] if expected_mod not in candidates: mismatches.append( { @@ -684,17 +727,20 @@ def compare_parity(truth_rows: list[dict], stack_rows: list[dict]) -> dict: "eb_stack": candidates, } ) - for key, candidates in st_deps_by_key.items(): - if key not in truth_deps_by_key: - kind, name = key - mismatches.append( - { - "rel": rel, - "field": f"extra_{kind}_dep:{name}", - "easybuild": [], - "eb_stack": candidates, - } - ) + for dep in stack.get("deps", []): + kind = str(dep.get("kind") or "") + if _is_external(dep) or any(_same_dep(dep, other) for other in external_truth): + continue + if any(_same_dep(dep, other) for other in truth_by_kind.get(kind, [])): + continue + mismatches.append( + { + "rel": rel, + "field": f"extra_{kind}_dep:{dep.get('name')}", + "easybuild": [], + "eb_stack": [dep.get("resolved_module")], + } + ) return { "checked": checked, diff --git a/src/build_order.rs b/src/build_order.rs index ef905c78..bdc3aa25 100644 --- a/src/build_order.rs +++ b/src/build_order.rs @@ -1635,6 +1635,11 @@ pub struct ParityDepResolution { pub version_req: String, /// Optional versionsuffix constraint. pub versionsuffix: Option, + /// Resolved dependency toolchain name, or the tuple's own toolchain. + /// Empty when neither is known. + pub toolchain_name: String, + /// Resolved dependency toolchain version. Empty when [`Self::toolchain_name`] is. + pub toolchain_version: String, /// Selected dependency module name (`Name/full_version`), if found. pub resolved_module: Option, } @@ -1664,15 +1669,18 @@ impl<'a> ParityTreeIndex<'a> { ("build", &candidate.builddependencies), ] { for dep in deps { - let resolved_module = - resolve_dep(&self.by_name, candidate, dep, Choice::Newest, self.all) - .map(|matched| module_name(&ModuleKey::of(matched))); + let matched = resolve_dep(&self.by_name, candidate, dep, Choice::Newest, self.all); + let toolchain = matched + .map(|found| &found.toolchain) + .or(dep.toolchain.as_ref()); out.push(ParityDepResolution { kind, name: dep.name.clone(), version_req: dep.version_req.clone(), versionsuffix: dep.versionsuffix.clone(), - resolved_module, + toolchain_name: toolchain.map(|tc| tc.name.clone()).unwrap_or_default(), + toolchain_version: toolchain.map(|tc| tc.version.clone()).unwrap_or_default(), + resolved_module: matched.map(|found| module_name(&ModuleKey::of(found))), }); } } diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index f2fd0f17..ee6ffe98 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -700,3 +700,114 @@ fn parity_audit_ignores_external_modules_on_both_sides() { ); assert!(!output.status.success()); } + +#[test] +fn parity_audit_reports_extra_dependency_version_and_toolchain() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + generate_fixture_tree(&ec_root); + + let truth_path = temp.path().join("truth.json"); + let stack_path = temp.path().join("stack.json"); + let truth = serde_json::json!({ + "results": [{ + "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", + "ok": true, + "module_name": "ToolA/pre-1.0-foss-2024a-extra", + "versionsuffix": "-extra", + "exts_list": [ + {"name": "extone", "version": "0.1.0"}, + {"name": "exttwo", "version": "0.2.0"} + ], + "dependencies": [{ + "name": "zlib", + "version": "1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "external_module": false, + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + }], + "builddependencies": [] + }] + }); + let stack = serde_json::json!({ + "recipes": [{ + "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", + "ok": true, + "module_name": "ToolA/pre-1.0-foss-2024a-extra", + "versionsuffix": "-extra", + "exts_count": 2, + "dropped_exts": false, + "deps": [ + { + "kind": "runtime", + "name": "zlib", + "version_req": "==1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + }, + { + "kind": "runtime", + "name": "zlib", + "version_req": "==1.2.13", + "toolchain_name": "GCCcore", + "toolchain_version": "12.3.0", + "resolved_module": "zlib/1.2.13-GCCcore-12.3.0" + }, + { + "kind": "runtime", + "name": "zlib", + "version_req": "==1.3.1", + "toolchain_name": "GCC", + "toolchain_version": "13.3.0", + "resolved_module": "zlib/1.3.1-GCC-13.3.0" + } + ] + }] + }); + write_file(&truth_path, &serde_json::to_string_pretty(&truth).unwrap()); + write_file(&stack_path, &serde_json::to_string_pretty(&stack).unwrap()); + + let report_path = temp.path().join("report.json"); + let output = Command::new("python3") + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(&ec_root) + .arg("--truth-json") + .arg(&truth_path) + .arg("--eb-stack-json") + .arg(&stack_path) + .arg("--out") + .arg(&report_path) + .output() + .expect("run parity_audit.py version identity check"); + + let report: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); + let fields = mismatch_fields(&report); + assert!( + !fields.iter().any(|field| field == "runtime_dep:zlib"), + "the shared zlib 1.3.1 GCCcore candidate must match: {report}" + ); + let extra_modules: Vec = report["mismatches"] + .as_array() + .unwrap() + .iter() + .filter(|mismatch| mismatch["field"] == "extra_runtime_dep:zlib") + .map(|mismatch| mismatch["eb_stack"].to_string()) + .collect(); + assert!( + extra_modules + .iter() + .any(|text| text.contains("zlib/1.2.13-GCCcore-12.3.0")), + "extra version under zlib must be reported: {extra_modules:?}" + ); + assert!( + extra_modules + .iter() + .any(|text| text.contains("zlib/1.3.1-GCC-13.3.0")), + "extra toolchain under zlib must be reported: {extra_modules:?}" + ); + assert!(!output.status.success()); +} From 02b100a130ce7664c2ef68d7051eeb39716442bf Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:24 +0000 Subject: [PATCH 07/17] fix(parity): fail closed when EasyBuild configuration fails extract_easybuild_truth swallowed every exception from set_up_configuration and carried on, so a broken EasyBuild configuration file produced truth computed from default robot, module and environment settings. The audit now exits with the configuration error instead. --- ...+parity-audit-config-fail-closed.bugfix.md | 1 + scripts/parity_audit.py | 10 +++-- tests/parity_audit_script.rs | 42 +++++++++++++++++++ 3 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 changelog.d/+parity-audit-config-fail-closed.bugfix.md diff --git a/changelog.d/+parity-audit-config-fail-closed.bugfix.md b/changelog.d/+parity-audit-config-fail-closed.bugfix.md new file mode 100644 index 00000000..572c9105 --- /dev/null +++ b/changelog.d/+parity-audit-config-fail-closed.bugfix.md @@ -0,0 +1 @@ +Fail the parity audit when EasyBuild's `set_up_configuration` raises, instead of continuing on a partial configuration. diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index 51e667e6..9fac9739 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -364,15 +364,17 @@ def extract_easybuild_truth( f"Import error: {exc}" ) from exc - try: - from easybuild.tools.options import set_up_configuration + from easybuild.tools.options import set_up_configuration + # A partial configuration would leave robot, module and environment + # settings at defaults the truth was never meant to use. + try: set_up_configuration( args=[f"--robot={root}"], silent=True, ) - except Exception: - pass + except (Exception, SystemExit) as exc: + raise SystemExit(f"parity_audit: EasyBuild configuration failed: {exc}") from exc if hasattr(eb_modules, "NoModulesTool") and hasattr(eb_easyconfig, "modules_tool"): orig_modules_tool = eb_easyconfig.modules_tool diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index ee6ffe98..e9433928 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -374,6 +374,48 @@ fn parity_audit_resolves_with_easybuild_framework() { ); } +#[test] +fn parity_audit_fails_closed_when_easybuild_configuration_fails() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + let py_stub = temp.path().join("py_stub"); + let report = temp.path().join("report.json"); + generate_fixture_tree(&ec_root); + generate_easybuild_python_stub(&py_stub); + write_file( + &py_stub.join("easybuild/tools/options.py"), + r#"ROBOT_ROOT = None + +def set_up_configuration(args=None, silent=True): + raise RuntimeError("broken EasyBuild configuration file") +"#, + ); + + let output = Command::new("python3") + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(&ec_root) + .arg("--sample-size") + .arg("4") + .arg("--pythonpath") + .arg(&py_stub) + .arg("--eb-stack") + .arg(env!("CARGO_BIN_EXE_eb-stack")) + .arg("--out") + .arg(&report) + .output() + .expect("run parity_audit.py"); + + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!output.status.success(), "stderr:\n{stderr}"); + assert!( + stderr.contains("EasyBuild configuration failed") + && stderr.contains("broken EasyBuild configuration file"), + "stderr:\n{stderr}" + ); + assert!(!report.exists(), "no report from a partial configuration"); +} + #[test] fn parity_audit_exits_nonzero_on_mismatch_and_dropped_exts() { let temp = tempfile::tempdir().expect("tempdir"); From 555a7d9458881d08335bd731a8beb5e8ae4bdb3d Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:25 +0000 Subject: [PATCH 08/17] build(parity): lock the EasyBuild install with hashes Exact version pins still let pip pick any artifact for those versions, and the EasyBuild sdists build with an unpinned setuptools in an isolated environment. scripts/easybuild-build-requirements.txt locks setuptools as the build backend, and both lock files carry sha256 hashes. The framework test installs the build lock with `--only-binary :all:`, then EasyBuild with `--no-build-isolation`, both with `--require-hashes`, and checks that every locked package carries a hash. --- .../+parity-audit-easybuild-hashes.bugfix.md | 1 + scripts/easybuild-build-requirements.txt | 6 ++ scripts/easybuild-requirements.txt | 17 +++- tests/parity_audit_script.rs | 95 ++++++++++++++----- 4 files changed, 92 insertions(+), 27 deletions(-) create mode 100644 changelog.d/+parity-audit-easybuild-hashes.bugfix.md create mode 100644 scripts/easybuild-build-requirements.txt diff --git a/changelog.d/+parity-audit-easybuild-hashes.bugfix.md b/changelog.d/+parity-audit-easybuild-hashes.bugfix.md new file mode 100644 index 00000000..fe970d69 --- /dev/null +++ b/changelog.d/+parity-audit-easybuild-hashes.bugfix.md @@ -0,0 +1 @@ +Lock the parity audit's EasyBuild install, including the setuptools build backend, to exact versions with sha256 hashes and install it with `--require-hashes`. diff --git a/scripts/easybuild-build-requirements.txt b/scripts/easybuild-build-requirements.txt new file mode 100644 index 00000000..db1bf886 --- /dev/null +++ b/scripts/easybuild-build-requirements.txt @@ -0,0 +1,6 @@ +# Build backend for the EasyBuild sdists, which have no pyproject.toml and +# would otherwise get an unpinned setuptools in an isolated build. Install +# this file first, then scripts/easybuild-requirements.txt with +# --no-build-isolation, both with --require-hashes. +setuptools==84.2.1 \ + --hash=sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2 diff --git a/scripts/easybuild-requirements.txt b/scripts/easybuild-requirements.txt index a320ef7e..9c1331b4 100644 --- a/scripts/easybuild-requirements.txt +++ b/scripts/easybuild-requirements.txt @@ -1,4 +1,13 @@ -# Exact EasyBuild pins for the parity audit. tests/parity_audit_script.rs -# installs this file into a virtual environment of its own. -easybuild-framework==5.4.2 -easybuild-easyblocks==5.4.2 +# Exact EasyBuild pins for the parity audit, with artifact hashes. +# tests/parity_audit_script.rs installs it into a virtual environment of +# its own, after scripts/easybuild-build-requirements.txt: +# +# pip install --require-hashes --only-binary :all: -r scripts/easybuild-build-requirements.txt +# pip install --require-hashes --no-build-isolation -r scripts/easybuild-requirements.txt +# +# Neither package declares a runtime dependency; --require-hashes refuses +# one that appears without a pin here. +easybuild-framework==5.4.2 \ + --hash=sha256:284fe46e92defef7dd8827082064285a806a767f6fd3322bfe26c859afbb730f +easybuild-easyblocks==5.4.2 \ + --hash=sha256:6af03a367baa46dfcf9378cf6dc40c545c79985484177313cfe81627d33aa6de diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index e9433928..b15ce954 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -7,24 +7,79 @@ fn repo_root() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } -fn pinned_easybuild_specs() -> Vec { - let path = repo_root().join("scripts/easybuild-requirements.txt"); +const EASYBUILD_BUILD_LOCK: &str = "scripts/easybuild-build-requirements.txt"; +const EASYBUILD_LOCK: &str = "scripts/easybuild-requirements.txt"; + +/// Requirements in a pip lock file, continuation lines joined. +fn locked_requirements(rel: &str) -> Vec { + let path = repo_root().join(rel); let text = std::fs::read_to_string(&path) .unwrap_or_else(|err| panic!("read {}: {err}", path.display())); - let specs: Vec = text - .lines() - .map(str::trim) - .filter(|line| !line.is_empty() && !line.starts_with('#')) - .map(str::to_string) - .collect(); - assert!(!specs.is_empty(), "EasyBuild requirements file is empty"); - for spec in &specs { - assert!( - spec.contains("=="), - "EasyBuild requirement must pin an exact version: {spec}" - ); + let mut requirements = Vec::new(); + let mut current = String::new(); + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + match line.strip_suffix('\\') { + Some(part) => current.push_str(part), + None => { + current.push_str(line); + requirements.push(std::mem::take(&mut current)); + } + } + } + assert!(current.is_empty(), "{rel} ends in a continuation"); + requirements +} + +/// Install the locked EasyBuild into `python`'s environment. +fn install_locked_easybuild(python: &Path) { + for args in [ + vec!["--only-binary", ":all:", "-r", EASYBUILD_BUILD_LOCK], + vec!["--no-build-isolation", "-r", EASYBUILD_LOCK], + ] { + let status = Command::new(python) + .current_dir(repo_root()) + .args(["-m", "pip", "install", "--disable-pip-version-check"]) + .arg("--require-hashes") + .args(&args) + .status() + .expect("run pip"); + assert!(status.success(), "pip install {args:?}"); } - specs +} + +#[test] +fn easybuild_locks_pin_every_package_with_a_hash() { + for rel in [EASYBUILD_BUILD_LOCK, EASYBUILD_LOCK] { + let requirements = locked_requirements(rel); + assert!(!requirements.is_empty(), "{rel} pins nothing"); + for requirement in &requirements { + let spec = requirement.split_whitespace().next().unwrap_or(""); + assert!( + spec.contains("==") && !spec.contains('*'), + "{rel}: {requirement} must pin an exact version" + ); + let hashes: Vec<&str> = requirement + .split_whitespace() + .filter_map(|token| token.strip_prefix("--hash=sha256:")) + .collect(); + assert!( + !hashes.is_empty() + && hashes + .iter() + .all(|hash| hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit())), + "{rel}: {requirement} must carry a sha256 hash" + ); + } + } + let packages: Vec = locked_requirements(EASYBUILD_LOCK) + .iter() + .filter_map(|requirement| requirement.split("==").next().map(str::to_string)) + .collect(); + assert_eq!(packages, ["easybuild-framework", "easybuild-easyblocks"]); } fn mismatch_fields(report: &serde_json::Value) -> Vec { @@ -295,8 +350,7 @@ fn parity_audit_passes_against_generated_easybuild_stub_and_eb_stack() { } /// Resolves a GCCcore dependency and an empty toolchain through the real -/// EasyBuild framework, at the versions `scripts/easybuild-requirements.txt` -/// pins. +/// EasyBuild framework, installed from the hashed locks in `scripts/`. #[test] fn parity_audit_resolves_with_easybuild_framework() { let temp = tempfile::tempdir().expect("tempdir"); @@ -314,12 +368,7 @@ fn parity_audit_resolves_with_easybuild_framework() { venv_status.success(), "create EasyBuild virtual environment" ); - let mut install = Command::new(&python); - install - .args(["-m", "pip", "install", "--disable-pip-version-check"]) - .args(pinned_easybuild_specs()); - let install_status = install.status().expect("install EasyBuild framework"); - assert!(install_status.success(), "install EasyBuild framework"); + install_locked_easybuild(&python); let output = Command::new(&python) .arg(repo_root().join("scripts/parity_audit.py")) From ee4c77d12e902d3efcdcc8f5f25feb53ac3d5e7f Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:26 +0000 Subject: [PATCH 09/17] fix(parity): mark external modules in parity records The comparator recognised an external module on the eb-stack side by its identity, so an external module that eb-stack resolved to an ordinary in-tree build of the same name and version matched. Every recipe parity-audit dependency record now carries an external_module marker; eb-stack refuses recipes that list an external module, so it is always false. The comparator requires the marker, reports a record without it, and pairs an EasyBuild external module only with a dependency marked external, reporting external_resolved_in_tree or external_missing otherwise. --- .../+parity-audit-external-marker.bugfix.md | 1 + scripts/parity_audit.py | 64 +++++-- src/build_order.rs | 6 + tests/parity_audit_script.rs | 169 +++++++++++++++++- 4 files changed, 222 insertions(+), 18 deletions(-) create mode 100644 changelog.d/+parity-audit-external-marker.bugfix.md diff --git a/changelog.d/+parity-audit-external-marker.bugfix.md b/changelog.d/+parity-audit-external-marker.bugfix.md new file mode 100644 index 00000000..b0584ff3 --- /dev/null +++ b/changelog.d/+parity-audit-external-marker.bugfix.md @@ -0,0 +1 @@ +Every `recipe parity-audit` dependency record now carries an `external_module` marker, and the parity comparator requires it. An external module that eb-stack resolves to an in-tree build is reported instead of matched by identity. diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index 9fac9739..1726af4d 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -11,10 +11,12 @@ Compares ``eb-stack recipe parity-audit`` against EasyBuild (or a pre-generated ``--truth-json`` oracle) across parse status, dropped ``exts_list``, ``module_name``, ``versionsuffix``, ``exts_count``, and -nearest-hierarchy-level dependency resolution. External modules are -left out of both sides. A dependency matches on name and version, and -on toolchain when both sides name one. Exits 0 on full parity and 1 -on any mismatch or error. +nearest-hierarchy-level dependency resolution. Every eb-stack +dependency record carries an ``external_module`` marker; an EasyBuild +external module pairs only with a dependency marked external, so an +external module resolved to an in-tree build is a mismatch. A dependency +matches on name and version, and on toolchain when both sides name one. +Exits 0 on full parity and 1 on any mismatch or error. """ from __future__ import annotations @@ -686,18 +688,54 @@ def compare_parity(truth_rows: list[dict], stack_rows: list[dict]) -> dict: } ) - # External modules have no toolchain. Drop them on both sides so an - # eb-stack external dependency is not reported as extra. - stack_deps = [dep for dep in stack.get("deps", []) if not _is_external(dep)] - external_truth: list[dict] = [] + # External modules have no toolchain, so they pair only with a stack + # dependency that says it is external. The marker is required: an + # identity match alone would hide an external module eb-stack + # resolved to an ordinary in-tree build. + stack_deps: list[dict] = [] + stack_external: list[dict] = [] + for dep in stack.get("deps", []): + kind = str(dep.get("kind") or "") + if not isinstance(dep.get("external_module"), bool): + mismatches.append( + { + "rel": rel, + "field": f"{kind}_dep:{dep.get('name')}:missing_external_marker", + "easybuild": None, + "eb_stack": dep.get("resolved_module"), + } + ) + (stack_external if _is_external(dep) else stack_deps).append(dep) + external_truth: dict[str, list[dict]] = {"runtime": [], "build": []} truth_by_kind: dict[str, list[dict]] = {"runtime": [], "build": []} for kind, field in (("runtime", "dependencies"), ("build", "builddependencies")): for dep in truth.get(field, []): if _is_external(dep): - external_truth.append(dep) + external_truth[kind].append(dep) continue truth_by_kind[kind].append(dep) + for kind, deps in external_truth.items(): + for dep in deps: + if any( + other.get("kind") == kind and _same_dep(dep, other) for other in stack_external + ): + continue + in_tree = [ + other.get("resolved_module") + for other in stack_deps + if other.get("kind") == kind and _same_dep(dep, other) + ] + mismatches.append( + { + "rel": rel, + "field": f"{kind}_dep:{dep['name']}:" + + ("external_resolved_in_tree" if in_tree else "external_missing"), + "easybuild": dep.get("resolved_module") or dep["name"], + "eb_stack": in_tree, + } + ) + def _stack_for(kind: str, dep: dict) -> list[dict]: return [ other @@ -731,9 +769,13 @@ def _stack_for(kind: str, dep: dict) -> list[dict]: ) for dep in stack.get("deps", []): kind = str(dep.get("kind") or "") - if _is_external(dep) or any(_same_dep(dep, other) for other in external_truth): + if _is_external(dep): + if any(_same_dep(dep, other) for other in external_truth.get(kind, [])): + continue + elif any(_same_dep(dep, other) for other in truth_by_kind.get(kind, [])): continue - if any(_same_dep(dep, other) for other in truth_by_kind.get(kind, [])): + elif any(_same_dep(dep, other) for other in external_truth.get(kind, [])): + # Already reported as external_resolved_in_tree. continue mismatches.append( { diff --git a/src/build_order.rs b/src/build_order.rs index bdc3aa25..bf57efc5 100644 --- a/src/build_order.rs +++ b/src/build_order.rs @@ -1642,6 +1642,11 @@ pub struct ParityDepResolution { pub toolchain_version: String, /// Selected dependency module name (`Name/full_version`), if found. pub resolved_module: Option, + /// Whether the dependency is an EasyBuild external module. eb-stack + /// refuses a recipe that lists one (`EXTERNAL_MODULE` does not parse), + /// so every record it emits is an in-tree resolution and says so; the + /// comparator never has to guess it from the dependency's identity. + pub external_module: bool, } /// Pre-indexed candidate table for resolving dependencies across a tree. @@ -1681,6 +1686,7 @@ impl<'a> ParityTreeIndex<'a> { toolchain_name: toolchain.map(|tc| tc.name.clone()).unwrap_or_default(), toolchain_version: toolchain.map(|tc| tc.version.clone()).unwrap_or_default(), resolved_module: matched.map(|found| module_name(&ModuleKey::of(found))), + external_module: false, }); } } diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index b15ce954..caef318b 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -560,8 +560,8 @@ fn parity_audit_reports_dropped_extensions_missing_toolchains_and_extra_deps() { "dropped_exts": true, "skipped_statements": ["exts_list"], "deps": [ - {"kind": "runtime", "name": "zlib", "resolved_module": null}, - {"kind": "build", "name": "CMake", "resolved_module": "CMake/3.29.3"} + {"kind": "runtime", "name": "zlib", "resolved_module": null, "external_module": false}, + {"kind": "build", "name": "CMake", "resolved_module": "CMake/3.29.3", "external_module": false} ] }] }); @@ -748,13 +748,15 @@ fn parity_audit_ignores_external_modules_on_both_sides() { "version_req": "==1.3.1", "toolchain_name": "GCCcore", "toolchain_version": "13.3.0", - "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0", + "external_module": false }, { "kind": "build", "name": "Ninja", "version_req": "==1.11.1", - "resolved_module": "Ninja/1.11.1" + "resolved_module": "Ninja/1.11.1", + "external_module": false } ] }] @@ -836,7 +838,8 @@ fn parity_audit_reports_extra_dependency_version_and_toolchain() { "version_req": "==1.3.1", "toolchain_name": "GCCcore", "toolchain_version": "13.3.0", - "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0", + "external_module": false }, { "kind": "runtime", @@ -844,7 +847,8 @@ fn parity_audit_reports_extra_dependency_version_and_toolchain() { "version_req": "==1.2.13", "toolchain_name": "GCCcore", "toolchain_version": "12.3.0", - "resolved_module": "zlib/1.2.13-GCCcore-12.3.0" + "resolved_module": "zlib/1.2.13-GCCcore-12.3.0", + "external_module": false }, { "kind": "runtime", @@ -852,7 +856,8 @@ fn parity_audit_reports_extra_dependency_version_and_toolchain() { "version_req": "==1.3.1", "toolchain_name": "GCC", "toolchain_version": "13.3.0", - "resolved_module": "zlib/1.3.1-GCC-13.3.0" + "resolved_module": "zlib/1.3.1-GCC-13.3.0", + "external_module": false } ] }] @@ -902,3 +907,153 @@ fn parity_audit_reports_extra_dependency_version_and_toolchain() { ); assert!(!output.status.success()); } + +fn run_comparator( + temp: &Path, + ec_root: &Path, + truth: &serde_json::Value, + stack: &serde_json::Value, +) -> (std::process::Output, serde_json::Value) { + let truth_path = temp.join("truth.json"); + let stack_path = temp.join("stack.json"); + let report_path = temp.join("report.json"); + write_file(&truth_path, &serde_json::to_string_pretty(truth).unwrap()); + write_file(&stack_path, &serde_json::to_string_pretty(stack).unwrap()); + let output = Command::new("python3") + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(ec_root) + .arg("--truth-json") + .arg(&truth_path) + .arg("--eb-stack-json") + .arg(&stack_path) + .arg("--out") + .arg(&report_path) + .output() + .expect("run parity_audit.py"); + let report = serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); + (output, report) +} + +fn tool_a_truth(dependencies: serde_json::Value) -> serde_json::Value { + serde_json::json!({ + "results": [{ + "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", + "ok": true, + "module_name": "ToolA/pre-1.0-foss-2024a-extra", + "versionsuffix": "-extra", + "exts_list": [ + {"name": "extone", "version": "0.1.0"}, + {"name": "exttwo", "version": "0.2.0"} + ], + "dependencies": dependencies, + "builddependencies": [] + }] + }) +} + +fn tool_a_stack(deps: serde_json::Value) -> serde_json::Value { + serde_json::json!({ + "recipes": [{ + "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", + "ok": true, + "module_name": "ToolA/pre-1.0-foss-2024a-extra", + "versionsuffix": "-extra", + "exts_count": 2, + "dropped_exts": false, + "deps": deps + }] + }) +} + +#[test] +fn parity_audit_reports_an_external_module_resolved_in_tree() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + generate_fixture_tree(&ec_root); + let truth = tool_a_truth(serde_json::json!([{ + "name": "cray-mpich", + "version": "8.1.25", + "external_module": true, + "resolved_module": "cray-mpich/8.1.25", + "toolchain_name": "" + }])); + let stack = tool_a_stack(serde_json::json!([{ + "kind": "runtime", + "name": "cray-mpich", + "version_req": "==8.1.25", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "resolved_module": "cray-mpich/8.1.25-GCCcore-13.3.0", + "external_module": false + }])); + + let (output, report) = run_comparator(temp.path(), &ec_root, &truth, &stack); + let fields = mismatch_fields(&report); + assert_eq!( + fields, + ["runtime_dep:cray-mpich:external_resolved_in_tree"], + "{report}" + ); + assert!(!output.status.success()); +} + +#[test] +fn parity_audit_requires_the_external_marker_on_every_stack_dep() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + generate_fixture_tree(&ec_root); + let zlib = serde_json::json!({ + "name": "zlib", + "version": "1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "external_module": false, + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + }); + let truth = tool_a_truth(serde_json::json!([zlib])); + let stack = tool_a_stack(serde_json::json!([{ + "kind": "runtime", + "name": "zlib", + "version_req": "==1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + }])); + + let (output, report) = run_comparator(temp.path(), &ec_root, &truth, &stack); + assert_eq!( + mismatch_fields(&report), + ["runtime_dep:zlib:missing_external_marker"], + "{report}" + ); + assert!(!output.status.success()); +} + +#[test] +fn recipe_parity_audit_marks_every_dependency_record() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + generate_fixture_tree(&ec_root); + let recipes = temp.path().join("recipes.txt"); + write_file(&recipes, "t/ToolA/ToolA-1.0-foss-2024a-extra.eb\n"); + + let output = Command::new(env!("CARGO_BIN_EXE_eb-stack")) + .args(["recipe", "parity-audit", "--easyconfigs"]) + .arg(&ec_root) + .arg("--recipes-file") + .arg(&recipes) + .output() + .expect("run eb-stack recipe parity-audit"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let doc: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + let deps = doc["recipes"][0]["deps"].as_array().unwrap(); + assert_eq!(deps.len(), 2, "{doc}"); + for dep in deps { + assert_eq!(dep["external_module"], false, "{dep}"); + } +} From 9f573ffdde261f97ed7e611e7805a833e89b98d6 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:27 +0000 Subject: [PATCH 10/17] test(parity): share the ToolA comparator helpers The first four ToolA comparator tests each spelled out the full truth and stack documents and the parity_audit.py command line, which later tests get from tool_a_truth, tool_a_stack and run_comparator. They now build on those helpers and override only the fields they exercise. run_comparator and the new run_comparator_against_eb_stack share run_parity_audit, so the test that runs the real eb-stack binary uses the same runner. That test now asserts the exact mismatch fields instead of their count. --- .../+parity-audit-test-helpers.misc.md | 1 + tests/parity_audit_script.rs | 420 ++++++------------ 2 files changed, 149 insertions(+), 272 deletions(-) create mode 100644 changelog.d/+parity-audit-test-helpers.misc.md diff --git a/changelog.d/+parity-audit-test-helpers.misc.md b/changelog.d/+parity-audit-test-helpers.misc.md new file mode 100644 index 00000000..713ab3ad --- /dev/null +++ b/changelog.d/+parity-audit-test-helpers.misc.md @@ -0,0 +1 @@ +Build the early ToolA parity comparator tests from the shared truth, stack and runner helpers. diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index caef318b..234fc0a6 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -471,60 +471,27 @@ fn parity_audit_exits_nonzero_on_mismatch_and_dropped_exts() { let ec_root = temp.path().join("easyconfigs"); generate_fixture_tree(&ec_root); - let truth_path = temp.path().join("bad-truth.json"); - let truth = serde_json::json!({ - "results": [ - { - "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", - "bucket": "sample:exts_list", - "ok": true, - "name": "ToolA", - "version": "1.0", - "versionprefix": "pre-", - "versionsuffix": "-wrong", - "toolchain_name": "foss", - "toolchain_version": "2024a", - "module_name": "ToolA/pre-1.0-foss-2024a-extra", - "dependencies": [ - { - "name": "zlib", - "version": "1.3.1", - "versionsuffix": "", - "toolchain_name": "GCCcore", - "toolchain_version": "13.3.0", - "external_module": false - } - ], - "builddependencies": [], - "exts_list": [ - {"name": "extone", "version": "0.1.0"} - ] - } - ] - }); - write_file(&truth_path, &serde_json::to_string_pretty(&truth).unwrap()); + let mut truth = tool_a_truth(serde_json::json!([{ + "name": "zlib", + "version": "1.3.1", + "versionsuffix": "", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "external_module": false + }])); + truth["results"][0]["versionsuffix"] = "-wrong".into(); + truth["results"][0]["exts_list"] = serde_json::json!([{"name": "extone", "version": "0.1.0"}]); - let report_path = temp.path().join("bad-report.json"); - let output = Command::new("python3") - .arg(repo_root().join("scripts/parity_audit.py")) - .arg("--easyconfigs") - .arg(&ec_root) - .arg("--truth-json") - .arg(&truth_path) - .arg("--eb-stack") - .arg(env!("CARGO_BIN_EXE_eb-stack")) - .arg("--out") - .arg(&report_path) - .output() - .expect("run parity_audit.py mismatch check"); + let (output, report) = run_comparator_against_eb_stack(temp.path(), &ec_root, &truth); assert!( !output.status.success(), "parity_audit.py must fail when versionsuffix/exts_count disagree" ); - let report: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); - assert_eq!(report["mismatch_count"], 3); + assert_eq!( + mismatch_fields(&report), + ["versionsuffix", "exts_count", "extra_build_dep:CMake"] + ); } #[test] @@ -533,67 +500,29 @@ fn parity_audit_reports_dropped_extensions_missing_toolchains_and_extra_deps() { let ec_root = temp.path().join("easyconfigs"); generate_fixture_tree(&ec_root); - let truth_path = temp.path().join("truth.json"); - let stack_path = temp.path().join("stack.json"); - let truth = serde_json::json!({ - "results": [{ - "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", - "ok": true, - "module_name": "ToolA/pre-1.0-foss-2024a-extra", - "versionsuffix": "-extra", - "exts_list": [], - "dependencies": [{ - "name": "zlib", - "toolchain_name": null, - "external_module": false - }], - "builddependencies": [] - }] - }); - let stack = serde_json::json!({ - "recipes": [{ - "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", - "ok": true, - "module_name": "ToolA/pre-1.0-foss-2024a-extra", - "versionsuffix": "-extra", - "exts_count": 0, - "dropped_exts": true, - "skipped_statements": ["exts_list"], - "deps": [ - {"kind": "runtime", "name": "zlib", "resolved_module": null, "external_module": false}, - {"kind": "build", "name": "CMake", "resolved_module": "CMake/3.29.3", "external_module": false} - ] - }] - }); - write_file(&truth_path, &serde_json::to_string_pretty(&truth).unwrap()); - write_file(&stack_path, &serde_json::to_string_pretty(&stack).unwrap()); + let mut truth = tool_a_truth(serde_json::json!([{ + "name": "zlib", + "toolchain_name": null, + "external_module": false + }])); + truth["results"][0]["exts_list"] = serde_json::json!([]); + let mut stack = tool_a_stack(serde_json::json!([ + {"kind": "runtime", "name": "zlib", "resolved_module": null, "external_module": false}, + {"kind": "build", "name": "CMake", "resolved_module": "CMake/3.29.3", "external_module": false} + ])); + stack["recipes"][0]["exts_count"] = 0.into(); + stack["recipes"][0]["dropped_exts"] = true.into(); + stack["recipes"][0]["skipped_statements"] = serde_json::json!(["exts_list"]); - let report_path = temp.path().join("report.json"); - let output = Command::new("python3") - .arg(repo_root().join("scripts/parity_audit.py")) - .arg("--easyconfigs") - .arg(&ec_root) - .arg("--truth-json") - .arg(&truth_path) - .arg("--eb-stack-json") - .arg(&stack_path) - .arg("--out") - .arg(&report_path) - .output() - .expect("run parity_audit.py mismatch check"); + let (output, report) = run_comparator(temp.path(), &ec_root, &truth, &stack); assert!(!output.status.success()); - let report: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); - let fields: Vec<&str> = report["mismatches"] - .as_array() - .unwrap() + let fields = mismatch_fields(&report); + assert!(fields.iter().any(|field| field == "dropped_exts")); + assert!(fields .iter() - .map(|mismatch| mismatch["field"].as_str().unwrap()) - .collect(); - assert!(fields.contains(&"dropped_exts")); - assert!(fields.contains(&"runtime_dep:zlib:missing_toolchain")); - assert!(fields.contains(&"extra_build_dep:CMake")); + .any(|field| field == "runtime_dep:zlib:missing_toolchain")); + assert!(fields.iter().any(|field| field == "extra_build_dep:CMake")); } #[test] @@ -694,92 +623,51 @@ fn parity_audit_ignores_external_modules_on_both_sides() { let ec_root = temp.path().join("easyconfigs"); generate_fixture_tree(&ec_root); - let truth_path = temp.path().join("truth.json"); - let stack_path = temp.path().join("stack.json"); - let truth = serde_json::json!({ - "results": [{ - "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", - "ok": true, - "module_name": "ToolA/pre-1.0-foss-2024a-extra", - "versionsuffix": "-extra", - "exts_list": [ - {"name": "extone", "version": "0.1.0"}, - {"name": "exttwo", "version": "0.2.0"} - ], - "dependencies": [ - { - "name": "cray-mpich", - "version": "8.1.25", - "external_module": true, - "resolved_module": "cray-mpich/8.1.25", - "toolchain_name": "" - }, - { - "name": "zlib", - "version": "1.3.1", - "toolchain_name": "GCCcore", - "toolchain_version": "13.3.0", - "external_module": false, - "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" - } - ], - "builddependencies": [] - }] - }); - let stack = serde_json::json!({ - "recipes": [{ - "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", - "ok": true, - "module_name": "ToolA/pre-1.0-foss-2024a-extra", - "versionsuffix": "-extra", - "exts_count": 2, - "dropped_exts": false, - "deps": [ - { - "kind": "runtime", - "name": "cray-mpich", - "version_req": "==8.1.25", - "external_module": true, - "resolved_module": "cray-mpich/8.1.25" - }, - { - "kind": "runtime", - "name": "zlib", - "version_req": "==1.3.1", - "toolchain_name": "GCCcore", - "toolchain_version": "13.3.0", - "resolved_module": "zlib/1.3.1-GCCcore-13.3.0", - "external_module": false - }, - { - "kind": "build", - "name": "Ninja", - "version_req": "==1.11.1", - "resolved_module": "Ninja/1.11.1", - "external_module": false - } - ] - }] - }); - write_file(&truth_path, &serde_json::to_string_pretty(&truth).unwrap()); - write_file(&stack_path, &serde_json::to_string_pretty(&stack).unwrap()); + let truth = tool_a_truth(serde_json::json!([ + { + "name": "cray-mpich", + "version": "8.1.25", + "external_module": true, + "resolved_module": "cray-mpich/8.1.25", + "toolchain_name": "" + }, + { + "name": "zlib", + "version": "1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "external_module": false, + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + } + ])); + let stack = tool_a_stack(serde_json::json!([ + { + "kind": "runtime", + "name": "cray-mpich", + "version_req": "==8.1.25", + "external_module": true, + "resolved_module": "cray-mpich/8.1.25" + }, + { + "kind": "runtime", + "name": "zlib", + "version_req": "==1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0", + "external_module": false + }, + { + "kind": "build", + "name": "Ninja", + "version_req": "==1.11.1", + "resolved_module": "Ninja/1.11.1", + "external_module": false + } + ])); - let report_path = temp.path().join("report.json"); - let output = Command::new("python3") - .arg(repo_root().join("scripts/parity_audit.py")) - .arg("--easyconfigs") - .arg(&ec_root) - .arg("--truth-json") - .arg(&truth_path) - .arg("--eb-stack-json") - .arg(&stack_path) - .arg("--out") - .arg(&report_path) - .output() - .expect("run parity_audit.py external-module check"); + let (output, report) = run_comparator(temp.path(), &ec_root, &truth, &stack); - let report: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); let fields = mismatch_fields(&report); assert!( !fields @@ -800,87 +688,46 @@ fn parity_audit_reports_extra_dependency_version_and_toolchain() { let ec_root = temp.path().join("easyconfigs"); generate_fixture_tree(&ec_root); - let truth_path = temp.path().join("truth.json"); - let stack_path = temp.path().join("stack.json"); - let truth = serde_json::json!({ - "results": [{ - "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", - "ok": true, - "module_name": "ToolA/pre-1.0-foss-2024a-extra", - "versionsuffix": "-extra", - "exts_list": [ - {"name": "extone", "version": "0.1.0"}, - {"name": "exttwo", "version": "0.2.0"} - ], - "dependencies": [{ - "name": "zlib", - "version": "1.3.1", - "toolchain_name": "GCCcore", - "toolchain_version": "13.3.0", - "external_module": false, - "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" - }], - "builddependencies": [] - }] - }); - let stack = serde_json::json!({ - "recipes": [{ - "rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", - "ok": true, - "module_name": "ToolA/pre-1.0-foss-2024a-extra", - "versionsuffix": "-extra", - "exts_count": 2, - "dropped_exts": false, - "deps": [ - { - "kind": "runtime", - "name": "zlib", - "version_req": "==1.3.1", - "toolchain_name": "GCCcore", - "toolchain_version": "13.3.0", - "resolved_module": "zlib/1.3.1-GCCcore-13.3.0", - "external_module": false - }, - { - "kind": "runtime", - "name": "zlib", - "version_req": "==1.2.13", - "toolchain_name": "GCCcore", - "toolchain_version": "12.3.0", - "resolved_module": "zlib/1.2.13-GCCcore-12.3.0", - "external_module": false - }, - { - "kind": "runtime", - "name": "zlib", - "version_req": "==1.3.1", - "toolchain_name": "GCC", - "toolchain_version": "13.3.0", - "resolved_module": "zlib/1.3.1-GCC-13.3.0", - "external_module": false - } - ] - }] - }); - write_file(&truth_path, &serde_json::to_string_pretty(&truth).unwrap()); - write_file(&stack_path, &serde_json::to_string_pretty(&stack).unwrap()); + let truth = tool_a_truth(serde_json::json!([{ + "name": "zlib", + "version": "1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "external_module": false, + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + }])); + let stack = tool_a_stack(serde_json::json!([ + { + "kind": "runtime", + "name": "zlib", + "version_req": "==1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0", + "external_module": false + }, + { + "kind": "runtime", + "name": "zlib", + "version_req": "==1.2.13", + "toolchain_name": "GCCcore", + "toolchain_version": "12.3.0", + "resolved_module": "zlib/1.2.13-GCCcore-12.3.0", + "external_module": false + }, + { + "kind": "runtime", + "name": "zlib", + "version_req": "==1.3.1", + "toolchain_name": "GCC", + "toolchain_version": "13.3.0", + "resolved_module": "zlib/1.3.1-GCC-13.3.0", + "external_module": false + } + ])); - let report_path = temp.path().join("report.json"); - let output = Command::new("python3") - .arg(repo_root().join("scripts/parity_audit.py")) - .arg("--easyconfigs") - .arg(&ec_root) - .arg("--truth-json") - .arg(&truth_path) - .arg("--eb-stack-json") - .arg(&stack_path) - .arg("--out") - .arg(&report_path) - .output() - .expect("run parity_audit.py version identity check"); + let (output, report) = run_comparator(temp.path(), &ec_root, &truth, &stack); - let report: serde_json::Value = - serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); let fields = mismatch_fields(&report); assert!( !fields.iter().any(|field| field == "runtime_dep:zlib"), @@ -914,19 +761,48 @@ fn run_comparator( truth: &serde_json::Value, stack: &serde_json::Value, ) -> (std::process::Output, serde_json::Value) { - let truth_path = temp.join("truth.json"); let stack_path = temp.join("stack.json"); + write_file(&stack_path, &serde_json::to_string_pretty(stack).unwrap()); + run_parity_audit( + temp, + ec_root, + truth, + &["--eb-stack-json".as_ref(), stack_path.as_os_str()], + ) +} + +fn run_comparator_against_eb_stack( + temp: &Path, + ec_root: &Path, + truth: &serde_json::Value, +) -> (std::process::Output, serde_json::Value) { + run_parity_audit( + temp, + ec_root, + truth, + &[ + "--eb-stack".as_ref(), + env!("CARGO_BIN_EXE_eb-stack").as_ref(), + ], + ) +} + +fn run_parity_audit( + temp: &Path, + ec_root: &Path, + truth: &serde_json::Value, + stack_args: &[&std::ffi::OsStr], +) -> (std::process::Output, serde_json::Value) { + let truth_path = temp.join("truth.json"); let report_path = temp.join("report.json"); write_file(&truth_path, &serde_json::to_string_pretty(truth).unwrap()); - write_file(&stack_path, &serde_json::to_string_pretty(stack).unwrap()); let output = Command::new("python3") .arg(repo_root().join("scripts/parity_audit.py")) .arg("--easyconfigs") .arg(ec_root) .arg("--truth-json") .arg(&truth_path) - .arg("--eb-stack-json") - .arg(&stack_path) + .args(stack_args) .arg("--out") .arg(&report_path) .output() From acc2cc70c909f0b5f13aaf8482c36134ebcf1f45 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:28 +0000 Subject: [PATCH 11/17] fix(parity): run targeted easyblock hooks in the oracle The oracle read module names and dependencies from the easyconfig alone, so an easyblock that changes them while writing its module passed unexamined, even though the sample targets exactly those easyblocks. For every targeted recipe extract_easybuild_truth now instantiates the easyblock and writes its module with make_module_step(fake=True). From that file it compares the module name, the module loads and the EBVERSION value with what eb-stack resolved. EasyBuild runs with a modules tool that loads nothing, Tcl module syntax and a throwaway prefix, so the host's modules and configuration do not leak in. `--include-easyblocks` adds site easyblocks to discovery and to EasyBuild. Easyblocks run helpers that call a bare python; PythonPackage asks it for the library directory while writing the module. For the duration of the run a bin directory in the work directory, with only a python symlink to the audit's interpreter, comes first on PATH. PATH, tempfile.tempdir and the work directory are restored or removed in a finally block, whatever the run raises. fixtures/parity_audit_hooks/ contains two easyblocks whose hooks eb-stack cannot see, one adding a module load and one changing the version, and the audit must report both. fixtures/parity_audit_python/ contains a PythonPackage recipe that the audit runs with a failing python first on PATH, and it must still write the module and match. --- .../+parity-audit-easyblock-hooks.bugfix.md | 1 + fixtures/parity_audit_hooks/LICENSE | 339 ++++++++++++++++++ fixtures/parity_audit_hooks/README.md | 15 + .../parity_audit_hooks/easyblocks/hookload.py | 8 + .../easyblocks/hookversion.py | 8 + .../easyconfigs/h/HookLoad/HookLoad-1.0.eb | 7 + .../h/HookVersion/HookVersion-1.0.eb | 6 + .../easyconfigs/z/zlib/zlib-1.3.1.eb | 7 + fixtures/parity_audit_python/LICENSE | 339 ++++++++++++++++++ fixtures/parity_audit_python/README.md | 13 + .../easyconfigs/p/PyPkg/PyPkg-1.0.eb | 11 + scripts/parity_audit.py | 336 +++++++++++++---- tests/parity_audit_script.rs | 216 ++++++++++- 13 files changed, 1213 insertions(+), 93 deletions(-) create mode 100644 changelog.d/+parity-audit-easyblock-hooks.bugfix.md create mode 100644 fixtures/parity_audit_hooks/LICENSE create mode 100644 fixtures/parity_audit_hooks/README.md create mode 100644 fixtures/parity_audit_hooks/easyblocks/hookload.py create mode 100644 fixtures/parity_audit_hooks/easyblocks/hookversion.py create mode 100644 fixtures/parity_audit_hooks/easyconfigs/h/HookLoad/HookLoad-1.0.eb create mode 100644 fixtures/parity_audit_hooks/easyconfigs/h/HookVersion/HookVersion-1.0.eb create mode 100644 fixtures/parity_audit_hooks/easyconfigs/z/zlib/zlib-1.3.1.eb create mode 100644 fixtures/parity_audit_python/LICENSE create mode 100644 fixtures/parity_audit_python/README.md create mode 100644 fixtures/parity_audit_python/easyconfigs/p/PyPkg/PyPkg-1.0.eb diff --git a/changelog.d/+parity-audit-easyblock-hooks.bugfix.md b/changelog.d/+parity-audit-easyblock-hooks.bugfix.md new file mode 100644 index 00000000..a97ec7c3 --- /dev/null +++ b/changelog.d/+parity-audit-easyblock-hooks.bugfix.md @@ -0,0 +1 @@ +`scripts/parity_audit.py` now runs the easyblock of every targeted recipe: it writes the module with `make_module_step(fake=True)` and compares the module name, module loads and `EBVERSION` with what eb-stack resolved. `--include-easyblocks` adds site easyblocks to discovery and to EasyBuild. A bare `python` run by an easyblock, as `PythonPackage` does, resolves to the audit's own interpreter. diff --git a/fixtures/parity_audit_hooks/LICENSE b/fixtures/parity_audit_hooks/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/fixtures/parity_audit_hooks/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/fixtures/parity_audit_hooks/README.md b/fixtures/parity_audit_hooks/README.md new file mode 100644 index 00000000..012f31ac --- /dev/null +++ b/fixtures/parity_audit_hooks/README.md @@ -0,0 +1,15 @@ +# Parity fixture: easyblock hooks + +Easyconfigs and easyblocks for the real EasyBuild parity audit +(`parity_audit_compares_modules_generated_by_targeted_easyblocks`). +`HookLoad` uses an easyblock whose `make_module_dep` adds a module load +the recipe does not declare. `HookVersion` uses an easyblock whose +`make_module_step` changes the version written to the module. eb-stack +reads neither hook, so the audit must report both. Excluded from the +published `eb_stack` crate via `Cargo.toml` +`exclude = ["fixtures/parity_*/"]`. + +`LICENSE` is the GNU General Public License v2.0 text kept with the +other parity fixtures, since the easyblocks subclass EasyBuild's +`ConfigureMake` +(`sha256: 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643`). diff --git a/fixtures/parity_audit_hooks/easyblocks/hookload.py b/fixtures/parity_audit_hooks/easyblocks/hookload.py new file mode 100644 index 00000000..7a0d7afe --- /dev/null +++ b/fixtures/parity_audit_hooks/easyblocks/hookload.py @@ -0,0 +1,8 @@ +"""Easyblock whose make_module_dep loads a module no dependency names.""" +from easybuild.easyblocks.generic.configuremake import ConfigureMake + + +class EB_HookLoad(ConfigureMake): + def make_module_dep(self, *args, **kwargs): + loads = super().make_module_dep(*args, **kwargs) + return loads + self.module_generator.load_module('hookdep/1.0') diff --git a/fixtures/parity_audit_hooks/easyblocks/hookversion.py b/fixtures/parity_audit_hooks/easyblocks/hookversion.py new file mode 100644 index 00000000..0469c525 --- /dev/null +++ b/fixtures/parity_audit_hooks/easyblocks/hookversion.py @@ -0,0 +1,8 @@ +"""Easyblock whose make_module_step records a version the recipe does not.""" +from easybuild.easyblocks.generic.configuremake import ConfigureMake + + +class EB_HookVersion(ConfigureMake): + def make_module_step(self, *args, **kwargs): + self.cfg['version'] = self.cfg['version'] + '.post1' + return super().make_module_step(*args, **kwargs) diff --git a/fixtures/parity_audit_hooks/easyconfigs/h/HookLoad/HookLoad-1.0.eb b/fixtures/parity_audit_hooks/easyconfigs/h/HookLoad/HookLoad-1.0.eb new file mode 100644 index 00000000..d11c93d2 --- /dev/null +++ b/fixtures/parity_audit_hooks/easyconfigs/h/HookLoad/HookLoad-1.0.eb @@ -0,0 +1,7 @@ +name = 'HookLoad' +version = '1.0' +homepage = 'https://example.org/' +description = 'Its easyblock adds a module load in make_module_dep' +toolchain = SYSTEM +dependencies = [('zlib', '1.3.1')] +moduleclass = 'tools' diff --git a/fixtures/parity_audit_hooks/easyconfigs/h/HookVersion/HookVersion-1.0.eb b/fixtures/parity_audit_hooks/easyconfigs/h/HookVersion/HookVersion-1.0.eb new file mode 100644 index 00000000..ace82481 --- /dev/null +++ b/fixtures/parity_audit_hooks/easyconfigs/h/HookVersion/HookVersion-1.0.eb @@ -0,0 +1,6 @@ +name = 'HookVersion' +version = '1.0' +homepage = 'https://example.org/' +description = 'Its easyblock changes the version while writing the module' +toolchain = SYSTEM +moduleclass = 'tools' diff --git a/fixtures/parity_audit_hooks/easyconfigs/z/zlib/zlib-1.3.1.eb b/fixtures/parity_audit_hooks/easyconfigs/z/zlib/zlib-1.3.1.eb new file mode 100644 index 00000000..e37c744b --- /dev/null +++ b/fixtures/parity_audit_hooks/easyconfigs/z/zlib/zlib-1.3.1.eb @@ -0,0 +1,7 @@ +easyblock = 'ConfigureMake' +name = 'zlib' +version = '1.3.1' +homepage = 'https://zlib.net/' +description = 'zlib' +toolchain = SYSTEM +moduleclass = 'lib' diff --git a/fixtures/parity_audit_python/LICENSE b/fixtures/parity_audit_python/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/fixtures/parity_audit_python/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/fixtures/parity_audit_python/README.md b/fixtures/parity_audit_python/README.md new file mode 100644 index 00000000..3609e9fe --- /dev/null +++ b/fixtures/parity_audit_python/README.md @@ -0,0 +1,13 @@ +# Parity fixture: PythonPackage module generation + +A minimal easyconfig for the real EasyBuild parity audit +(`parity_audit_runs_python_easyblocks_with_its_own_interpreter`). +`PythonPackage.make_module_extra` asks a bare `python` for its library +directory (`det_pylibdir`), so writing this recipe's module runs +whichever `python` comes first on `PATH`. The audit must bind that name +to its own interpreter. Excluded from the published `eb_stack` crate +via `Cargo.toml` `exclude = ["fixtures/parity_*/"]`. + +`LICENSE` is the GNU General Public License v2.0 text kept with the +other parity fixtures +(`sha256: 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643`). diff --git a/fixtures/parity_audit_python/easyconfigs/p/PyPkg/PyPkg-1.0.eb b/fixtures/parity_audit_python/easyconfigs/p/PyPkg/PyPkg-1.0.eb new file mode 100644 index 00000000..bd236a24 --- /dev/null +++ b/fixtures/parity_audit_python/easyconfigs/p/PyPkg/PyPkg-1.0.eb @@ -0,0 +1,11 @@ +easyblock = 'PythonPackage' + +name = 'PyPkg' +version = '1.0' +homepage = 'https://example.org/' +description = 'A PythonPackage recipe, whose module step asks a bare python for its library directory' +toolchain = SYSTEM + +options = {'modulename': False} + +moduleclass = 'tools' diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index 1726af4d..5d4e571e 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -2,11 +2,15 @@ """Reproducible parity audit between EasyBuild and ``eb-stack``. Selects a deterministic stratified sample across an easyconfigs tree -(seeded via ``--seed``) plus a targeted set of recipes using easyblocks -that touch module naming (``ModuleRC``, ``Toolchain``, ``Bundle``, -``Amber``, ``versionprefix``, ``modaltsoftname``, and any easyblock in -``--easybuild-easyblocks`` overriding ``det_full_module_name`` or using -``modaltsoftname``). +(seeded via ``--seed``) plus a targeted set of recipes whose module +EasyBuild's easyblock hooks may shape: recipes using the ``ModuleRC``, +``Toolchain``, ``Bundle`` or ``Amber`` easyblocks, recipes setting +``versionprefix`` or ``modaltsoftname``, and recipes using an easyblock +found in the installed ``easybuild.easyblocks`` package, +``--easybuild-easyblocks`` or ``--include-easyblocks`` that overrides a +module-writing method (``module_naming``), a template method +(``template``), a toolchain hook (``toolchain``), or touches a naming +attribute such as ``modaltsoftname`` (``naming_attr``). Compares ``eb-stack recipe parity-audit`` against EasyBuild (or a pre-generated ``--truth-json`` oracle) across parse status, dropped @@ -16,7 +20,20 @@ external module pairs only with a dependency marked external, so an external module resolved to an in-tree build is a mismatch. A dependency matches on name and version, and on toolchain when both sides name one. -Exits 0 on full parity and 1 on any mismatch or error. + +For every targeted recipe the oracle instantiates the recipe's easyblock +and has it write its module file (``make_module_step(fake=True)``), so +each overridden hook runs. From that file it compares the module name +(the file's path), the ``module load`` statements against the toolchain +module and eb-stack's resolved runtime dependencies in order, and the +``EBVERSION*`` value against the recipe version. Environment content the +hooks write (paths, variables) has no eb-stack counterpart and is not +compared. EasyBuild runs with ``EbStackAuditModulesTool``, which loads +no modules, and Tcl module syntax; the flat ``EasyBuildMNS`` needs no +loaded module to place a module file. + +Exits 0 on full parity and 1 on any mismatch or error, including an +EasyBuild configuration or easyblock that fails. """ from __future__ import annotations @@ -77,6 +94,13 @@ def parse_args(argv: list[str]) -> argparse.Namespace: default=None, help="Optional easybuild-easyblocks checkout path to scan and add to sys.path.", ) + parser.add_argument( + "--include-easyblocks", + type=Path, + action="append", + default=[], + help="Easyblock file to pass to EasyBuild's --include-easyblocks and scan for hooks.", + ) parser.add_argument( "--pythonpath", action="append", @@ -164,37 +188,52 @@ def _decode_eb_class_name(cls_name: str) -> str: ) -def _class_touches_naming_or_hooks(cls_node: ast.ClassDef) -> bool: +def _class_hook_categories(cls_node: ast.ClassDef) -> set[str]: + categories: set[str] = set() for base in cls_node.bases: - if isinstance(base, ast.Name) and base.id == "Toolchain": - return True - if isinstance(base, ast.Attribute) and base.attr == "Toolchain": - return True + if (isinstance(base, ast.Name) and base.id == "Toolchain") or ( + isinstance(base, ast.Attribute) and base.attr == "Toolchain" + ): + categories.add("toolchain") for node in ast.walk(cls_node): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): - if ( - node.name in _MODULE_NAMING_METHODS - or node.name in _VERSION_TEMPLATE_METHODS - or node.name in _TOOLCHAIN_HOOK_METHODS - or "toolchain" in node.name.lower() - ): - return True + if node.name in _MODULE_NAMING_METHODS: + categories.add("module_naming") + if node.name in _VERSION_TEMPLATE_METHODS: + categories.add("template") + if node.name in _TOOLCHAIN_HOOK_METHODS or "toolchain" in node.name.lower(): + categories.add("toolchain") elif isinstance(node, ast.Attribute) and node.attr in _NAMING_TEMPLATE_ATTRS: - return True + categories.add("naming_attr") elif isinstance(node, ast.Name) and node.id in _NAMING_TEMPLATE_ATTRS: - return True + categories.add("naming_attr") elif isinstance(node, ast.Constant) and isinstance(node.value, str): if node.value in _NAMING_TEMPLATE_ATTRS: - return True - return False + categories.add("naming_attr") + return categories -def discover_easyblocks_touching_naming(easyblocks_root: Path | None) -> list[str]: - if easyblocks_root is None or not easyblocks_root.is_dir(): - return [] - matched: set[str] = set() - for path in sorted(easyblocks_root.rglob("*.py")): +def installed_easyblocks_root() -> Path | None: + """The importable ``easybuild.easyblocks`` package, if any.""" + try: + import easybuild.easyblocks as easyblocks + except ImportError: + return None + paths = list(getattr(easyblocks, "__path__", [])) + return Path(paths[0]) if paths else None + + +def discover_easyblocks_touching_naming(sources: list[Path]) -> dict[str, set[str]]: + """Hook categories per easyblock name, from directories and files.""" + files: list[Path] = [] + for source in sources: + if source.is_dir(): + files.extend(sorted(source.rglob("*.py"))) + elif source.is_file(): + files.append(source) + matched: dict[str, set[str]] = {} + for path in files: try: text = path.read_text(encoding="utf-8", errors="ignore") except OSError: @@ -206,13 +245,16 @@ def discover_easyblocks_touching_naming(easyblocks_root: Path | None) -> list[st for node in ast.walk(tree): if not isinstance(node, ast.ClassDef): continue - if _class_touches_naming_or_hooks(node): - cls = node.name - matched.add(cls) - if cls.startswith("EB_"): - matched.add(cls[3:]) - matched.add(_decode_eb_class_name(cls)) - return sorted(matched) + categories = _class_hook_categories(node) + if not categories: + continue + cls = node.name + names = {cls} + if cls.startswith("EB_"): + names.update({cls[3:], _decode_eb_class_name(cls)}) + for name in names: + matched.setdefault(name, set()).update(categories) + return matched def collect_easyconfig_files(root: Path) -> list[tuple[str, str]]: @@ -226,7 +268,10 @@ def collect_easyconfig_files(root: Path) -> list[tuple[str, str]]: return files -def classify_recipe(rel: str, text: str, extra_easyblocks: set[str]) -> tuple[str, bool]: +def classify_recipe( + rel: str, text: str, extra_easyblocks: dict[str, set[str]] +) -> tuple[str, set[str]]: + """The sample bucket and the hook categories that target the recipe.""" easyblock_match = re.search( r"^\s*easyblock\s*=\s*['\"]([^'\"]+)['\"]", text, re.MULTILINE ) @@ -238,13 +283,17 @@ def classify_recipe(rel: str, text: str, extra_easyblocks: set[str]) -> tuple[st tc_match = _TOOLCHAIN_RE.search(text) tc_name = tc_match.group(1) if tc_match else "system" - is_targeted = ( - easyblock in TARGETED_EASYBLOCKS - or easyblock in extra_easyblocks - or (not easyblock and software_name in extra_easyblocks) - or bool(re.search(r"^\s*version_?prefix\s*=", text, re.MULTILINE)) - or bool(re.search(r"^\s*(?:modaltsoftname|env_mod_alt_soft_name)\s*=", text, re.MULTILINE)) - ) + categories: set[str] = set() + if easyblock in TARGETED_EASYBLOCKS: + categories.add(f"easyblock:{easyblock}") + if easyblock: + categories.update(extra_easyblocks.get(easyblock, set())) + else: + categories.update(extra_easyblocks.get(software_name, set())) + if re.search(r"^\s*version_?prefix\s*=", text, re.MULTILINE): + categories.add("versionprefix") + if re.search(r"^\s*(?:modaltsoftname|env_mod_alt_soft_name)\s*=", text, re.MULTILINE): + categories.add("modaltsoftname") if easyblock == "Toolchain" or tc_name in ("foss", "intel", "gompi", "gfbf", "NVHPC"): bucket = f"tc:{tc_name}" @@ -258,7 +307,7 @@ def classify_recipe(rel: str, text: str, extra_easyblocks: set[str]) -> tuple[st bucket = "deps" else: bucket = f"tc:{tc_name}" - return bucket, is_targeted + return bucket, categories def select_sample( @@ -266,20 +315,19 @@ def select_sample( seed: int, sample_size: int, include_targeted: bool, - extra_easyblocks: list[str], + extra_easyblocks: dict[str, set[str]], ) -> tuple[list[str], dict[str, str]]: files = collect_easyconfig_files(root) - extra_set = set(extra_easyblocks) buckets: dict[str, list[str]] = {} targeted: list[str] = [] reasons: dict[str, str] = {} for rel, text in files: - bucket, is_targeted = classify_recipe(rel, text, extra_set) + bucket, categories = classify_recipe(rel, text, extra_easyblocks) buckets.setdefault(bucket, []).append(rel) - if include_targeted and is_targeted: + if include_targeted and categories: targeted.append(rel) - reasons[rel] = "targeted" + reasons[rel] = "targeted:" + ",".join(sorted(categories)) rng = random.Random(seed) chosen: list[str] = [] @@ -338,14 +386,11 @@ def format_eb_dep_module(dep: dict) -> str: return f"{name}/{vprefix}{version}{tc_part}{vsuffix}" -def extract_easybuild_truth( - root: Path, - rels: list[str], - reasons: dict[str, str], +def add_easybuild_to_path( framework_dir: Path | None, easyblocks_dir: Path | None, extra_pythonpath: list[str], -) -> dict: +) -> None: for entry in reversed(extra_pythonpath): if entry and entry not in sys.path: sys.path.insert(0, entry) @@ -355,40 +400,131 @@ def extract_easybuild_truth( if resolved not in sys.path: sys.path.insert(0, resolved) + +_MODULE_LOAD_RE = re.compile(r"^\s*module load (\S+)\s*$", re.MULTILINE) +_EBVERSION_RE = re.compile(r'^setenv\s+EBVERSION\S*\s+"([^"]*)"', re.MULTILINE) + + +def easyblock_module_truth(easyconfig_class, get_easyblock_class, path: Path) -> dict: + """What the recipe's easyblock writes into its module file. + + The easyblock gets a fresh easyconfig, since its constructor and hooks + may change it. The toolchain is handed the recipe's dependencies as + ``prepare_step`` would, without loading their modules. + """ + ec = easyconfig_class(str(path), validate=False) + app_class = get_easyblock_class(ec["easyblock"], name=ec["name"]) + app = app_class(ec) + try: + app.gen_installdir() + # make_module_dep recognises the top of the flat module tree by + # comparing existing paths. + os.makedirs(app.installdir_mod, exist_ok=True) + app.toolchain.dependencies = list(app.cfg.dependencies()) + module_dir = Path(app.make_module_step(fake=True)) + module_file = Path(app.module_generator.get_module_filepath(fake=True)) + text = module_file.read_text(encoding="utf-8") + finally: + app.close_log() + versions = _EBVERSION_RE.findall(text) + return { + "easyblock": app_class.__name__, + "generated_module_name": module_file.relative_to(module_dir).as_posix(), + "generated_module_loads": _MODULE_LOAD_RE.findall(text), + "generated_module_version": versions[0] if len(versions) == 1 else None, + } + + +def extract_easybuild_truth( + root: Path, + rels: list[str], + reasons: dict[str, str], + include_easyblocks: list[Path], +) -> dict: try: - from easybuild.framework.easyconfig import easyconfig as eb_easyconfig - from easybuild.framework.easyconfig.easyconfig import EasyConfig - from easybuild.tools import modules as eb_modules + from easybuild.base import fancylogger + from easybuild.framework.easyconfig.easyconfig import EasyConfig, get_easyblock_class + from easybuild.tools.build_log import EasyBuildError from easybuild.tools.module_naming_scheme.easybuild_mns import EasyBuildMNS + from easybuild.tools.modules import NoModulesTool + from easybuild.tools.options import set_up_configuration except ImportError as exc: raise SystemExit( "EasyBuild is not importable; pass --truth-json or --easybuild-framework. " f"Import error: {exc}" ) from exc + # A ModulesTool subclass is a --modules-tool choice. This one never + # loads a module, so the truth does not depend on the host's modules. + class EbStackAuditModulesTool(NoModulesTool): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.log = fancylogger.getLogger(self.__class__.__name__, fname=False) + self.supports_depends_on = False + self.supports_tcl_getenv = False + self.supports_tcl_check_group = False + self.supports_safe_auto_load = False + self.supports_extensions = False + + def load(self, modules, *args, **kwargs): + if modules: + raise EasyBuildError("the parity audit loads no modules: %s", modules) + + workdir = Path(tempfile.mkdtemp(prefix="parity-audit-")) + # EasyBuild helpers such as det_pylibdir run a bare `python`. Only that + # name is bound to this interpreter; its own directory may hold eb. + shim_bin = workdir / "bin" + shim_bin.mkdir() + (shim_bin / "python").symlink_to(sys.executable) + orig_path = os.environ.get("PATH") + # EasyBuild points tempfile at its own tmpdir under workdir. + orig_tempdir = tempfile.tempdir + os.environ["PATH"] = os.pathsep.join(filter(None, [str(shim_bin), orig_path])) + try: + return _easybuild_truth( + root, rels, reasons, include_easyblocks, workdir, EbStackAuditModulesTool + ) + finally: + if orig_path is None: + os.environ.pop("PATH", None) + else: + os.environ["PATH"] = orig_path + tempfile.tempdir = orig_tempdir + shutil.rmtree(workdir, ignore_errors=True) + + +def _easybuild_truth( + root: Path, + rels: list[str], + reasons: dict[str, str], + include_easyblocks: list[Path], + workdir: Path, + modules_tool: type, +) -> dict: + from easybuild.framework.easyconfig.easyconfig import EasyConfig, get_easyblock_class + from easybuild.tools.module_naming_scheme.easybuild_mns import EasyBuildMNS from easybuild.tools.options import set_up_configuration + args = [ + f"--robot={root}", + f"--modules-tool={modules_tool.__name__}", + # EasyBuild requires Lmod for Lua module files. + "--module-syntax=Tcl", + f"--prefix={workdir}", + f"--tmpdir={workdir / 'tmp'}", + "--ignore-osdeps", + ] + if include_easyblocks: + args.append( + "--include-easyblocks=" + ",".join(str(p.resolve()) for p in include_easyblocks) + ) # A partial configuration would leave robot, module and environment # settings at defaults the truth was never meant to use. try: - set_up_configuration( - args=[f"--robot={root}"], - silent=True, - ) + set_up_configuration(args=args, silent=True) except (Exception, SystemExit) as exc: raise SystemExit(f"parity_audit: EasyBuild configuration failed: {exc}") from exc - if hasattr(eb_modules, "NoModulesTool") and hasattr(eb_easyconfig, "modules_tool"): - orig_modules_tool = eb_easyconfig.modules_tool - - def _safe_modules_tool(*args, **kwargs): - try: - return orig_modules_tool(*args, **kwargs) - except Exception: - return eb_modules.NoModulesTool(testing=True) - - eb_easyconfig.modules_tool = _safe_modules_tool - mns = EasyBuildMNS() results = [] for rel in rels: @@ -421,8 +557,15 @@ def _safe_modules_tool(*args, **kwargs): exts = ec.get("exts_list", resolve=False) or [] except TypeError: exts = ec.get("exts_list") or [] + hooks = {} + if reasons.get(rel, "").startswith("targeted"): + try: + hooks = easyblock_module_truth(EasyConfig, get_easyblock_class, path) + except Exception as exc: + raise RuntimeError(f"easyblock hooks: {exc}") from exc results.append( { + **hooks, "rel": rel, "bucket": reasons.get(rel, ""), "ok": True, @@ -598,6 +741,40 @@ def _same_dep(left: dict, right: dict) -> bool: return not (left_tc and right_tc and left_tc != right_tc) +def expected_module_loads(stack: dict) -> list: + """The loads EasyBuild writes for eb-stack's answer: the toolchain + module unless SYSTEM, then each runtime dependency in recipe order.""" + loads: list = [] + toolchain = stack.get("toolchain") or {} + name = str(toolchain.get("name") or "") + if name and name.lower() != "system": + loads.append(f"{name}/{toolchain.get('version') or ''}") + loads.extend( + dep.get("resolved_module") for dep in stack.get("deps", []) if dep.get("kind") == "runtime" + ) + return loads + + +def compare_generated_module(rel: str, truth: dict, stack: dict) -> list[dict]: + """Compare the module file a targeted recipe's easyblock wrote.""" + found = [] + for field, easybuild, eb_stack in ( + ("generated_module_name", truth.get("generated_module_name"), stack.get("module_name")), + ("generated_module_loads", truth.get("generated_module_loads"), expected_module_loads(stack)), + ("generated_module_version", truth.get("generated_module_version"), stack.get("version")), + ): + if easybuild != eb_stack: + found.append( + { + "rel": rel, + "field": field, + "easybuild": easybuild, + "eb_stack": eb_stack, + } + ) + return found + + def compare_parity(truth_rows: list[dict], stack_rows: list[dict]) -> dict: by_rel_stack = {row["rel"]: row for row in stack_rows} mismatches: list[dict] = [] @@ -688,6 +865,9 @@ def compare_parity(truth_rows: list[dict], stack_rows: list[dict]) -> dict: } ) + if "generated_module_name" in truth: + mismatches.extend(compare_generated_module(rel, truth, stack)) + # External modules have no toolchain, so they pair only with a stack # dependency that says it is external. The marker is required: an # identity match alone would hide an external module eb-stack @@ -799,14 +979,18 @@ def main(argv: list[str]) -> int: if not root.is_dir(): raise SystemExit(f"easyconfigs root is not a directory: {root}") - extra_easyblocks = discover_easyblocks_touching_naming(args.easybuild_easyblocks) - if args.truth_json is not None: truth_doc = json.loads(args.truth_json.read_text(encoding="utf-8")) truth_rows = truth_doc["results"] rels = [row["rel"] for row in truth_rows] reasons = {row["rel"]: row.get("bucket", "truth") for row in truth_rows} else: + add_easybuild_to_path(args.easybuild_framework, args.easybuild_easyblocks, args.pythonpath) + easyblock_sources = [args.easybuild_easyblocks or installed_easyblocks_root()] + extra_easyblocks = discover_easyblocks_touching_naming( + [source for source in easyblock_sources if source is not None] + + args.include_easyblocks + ) rels, reasons = select_sample( root=root, seed=args.seed, @@ -818,9 +1002,7 @@ def main(argv: list[str]) -> int: root=root, rels=rels, reasons=reasons, - framework_dir=args.easybuild_framework, - easyblocks_dir=args.easybuild_easyblocks, - extra_pythonpath=args.pythonpath, + include_easyblocks=args.include_easyblocks, ) truth_rows = truth_doc["results"] if args.emit_truth is not None: @@ -836,7 +1018,7 @@ def main(argv: list[str]) -> int: report["seed"] = args.seed report["sample_size"] = args.sample_size report["selected_count"] = len(rels) - report["targeted_count"] = sum(1 for r in reasons.values() if r == "targeted") + report["targeted_count"] = sum(1 for r in reasons.values() if r.startswith("targeted")) if args.out is not None: args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index 234fc0a6..c3b4137c 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -34,6 +34,20 @@ fn locked_requirements(rel: &str) -> Vec { requirements } +/// Create a virtual environment holding the locked EasyBuild. +fn locked_easybuild_venv(dir: &Path) -> PathBuf { + let venv = dir.join("easybuild-venv"); + let status = Command::new("python3") + .args(["-m", "venv"]) + .arg(&venv) + .status() + .expect("create EasyBuild virtual environment"); + assert!(status.success(), "create EasyBuild virtual environment"); + let python = venv.join("bin/python"); + install_locked_easybuild(&python); + python +} + /// Install the locked EasyBuild into `python`'s environment. fn install_locked_easybuild(python: &Path) { for args in [ @@ -202,6 +216,7 @@ fn generate_easyblocks_stub(root: &Path) { fn generate_easybuild_python_stub(root: &Path) { for rel in [ "easybuild/__init__.py", + "easybuild/base/__init__.py", "easybuild/framework/__init__.py", "easybuild/framework/easyconfig/__init__.py", "easybuild/tools/__init__.py", @@ -209,6 +224,18 @@ fn generate_easybuild_python_stub(root: &Path) { ] { write_file(&root.join(rel), ""); } + write_file( + &root.join("easybuild/base/fancylogger.py"), + r#"import logging + +def getLogger(name=None, fname=True): + return logging.getLogger(name) +"#, + ); + write_file( + &root.join("easybuild/tools/build_log.py"), + "class EasyBuildError(Exception):\n pass\n", + ); write_file( &root.join("easybuild/tools/options.py"), r#"ROBOT_ROOT = None @@ -223,8 +250,8 @@ def set_up_configuration(args=None, silent=True): write_file( &root.join("easybuild/tools/modules.py"), r#"class NoModulesTool: - def __init__(self, testing=False): - self.testing = testing + def __init__(self, *args, **kwargs): + self.version = None "#, ); write_file( @@ -240,7 +267,8 @@ def set_up_configuration(args=None, silent=True): ); write_file( &root.join("easybuild/framework/easyconfig/easyconfig.py"), - r#"from pathlib import Path + r#"import tempfile +from pathlib import Path from easybuild.tools import options from easybuild.tools.module_naming_scheme.easybuild_mns import EasyBuildMNS @@ -279,6 +307,7 @@ def _resolve_dep(dep_tuple, robot_root): class EasyConfig(dict): def __init__(self, path, validate=False): super().__init__(_parse_eb(path)) + self.setdefault("easyblock", None) self._robot = options.ROBOT_ROOT or str(Path(path).parents[2]) def dependencies(self): @@ -286,6 +315,46 @@ class EasyConfig(dict): def builddependencies(self): return [_resolve_dep(d, self._robot) for d in self.get("builddependencies", [])] + +class _Toolchain: + dependencies = [] + +class _ModuleGenerator: + def __init__(self, app): + self.app = app + + def get_module_filepath(self, fake=False): + return str(Path(self.app.module_dir) / EasyBuildMNS().det_full_module_name(self.app.cfg)) + +class StubEasyBlock: + """Writes the module file a ConfigureMake easyblock would: a load for + the toolchain unless SYSTEM, then one per runtime dependency.""" + + def __init__(self, ec): + self.cfg = ec + self.toolchain = _Toolchain() + self.module_generator = _ModuleGenerator(self) + + def gen_installdir(self): + self.installdir_mod = tempfile.mkdtemp() + + def make_module_step(self, fake=False): + self.module_dir = tempfile.mkdtemp() + tc = self.cfg.get("toolchain") or {"name": "system", "version": "system"} + loads = [] if tc["name"].lower() == "system" else [f"{tc['name']}/{tc['version']}"] + loads += [dep["full_mod_name"] for dep in self.toolchain.dependencies] + path = Path(self.module_generator.get_module_filepath(fake=True)) + path.parent.mkdir(parents=True, exist_ok=True) + text = '#%Module\n' + "".join(f"module load {mod}\n" for mod in loads) + text += f'setenv\tEBVERSION{self.cfg["name"].upper()}\t\t"{self.cfg["version"]}"\n' + path.write_text(text) + return self.module_dir + + def close_log(self): + pass + +def get_easyblock_class(easyblock, name=None): + return StubEasyBlock "#, ); } @@ -356,19 +425,7 @@ fn parity_audit_resolves_with_easybuild_framework() { let temp = tempfile::tempdir().expect("tempdir"); let ec_root = repo_root().join("fixtures/parity_audit_framework/easyconfigs"); let report = temp.path().join("report.json"); - let venv = temp.path().join("easybuild-venv"); - let python = venv.join("bin/python"); - - let venv_status = Command::new("python3") - .args(["-m", "venv"]) - .arg(&venv) - .status() - .expect("create EasyBuild virtual environment"); - assert!( - venv_status.success(), - "create EasyBuild virtual environment" - ); - install_locked_easybuild(&python); + let python = locked_easybuild_venv(temp.path()); let output = Command::new(&python) .arg(repo_root().join("scripts/parity_audit.py")) @@ -423,6 +480,133 @@ fn parity_audit_resolves_with_easybuild_framework() { ); } +#[test] +fn parity_audit_compares_modules_generated_by_targeted_easyblocks() { + let temp = tempfile::tempdir().expect("tempdir"); + let fixture = repo_root().join("fixtures/parity_audit_hooks"); + let report = temp.path().join("report.json"); + let python = locked_easybuild_venv(temp.path()); + + let output = Command::new(&python) + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(fixture.join("easyconfigs")) + .arg("--sample-size") + .arg("0") + .arg("--include-easyblocks") + .arg(fixture.join("easyblocks/hookload.py")) + .arg("--include-easyblocks") + .arg(fixture.join("easyblocks/hookversion.py")) + .arg("--eb-stack") + .arg(env!("CARGO_BIN_EXE_eb-stack")) + .arg("--out") + .arg(&report) + .output() + .expect("run parity_audit.py with easybuild-framework"); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report).unwrap_or_default()) + .unwrap_or(serde_json::Value::Null); + assert_eq!( + doc["targeted_count"], 2, + "stdout:\n{stdout}\nstderr:\n{stderr}\n{doc}" + ); + let mut found: Vec<(String, String)> = doc["mismatches"] + .as_array() + .map(Vec::as_slice) + .unwrap_or_default() + .iter() + .map(|m| { + ( + m["rel"].as_str().unwrap_or_default().to_string(), + m["field"].as_str().unwrap_or_default().to_string(), + ) + }) + .collect(); + found.sort(); + assert_eq!( + found, + [ + ( + "h/HookLoad/HookLoad-1.0.eb".to_string(), + "generated_module_loads".to_string() + ), + ( + "h/HookVersion/HookVersion-1.0.eb".to_string(), + "generated_module_version".to_string() + ), + ], + "stdout:\n{stdout}\nstderr:\n{stderr}\n{doc}" + ); + assert!( + !output.status.success(), + "stdout:\n{stdout}\nstderr:\n{stderr}" + ); +} + +/// `PythonPackage` asks a bare `python` for its library directory while it +/// writes the module. With a `python` that always fails first on `PATH`, +/// the audit must still run the easyblock with its own interpreter. +#[test] +fn parity_audit_runs_python_easyblocks_with_its_own_interpreter() { + let temp = tempfile::tempdir().expect("tempdir"); + let fixture = repo_root().join("fixtures/parity_audit_python"); + let report = temp.path().join("report.json"); + let truth = temp.path().join("truth.json"); + let python = locked_easybuild_venv(temp.path()); + let broken = temp.path().join("broken-python"); + std::fs::create_dir_all(&broken).expect("create broken python dir"); + std::os::unix::fs::symlink("/bin/false", broken.join("python")).expect("link python"); + let path = std::env::join_paths(std::iter::once(broken).chain(std::env::split_paths( + &std::env::var_os("PATH").unwrap_or_default(), + ))) + .expect("join PATH"); + + let output = Command::new(&python) + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(fixture.join("easyconfigs")) + .arg("--sample-size") + .arg("0") + .arg("--eb-stack") + .arg(env!("CARGO_BIN_EXE_eb-stack")) + .arg("--emit-truth") + .arg(&truth) + .arg("--out") + .arg(&report) + .env("PATH", path) + .output() + .expect("run parity_audit.py with easybuild-framework"); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report).unwrap_or_default()) + .unwrap_or(serde_json::Value::Null); + assert!( + doc["targeted_count"].as_u64().unwrap_or_default() >= 1, + "stdout:\n{stdout}\nstderr:\n{stderr}\n{doc}" + ); + assert_eq!( + doc["mismatches"], + serde_json::json!([]), + "stdout:\n{stdout}\nstderr:\n{stderr}" + ); + let truth: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&truth).unwrap_or_default()) + .unwrap_or(serde_json::Value::Null); + assert_eq!( + truth["results"][0]["generated_module_name"], "PyPkg/1.0", + "the PythonPackage easyblock must write the module: {truth}" + ); + assert!( + output.status.success(), + "stdout:\n{stdout}\nstderr:\n{stderr}" + ); +} + #[test] fn parity_audit_fails_closed_when_easybuild_configuration_fails() { let temp = tempfile::tempdir().expect("tempdir"); From 12c0b3e0905af34593006795092d142a9453099b Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:29 +0000 Subject: [PATCH 12/17] fix(parity): prepare targeted easyblocks as eb does easyblock_module_truth called make_module_step on a bare easyblock. eb runs post_init first, which sets the build parallelism, and refreshes the run-step templates such as %(installdir)s before each step. Without them, recipes whose module names a path through %(installdir)s (Geant4-data, VSCode, HIP, imkl and the Dataset models) failed with unresolved templates. EB_GROMACS also refuses to write a module for a missing installation unless `--module-only` and `--force` are set, which `eb --module-only --force` does. The oracle now calls post_init and update_config_template_run_step before make_module_step and configures EasyBuild with `--module-only` and `--force`. fixtures/parity_audit_prepare/ contains an easyblock for each case, and the audit must evaluate all three without error. --- .../+parity-audit-easyblock-prepare.bugfix.md | 1 + fixtures/parity_audit_prepare/LICENSE | 339 ++++++++++++++++++ fixtures/parity_audit_prepare/README.md | 17 + .../easyblocks/hookinstalled.py | 14 + .../easyblocks/hookparallel.py | 8 + .../easyblocks/hooktemplate.py | 8 + .../h/HookInstalled/HookInstalled-1.0.eb | 6 + .../h/HookParallel/HookParallel-1.0.eb | 6 + .../h/HookTemplate/HookTemplate-1.0.eb | 6 + scripts/parity_audit.py | 12 +- tests/parity_audit_script.rs | 57 +++ 11 files changed, 472 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+parity-audit-easyblock-prepare.bugfix.md create mode 100644 fixtures/parity_audit_prepare/LICENSE create mode 100644 fixtures/parity_audit_prepare/README.md create mode 100644 fixtures/parity_audit_prepare/easyblocks/hookinstalled.py create mode 100644 fixtures/parity_audit_prepare/easyblocks/hookparallel.py create mode 100644 fixtures/parity_audit_prepare/easyblocks/hooktemplate.py create mode 100644 fixtures/parity_audit_prepare/easyconfigs/h/HookInstalled/HookInstalled-1.0.eb create mode 100644 fixtures/parity_audit_prepare/easyconfigs/h/HookParallel/HookParallel-1.0.eb create mode 100644 fixtures/parity_audit_prepare/easyconfigs/h/HookTemplate/HookTemplate-1.0.eb diff --git a/changelog.d/+parity-audit-easyblock-prepare.bugfix.md b/changelog.d/+parity-audit-easyblock-prepare.bugfix.md new file mode 100644 index 00000000..5641d080 --- /dev/null +++ b/changelog.d/+parity-audit-easyblock-prepare.bugfix.md @@ -0,0 +1 @@ +Prepare targeted easyblocks as `eb --module-only --force` does, with `post_init` and the run-step templates, before the parity audit writes their modules. diff --git a/fixtures/parity_audit_prepare/LICENSE b/fixtures/parity_audit_prepare/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/fixtures/parity_audit_prepare/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/fixtures/parity_audit_prepare/README.md b/fixtures/parity_audit_prepare/README.md new file mode 100644 index 00000000..0105437c --- /dev/null +++ b/fixtures/parity_audit_prepare/README.md @@ -0,0 +1,17 @@ +# Parity fixture: easyblock preparation + +Easyconfigs and easyblocks for the real EasyBuild parity audit +(`parity_audit_prepares_targeted_easyblocks_like_easybuild`). Each +easyblock writes its module only after the preparation `eb` does before +`make_module_step`: `HookTemplate` resolves `%(installdir)s`, which +`update_config_template_run_step` defines; `HookParallel` reads the +parallelism `post_init` sets; `HookInstalled` refuses a missing +installation unless `--module-only --force` is set, as `EB_GROMACS` does. +eb-stack agrees with all three modules, so the audit must report no +mismatch. Excluded from the published `eb_stack` crate via `Cargo.toml` +`exclude = ["fixtures/parity_*/"]`. + +`LICENSE` is the GNU General Public License v2.0 text kept with the +other parity fixtures, since the easyblocks subclass EasyBuild's +`ConfigureMake` +(`sha256: 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643`). diff --git a/fixtures/parity_audit_prepare/easyblocks/hookinstalled.py b/fixtures/parity_audit_prepare/easyblocks/hookinstalled.py new file mode 100644 index 00000000..b18cfb91 --- /dev/null +++ b/fixtures/parity_audit_prepare/easyblocks/hookinstalled.py @@ -0,0 +1,14 @@ +"""Easyblock that needs an installation unless forced to write only a module.""" +import os + +from easybuild.easyblocks.generic.configuremake import ConfigureMake +from easybuild.tools.build_log import EasyBuildError +from easybuild.tools.config import build_option + + +class EB_HookInstalled(ConfigureMake): + def make_module_step(self, *args, **kwargs): + if not os.path.isdir(os.path.join(self.installdir, 'lib')): + if not (build_option('force') and build_option('module_only')): + raise EasyBuildError("No lib directory in %s", self.installdir) + return super().make_module_step(*args, **kwargs) diff --git a/fixtures/parity_audit_prepare/easyblocks/hookparallel.py b/fixtures/parity_audit_prepare/easyblocks/hookparallel.py new file mode 100644 index 00000000..8af55128 --- /dev/null +++ b/fixtures/parity_audit_prepare/easyblocks/hookparallel.py @@ -0,0 +1,8 @@ +"""Easyblock whose module records the build parallelism.""" +from easybuild.easyblocks.generic.configuremake import ConfigureMake + + +class EB_HookParallel(ConfigureMake): + def make_module_step(self, *args, **kwargs): + self.cfg['modextravars'] = {'HOOKPARALLEL_JOBS': str(self.cfg.parallel)} + return super().make_module_step(*args, **kwargs) diff --git a/fixtures/parity_audit_prepare/easyblocks/hooktemplate.py b/fixtures/parity_audit_prepare/easyblocks/hooktemplate.py new file mode 100644 index 00000000..4b5b5e86 --- /dev/null +++ b/fixtures/parity_audit_prepare/easyblocks/hooktemplate.py @@ -0,0 +1,8 @@ +"""Easyblock whose module names a path through the %(installdir)s template.""" +from easybuild.easyblocks.generic.configuremake import ConfigureMake + + +class EB_HookTemplate(ConfigureMake): + def make_module_step(self, *args, **kwargs): + self.cfg['modextravars'] = {'HOOKTEMPLATE_DATA': '%(installdir)s/data'} + return super().make_module_step(*args, **kwargs) diff --git a/fixtures/parity_audit_prepare/easyconfigs/h/HookInstalled/HookInstalled-1.0.eb b/fixtures/parity_audit_prepare/easyconfigs/h/HookInstalled/HookInstalled-1.0.eb new file mode 100644 index 00000000..8ffb2d91 --- /dev/null +++ b/fixtures/parity_audit_prepare/easyconfigs/h/HookInstalled/HookInstalled-1.0.eb @@ -0,0 +1,6 @@ +name = 'HookInstalled' +version = '1.0' +homepage = 'https://example.org/' +description = 'Its easyblock needs an installation unless --module-only --force' +toolchain = SYSTEM +moduleclass = 'tools' diff --git a/fixtures/parity_audit_prepare/easyconfigs/h/HookParallel/HookParallel-1.0.eb b/fixtures/parity_audit_prepare/easyconfigs/h/HookParallel/HookParallel-1.0.eb new file mode 100644 index 00000000..5808e873 --- /dev/null +++ b/fixtures/parity_audit_prepare/easyconfigs/h/HookParallel/HookParallel-1.0.eb @@ -0,0 +1,6 @@ +name = 'HookParallel' +version = '1.0' +homepage = 'https://example.org/' +description = 'Its easyblock records the build parallelism in its module' +toolchain = SYSTEM +moduleclass = 'tools' diff --git a/fixtures/parity_audit_prepare/easyconfigs/h/HookTemplate/HookTemplate-1.0.eb b/fixtures/parity_audit_prepare/easyconfigs/h/HookTemplate/HookTemplate-1.0.eb new file mode 100644 index 00000000..50f50fd2 --- /dev/null +++ b/fixtures/parity_audit_prepare/easyconfigs/h/HookTemplate/HookTemplate-1.0.eb @@ -0,0 +1,6 @@ +name = 'HookTemplate' +version = '1.0' +homepage = 'https://example.org/' +description = 'Its easyblock names a module path through the installdir template' +toolchain = SYSTEM +moduleclass = 'tools' diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index 5d4e571e..c455ac72 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -409,17 +409,21 @@ def easyblock_module_truth(easyconfig_class, get_easyblock_class, path: Path) -> """What the recipe's easyblock writes into its module file. The easyblock gets a fresh easyconfig, since its constructor and hooks - may change it. The toolchain is handed the recipe's dependencies as - ``prepare_step`` would, without loading their modules. + may change it, and the preparation ``eb`` gives it before any step: + ``post_init`` and the run-step templates such as ``%(installdir)s``. + The toolchain is handed the recipe's dependencies as ``prepare_step`` + would, without loading their modules. """ ec = easyconfig_class(str(path), validate=False) app_class = get_easyblock_class(ec["easyblock"], name=ec["name"]) app = app_class(ec) try: + app.post_init() app.gen_installdir() # make_module_dep recognises the top of the flat module tree by # comparing existing paths. os.makedirs(app.installdir_mod, exist_ok=True) + app.update_config_template_run_step() app.toolchain.dependencies = list(app.cfg.dependencies()) module_dir = Path(app.make_module_step(fake=True)) module_file = Path(app.module_generator.get_module_filepath(fake=True)) @@ -513,6 +517,10 @@ def _easybuild_truth( f"--prefix={workdir}", f"--tmpdir={workdir / 'tmp'}", "--ignore-osdeps", + # What `eb --module-only --force` sets; easyblocks such as + # EB_GROMACS only write a module for a missing installation then. + "--module-only", + "--force", ] if include_easyblocks: args.append( diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index c3b4137c..6dab9593 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -335,6 +335,12 @@ class StubEasyBlock: self.toolchain = _Toolchain() self.module_generator = _ModuleGenerator(self) + def post_init(self): + pass + + def update_config_template_run_step(self): + pass + def gen_installdir(self): self.installdir_mod = tempfile.mkdtemp() @@ -607,6 +613,57 @@ fn parity_audit_runs_python_easyblocks_with_its_own_interpreter() { ); } +/// Targeted easyblocks get the preparation `eb --module-only --force` gives +/// them before `make_module_step`, so modules that resolve +/// `%(installdir)s`, read the parallelism or expect no installation are +/// audited instead of failing. +#[test] +fn parity_audit_prepares_targeted_easyblocks_like_easybuild() { + let temp = tempfile::tempdir().expect("tempdir"); + let fixture = repo_root().join("fixtures/parity_audit_prepare"); + let report = temp.path().join("report.json"); + let python = locked_easybuild_venv(temp.path()); + + let mut command = Command::new(&python); + command + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(fixture.join("easyconfigs")) + .arg("--sample-size") + .arg("0"); + for easyblock in ["hookinstalled.py", "hookparallel.py", "hooktemplate.py"] { + command + .arg("--include-easyblocks") + .arg(fixture.join("easyblocks").join(easyblock)); + } + let output = command + .arg("--eb-stack") + .arg(env!("CARGO_BIN_EXE_eb-stack")) + .arg("--out") + .arg(&report) + .output() + .expect("run parity_audit.py with easybuild-framework"); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report).unwrap_or_default()) + .unwrap_or(serde_json::Value::Null); + assert_eq!( + doc["targeted_count"], 3, + "stdout:\n{stdout}\nstderr:\n{stderr}\n{doc}" + ); + assert_eq!( + doc["mismatches"], + serde_json::json!([]), + "stdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + output.status.success(), + "stdout:\n{stdout}\nstderr:\n{stderr}" + ); +} + #[test] fn parity_audit_fails_closed_when_easybuild_configuration_fails() { let temp = tempfile::tempdir().expect("tempdir"); From 4147f5cda82dc9413fac12122a6b249502467eee Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:30 +0000 Subject: [PATCH 13/17] fix(parity): decode easyblock class names with EasyBuild _decode_eb_class_name undid only some of EasyBuild's class name encoding, so EB_FFTW_period_MPI and EB_Term_colon__colon_ReadLine_colon__colon_Gnu mapped to names no easyconfig uses and their recipes were never targeted. Discovery now uses easybuild.tools.filetools.decode_class_name, which EasyBuild itself uses to find an easyblock for a software name. fixtures/parity_audit_class_names/ contains a FFTW.MPI recipe with an EB_FFTW_period_MPI easyblock, which the audit must target. --- .../+parity-audit-class-names.bugfix.md | 1 + fixtures/parity_audit_class_names/LICENSE | 339 ++++++++++++++++++ fixtures/parity_audit_class_names/README.md | 14 + .../easyblocks/fftwmpi.py | 8 + .../easyconfigs/f/FFTW.MPI/FFTW.MPI-3.3.10.eb | 6 + scripts/parity_audit.py | 19 +- tests/parity_audit_script.rs | 50 +++ 7 files changed, 426 insertions(+), 11 deletions(-) create mode 100644 changelog.d/+parity-audit-class-names.bugfix.md create mode 100644 fixtures/parity_audit_class_names/LICENSE create mode 100644 fixtures/parity_audit_class_names/README.md create mode 100644 fixtures/parity_audit_class_names/easyblocks/fftwmpi.py create mode 100644 fixtures/parity_audit_class_names/easyconfigs/f/FFTW.MPI/FFTW.MPI-3.3.10.eb diff --git a/changelog.d/+parity-audit-class-names.bugfix.md b/changelog.d/+parity-audit-class-names.bugfix.md new file mode 100644 index 00000000..095a3b4e --- /dev/null +++ b/changelog.d/+parity-audit-class-names.bugfix.md @@ -0,0 +1 @@ +Decode easyblock class names with EasyBuild's own `decode_class_name`, so the parity audit targets recipes such as `FFTW.MPI` whose easyblock class name encodes punctuation. diff --git a/fixtures/parity_audit_class_names/LICENSE b/fixtures/parity_audit_class_names/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/fixtures/parity_audit_class_names/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/fixtures/parity_audit_class_names/README.md b/fixtures/parity_audit_class_names/README.md new file mode 100644 index 00000000..57eee4a5 --- /dev/null +++ b/fixtures/parity_audit_class_names/README.md @@ -0,0 +1,14 @@ +# Parity fixture: encoded easyblock class names + +Easyconfig and easyblock for the real EasyBuild parity audit +(`parity_audit_targets_easyblocks_by_their_decoded_class_names`). +`FFTW.MPI` uses `EB_FFTW_period_MPI`, whose class name EasyBuild encodes +with `encode_class_name`, so the audit has to decode it the same way to +target the recipe. eb-stack agrees with the generated module, so the +audit must report no mismatch. Excluded from the published `eb_stack` +crate via `Cargo.toml` `exclude = ["fixtures/parity_*/"]`. + +`LICENSE` is the GNU General Public License v2.0 text kept with the +other parity fixtures, since the easyblock subclasses EasyBuild's +`ConfigureMake` +(`sha256: 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643`). diff --git a/fixtures/parity_audit_class_names/easyblocks/fftwmpi.py b/fixtures/parity_audit_class_names/easyblocks/fftwmpi.py new file mode 100644 index 00000000..14b13459 --- /dev/null +++ b/fixtures/parity_audit_class_names/easyblocks/fftwmpi.py @@ -0,0 +1,8 @@ +"""Easyblock whose class name EasyBuild encodes, as upstream's FFTW.MPI one.""" +from easybuild.easyblocks.generic.configuremake import ConfigureMake + + +class EB_FFTW_period_MPI(ConfigureMake): + def make_module_step(self, *args, **kwargs): + self.cfg['modextravars'] = {'FFTW_MPI_DECODED': 'yes'} + return super().make_module_step(*args, **kwargs) diff --git a/fixtures/parity_audit_class_names/easyconfigs/f/FFTW.MPI/FFTW.MPI-3.3.10.eb b/fixtures/parity_audit_class_names/easyconfigs/f/FFTW.MPI/FFTW.MPI-3.3.10.eb new file mode 100644 index 00000000..cf9c38b9 --- /dev/null +++ b/fixtures/parity_audit_class_names/easyconfigs/f/FFTW.MPI/FFTW.MPI-3.3.10.eb @@ -0,0 +1,6 @@ +name = 'FFTW.MPI' +version = '3.3.10' +homepage = 'https://example.org/' +description = 'Its easyblock class name encodes the period in its name' +toolchain = SYSTEM +moduleclass = 'numlib' diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index c455ac72..ce54a9ac 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -178,16 +178,6 @@ def parse_args(argv: list[str]) -> argparse.Namespace: ) -def _decode_eb_class_name(cls_name: str) -> str: - raw = cls_name[3:] if cls_name.startswith("EB_") else cls_name - return ( - raw.replace("_minus_", "-") - .replace("_plus_", "+") - .replace("_dot_", ".") - .replace("_underscore_", "_") - ) - - def _class_hook_categories(cls_node: ast.ClassDef) -> set[str]: categories: set[str] = set() for base in cls_node.bases: @@ -226,6 +216,13 @@ def installed_easyblocks_root() -> Path | None: def discover_easyblocks_touching_naming(sources: list[Path]) -> dict[str, set[str]]: """Hook categories per easyblock name, from directories and files.""" + try: + from easybuild.tools.filetools import decode_class_name + except ImportError as exc: + raise SystemExit( + "EasyBuild is not importable; pass --truth-json or --easybuild-framework. " + f"Import error: {exc}" + ) from exc files: list[Path] = [] for source in sources: if source.is_dir(): @@ -251,7 +248,7 @@ def discover_easyblocks_touching_naming(sources: list[Path]) -> dict[str, set[st cls = node.name names = {cls} if cls.startswith("EB_"): - names.update({cls[3:], _decode_eb_class_name(cls)}) + names.update({cls[3:], decode_class_name(cls)}) for name in names: matched.setdefault(name, set()).update(categories) return matched diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index 6dab9593..8c3c01df 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -245,6 +245,14 @@ def set_up_configuration(args=None, silent=True): for arg in args or []: if arg.startswith("--robot="): ROBOT_ROOT = arg.split("=", 1)[1] +"#, + ); + write_file( + &root.join("easybuild/tools/filetools.py"), + r#"def decode_class_name(name): + if not name.startswith("EB_"): + return name + return name[3:].replace("_minus_", "-") "#, ); write_file( @@ -664,6 +672,48 @@ fn parity_audit_prepares_targeted_easyblocks_like_easybuild() { ); } +#[test] +fn parity_audit_targets_easyblocks_by_their_decoded_class_names() { + let temp = tempfile::tempdir().expect("tempdir"); + let fixture = repo_root().join("fixtures/parity_audit_class_names"); + let report = temp.path().join("report.json"); + let python = locked_easybuild_venv(temp.path()); + + let output = Command::new(&python) + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(fixture.join("easyconfigs")) + .arg("--sample-size") + .arg("0") + .arg("--include-easyblocks") + .arg(fixture.join("easyblocks/fftwmpi.py")) + .arg("--eb-stack") + .arg(env!("CARGO_BIN_EXE_eb-stack")) + .arg("--out") + .arg(&report) + .output() + .expect("run parity_audit.py with easybuild-framework"); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report).unwrap_or_default()) + .unwrap_or(serde_json::Value::Null); + assert_eq!( + doc["targeted_count"], 1, + "FFTW.MPI must be targeted through EB_FFTW_period_MPI\nstdout:\n{stdout}\nstderr:\n{stderr}\n{doc}" + ); + assert_eq!( + doc["mismatches"], + serde_json::json!([]), + "stdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + output.status.success(), + "stdout:\n{stdout}\nstderr:\n{stderr}" + ); +} + #[test] fn parity_audit_fails_closed_when_easybuild_configuration_fails() { let temp = tempfile::tempdir().expect("tempdir"); From f08ad20745cef4cdc3bf0dec70f3aa5301ed5a28 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:31 +0000 Subject: [PATCH 14/17] fix(parity): compare generated module loads as a set A recipe that gives its dependencies as a set gets them written to its module in hash order, so comparing loads in recipe order reported mismatches that differ only in order. Both sides are now sorted before the comparison. --- .../+parity-audit-module-load-order.bugfix.md | 1 + scripts/parity_audit.py | 14 +++++++--- tests/parity_audit_script.rs | 27 +++++++++++++++++++ 3 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 changelog.d/+parity-audit-module-load-order.bugfix.md diff --git a/changelog.d/+parity-audit-module-load-order.bugfix.md b/changelog.d/+parity-audit-module-load-order.bugfix.md new file mode 100644 index 00000000..94240548 --- /dev/null +++ b/changelog.d/+parity-audit-module-load-order.bugfix.md @@ -0,0 +1 @@ +`scripts/parity_audit.py` compares generated module loads without regard to order, since a recipe that gives its dependencies as a set gets them written in hash order. diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index ce54a9ac..1f89aacf 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -25,7 +25,7 @@ and has it write its module file (``make_module_step(fake=True)``), so each overridden hook runs. From that file it compares the module name (the file's path), the ``module load`` statements against the toolchain -module and eb-stack's resolved runtime dependencies in order, and the +module and eb-stack's resolved runtime dependencies (in any order), and the ``EBVERSION*`` value against the recipe version. Environment content the hooks write (paths, variables) has no eb-stack counterpart and is not compared. EasyBuild runs with ``EbStackAuditModulesTool``, which loads @@ -748,7 +748,9 @@ def _same_dep(left: dict, right: dict) -> bool: def expected_module_loads(stack: dict) -> list: """The loads EasyBuild writes for eb-stack's answer: the toolchain - module unless SYSTEM, then each runtime dependency in recipe order.""" + module unless SYSTEM, and each runtime dependency. Sorted, since a + recipe may give its dependencies as a set, which EasyBuild writes in + hash order.""" loads: list = [] toolchain = stack.get("toolchain") or {} name = str(toolchain.get("name") or "") @@ -757,7 +759,7 @@ def expected_module_loads(stack: dict) -> list: loads.extend( dep.get("resolved_module") for dep in stack.get("deps", []) if dep.get("kind") == "runtime" ) - return loads + return sorted(loads, key=str) def compare_generated_module(rel: str, truth: dict, stack: dict) -> list[dict]: @@ -765,7 +767,11 @@ def compare_generated_module(rel: str, truth: dict, stack: dict) -> list[dict]: found = [] for field, easybuild, eb_stack in ( ("generated_module_name", truth.get("generated_module_name"), stack.get("module_name")), - ("generated_module_loads", truth.get("generated_module_loads"), expected_module_loads(stack)), + ( + "generated_module_loads", + sorted(truth.get("generated_module_loads") or [], key=str), + expected_module_loads(stack), + ), ("generated_module_version", truth.get("generated_module_version"), stack.get("version")), ): if easybuild != eb_stack: diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index 8c3c01df..7688f4d5 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -1165,6 +1165,33 @@ fn parity_audit_reports_an_external_module_resolved_in_tree() { assert!(!output.status.success()); } +#[test] +fn parity_audit_ignores_the_order_of_generated_module_loads() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + generate_fixture_tree(&ec_root); + let mut truth = tool_a_truth(serde_json::json!([])); + let row = &mut truth["results"][0]; + row["generated_module_name"] = "ToolA/pre-1.0-foss-2024a-extra".into(); + row["generated_module_loads"] = serde_json::json!(["foss/2024a", "zlib/1.3.1", "bzip2/1.0.8"]); + row["generated_module_version"] = "1.0".into(); + let mut stack = tool_a_stack(serde_json::json!([ + {"kind": "runtime", "name": "bzip2", "version_req": "==1.0.8", "resolved_module": "bzip2/1.0.8", "external_module": false}, + {"kind": "runtime", "name": "zlib", "version_req": "==1.3.1", "resolved_module": "zlib/1.3.1", "external_module": false} + ])); + let recipe = &mut stack["recipes"][0]; + recipe["toolchain"] = serde_json::json!({"name": "foss", "version": "2024a"}); + recipe["version"] = "1.0".into(); + truth["results"][0]["dependencies"] = serde_json::json!([ + {"name": "zlib", "version": "1.3.1", "toolchain_name": "SYSTEM", "resolved_module": "zlib/1.3.1"}, + {"name": "bzip2", "version": "1.0.8", "toolchain_name": "SYSTEM", "resolved_module": "bzip2/1.0.8"} + ]); + + let (output, report) = run_comparator(temp.path(), &ec_root, &truth, &stack); + assert_eq!(report["mismatch_count"], 0, "{report}"); + assert!(output.status.success(), "{report}"); +} + #[test] fn parity_audit_requires_the_external_marker_on_every_stack_dep() { let temp = tempfile::tempdir().expect("tempdir"); From 04c78d12530d1d263ca423e7dbe562bf52395ab4 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:32 +0000 Subject: [PATCH 15/17] feat(parity): hold audit mismatches to a baseline A full corpus run has mismatches that are expected, such as recipes EasyBuild cannot evaluate without installed software, so a plain non-zero exit cannot fail CI. `--baseline` compares a run with a recorded set of mismatches, by recipe and field, and fails on a new one, on one that no longer occurs, and on a baseline taken with another seed or sample size. `--write-baseline` records a run, with the easyconfigs commit from `--easyconfigs-commit`. --- changelog.d/+parity-audit-baseline.feature.md | 1 + scripts/parity_audit.py | 84 +++++++++++++++- tests/parity_audit_script.rs | 96 +++++++++++++++++++ 3 files changed, 179 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+parity-audit-baseline.feature.md diff --git a/changelog.d/+parity-audit-baseline.feature.md b/changelog.d/+parity-audit-baseline.feature.md new file mode 100644 index 00000000..3129e214 --- /dev/null +++ b/changelog.d/+parity-audit-baseline.feature.md @@ -0,0 +1 @@ +`scripts/parity_audit.py --baseline` compares a run with a recorded set of expected mismatches, by recipe and field, and fails on any new or no-longer-occurring one; `--write-baseline` records it. diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index 1f89aacf..4f4a0365 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -33,7 +33,11 @@ loaded module to place a module file. Exits 0 on full parity and 1 on any mismatch or error, including an -EasyBuild configuration or easyblock that fails. +EasyBuild configuration or easyblock that fails. With ``--baseline`` it +instead exits 1 only when the mismatches, by recipe and field, differ +from the baseline's in either direction, or when the baseline was taken +with another seed or sample size. ``--write-baseline`` records a run's +mismatches for that. """ from __future__ import annotations @@ -137,6 +141,27 @@ def parse_args(argv: list[str]) -> argparse.Namespace: default=None, help="Optional path to write the full parity report JSON.", ) + parser.add_argument( + "--baseline", + type=Path, + default=None, + help=( + "Expected mismatches for this tree, seed and sample size, as written by " + "--write-baseline. Exits non-zero on a mismatch it does not list, on an " + "entry that no longer occurs, or when its seed or sample size differ." + ), + ) + parser.add_argument( + "--write-baseline", + type=Path, + default=None, + help="Write this run's mismatches as a baseline for --baseline.", + ) + parser.add_argument( + "--easyconfigs-commit", + default=None, + help="easybuild-easyconfigs commit of --easyconfigs, recorded by --write-baseline.", + ) return parser.parse_args(argv) @@ -984,6 +1009,43 @@ def _stack_for(kind: str, dep: dict) -> list[dict]: } +def _mismatch_keys(mismatches: list[dict]) -> list[dict]: + keys = {(m["rel"], m["field"]) for m in mismatches} + return [{"rel": rel, "field": field} for rel, field in sorted(keys)] + + +def write_baseline(path: Path, report: dict, easyconfigs_commit: str | None) -> None: + doc = { + "easyconfigs_commit": easyconfigs_commit, + "seed": report["seed"], + "sample_size": report["sample_size"], + "mismatches": _mismatch_keys(report["mismatches"]), + } + path.write_text(json.dumps(doc, indent=2) + "\n", encoding="utf-8") + + +def check_baseline(path: Path, report: dict) -> dict: + """Diff this run's mismatches, by recipe and field, against a baseline. + + Messages are not compared: EasyBuild errors name temporary paths. + """ + doc = json.loads(path.read_text(encoding="utf-8")) + problems = [ + f"baseline {key} is {doc.get(key)!r}, this run used {report[key]!r}" + for key in ("seed", "sample_size") + if doc.get(key) != report[key] + ] + expected = {(m["rel"], m["field"]) for m in doc.get("mismatches", [])} + found = {(m["rel"], m["field"]) for m in report["mismatches"]} + return { + "path": str(path), + "easyconfigs_commit": doc.get("easyconfigs_commit"), + "problems": problems, + "new": _mismatch_keys([{"rel": r, "field": f} for r, f in found - expected]), + "resolved": _mismatch_keys([{"rel": r, "field": f} for r, f in expected - found]), + } + + def main(argv: list[str]) -> int: args = parse_args(argv) root = args.easyconfigs.resolve() @@ -1031,6 +1093,11 @@ def main(argv: list[str]) -> int: report["selected_count"] = len(rels) report["targeted_count"] = sum(1 for r in reasons.values() if r.startswith("targeted")) + if args.baseline is not None: + report["baseline"] = check_baseline(args.baseline, report) + if args.write_baseline is not None: + write_baseline(args.write_baseline, report, args.easyconfigs_commit) + if args.out is not None: args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") @@ -1045,7 +1112,20 @@ def main(argv: list[str]) -> int: f" MISMATCH {item['rel']} [{item['field']}]: " f"easybuild={item['easybuild']!r} eb-stack={item['eb_stack']!r}" ) - return 1 if report["mismatch_count"] > 0 else 0 + baseline = report.get("baseline") + if baseline is None: + return 1 if report["mismatch_count"] > 0 else 0 + for problem in baseline["problems"]: + print(f" BASELINE {problem}") + for item in baseline["new"]: + print(f" NEW {item['rel']} [{item['field']}]") + for item in baseline["resolved"]: + print(f" RESOLVED {item['rel']} [{item['field']}] (remove it from the baseline)") + print( + f"parity_audit: baseline new={len(baseline['new'])} " + f"resolved={len(baseline['resolved'])}" + ) + return 1 if baseline["problems"] or baseline["new"] or baseline["resolved"] else 0 if __name__ == "__main__": diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index 7688f4d5..58b5654d 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -1192,6 +1192,102 @@ fn parity_audit_ignores_the_order_of_generated_module_loads() { assert!(output.status.success(), "{report}"); } +#[test] +fn parity_audit_holds_mismatches_to_a_baseline() { + let temp = tempfile::tempdir().expect("tempdir"); + let ec_root = temp.path().join("easyconfigs"); + generate_fixture_tree(&ec_root); + let truth_path = temp.path().join("truth.json"); + let stack_path = temp.path().join("stack.json"); + let baseline = temp.path().join("baseline.json"); + let report_path = temp.path().join("report.json"); + let truth = tool_a_truth(serde_json::json!([{ + "name": "zlib", + "version": "1.3.1", + "toolchain_name": "GCCcore", + "toolchain_version": "13.3.0", + "resolved_module": "zlib/1.3.1-GCCcore-13.3.0" + }])); + write_file(&truth_path, &serde_json::to_string_pretty(&truth).unwrap()); + write_file( + &stack_path, + &serde_json::to_string_pretty(&tool_a_stack(serde_json::json!([]))).unwrap(), + ); + let audit = |extra: &[&str]| { + let output = Command::new("python3") + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(&ec_root) + .arg("--truth-json") + .arg(&truth_path) + .arg("--eb-stack-json") + .arg(&stack_path) + .arg("--out") + .arg(&report_path) + .args(extra) + .output() + .expect("run parity_audit.py"); + let report: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report_path).unwrap()).unwrap(); + (output.status.success(), report) + }; + let baseline_arg = baseline.to_str().unwrap(); + + let (ok, _) = audit(&[ + "--write-baseline", + baseline_arg, + "--easyconfigs-commit", + "abc123", + ]); + assert!(!ok, "a mismatch without --baseline still fails"); + let written: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&baseline).unwrap()).unwrap(); + assert_eq!( + written, + serde_json::json!({ + "easyconfigs_commit": "abc123", + "seed": 20261121, + "sample_size": 2000, + "mismatches": [{"rel": "t/ToolA/ToolA-1.0-foss-2024a-extra.eb", "field": "runtime_dep:zlib"}] + }) + ); + + let (ok, report) = audit(&["--baseline", baseline_arg]); + assert!(ok, "{report}"); + assert_eq!(report["baseline"]["new"], serde_json::json!([])); + assert_eq!(report["baseline"]["resolved"], serde_json::json!([])); + + let mut stale = written.clone(); + stale["mismatches"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({"rel": "g/Gone/Gone-1.0.eb", "field": "easybuild_error"})); + write_file(&baseline, &serde_json::to_string_pretty(&stale).unwrap()); + let (ok, report) = audit(&["--baseline", baseline_arg]); + assert!(!ok, "{report}"); + assert_eq!( + report["baseline"]["resolved"], + serde_json::json!([{"rel": "g/Gone/Gone-1.0.eb", "field": "easybuild_error"}]) + ); + + let mut empty = written.clone(); + empty["mismatches"] = serde_json::json!([]); + write_file(&baseline, &serde_json::to_string_pretty(&empty).unwrap()); + let (ok, report) = audit(&["--baseline", baseline_arg]); + assert!(!ok, "{report}"); + assert_eq!(report["baseline"]["new"], written["mismatches"]); + + let mut reseeded = written.clone(); + reseeded["seed"] = 7.into(); + write_file(&baseline, &serde_json::to_string_pretty(&reseeded).unwrap()); + let (ok, report) = audit(&["--baseline", baseline_arg]); + assert!(!ok, "{report}"); + assert_eq!( + report["baseline"]["problems"], + serde_json::json!(["baseline seed is 7, this run used 20261121"]) + ); +} + #[test] fn parity_audit_requires_the_external_marker_on_every_stack_dep() { let temp = tempfile::tempdir().expect("tempdir"); From addf6cfc75465d204f8e6190d351904c682473e3 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:33 +0000 Subject: [PATCH 16/17] ci(parity): audit a pinned easyconfigs corpus scripts/parity-audit-corpus.sh fetches the easybuild-easyconfigs commit a baseline records (the v5.4.2 release) into a cache directory, reusing a clean checkout at that commit, and runs the audit with the baseline's seed and sample size. A new parity-corpus CI job caches the checkout and runs the script against a debug eb-stack build. The job installs the locked EasyBuild into a virtual environment under the runner's temporary directory and passes its interpreter as PYTHON, so eb stays off PATH for the rest of the job. scripts/parity-audit-corpus-baseline.json lists 111 recipes. EasyBuild 5.4.2 cannot write a module for them without installed software, loaded build modules or existing target modules. They are buildenv, the EasyBuild meta recipes, ModuleRC wrappers around CUDAcompat, dotNET-Core, Java and STAR-CCM+, Clang, LLVM, ROCm-LLVM, impi and VEP. --- .github/workflows/ci_test.yml | 43 ++ changelog.d/+parity-audit-corpus-ci.misc.md | 1 + scripts/easybuild-requirements.txt | 5 +- scripts/parity-audit-corpus-baseline.json | 451 ++++++++++++++++++++ scripts/parity-audit-corpus.sh | 51 +++ tests/parity_audit_script.rs | 118 +++++ 6 files changed, 667 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+parity-audit-corpus-ci.misc.md create mode 100644 scripts/parity-audit-corpus-baseline.json create mode 100755 scripts/parity-audit-corpus.sh diff --git a/.github/workflows/ci_test.yml b/.github/workflows/ci_test.yml index 641304f5..d2fd0808 100644 --- a/.github/workflows/ci_test.yml +++ b/.github/workflows/ci_test.yml @@ -256,6 +256,49 @@ jobs: --test source_probe \ -- --nocapture + parity-corpus: + name: parity audit (pinned easyconfigs corpus) + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - uses: actions/setup-python@v6 + with: + python-version: '3.14' + # A virtual environment keeps eb off PATH for the cargo build. + - name: Install locked EasyBuild + run: | + python -m venv "$RUNNER_TEMP/easybuild" + "$RUNNER_TEMP/easybuild/bin/python" -m pip install --require-hashes --only-binary :all: \ + -r scripts/easybuild-build-requirements.txt + "$RUNNER_TEMP/easybuild/bin/python" -m pip install --require-hashes --no-build-isolation \ + -r scripts/easybuild-requirements.txt + - name: Corpus pin + id: pin + run: | + python -c 'import json; print("commit=" + json.load(open("scripts/parity-audit-corpus-baseline.json"))["easyconfigs_commit"])' >> "$GITHUB_OUTPUT" + - uses: actions/cache@v6 + with: + path: ${{ runner.temp }}/parity-corpus + key: parity-corpus-easyconfigs-${{ steps.pin.outputs.commit }} + - name: Build eb-stack + run: cargo build --locked + - name: Audit the pinned corpus against its baseline + env: + PYTHON: ${{ runner.temp }}/easybuild/bin/python + run: | + scripts/parity-audit-corpus.sh "${{ runner.temp }}/parity-corpus" \ + --eb-stack target/debug/eb-stack \ + --out parity-corpus-report.json + - uses: actions/upload-artifact@v7 + if: always() + with: + name: parity-corpus-report + path: parity-corpus-report.json + if-no-files-found: ignore + cli-smoke: name: CLI smoke (package bundle + recipe checks) runs-on: ubuntu-latest diff --git a/changelog.d/+parity-audit-corpus-ci.misc.md b/changelog.d/+parity-audit-corpus-ci.misc.md new file mode 100644 index 00000000..61483e56 --- /dev/null +++ b/changelog.d/+parity-audit-corpus-ci.misc.md @@ -0,0 +1 @@ +CI audits a pinned easybuild-easyconfigs corpus (the v5.4.2 release commit, seed 20261120, 100 sampled recipes plus every targeted one) with `scripts/parity-audit-corpus.sh`, from a cached shallow fetch of that commit, and compares the result with `scripts/parity-audit-corpus-baseline.json`. diff --git a/scripts/easybuild-requirements.txt b/scripts/easybuild-requirements.txt index 9c1331b4..074d2b44 100644 --- a/scripts/easybuild-requirements.txt +++ b/scripts/easybuild-requirements.txt @@ -1,6 +1,7 @@ # Exact EasyBuild pins for the parity audit, with artifact hashes. -# tests/parity_audit_script.rs installs it into a virtual environment of -# its own, after scripts/easybuild-build-requirements.txt: +# tests/parity_audit_script.rs and the parity-corpus CI job install it into +# virtual environments of their own, after +# scripts/easybuild-build-requirements.txt: # # pip install --require-hashes --only-binary :all: -r scripts/easybuild-build-requirements.txt # pip install --require-hashes --no-build-isolation -r scripts/easybuild-requirements.txt diff --git a/scripts/parity-audit-corpus-baseline.json b/scripts/parity-audit-corpus-baseline.json new file mode 100644 index 00000000..b99917b4 --- /dev/null +++ b/scripts/parity-audit-corpus-baseline.json @@ -0,0 +1,451 @@ +{ + "easyconfigs_commit": "c8d938afbabac47cd59bfc5279b107155225ef6e", + "seed": 20261120, + "sample_size": 100, + "mismatches": [ + { + "rel": "b/buildenv/buildenv-default-foss-2022a-CUDA-11.7.0.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2022a.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2022b-CUDA-12.0.0.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2022b.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2023a-CUDA-12.1.1.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2023a.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2023b-CUDA-12.4.0.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2023b.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2024a-CUDA-12.6.0.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2024a.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2025a-CUDA-12.8.0.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2025a.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2025b-CUDA-12.9.1.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2025b.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2026.1-CUDA-13.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-foss-2026.1.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-intel-2022a.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-intel-2022b.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-intel-2023a.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-intel-2023b.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-intel-2024a.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-intel-2025a.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-intel-2025b.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-intel-2026.1.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-lfoss-2025b.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-lfoss-2026.1.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-lmpflf-2026.1.eb", + "field": "easybuild_error" + }, + { + "rel": "b/buildenv/buildenv-default-nvompi-2022.07.eb", + "field": "easybuild_error" + }, + { + "rel": "c/CUDAcompat/CUDAcompat-11.6.eb", + "field": "easybuild_error" + }, + { + "rel": "c/CUDAcompat/CUDAcompat-11.7.eb", + "field": "easybuild_error" + }, + { + "rel": "c/CUDAcompat/CUDAcompat-11.eb", + "field": "easybuild_error" + }, + { + "rel": "c/Clang/Clang-18.1.8-GCCcore-13.3.0-CUDA-12.6.0.eb", + "field": "easybuild_error" + }, + { + "rel": "c/Clang/Clang-18.1.8-GCCcore-13.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "d/dotNET-Core/dotNET-Core-10.0.eb", + "field": "easybuild_error" + }, + { + "rel": "d/dotNET-Core/dotNET-Core-6.0.eb", + "field": "easybuild_error" + }, + { + "rel": "d/dotNET-Core/dotNET-Core-8.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-0.5.0.0beta1.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-0.5.0.0beta2.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.3.4.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.4.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.4.1.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.4.2.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.5.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.5.1.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.5.2.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.5.3.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.5.4.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.5.5.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.6.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.6.1.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.6.2.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.7.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.7.1.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.7.2.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.8.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.8.1.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.8.2.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.9.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.9.1.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.9.2.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.9.3.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-4.9.4.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-5.0.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-5.1.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-5.1.1.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-5.1.2.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-5.2.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-5.2.1.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-5.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-5.3.1.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-5.4.0.eb", + "field": "easybuild_error" + }, + { + "rel": "e/EasyBuild/EasyBuild-5.4.1.eb", + "field": "easybuild_error" + }, + { + "rel": "i/impi/impi-2021.13.0-intel-compilers-2024.2.0.eb", + "field": "easybuild_error" + }, + { + "rel": "i/impi/impi-2021.15.0-intel-compilers-2025.1.1.eb", + "field": "easybuild_error" + }, + { + "rel": "i/impi/impi-2021.16.1-intel-compilers-2025.2.0.eb", + "field": "easybuild_error" + }, + { + "rel": "i/impi/impi-2021.17.2-intel-compilers-2025.3.3.eb", + "field": "easybuild_error" + }, + { + "rel": "j/Java/Java-11.eb", + "field": "easybuild_error" + }, + { + "rel": "j/Java/Java-15.eb", + "field": "easybuild_error" + }, + { + "rel": "j/Java/Java-16.eb", + "field": "easybuild_error" + }, + { + "rel": "j/Java/Java-17.eb", + "field": "easybuild_error" + }, + { + "rel": "j/Java/Java-19.eb", + "field": "easybuild_error" + }, + { + "rel": "j/Java/Java-21.eb", + "field": "easybuild_error" + }, + { + "rel": "j/Java/Java-23.eb", + "field": "easybuild_error" + }, + { + "rel": "j/Java/Java-25.eb", + "field": "easybuild_error" + }, + { + "rel": "j/Java/Java-8.eb", + "field": "easybuild_error" + }, + { + "rel": "l/LLVM/LLVM-18.1.8-GCCcore-13.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "l/LLVM/LLVM-19.1.7-GCCcore-13.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "l/LLVM/LLVM-20.1.4-GCCcore-13.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "l/LLVM/LLVM-20.1.5-GCCcore-13.2.0.eb", + "field": "easybuild_error" + }, + { + "rel": "l/LLVM/LLVM-20.1.5-GCCcore-13.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "l/LLVM/LLVM-20.1.7-GCCcore-14.2.0.eb", + "field": "easybuild_error" + }, + { + "rel": "l/LLVM/LLVM-20.1.8-GCCcore-14.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "l/LLVM/LLVM-21.1.8-GCCcore-15.2.0.eb", + "field": "easybuild_error" + }, + { + "rel": "r/ROCm-LLVM/ROCm-LLVM-19.0.0-GCCcore-14.2.0-ROCm-6.4.1.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-2302-r8.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-2302.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-2310-r8.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-2310.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-2410-r8.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-2410.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-24xx-r8.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-24xx.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-2510-r8.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-2602-r8.eb", + "field": "easybuild_error" + }, + { + "rel": "s/STAR-CCM+/STAR-CCM+-2602.eb", + "field": "easybuild_error" + }, + { + "rel": "v/VEP/VEP-107-GCC-11.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "v/VEP/VEP-111-GCC-12.2.0.eb", + "field": "easybuild_error" + }, + { + "rel": "v/VEP/VEP-113.0-GCC-12.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "v/VEP/VEP-113.3-GCC-13.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "v/VEP/VEP-115.2-GCC-13.3.0.eb", + "field": "easybuild_error" + }, + { + "rel": "v/VEP/VEP-115.2-GCC-14.3.0.eb", + "field": "easybuild_error" + } + ] +} diff --git a/scripts/parity-audit-corpus.sh b/scripts/parity-audit-corpus.sh new file mode 100755 index 00000000..9f199384 --- /dev/null +++ b/scripts/parity-audit-corpus.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Run scripts/parity_audit.py over the easybuild-easyconfigs commit, seed +# and sample size that a baseline records, and hold the run to it. +# +# Usage: scripts/parity-audit-corpus.sh [parity_audit.py args...] +# +# The checkout is a shallow fetch of that one commit into +# /easybuild-easyconfigs. A clean checkout already at the commit +# is reused; anything else there is fetched again. +# +# PARITY_BASELINE baseline (default scripts/parity-audit-corpus-baseline.json) +# EASYCONFIGS_URL remote (default the easybuilders GitHub repository) +# PYTHON interpreter with the locked EasyBuild (default python) + +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cache=${1:?usage: scripts/parity-audit-corpus.sh [parity_audit.py args...]} +shift +baseline=${PARITY_BASELINE:-$root/scripts/parity-audit-corpus-baseline.json} +url=${EASYCONFIGS_URL:-https://github.com/easybuilders/easybuild-easyconfigs.git} +python=${PYTHON:-python} + +read -r commit seed sample_size < <( + "$python" -c 'import json, sys +doc = json.load(open(sys.argv[1], encoding="utf-8")) +print(doc["easyconfigs_commit"], doc["seed"], doc["sample_size"])' "$baseline" +) + +checkout=$cache/easybuild-easyconfigs +if [[ -d $checkout/.git ]]; then + head=$(git -C "$checkout" rev-parse HEAD 2>/dev/null || true) + if [[ $head != "$commit" || -n $(git -C "$checkout" status --porcelain) ]]; then + rm -rf "$checkout" + fi +fi +if [[ ! -d $checkout/.git ]]; then + rm -rf "$checkout" + mkdir -p "$cache" + git init -q "$checkout" + git -C "$checkout" fetch -q --depth 1 --no-tags "$url" "$commit" + git -C "$checkout" -c advice.detachedHead=false checkout -q --detach FETCH_HEAD +fi +test "$(git -C "$checkout" rev-parse HEAD)" = "$commit" + +exec "$python" "$root/scripts/parity_audit.py" \ + --easyconfigs "$checkout/easybuild/easyconfigs" \ + --seed "$seed" \ + --sample-size "$sample_size" \ + --baseline "$baseline" \ + "$@" diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index 58b5654d..33fda9af 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -714,6 +714,124 @@ fn parity_audit_targets_easyblocks_by_their_decoded_class_names() { ); } +fn git(dir: &Path, args: &[&str]) -> String { + let output = Command::new("git") + .current_dir(dir) + .args([ + "-c", + "commit.gpgsign=false", + "-c", + "core.hooksPath=/dev/null", + ]) + .args(args) + .env("GIT_AUTHOR_NAME", "eb-stack test") + .env("GIT_AUTHOR_EMAIL", "test@example.org") + .env("GIT_COMMITTER_NAME", "eb-stack test") + .env("GIT_COMMITTER_EMAIL", "test@example.org") + .output() + .expect("run git"); + assert!( + output.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout).trim().to_string() +} + +#[test] +fn parity_audit_corpus_script_audits_the_pinned_commit_against_its_baseline() { + let temp = tempfile::tempdir().expect("tempdir"); + let upstream = temp.path().join("upstream"); + let py_stub = temp.path().join("py_stub"); + let eblocks = temp.path().join("easyblocks"); + let cache = temp.path().join("cache"); + let baseline = temp.path().join("baseline.json"); + let report = temp.path().join("report.json"); + generate_fixture_tree(&upstream.join("easybuild/easyconfigs")); + generate_easybuild_python_stub(&py_stub); + generate_easyblocks_stub(&eblocks); + git(&upstream, &["init", "-q"]); + git( + &upstream, + &["config", "uploadpack.allowAnySHA1InWant", "true"], + ); + git(&upstream, &["add", "-A"]); + git(&upstream, &["commit", "-q", "-m", "pinned"]); + let pinned = git(&upstream, &["rev-parse", "HEAD"]); + write_file(&upstream.join("NEWS"), "after the pin\n"); + git(&upstream, &["add", "-A"]); + git(&upstream, &["commit", "-q", "-m", "later"]); + write_file( + &baseline, + &serde_json::to_string_pretty(&serde_json::json!({ + "easyconfigs_commit": pinned, + "seed": 42, + "sample_size": 4, + "mismatches": [] + })) + .unwrap(), + ); + let checkout = cache.join("easybuild-easyconfigs"); + let run = || { + let output = Command::new("bash") + .arg(repo_root().join("scripts/parity-audit-corpus.sh")) + .arg(&cache) + .arg("--easybuild-easyblocks") + .arg(&eblocks) + .arg("--pythonpath") + .arg(&py_stub) + .arg("--eb-stack") + .arg(env!("CARGO_BIN_EXE_eb-stack")) + .arg("--out") + .arg(&report) + .env("PARITY_BASELINE", &baseline) + .env("EASYCONFIGS_URL", format!("file://{}", upstream.display())) + .env("PYTHON", "python3") + .output() + .expect("run parity-audit-corpus.sh"); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&report).unwrap_or_default()) + .unwrap_or(serde_json::Value::Null); + assert!( + output.status.success(), + "stdout:\n{}\nstderr:\n{}\n{doc}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + doc + }; + + let doc = run(); + assert_eq!(doc["seed"], 42); + assert_eq!(doc["sample_size"], 4); + assert_eq!(doc["baseline"]["new"], serde_json::json!([])); + assert_eq!(git(&checkout, &["rev-parse", "HEAD"]), pinned); + assert_eq!( + git(&checkout, &["rev-parse", "--is-shallow-repository"]), + "true" + ); + assert!(!checkout.join("NEWS").exists()); + + write_file(&checkout.join("stray.txt"), "not from upstream\n"); + run(); + assert_eq!(git(&checkout, &["rev-parse", "HEAD"]), pinned); + assert!( + !checkout.join("stray.txt").exists(), + "a dirty checkout is fetched again" + ); + + let committed: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(repo_root().join("scripts/parity-audit-corpus-baseline.json")) + .expect("read the corpus baseline"), + ) + .expect("parse the corpus baseline"); + let commit = committed["easyconfigs_commit"].as_str().unwrap_or_default(); + assert!( + commit.len() == 40 && commit.bytes().all(|b| b.is_ascii_hexdigit()), + "the corpus baseline pins a full commit, got {commit:?}" + ); +} + #[test] fn parity_audit_fails_closed_when_easybuild_configuration_fails() { let temp = tempfile::tempdir().expect("tempdir"); From 83d7b2e8a07b2ec1b1dfdf11f112dc9dd7af0d3a Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Sat, 21 Nov 2026 03:50:34 +0000 Subject: [PATCH 17/17] fix(parity): treat SystemExit from easyblocks as a recipe error extract_easybuild_truth caught Exception around each recipe and around its easyblock hooks. SystemExit is not an Exception, so an easyblock that called sys.exit(0) while writing its module ended the whole audit with status 0, before any report was written. Both handlers now catch SystemExit as well and record it as SystemExit(code), so the recipe becomes an easybuild_error mismatch, the report is written and the audit exits non-zero. fixtures/parity_audit_exit/ contains an easyblock whose make_module_step raises SystemExit(0), and the audit must fail on it. --- .../+parity-audit-easyblock-exit.bugfix.md | 1 + fixtures/parity_audit_exit/LICENSE | 339 ++++++++++++++++++ fixtures/parity_audit_exit/README.md | 13 + .../parity_audit_exit/easyblocks/hookexit.py | 7 + .../easyconfigs/h/HookExit/HookExit-1.0.eb | 6 + scripts/parity_audit.py | 16 +- tests/parity_audit_script.rs | 42 +++ 7 files changed, 420 insertions(+), 4 deletions(-) create mode 100644 changelog.d/+parity-audit-easyblock-exit.bugfix.md create mode 100644 fixtures/parity_audit_exit/LICENSE create mode 100644 fixtures/parity_audit_exit/README.md create mode 100644 fixtures/parity_audit_exit/easyblocks/hookexit.py create mode 100644 fixtures/parity_audit_exit/easyconfigs/h/HookExit/HookExit-1.0.eb diff --git a/changelog.d/+parity-audit-easyblock-exit.bugfix.md b/changelog.d/+parity-audit-easyblock-exit.bugfix.md new file mode 100644 index 00000000..aad930f4 --- /dev/null +++ b/changelog.d/+parity-audit-easyblock-exit.bugfix.md @@ -0,0 +1 @@ +When an easyblock or easyconfig raises `SystemExit`, `scripts/parity_audit.py` records an EasyBuild error for that recipe. The audit then writes its report and exits non-zero, instead of stopping early with the easyblock's exit status. diff --git a/fixtures/parity_audit_exit/LICENSE b/fixtures/parity_audit_exit/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/fixtures/parity_audit_exit/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/fixtures/parity_audit_exit/README.md b/fixtures/parity_audit_exit/README.md new file mode 100644 index 00000000..a22928c5 --- /dev/null +++ b/fixtures/parity_audit_exit/README.md @@ -0,0 +1,13 @@ +# Parity fixture: easyblock exit + +An easyconfig and easyblock for the real EasyBuild parity audit +(`parity_audit_fails_when_an_easyblock_exits`). `HookExit` uses an +easyblock whose `make_module_step` raises `SystemExit(0)`. The audit +must record that as an EasyBuild error and exit non-zero, not stop +with status 0 and no report. Excluded from the published `eb_stack` +crate via `Cargo.toml` `exclude = ["fixtures/parity_*/"]`. + +`LICENSE` is the GNU General Public License v2.0 text kept with the +other parity fixtures, since the easyblock subclasses EasyBuild's +`ConfigureMake` +(`sha256: 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643`). diff --git a/fixtures/parity_audit_exit/easyblocks/hookexit.py b/fixtures/parity_audit_exit/easyblocks/hookexit.py new file mode 100644 index 00000000..c6f5d87e --- /dev/null +++ b/fixtures/parity_audit_exit/easyblocks/hookexit.py @@ -0,0 +1,7 @@ +"""Easyblock whose make_module_step exits the interpreter with status 0.""" +from easybuild.easyblocks.generic.configuremake import ConfigureMake + + +class EB_HookExit(ConfigureMake): + def make_module_step(self, *args, **kwargs): + raise SystemExit(0) diff --git a/fixtures/parity_audit_exit/easyconfigs/h/HookExit/HookExit-1.0.eb b/fixtures/parity_audit_exit/easyconfigs/h/HookExit/HookExit-1.0.eb new file mode 100644 index 00000000..7069219f --- /dev/null +++ b/fixtures/parity_audit_exit/easyconfigs/h/HookExit/HookExit-1.0.eb @@ -0,0 +1,6 @@ +name = 'HookExit' +version = '1.0' +homepage = 'https://example.org/' +description = 'Its easyblock exits with status 0 while writing the module' +toolchain = SYSTEM +moduleclass = 'tools' diff --git a/scripts/parity_audit.py b/scripts/parity_audit.py index 4f4a0365..8881dd75 100755 --- a/scripts/parity_audit.py +++ b/scripts/parity_audit.py @@ -591,8 +591,8 @@ def _easybuild_truth( if reasons.get(rel, "").startswith("targeted"): try: hooks = easyblock_module_truth(EasyConfig, get_easyblock_class, path) - except Exception as exc: - raise RuntimeError(f"easyblock hooks: {exc}") from exc + except (Exception, SystemExit) as exc: + raise RuntimeError(f"easyblock hooks: {_error_text(exc)}") from exc results.append( { **hooks, @@ -619,18 +619,26 @@ def _easybuild_truth( ], } ) - except Exception as exc: + # An easyblock may call sys.exit; that is a failed recipe, not an + # empty and successful audit. + except (Exception, SystemExit) as exc: results.append( { "rel": rel, "bucket": reasons.get(rel, ""), "ok": False, - "error": str(exc), + "error": _error_text(exc), } ) return {"results": results} +def _error_text(exc: BaseException) -> str: + if isinstance(exc, SystemExit): + return f"SystemExit({exc.code!r})" + return str(exc) + + def dep_to_dict(dep) -> dict: if isinstance(dep, dict): tc = dep.get("toolchain") or {} diff --git a/tests/parity_audit_script.rs b/tests/parity_audit_script.rs index 33fda9af..fa5384da 100644 --- a/tests/parity_audit_script.rs +++ b/tests/parity_audit_script.rs @@ -672,6 +672,48 @@ fn parity_audit_prepares_targeted_easyblocks_like_easybuild() { ); } +/// An easyblock that calls `sys.exit(0)` while writing its module is a +/// failed recipe: the audit still writes its report and exits non-zero. +#[test] +fn parity_audit_fails_when_an_easyblock_exits() { + let temp = tempfile::tempdir().expect("tempdir"); + let fixture = repo_root().join("fixtures/parity_audit_exit"); + let report = temp.path().join("report.json"); + let python = locked_easybuild_venv(temp.path()); + + let output = Command::new(&python) + .arg(repo_root().join("scripts/parity_audit.py")) + .arg("--easyconfigs") + .arg(fixture.join("easyconfigs")) + .arg("--sample-size") + .arg("0") + .arg("--include-easyblocks") + .arg(fixture.join("easyblocks/hookexit.py")) + .arg("--eb-stack") + .arg(env!("CARGO_BIN_EXE_eb-stack")) + .arg("--out") + .arg(&report) + .output() + .expect("run parity_audit.py with easybuild-framework"); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + !output.status.success(), + "stdout:\n{stdout}\nstderr:\n{stderr}" + ); + let doc: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(&report) + .unwrap_or_else(|err| panic!("report not written ({err}):\n{stdout}\n{stderr}")), + ) + .expect("parse report"); + assert_eq!(mismatch_fields(&doc), vec!["easybuild_error"], "{doc}"); + assert_eq!( + doc["mismatches"][0]["easybuild"], "easyblock hooks: SystemExit(0)", + "{doc}" + ); +} + #[test] fn parity_audit_targets_easyblocks_by_their_decoded_class_names() { let temp = tempfile::tempdir().expect("tempdir");