diff --git a/tests/unit/utils/github/test_variant_bundles.py b/tests/unit/utils/github/test_variant_bundles.py index 70bcd80a1b..3d75dec599 100644 --- a/tests/unit/utils/github/test_variant_bundles.py +++ b/tests/unit/utils/github/test_variant_bundles.py @@ -6,6 +6,8 @@ import json import unittest from unittest.mock import patch +from humanfriendly import parse_size + from utils.github import variant_bundles as vb @@ -40,10 +42,10 @@ class TestExpandApps(unittest.TestCase): "web-app-five": [{}, {}, {}, {}, {}], } - def test_role_within_bundle_size_stays_full_matrix(self) -> None: + def test_role_within_bundle_size_shows_all_variants(self) -> None: self.assertEqual( vb.expand_apps(["web-app-three"], self.VARIANTS, 3), - [{"apps": "web-app-three", "variant": "", "variant_slug": ""}], + [{"apps": "web-app-three", "variant": "0,1,2", "variant_slug": "0-1-2"}], ) def test_missing_variants_treated_as_single(self) -> None: @@ -66,17 +68,79 @@ class TestExpandApps(unittest.TestCase): self.assertEqual( out, [ - {"apps": "web-app-single", "variant": "", "variant_slug": ""}, + {"apps": "web-app-single", "variant": "0", "variant_slug": "0"}, {"apps": "web-app-five", "variant": "0,1,2", "variant_slug": "0-1-2"}, {"apps": "web-app-five", "variant": "3,4", "variant_slug": "3-4"}, ], ) + def test_storage_cap_splits_within_bundle_size(self) -> None: + gb = 1_000_000_000 + out = vb.expand_apps( + ["web-app-three"], + self.VARIANTS, + 3, + storages_per_app={"web-app-three": [300 * gb, 300 * gb, 300 * gb]}, + max_storage_bytes=400 * gb, + ) + self.assertEqual( + out, + [ + {"apps": "web-app-three", "variant": "0", "variant_slug": "0"}, + {"apps": "web-app-three", "variant": "1", "variant_slug": "1"}, + {"apps": "web-app-three", "variant": "2", "variant_slug": "2"}, + ], + ) + + +class TestBundleIndices(unittest.TestCase): + def test_count_only_matches_chunk_indices(self) -> None: + self.assertEqual(vb.bundle_indices(6, 3), [[0, 1, 2], [3, 4, 5]]) + self.assertEqual(vb.bundle_indices(5, 3), [[0, 1, 2], [3, 4]]) + self.assertEqual(vb.bundle_indices(3, 3), [[0, 1, 2]]) + + def test_storage_cap_opens_new_bundle_early(self) -> None: + gb = 1_000_000_000 + storages = [206 * gb, 150 * gb, 159 * gb, 148 * gb, 164 * gb, 143 * gb] + self.assertEqual( + vb.bundle_indices(6, 3, storages, 400 * gb), + [[0, 1], [2, 3], [4, 5]], + ) + + def test_single_variant_over_cap_stands_alone(self) -> None: + gb = 1_000_000_000 + self.assertEqual( + vb.bundle_indices(2, 3, [500 * gb, 100 * gb], 400 * gb), + [[0], [1]], + ) + + def test_none_storage_falls_back_to_count(self) -> None: + self.assertEqual( + vb.bundle_indices(4, 3, [None, None, None, None], 400_000_000_000), + [[0, 1, 2], [3]], + ) + + +class TestResolveMaxStorage(unittest.TestCase): + def test_default_when_unset(self) -> None: + self.assertEqual(vb.resolve_max_storage(""), int(parse_size("400GB"))) + + def test_explicit_value(self) -> None: + self.assertEqual(vb.resolve_max_storage("200GB"), int(parse_size("200GB"))) + + def test_zero_disables_cap(self) -> None: + self.assertIsNone(vb.resolve_max_storage("0")) + + def test_invalid_rejected(self) -> None: + with self.assertRaises(ValueError): + vb.resolve_max_storage("huge") + class TestMain(unittest.TestCase): def test_reads_argv_and_prints_json(self) -> None: with ( patch.object(vb, "get_variants", return_value={"web-app-five": [{}] * 5}), + patch.object(vb, "app_variant_storages", return_value={}), patch.dict("os.environ", {"INFINITO_VARIANT_BUNDLE_SIZE": "3"}), patch("builtins.print") as mock_print, ): @@ -94,6 +158,7 @@ class TestMain(unittest.TestCase): def test_empty_input_yields_empty_list(self) -> None: with ( patch.object(vb, "get_variants", return_value={}), + patch.object(vb, "app_variant_storages", return_value={}), patch("builtins.print") as mock_print, ): rc = vb.main([""]) @@ -103,6 +168,7 @@ class TestMain(unittest.TestCase): def test_non_list_json_rejected(self) -> None: with ( patch.object(vb, "get_variants", return_value={}), + patch.object(vb, "app_variant_storages", return_value={}), self.assertRaises(SystemExit), ): vb.main(['"web-app-five"']) diff --git a/utils/env/handlers/infinito_variant_bundle_max_storage.py b/utils/env/handlers/infinito_variant_bundle_max_storage.py new file mode 100644 index 0000000000..e8eb0fde93 --- /dev/null +++ b/utils/env/handlers/infinito_variant_bundle_max_storage.py @@ -0,0 +1,21 @@ +"""INFINITO_VARIANT_BUNDLE_MAX_STORAGE: cumulative min_storage budget per CI +runner before the discovery (utils.github.variant_bundles) splits a role onto +another runner — so storage-heavy variants are not stacked onto one runner that +then runs too long. Defaults to 400GB everywhere.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from utils.env.builder import BuildContext, EnvBuilder + +KEY = "INFINITO_VARIANT_BUNDLE_MAX_STORAGE" +COMMENT = ( + "Cumulative min_storage per CI runner before the deploy-matrix discovery " + "(utils.github.variant_bundles) splits a role across runners." +) + + +def apply(eb: EnvBuilder, ctx: BuildContext) -> None: + eb.setdefault(KEY, "400GB", comment=COMMENT) diff --git a/utils/github/variant_bundles.py b/utils/github/variant_bundles.py index 8ca812639b..24abaf8287 100644 --- a/utils/github/variant_bundles.py +++ b/utils/github/variant_bundles.py @@ -1,12 +1,18 @@ """Expand a discovered app-id list into CI deploy-matrix entries. A role whose matrix-deploy declares more variants than a single runner should -iterate (``INFINITO_VARIANT_BUNDLE_SIZE``, default 3) is split into bundles of -consecutive variant indices, one runner per bundle — e.g. a 5-variant role -becomes ``0,1,2`` and ``3,4``. Roles that fit one runner stay a single entry. +iterate is split into bundles of consecutive variant indices, one runner per +bundle — e.g. a 5-variant role becomes ``0,1,2`` and ``3,4``. A new bundle opens +as soon as the current one would exceed ``INFINITO_VARIANT_BUNDLE_SIZE`` variants +(default 3) OR ``INFINITO_VARIANT_BUNDLE_MAX_STORAGE`` cumulative ``min_storage`` +(default 400GB), so storage-heavy variants are not stacked onto one runner that +would then run too long. Roles that fit one runner stay a single entry but still +carry their full ``0,…,N-1`` variant CSV, so every job name shows the variants it +covers. Each entry is ``{"apps": , "variant": "", "variant_slug": ""}``; -an empty ``variant`` means full-matrix mode. The ``variant`` slice is threaded +``variant`` is empty only for a role that declares no variants (a plain base +deploy). The ``variant`` slice is threaded through to ``cli.administration.deploy.development`` via the ``variant`` environment variable (consumed by ``--variant``), so a runner only iterates the rounds in its bundle. ``variant_slug`` is a comma-free copy for artifact/job @@ -18,15 +24,28 @@ from __future__ import annotations import json import os import sys +from pathlib import Path from typing import TYPE_CHECKING +from humanfriendly import parse_size + from utils.cache.applications import get_variants +from utils.roles.applications.services.registry import ( + build_service_registry_from_applications, + load_applications_from_roles_dir, +) +from utils.roles.applications.services.resources import ( + aggregate, + collect_role_resources, +) if TYPE_CHECKING: from collections.abc import Iterable, Mapping, Sequence from typing import Any DEFAULT_BUNDLE_SIZE = 3 +DEFAULT_MAX_STORAGE = "400GB" +ROLES_DIR = Path(__file__).resolve().parents[2] / "roles" def resolve_bundle_size(raw: str | None = None) -> int: @@ -46,6 +65,58 @@ def resolve_bundle_size(raw: str | None = None) -> int: return size +def resolve_max_storage(raw: str | None = None) -> int | None: + if raw is None: + raw = os.environ.get("INFINITO_VARIANT_BUNDLE_MAX_STORAGE") + value = (raw or "").strip() + if not value: + value = DEFAULT_MAX_STORAGE + if value.lower() in ("0", "off", "none"): + return None + try: + return int(parse_size(value)) + except Exception: + raise ValueError( + "INFINITO_VARIANT_BUNDLE_MAX_STORAGE must be a size like '400GB', " + f"got {value!r}" + ) from None + + +def bundle_indices( + count: int, + bundle_size: int, + storages: Sequence[int | None] | None = None, + max_storage_bytes: int | None = None, +) -> list[list[int]]: + """Greedily pack variant indices into bundles, opening a new bundle as soon + as the current one would exceed ``bundle_size`` variants OR + ``max_storage_bytes`` cumulative ``min_storage``; both counters reset per + bundle. With no storage cap this matches ``chunk_indices``. A single variant + that alone exceeds the storage cap still forms its own bundle.""" + bundles: list[list[int]] = [] + current: list[int] = [] + current_storage = 0 + for index in range(count): + size = 0 + if storages is not None and index < len(storages): + size = storages[index] or 0 + over_count = len(current) >= bundle_size + over_storage = ( + max_storage_bytes is not None + and bool(current) + and current_storage + size > max_storage_bytes + ) + if current and (over_count or over_storage): + bundles.append(current) + current = [] + current_storage = 0 + current.append(index) + current_storage += size + if current: + bundles.append(current) + return bundles + + def chunk_indices(count: int, bundle_size: int) -> list[list[int]]: return [ list(range(start, min(start + bundle_size, count))) @@ -71,20 +142,55 @@ def expand_apps( apps: Iterable[str], variants_per_app: Mapping[str, Sequence[Any]], bundle_size: int = DEFAULT_BUNDLE_SIZE, + *, + storages_per_app: Mapping[str, Sequence[int | None]] | None = None, + max_storage_bytes: int | None = None, ) -> list[dict[str, str]]: entries: list[dict[str, str]] = [] for app in apps: - count = variant_count(variants_per_app, app) - if count <= bundle_size: + variant_list = variants_per_app.get(app) or [] + if not variant_list: entries.append({"apps": app, "variant": "", "variant_slug": ""}) continue - entries.extend( - _entry(app, ",".join(map(str, chunk))) - for chunk in chunk_indices(count, bundle_size) + storages = (storages_per_app or {}).get(app) + bundles = bundle_indices( + len(variant_list), bundle_size, storages, max_storage_bytes ) + entries.extend(_entry(app, ",".join(map(str, chunk))) for chunk in bundles) return entries +def app_variant_storages( + apps: Iterable[str], + variants_per_app: Mapping[str, Sequence[Any]], + roles_dir: Path = ROLES_DIR, +) -> dict[str, list[int | None]]: + """Per-variant total ``min_storage`` (bytes) for each app, via the shared + resource collection (same machinery as the ``ressources`` CLI / budget + lint). Unknown apps and variants without storage yield ``None`` entries.""" + applications = load_applications_from_roles_dir(roles_dir) + registry = build_service_registry_from_applications(applications) + result: dict[str, list[int | None]] = {} + for app in apps: + sizes: list[int | None] = [] + for variant_config in variants_per_app.get(app) or []: + scoped = dict(applications) + scoped[app] = variant_config or {} + rows: list[dict[str, Any]] = [] + collect_role_resources( + role_name=app, + applications=scoped, + service_registry=registry, + visited=set(), + rows=rows, + warnings=[], + dedup=True, + ) + sizes.append(aggregate(rows).get("min_storage_bytes")) + result[app] = sizes + return result + + def main(argv: Sequence[str] | None = None) -> int: argv = list(sys.argv[1:] if argv is None else argv) raw = argv[0] if argv else sys.stdin.read() @@ -94,7 +200,14 @@ def main(argv: Sequence[str] | None = None) -> int: f"variant_bundles: expected a JSON array of app ids, got " f"{type(apps).__name__}" ) - entries = expand_apps(apps, get_variants(), resolve_bundle_size()) + variants_per_app = get_variants() + entries = expand_apps( + apps, + variants_per_app, + resolve_bundle_size(), + storages_per_app=app_variant_storages(apps, variants_per_app), + max_storage_bytes=resolve_max_storage(), + ) print(json.dumps(entries)) return 0