From 64129089e4a51d440d2ebf5c4610d500bdb78cc9 Mon Sep 17 00:00:00 2001 From: Tobias Fischer Date: Mon, 9 Nov 2026 12:56:22 +1000 Subject: [PATCH] ci_estimate: count one build per variant (Python version) With several Python versions pinned (lyrical, #193), a recipe with Python content makes one build per version, and the estimate counted recipes, not builds: #193's linux-64 run had 3474 builds where the estimate said 2487 packages. build_timings.variant_builds counts each recipe's builds from the multi-valued variant keys its build/host requirements name without a version (zipped keys as one axis, conditions evaluated for a native build), from the work dir's conda_build_config.yaml. ci_estimate counts builds, and a cached build per variant (the cache holds each variant's package). build-ci records a recipe's time per build (each variant's span, averaged), and vinca_timings multiplies it by the recipe's builds for packing the jobs. check_dependency_compat: variant_values and zip_groups; variant_pins now uses variant_values (same output, checked on all distros/platforms). Co-Authored-By: Claude Opus 5.5 --- tools/build_timings.py | 44 +++++++++++- tools/check_dependency_compat.py | 40 +++++++++-- tools/ci_estimate.py | 23 +++--- tools/robostack.py | 24 ++++--- tools/tests/test_build_timings.py | 114 ++++++++++++++++++++++++++++++ 5 files changed, 220 insertions(+), 25 deletions(-) diff --git a/tools/build_timings.py b/tools/build_timings.py index 3018fcacf..bcb97761f 100644 --- a/tools/build_timings.py +++ b/tools/build_timings.py @@ -6,7 +6,9 @@ update-build-timings` merges the last week's into shared/build_timings/.json, {recipe: {distro: seconds}}, one recipe per line, and `rs gha` hands vinca-gha each recipe's average over the distributions: a recipe new to one distribution still has a -time (the names are the same, ros2-). The compatibility recipes +time (the names are the same, ros2-). A time is per build: a recipe built for +several variants (Python versions) records each build's average, and counts once per +variant it builds (variant_builds). The compatibility recipes (ros--) aren't kept: they get ALIAS_SECONDS, and their uploads count for ros2-, which they are built right after. @@ -16,6 +18,7 @@ from __future__ import annotations import json +import math import statistics import subprocess import sys @@ -87,6 +90,37 @@ def dumps(recipes: dict) -> str: return "{\n" + ",\n".join(lines) + "\n}\n" +def variant_builds(recipes: Path, platform: str) -> dict[str, int]: + """How many builds each recipe in the directory makes on the platform: one per + combination of the multi-valued variant keys (conda_build_config.yaml next to the + directory) its build and host requirements name without a version, zipped keys + counting as one; e.g. 3 for a Python package when three Python versions are pinned. + Requirements under a condition count when it holds for a native build.""" + import yaml + + import check_dependency_compat as cdc + + config = recipes.parent / "conda_build_config.yaml" + if not config.is_file(): + return {} + key = lambda name: name.replace("-", "_") # noqa: E731 + values = {key(k): len(v) for k, v in cdc.variant_values(config, platform).items() if len(v) > 1} + axis = {k: frozenset(group) for group in cdc.zip_groups(config) for k in map(key, group)} + flags = {**cdc.platform_flags(platform), "build_platform": platform} + counts = {} + for path in sorted(recipes.glob("*/recipe.yaml")): + recipe = yaml.load(path.read_text(encoding="utf-8"), Loader=yaml.CSafeLoader) or {} + requirements = recipe.get("requirements") or {} + axes: dict[frozenset, int] = {} + for section in ("build", "host"): + for condition, spec in cdc.walk_requirements(requirements.get(section)): + name = key(spec) + if name in values and (condition is None or cdc.eval_selector(condition, flags)): + axes[axis.get(name, frozenset([name]))] = values[name] + counts[path.parent.name] = math.prod(axes.values()) + return counts + + def timings(distro: str, platform: str) -> dict | None: """{"recipes": {recipe: seconds}, "default": seconds} for the platform: each recipe's average over the distributions, and ALIAS_SECONDS for the distribution's compatibility @@ -102,10 +136,14 @@ def timings(distro: str, platform: str) -> dict | None: def vinca_timings(distro: str, platform: str, path: Path) -> bool: - """Write vinca-gha's --timings file for the platform (timings()); False when there are - no times yet.""" + """Write vinca-gha's --timings file for the platform (timings(), each recipe's time + times the builds it makes, variant_builds); False when there are no times yet.""" if (data := timings(distro, platform)) is None: return False + builds = variant_builds(path.parent / "recipes", platform) + data["recipes"] = {r: round(s * builds.get(r, 1), 1) for r, s in data["recipes"].items()} + data["recipes"].update({r: round(data["default"] * n, 1) for r, n in builds.items() + if n > 1 and r not in data["recipes"]}) path.write_text(json.dumps(data) + "\n") return True diff --git a/tools/check_dependency_compat.py b/tools/check_dependency_compat.py index b09c94e49..ff145731f 100644 --- a/tools/check_dependency_compat.py +++ b/tools/check_dependency_compat.py @@ -867,21 +867,21 @@ def constraint_compatible(constraint: str, pin_version: str) -> bool: _CBC_ITEM_RE = re.compile(r"^\s+-\s*(?P.*?)\s*(?:#\s*\[(?P.+?)\])?\s*$") -def variant_pins(variant_config: Path, platform: str) -> dict[str, str]: - """Single-valued pins from conda_build_config.yaml for this platform, keyed by dep name. +def variant_values(variant_config: Path, platform: str) -> dict[str, list[str]]: + """Every variant key of conda_build_config.yaml with its values for this platform. The file is scanned line by line (not YAML-loaded) so that values such as ``2.10`` keep their exact spelling and the ``# [selector]`` comments stay attached. """ flags = platform_flags(platform) - pins: dict[str, str] = {} + values: dict[str, list[str]] = {} key: Optional[str] = None key_active = False chosen: list[str] = [] def flush() -> None: - if key and key_active and len(chosen) == 1: - pins[normalized(key)] = chosen[0].split()[0] + if key and key_active: + values[key] = chosen for raw in variant_config.read_text(encoding="utf-8").splitlines(): line = raw.rstrip() @@ -905,7 +905,35 @@ def flush() -> None: if value and not value.startswith(("-", "[", "{")): chosen.append(value) flush() - return pins + return values + + +def zip_groups(variant_config: Path) -> list[set[str]]: + """The keys of each zip_keys entry: zipped keys vary together, as one variant axis.""" + groups: list[set[str]] = [] + inside = False + for raw in variant_config.read_text(encoding="utf-8").splitlines(): + line = raw.split("#", 1)[0].rstrip() + if not line: + continue + if not line[0].isspace(): + inside = line.startswith("zip_keys:") + continue + item = line.strip() + if not inside or not item.startswith("-"): + continue + if "[" in item: # - [a, b] + groups.append({k.strip() for k in item.strip("- []").split(",") if k.strip()}) + elif match := re.match(r"-\s+-\s*(\S+)$", item): # - - a (a new group) + groups.append({match.group(1)}) + elif groups: # - b (another key of the group) + groups[-1].add(item.lstrip("- ").strip()) + return groups + + +def variant_pins(variant_config: Path, platform: str) -> dict[str, str]: + """Single-valued pins from conda_build_config.yaml for this platform, keyed by dep name.""" + return {normalized(k): v[0].split()[0] for k, v in variant_values(variant_config, platform).items() if len(v) == 1} def load_repodata(source: str, platform: str) -> tuple[dict[str, Any], bool]: diff --git a/tools/ci_estimate.py b/tools/ci_estimate.py index 218280688..60eb5d2a5 100644 --- a/tools/ci_estimate.py +++ b/tools/ci_estimate.py @@ -2,8 +2,10 @@ python tools/ci_estimate.py --recipes distros//work/recipes --cache-dir --platform

-Recipes whose package is in the restored cache are skipped by rattler-build; the rest -are built, each taking its measured time (shared/build_timings, see build_timings.py). +A recipe makes one build per variant: per Python version for the packages with Python +content, when the distribution pins several (build_timings.variant_builds). Builds whose +package is in the restored cache are skipped by rattler-build; the rest are built, each +taking its recipe's measured time per build (shared/build_timings, see build_timings.py). The seconds per package below are rough averages from the jazzy full rebuild in October 2026 (wall clock of the build step, including environment setup): building one package, for platforms without measured times, and skipping one that is already in the cache. @@ -13,6 +15,7 @@ import datetime import os import sys +from collections import Counter from pathlib import Path import build_timings @@ -44,22 +47,26 @@ def main() -> int: args = parser.parse_args() recipes = {p.name for p in args.recipes.iterdir() if (p / "recipe.yaml").is_file()} if args.recipes.is_dir() else set() - cached = {f.name.rsplit("-", 2)[0] for f in args.cache_dir.glob("*.conda")} if args.cache_dir.is_dir() else set() - to_build = sorted(recipes - cached) - skipped = len(recipes & cached) + variants = build_timings.variant_builds(args.recipes, args.platform) if recipes else {} + builds = {r: variants.get(r, 1) for r in recipes} + cached = Counter(f.name.rsplit("-", 2)[0] for f in args.cache_dir.glob("*.conda")) if args.cache_dir.is_dir() else Counter() + to_build = {r: n - min(n, cached[r]) for r, n in builds.items() if n > cached[r]} + skipped = sum(min(n, cached[r]) for r, n in builds.items()) build, skip = SECONDS.get(args.platform, max(SECONDS.values())) distro = args.recipes.resolve().parent.parent.name # distros//work/recipes measured = build_timings.timings(distro, args.platform) if measured: - seconds = sum(measured["recipes"].get(r, measured["default"]) for r in to_build) + skipped * skip + seconds = sum(measured["recipes"].get(r, measured["default"]) * n for r, n in to_build.items()) + skipped * skip else: - seconds = len(to_build) * build + skipped * skip + seconds = sum(to_build.values()) * build + skipped * skip hours = seconds / 3600 rounds = int(hours // JOB_LIMIT_HOURS) + 1 done = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=seconds) + several = sum(1 for n in to_build.values() if n > 1) + packages = f" ({len(to_build)} recipes, {several} of them in several variants, e.g. one per Python version)" if several else "" text = ( - f"{len(to_build)} packages to build, {skipped} restored from the cache: " + f"{sum(to_build.values())} packages to build{packages}, {skipped} restored from the cache: " f"roughly {duration(seconds)} (done around {done:%H:%M} UTC)" ) if hours > JOB_LIMIT_HOURS: diff --git a/tools/robostack.py b/tools/robostack.py index 8b723dfa9..05dac44d0 100644 --- a/tools/robostack.py +++ b/tools/robostack.py @@ -123,12 +123,14 @@ def run_tee(cmd: list[str], cwd: Path) -> tuple[int, bytes]: def build_ci_parallel(distro: str, recipes: list[str], args: list[str], cwd: Path) -> int: """build-ci for all of a build job's recipes in one rattler-build run, building independent ones in parallel. Its JSON log tells which recipe each line belongs to: - printed as "HH:MM:SS [recipe] message", and each recipe's time (first to last line of - its build) is recorded for packing the build jobs, scaled so that the times add up to - the builds' wall time: overlapping builds share it. The compatibility recipes + printed as "HH:MM:SS [recipe] message", and each recipe's time per build (first to last + line of each of its builds, one per variant, averaged) is recorded for packing the build + jobs, scaled so that the times add up to the builds' wall time: overlapping builds share + it. The compatibility recipes (ros--) only repackage, but wait for others while building alongside: they are left out (build_timings gives them ALIAS_SECONDS).""" span: dict[str, list[str]] = {} # recipe -> [first, last] timestamp + builds: dict[str, list[str]] = {} # each build (name-version-build) -> [first, last] finished: set[str] = set() def show(line: bytes) -> None: @@ -140,6 +142,7 @@ def show(line: bytes) -> None: # the build itself: rattler-build renders every recipe up front if name and any(s.get("name") == "Running build for" for s in spans): span.setdefault(name, [entry["timestamp"]] * 2)[1] = entry["timestamp"] + builds.setdefault(recipe, [entry["timestamp"]] * 2)[1] = entry["timestamp"] if str(entry["fields"].get("message", "")).startswith("Archive written to"): finished.add(name) text = f"{entry['timestamp'][11:19]} [{name or '-'}] {entry['fields'].get('message', '')}\n" @@ -157,13 +160,18 @@ def show(line: bytes) -> None: import build_timings # for packing the build jobs by time from datetime import datetime - times = {r: [datetime.fromisoformat(t.replace("Z", "+00:00")) for t in span[r]] - for r in recipes if r in span and not r.startswith(f"ros-{distro}-")} - measured = {r: (last - first).total_seconds() for r, (first, last) in times.items()} + keep = set(recipes) + times = {b: [datetime.fromisoformat(t.replace("Z", "+00:00")) for t in builds[b]] + for b in builds if b.rsplit("-", 2)[0] in keep and not b.startswith(f"ros-{distro}-")} + measured = {b: (last - first).total_seconds() for b, (first, last) in times.items()} if times and sum(measured.values()): wall = (max(last for _, last in times.values()) - min(first for first, _ in times.values())).total_seconds() - for recipe, seconds in measured.items(): - build_timings.note(distro, recipe, seconds * wall / sum(measured.values())) + per_recipe: dict[str, list[float]] = {} + for build, seconds in measured.items(): + per_recipe.setdefault(build.rsplit("-", 2)[0], []).append(seconds * wall / sum(measured.values())) + for recipe in recipes: # in the job's order + if recipe in per_recipe: + build_timings.note(distro, recipe, sum(per_recipe[recipe]) / len(per_recipe[recipe])) return rc diff --git a/tools/tests/test_build_timings.py b/tools/tests/test_build_timings.py index 3ace74f16..3050df157 100644 --- a/tools/tests/test_build_timings.py +++ b/tools/tests/test_build_timings.py @@ -176,3 +176,117 @@ def run_build(cmd, cwd, show=None): monkeypatch.setattr(robostack, "rattler_build", lambda distro, args, skip_existing=True: ["rattler-build", *args]) assert robostack.build_ci_parallel("rolling", ["ros2-a", "ros2-b"], ["--recipe", "a", "--recipe", "b"], tmp_path) == 1 assert "Started but not finished: ros2-b" in capsys.readouterr().err + + +VARIANT_CONFIG = """\ +python: + - 3.12.* *_cpython # [not riscv64] + - 3.13.* *_cp313 # [not riscv64] + - 3.14.* *_cp314 +is_python_min: + - true # [not riscv64] + - false # [not riscv64] + - false # [not riscv64] + - true # [riscv64] +hdf5: + - '2' + - 1.14.6 +zip_keys: + - - python + - is_python_min +""" + + +def variant_recipes(tmp_path, distro="lyrical"): + work = tmp_path / "distros" / distro / "work" + (work / "recipes").mkdir(parents=True) + (work / "conda_build_config.yaml").write_text(VARIANT_CONFIG) + recipes = { + # C++ only: Python pinned to python_min in build, Python only for cross-compiling + "ros2-cpp": "requirements:\n build:\n - python ${{ python_min }}.*\n" + " - if: build_platform != target_platform\n then:\n - python\n" + " host:\n - eigen\n", + "ros2-py": "requirements:\n host:\n - python\n - numpy\n run:\n - python\n", + "ros2-py-hdf5": "requirements:\n host:\n - python\n - hdf5\n", + "ros2-win-py": "requirements:\n host:\n - if: win\n then:\n - python\n", + } + for name, text in recipes.items(): + (work / "recipes" / name).mkdir() + (work / "recipes" / name / "recipe.yaml").write_text(text) + return work / "recipes" + + +def test_variant_builds_counts_the_python_versions(tmp_path): + recipes = variant_recipes(tmp_path) + assert build_timings.variant_builds(recipes, "linux-64") == { + "ros2-cpp": 1, "ros2-py": 3, "ros2-py-hdf5": 6, "ros2-win-py": 1} + assert build_timings.variant_builds(recipes, "win-64")["ros2-win-py"] == 3 + # conda-forge has only 3.14 for riscv64: python and is_python_min are zipped, one variant + assert build_timings.variant_builds(recipes, "linux-riscv64")["ros2-py"] == 1 + + +def test_ci_estimate_counts_each_variant(tmp_path, monkeypatch, capsys): + import ci_estimate + + recipes = variant_recipes(tmp_path) + timings = tmp_path / "timings" + timings.mkdir() + (timings / "linux-64.json").write_text(build_timings.dumps( + {"ros2-cpp": {"lyrical": 60.0}, "ros2-py": {"lyrical": 100.0}, "ros2-py-hdf5": {"lyrical": 10.0}, + "ros2-win-py": {"lyrical": 30.0}})) + monkeypatch.setattr(build_timings, "TIMINGS", timings) + cache = tmp_path / "cache" + cache.mkdir() + for f in ("ros2-py-1.0-py312h0_1.conda", "ros2-cpp-1.0-h0_1.conda"): + (cache / f).write_text("") + monkeypatch.setenv("GITHUB_STEP_SUMMARY", "") + monkeypatch.setattr("sys.argv", ["ci_estimate.py", "--recipes", str(recipes), "--cache-dir", str(cache), + "--platform", "linux-64"]) + assert ci_estimate.main() == 0 + # ros2-py: 2 of 3 builds left, 200 s; ros2-py-hdf5 6 x 10 s; ros2-win-py 30 s; 2 cached x 2 s + out = capsys.readouterr().out + assert out.startswith("9 packages to build (3 recipes, 2 of them in several variants, e.g. one per " + "Python version), 2 restored from the cache: roughly 5 min") + + +def test_vinca_timings_count_each_variant(tmp_path, monkeypatch): + recipes = variant_recipes(tmp_path) + timings = tmp_path / "timings" + timings.mkdir() + (timings / "linux-64.json").write_text(build_timings.dumps( + {"ros2-cpp": {"lyrical": 60.0}, "ros2-py": {"lyrical": 100.0}})) + monkeypatch.setattr(build_timings, "TIMINGS", timings) + out = recipes.parent / "build_timings.json" + assert build_timings.vinca_timings("lyrical", "linux-64", out) + data = json.loads(out.read_text()) + # measured: per build times the builds; unmeasured with several builds: the default times them + assert data["recipes"]["ros2-cpp"] == 60.0 and data["recipes"]["ros2-py"] == 300.0 + assert data["recipes"]["ros2-py-hdf5"] == 6 * data["default"] + assert "ros2-win-py" not in data["recipes"] + + +def test_build_ci_parallel_times_each_variant(tmp_path, monkeypatch): + import robostack + + def line(t, build, message): + return (json.dumps({"timestamp": f"2026-10-24T07:00:{t:02d}.0Z", "fields": {"message": message}, + "spans": [{"recipe": build, "name": "Running build for"}]}) + "\n").encode() + + # ros2-a's two Python variants side by side (10 s each), then ros2-b alone (10 s) + log = [line(0, "ros2-a-1.0-py312h0_1", "Fetching source"), line(0, "ros2-a-1.0-py313h1_1", "Fetching source"), + line(10, "ros2-a-1.0-py312h0_1", "Artifact"), line(10, "ros2-a-1.0-py313h1_1", "Artifact"), + line(10, "ros2-b-1.0-h0_1", "Fetching source"), line(20, "ros2-b-1.0-h0_1", "Artifact")] + + def run_build(cmd, cwd, show=None): + for entry in log: + show(entry) + return 0 + + noted = [] + monkeypatch.setattr(robostack, "run_build", run_build) + monkeypatch.setattr(robostack, "rattler_build", lambda distro, args, skip_existing=True: ["rattler-build", *args]) + monkeypatch.setattr(build_timings, "note", lambda distro, recipe, seconds: noted.append((recipe, seconds))) + monkeypatch.setenv("GITHUB_ACTIONS", "true") + assert robostack.build_ci_parallel("lyrical", ["ros2-a", "ros2-b"], [], tmp_path) == 0 + # 30 s of builds in 20 s: each build's share, ros2-a's the average of its two builds + assert [(r, round(s, 2)) for r, s in noted] == [("ros2-a", 6.67), ("ros2-b", 6.67)]