diff --git a/.github/workflows/test-deploy-local.yml b/.github/workflows/test-deploy-local.yml index 4029fe5bb2..3940775869 100644 --- a/.github/workflows/test-deploy-local.yml +++ b/.github/workflows/test-deploy-local.yml @@ -82,7 +82,7 @@ jobs: run: ./scripts/github/resolve/output_apps.sh deploy: - name: 🚀 Deploy ${{ needs.discover.outputs.test_deploy_type }} app (${{ matrix.apps }}) + name: 🚀 Deploy ${{ needs.discover.outputs.test_deploy_type }} app (${{ matrix.apps }}${{ matrix.variant && format(' [{0}]', matrix.variant) || '' }}) if: needs.discover.outputs.apps != '' && needs.discover.outputs.apps != '[]' runs-on: ubuntu-latest timeout-minutes: 360 @@ -92,7 +92,7 @@ jobs: fail-fast: false max-parallel: 1 # immer linear matrix: - apps: ${{ fromJson(needs.discover.outputs.apps) }} + include: ${{ fromJson(needs.discover.outputs.apps) }} steps: # Reclaim runner space before Docker pulls start. Deploy jobs otherwise @@ -128,6 +128,7 @@ jobs: INFINITO_DEPLOY_TYPE: ${{ needs.discover.outputs.test_deploy_type }} INFINITO_DISTROS: ${{ needs.discover.outputs.distros }} apps: ${{ matrix.apps }} + variant: ${{ matrix.variant }} ANSIBLE_LOG_PATH: /tmp/ansible-${{ matrix.apps }}.log run: ./scripts/tests/deploy/ci/all.sh diff --git a/.github/workflows/test-deploy-server.yml b/.github/workflows/test-deploy-server.yml index f05b855c21..8d5cf7eafe 100644 --- a/.github/workflows/test-deploy-server.yml +++ b/.github/workflows/test-deploy-server.yml @@ -79,7 +79,7 @@ jobs: run: ./scripts/github/resolve/output_apps.sh server: - name: 🌐 Deploy ${{ matrix.apps }} + name: 🌐 Deploy ${{ matrix.apps }}${{ matrix.variant && format(' [{0}]', matrix.variant) || '' }} if: needs.discover.outputs.apps != '' && needs.discover.outputs.apps != '[]' runs-on: ubuntu-latest timeout-minutes: 360 @@ -88,7 +88,7 @@ jobs: strategy: fail-fast: false matrix: - apps: ${{ fromJson(needs.discover.outputs.apps) }} + include: ${{ fromJson(needs.discover.outputs.apps) }} steps: # Reclaim runner space before Docker pulls start. Server deploy tests pull @@ -129,6 +129,7 @@ jobs: shell: bash env: apps: ${{ matrix.apps }} + variant: ${{ matrix.variant }} ANSIBLE_LOG_PATH: /tmp/ansible-${{ matrix.apps }}.log run: ./scripts/tests/deploy/ci/all.sh @@ -156,6 +157,6 @@ jobs: if: always() uses: actions/upload-artifact@v7 with: - name: playwright-server-${{ matrix.apps }} + name: playwright-server-${{ matrix.apps }}${{ matrix.variant_slug && format('-{0}', matrix.variant_slug) || '' }} path: /tmp/playwright-artifacts/ if-no-files-found: ignore diff --git a/.github/workflows/test-deploy-universal.yml b/.github/workflows/test-deploy-universal.yml index fb1082409f..58c65234a5 100644 --- a/.github/workflows/test-deploy-universal.yml +++ b/.github/workflows/test-deploy-universal.yml @@ -75,7 +75,7 @@ jobs: run: ./scripts/github/resolve/output_apps.sh universal: - name: ✨ Deploy ${{ matrix.apps }} + name: ✨ Deploy ${{ matrix.apps }}${{ matrix.variant && format(' [{0}]', matrix.variant) || '' }} if: needs.discover.outputs.apps != '' && needs.discover.outputs.apps != '[]' runs-on: ubuntu-latest timeout-minutes: 360 @@ -84,7 +84,7 @@ jobs: strategy: fail-fast: false matrix: - apps: ${{ fromJson(needs.discover.outputs.apps) }} + include: ${{ fromJson(needs.discover.outputs.apps) }} steps: # Reclaim runner space before Docker pulls start. Deploy jobs otherwise @@ -124,6 +124,7 @@ jobs: shell: bash env: apps: ${{ matrix.apps }} + variant: ${{ matrix.variant }} ANSIBLE_LOG_PATH: /tmp/ansible-${{ matrix.apps }}.log run: ./scripts/tests/deploy/ci/all.sh diff --git a/.github/workflows/test-deploy-workstation.yml b/.github/workflows/test-deploy-workstation.yml index df77a00579..174cce5bb4 100644 --- a/.github/workflows/test-deploy-workstation.yml +++ b/.github/workflows/test-deploy-workstation.yml @@ -75,7 +75,7 @@ jobs: run: ./scripts/github/resolve/output_apps.sh workstation: - name: 🖥️ Deploy ${{ matrix.apps }} + name: 🖥️ Deploy ${{ matrix.apps }}${{ matrix.variant && format(' [{0}]', matrix.variant) || '' }} if: needs.discover.outputs.apps != '' && needs.discover.outputs.apps != '[]' runs-on: ubuntu-latest timeout-minutes: 360 @@ -84,7 +84,7 @@ jobs: strategy: fail-fast: false matrix: - apps: ${{ fromJson(needs.discover.outputs.apps) }} + include: ${{ fromJson(needs.discover.outputs.apps) }} steps: # Reclaim runner space before Docker pulls start. Deploy jobs otherwise @@ -124,6 +124,7 @@ jobs: shell: bash env: apps: ${{ matrix.apps }} + variant: ${{ matrix.variant }} ANSIBLE_LOG_PATH: /tmp/ansible-${{ matrix.apps }}.log run: ./scripts/tests/deploy/ci/all.sh diff --git a/cli/administration/deploy/development/deploy.py b/cli/administration/deploy/development/deploy.py index 82284bdb27..df14957075 100644 --- a/cli/administration/deploy/development/deploy.py +++ b/cli/administration/deploy/development/deploy.py @@ -16,25 +16,14 @@ from .common import ( make_compose, resolve_container, ) -from .inventory import filter_plan_to_variant, plan_dev_inventory_matrix +from .inventory import plan_dev_inventory_matrix from .runtime_budget import RuntimeBudget +from .variant_select import add_variant_args, apply_variant_filter if TYPE_CHECKING: from collections.abc import Mapping -def _env_variant() -> int | None: - raw = os.environ.get("variant", "").strip() - if not raw: - return None - try: - return int(raw) - except ValueError: - raise SystemExit( - f"variant environment variable must be an integer, got {raw!r}" - ) from None - - def _env_full_cycle() -> bool: return os.environ.get("full_cycle", "").strip().lower() == "true" @@ -177,18 +166,7 @@ def add_parser(sub: argparse._SubParsersAction) -> None: default=False, help="Enable/disable Ansible debug mode (default: disabled).", ) - p.add_argument( - "--variant", - type=int, - default=_env_variant(), - help=( - "Pin the matrix deploy to a single round (zero-based index), " - "skipping inter-round cleanup. Useful for redeploying one " - "specific variant without iterating the whole matrix. Defaults " - "to the variant environment variable when set, otherwise " - "full-matrix mode." - ), - ) + add_variant_args(p, action="deploy") p.add_argument( "--full-cycle", action=argparse.BooleanOptionalAction, @@ -262,7 +240,7 @@ def handler(args: argparse.Namespace) -> int: base_inventory_dir=str(args.inventory_dir), ) try: - plan = filter_plan_to_variant(plan, args.variant) + plan = apply_variant_filter(plan, args) except ValueError as exc: raise SystemExit(f"--variant: {exc}") from exc diff --git a/cli/administration/deploy/development/init.py b/cli/administration/deploy/development/init.py index 5f4df3f6da..516ae2d0f7 100644 --- a/cli/administration/deploy/development/init.py +++ b/cli/administration/deploy/development/init.py @@ -14,10 +14,10 @@ from .common import make_compose from .inventory import ( DevInventorySpec, build_dev_inventory, - filter_plan_to_variant, plan_dev_inventory_matrix, ) from .storage import detect_storage_constrained +from .variant_select import add_variant_args, apply_variant_filter if TYPE_CHECKING: import argparse @@ -67,32 +67,10 @@ def add_parser(sub: argparse._SubParsersAction) -> None: default=None, help="JSON object merged into inventory variables (overrides win).", ) - p.add_argument( - "--variant", - type=int, - default=_env_variant(), - help=( - "Pin the matrix init to a single round (zero-based index). " - "Useful when only one variant of a multi-variant app needs to " - "be (re-)materialised. Defaults to the variant " - "environment variable when set, otherwise full-matrix mode." - ), - ) + add_variant_args(p, action="init") p.set_defaults(_handler=handler) -def _env_variant() -> int | None: - raw = os.environ.get("variant", "").strip() - if not raw: - return None - try: - return int(raw) - except ValueError: - raise SystemExit( - f"variant environment variable must be an integer, got {raw!r}" - ) from None - - def handler(args: argparse.Namespace) -> int: compose = make_compose() @@ -154,7 +132,7 @@ def handler(args: argparse.Namespace) -> int: base_inventory_dir=str(args.inventory_dir), ) try: - plan = filter_plan_to_variant(plan, args.variant) + plan = apply_variant_filter(plan, args) except ValueError as exc: raise SystemExit(f"--variant: {exc}") from exc diff --git a/cli/administration/deploy/development/inventory/__init__.py b/cli/administration/deploy/development/inventory/__init__.py index 2b7c900de6..2e0181fd10 100644 --- a/cli/administration/deploy/development/inventory/__init__.py +++ b/cli/administration/deploy/development/inventory/__init__.py @@ -35,7 +35,7 @@ from __future__ import annotations from .builder import build_dev_inventory, build_dev_inventory_matrix from .legacy_resolver import _build_services_overrides_for_round, _resolve_round_include from .payload import _bake_overrides, _resolve_variant_payloads -from .planner import filter_plan_to_variant, plan_dev_inventory_matrix +from .planner import filter_plan_to_variants, plan_dev_inventory_matrix from .spec import DevInventorySpec, PlanEntry # Private helper names appear in `__all__` to silence ruff's F401 @@ -51,6 +51,6 @@ __all__ = [ "_resolve_variant_payloads", "build_dev_inventory", "build_dev_inventory_matrix", - "filter_plan_to_variant", + "filter_plan_to_variants", "plan_dev_inventory_matrix", ] diff --git a/cli/administration/deploy/development/inventory/planner.py b/cli/administration/deploy/development/inventory/planner.py index 2031e59b7b..a6e78a87d4 100644 --- a/cli/administration/deploy/development/inventory/planner.py +++ b/cli/administration/deploy/development/inventory/planner.py @@ -25,24 +25,28 @@ if TYPE_CHECKING: from .spec import PlanEntry -def filter_plan_to_variant( +def filter_plan_to_variants( plan: list[PlanEntry], - variant: int | None, + variants: list[int] | None, ) -> list[PlanEntry]: - """Pin a matrix plan to a single round when `variant` is set. + """Pin a matrix plan to a subset of rounds when `variants` is set. - `variant=None` returns the plan unchanged (full-matrix mode). An - explicit variant index is matched against the plan's round indices; - if it's out of range, raises `ValueError` so callers can surface a - clean operator-facing error rather than silently doing nothing. + `variants=None` returns the plan unchanged (full-matrix mode). This is the + runner-split entry point: a role with more variants than one runner should + iterate is sliced into bundles (e.g. ``0,1,2`` on one runner and ``3,4`` on + the next), each bundle passed as `variants`. Out-of-range indices raise + `ValueError` so the caller surfaces a clean operator error. """ - if variant is None: + if variants is None: return plan - for entry in plan: - if entry[0] == variant: - return [entry] available = sorted(entry[0] for entry in plan) - raise ValueError(f"variant {variant} out of range; available rounds: {available}") + missing = sorted(v for v in variants if v not in available) + if missing: + raise ValueError( + f"variants {missing} out of range; available rounds: {available}" + ) + wanted = set(variants) + return [entry for entry in plan if entry[0] in wanted] def plan_dev_inventory_matrix( diff --git a/cli/administration/deploy/development/runtime_budget.py b/cli/administration/deploy/development/runtime_budget.py index cec4ef8435..96811382b5 100644 --- a/cli/administration/deploy/development/runtime_budget.py +++ b/cli/administration/deploy/development/runtime_budget.py @@ -9,6 +9,20 @@ from utils.annotations.message import warning _BUFFER_SECONDS = 30 * 60 +_OVERFLOW_CUT = "cut" +_OVERFLOW_FAIL = "fail" +_OVERFLOW_MODES = (_OVERFLOW_CUT, _OVERFLOW_FAIL) + + +def _parse_overflow_mode(raw: str | None) -> str: + mode = (raw or "").strip().lower() or _OVERFLOW_CUT + if mode not in _OVERFLOW_MODES: + raise SystemExit( + f"INFINITO_VARIANT_TIME_OVERFLOW must be one of {_OVERFLOW_MODES}, " + f"got {raw!r}" + ) + return mode + def _parse_duration_seconds(raw: str | None) -> int | None: if not raw: @@ -31,12 +45,20 @@ def _parse_duration_seconds(raw: str | None) -> int | None: class RuntimeBudget: """Stops the variant matrix before INFINITO_MAX_RUNTIME is exceeded by projecting the next round from the longest round so far plus a buffer. - Warns (CI annotation) on early stop; never fails the deploy.""" + + INFINITO_VARIANT_TIME_OVERFLOW decides what happens when the remaining + rounds no longer fit the budget: ``cut`` (default) warns via a CI + annotation and skips the rest without failing; ``fail`` aborts the deploy + with a non-zero exit so a runner that cannot complete its whole variant + slice in time is treated as a hard failure rather than a silent cut.""" def __init__(self) -> None: self.max_seconds = _parse_duration_seconds( os.environ.get("INFINITO_MAX_RUNTIME") ) + self.overflow_mode = _parse_overflow_mode( + os.environ.get("INFINITO_VARIANT_TIME_OVERFLOW") + ) self._start = time.monotonic() self._longest_round = 0.0 self._round_start = 0.0 @@ -48,12 +70,21 @@ class RuntimeBudget: projected = elapsed + self._longest_round + _BUFFER_SECONDS if projected <= self.max_seconds: return False + detail = ( + f"after {done}/{total} round(s): elapsed {int(elapsed)}s + longest " + f"round {int(self._longest_round)}s + {_BUFFER_SECONDS}s buffer " + f"({int(projected)}s) would exceed INFINITO_MAX_RUNTIME " + f"({self.max_seconds}s); {total - done} round(s) remaining" + ) + if self.overflow_mode == _OVERFLOW_FAIL: + raise SystemExit( + f"Variant matrix budget exceeded {detail}. " + "INFINITO_VARIANT_TIME_OVERFLOW=fail — failing the deploy " + "instead of cutting the remaining rounds." + ) warning( - f"Stopped the variant matrix after {done}/{total} round(s): elapsed " - f"{int(elapsed)}s + longest round {int(self._longest_round)}s + " - f"{_BUFFER_SECONDS}s buffer ({int(projected)}s) would exceed " - f"INFINITO_MAX_RUNTIME ({self.max_seconds}s). Skipped {total - done} " - "remaining round(s) — not a failure.", + f"Stopped the variant matrix {detail}. Skipped the remaining " + "round(s) — not a failure (INFINITO_VARIANT_TIME_OVERFLOW=cut).", title="Deploy runtime budget", ) return True diff --git a/cli/administration/deploy/development/variant_select.py b/cli/administration/deploy/development/variant_select.py new file mode 100644 index 0000000000..4b17ca7fcc --- /dev/null +++ b/cli/administration/deploy/development/variant_select.py @@ -0,0 +1,53 @@ +"""Shared variant-selection for the dev-deploy ``init`` and ``deploy`` commands. + +A single ``--variant`` (comma-separated, zero-based) selects the matrix rounds a +run iterates: ``2`` pins one round, ``0,1,2`` is the runner-split bundle from CI +discovery, empty/unset is the full matrix. One value is just a one-element +bundle — there is no separate "variants" flag — and whether inter-round cleanup +runs follows the number of selected rounds, not the flag. Centralising this here +keeps init and deploy walking the exact same selection (SPOT).""" + +from __future__ import annotations + +import argparse +import os + +from .inventory import filter_plan_to_variants + + +def parse_variant_csv(raw: str) -> list[int]: + try: + return [int(tok.strip()) for tok in raw.split(",") if tok.strip()] + except ValueError: + raise argparse.ArgumentTypeError( + f"must be a comma-separated list of integers, got {raw!r}" + ) from None + + +def env_variant() -> list[int] | None: + raw = os.environ.get("variant", "").strip() + if not raw: + return None + try: + return parse_variant_csv(raw) + except argparse.ArgumentTypeError as exc: + raise SystemExit(f"variant environment variable {exc}") from None + + +def add_variant_args(parser: argparse.ArgumentParser, *, action: str) -> None: + parser.add_argument( + "--variant", + type=parse_variant_csv, + default=env_variant(), + help=( + f"Pin the matrix {action} to one or more rounds (comma-separated " + "zero-based indices, e.g. `2` or `0,1,2`). A single index pins one " + "round; multiple indices are the runner-split bundle. Empty/unset = " + "full matrix. Defaults to the variant environment variable when set." + ), + ) + + +def apply_variant_filter(plan, args): + """Filter `plan` to the rounds in `--variant`; empty/None = full matrix.""" + return filter_plan_to_variants(plan, args.variant or None) diff --git a/docs/contributing/actions/deploy.md b/docs/contributing/actions/deploy.md index fff8f3c573..2d0f35d998 100644 --- a/docs/contributing/actions/deploy.md +++ b/docs/contributing/actions/deploy.md @@ -46,19 +46,22 @@ This purges the app's containers + volumes + Ansible-managed state on the host, Only return to `mode=reinstall` when you have concrete evidence that the inventory or the host stack itself is broken (for example DNS or network failures during the deploy). -## Pinning A Single Variant 🎯 +## Pinning Variants (Single Or Bundle) 🎯 -For multi-variant roles you MAY restrict any of the `make compose-deploy` invocations above (and the dev CLI subcommands) to a single matrix round by setting `variant=`: +For multi-variant roles you MAY restrict any of the `make compose-deploy` invocations above (and the dev CLI subcommands) to one or more matrix rounds by setting `variant=` — a single index pins one round, a comma-separated list iterates that subset (the runner-split bundle CI produces), and empty/unset is the full matrix: ```bash # Variant 1 baseline only (no full matrix): make compose-deploy mode=reinstall apps="" full_cycle=true variant=1 +# A 3-round bundle (one CI runner's slice): +make compose-deploy mode=reinstall apps="" full_cycle=true variant=0,1,2 + # Edit-fix-redeploy loop pinned to that variant: make compose-deploy mode=update apps="" variant=1 ``` -Pinning is sticky: when iterating with `variant=`, you MUST set it on every command in the iteration. Mixing pinned and unpinned commands silently retargets a different folder. The full semantics (single-folder mode, no inter-round cleanup, out-of-range error) live in [variants.md](../design/variants.md). +Pinning is sticky: when iterating with `variant=`, you MUST set it on every command in the iteration. Mixing pinned and unpinned commands silently retargets a different folder. The full semantics (subset selection, no inter-round cleanup when one round, out-of-range error, CI runner-split) live in [variants.md](../design/variants.md). ## Direct CLI Invocation ⚙️ @@ -66,7 +69,7 @@ When you need a flag the make wrappers do not expose, call the dev CLI directly: ```bash infinito administration deploy development init --inventory-dir "${INFINITO_INVENTORY_DIR}" --apps "" -infinito administration deploy development deploy --inventory-dir "${INFINITO_INVENTORY_DIR}" --apps "" [--variant ] [--debug] +infinito administration deploy development deploy --inventory-dir "${INFINITO_INVENTORY_DIR}" --apps "" [--variant ] [--debug] ``` - `--inventory-dir` is always the BASE path. The wrapper appends the `-` suffix internally for matrix folders. diff --git a/docs/contributing/design/variants.md b/docs/contributing/design/variants.md index be77fa7f25..f65e1751cb 100644 --- a/docs/contributing/design/variants.md +++ b/docs/contributing/design/variants.md @@ -16,7 +16,8 @@ The development deploy CLI uses a **folder-per-round model** that splits cleanly 4. **Deploy iteration.** [deploy.py](../../../cli/administration/deploy/development/deploy.py) re-derives the same plan via `plan_dev_inventory_matrix` (the planner is a pure function shared between init and deploy) and runs one deploy per folder. **Every round deploys its full variant-aware include set.** Round R starts from a clean host (the previous round's include is purged before round R begins, see point 5), so every dep that round R needs MUST be redeployed. 5. **Cleanup between rounds.** Before each non-first iteration the wrapper runs [entity.sh](../../../scripts/tests/deploy/local/purge/entity.sh) for **every** app in the previous round's include set. The next round therefore boots from an empty host, which guarantees cross-round state coherence: nothing the previous round deployed (whether it stays in the current round's closure or falls out) can leak into round R, so variants are free to disagree on which deps they pull in. The final round is followed by no purge so the last state remains available for inspection or follow-up specs. 6. **`--full-cycle` (async update pass).** When set (or `full_cycle=true` on `make compose-deploy`), the wrapper runs each round's deploy TWICE: first the regular sync pass, then immediately a second pass with `-e ASYNC_ENABLED=true` overriding the host_var, against the SAME variant's folder, BEFORE moving to the next round. The two passes are therefore always co-located on the same host state; the async pass never accidentally targets a host that a previous round's variant left behind. -7. **Pinning to a single round.** Both init and deploy accept `--variant ` (same semantics as the `variant=` make arg) to pin operations to a single round's folder. In single-round mode no inter-round cleanup runs, since there is no previous round to diff against. The `make compose-deploy mode=update` flows honour the same `variant=` arg by suffixing `INFINITO_INVENTORY_DIR` / `INFINITO_INVENTORY_FILE` to `-`, so a redeploy can target one specific variant without iterating the full matrix. +7. **Pinning rounds (single or bundle).** Both init and deploy accept `--variant ` (same semantics as the `variant=` make arg): a single index (`1`) pins one round, a comma-separated list (`0,1,2`) iterates that subset, and empty/unset is the full matrix. When the selection is a single round no inter-round cleanup runs (no previous round to diff against); out-of-range indices raise a clean error. The `make compose-deploy mode=update` flows honour the same `variant=` arg by suffixing `INFINITO_INVENTORY_DIR` / `INFINITO_INVENTORY_FILE` to `-` (single index), so a redeploy can target one specific variant without iterating the full matrix. +8. **CI runner-split.** The deploy-matrix discovery ([variant_bundles.py](../../../utils/github/variant_bundles.py), wired via [output_apps.sh](../../../scripts/github/resolve/output_apps.sh)) splits any role with more than `INFINITO_VARIANT_BUNDLE_SIZE` (default 3) variants into bundles of consecutive indices — one matrix entry (runner) per bundle, e.g. a 5-variant role becomes `0,1,2` + `3,4`. Each runner receives its slice through the `variant` env (consumed by `--variant`). `INFINITO_VARIANT_TIME_OVERFLOW` (`cut`|`fail`) decides what happens when a runner cannot finish its slice within `INFINITO_MAX_RUNTIME`: `cut` (default) warns and skips the remaining rounds; `fail` aborts the deploy. The in-play loader (`utils.cache.applications.get_merged_applications`) uses each role's variant-free base config (the assembled `meta/.yml` payload) as the default and lets the inventory's `applications.` overrides win via deep merge: the inventory itself is the source of truth for what variant a round runs against. Variant 0 enumerates every dynamic service-key from `meta/services.yml` with `enabled: true, shared: true` so the "all flags on" baseline is explicit and deep-merge with a non-baseline override yields the expected variant-N shape (see [variants.md](../artefact/files/role/variants.md) for the file-format rule and [test_non_baseline_explicit_disables.py](../../../tests/integration/roles/meta/variants/test_non_baseline_explicit_disables.py) for the lint guard). diff --git a/scripts/github/resolve/output_apps.sh b/scripts/github/resolve/output_apps.sh index 0d89699a94..8d80fb9796 100755 --- a/scripts/github/resolve/output_apps.sh +++ b/scripts/github/resolve/output_apps.sh @@ -9,6 +9,11 @@ set -euo pipefail apps="$(./scripts/meta/resolve/apps.sh)" [[ -n "$apps" ]] || apps='[]' -echo "apps=$apps" >>"$GITHUB_OUTPUT" -echo "apps_json=$apps" >>"$GITHUB_OUTPUT" -echo "apps_json=$apps" +# Expand the flat app-id list into deploy-matrix entries, splitting any role +# with more variants than INFINITO_VARIANT_BUNDLE_SIZE (default 3) into bundles +# of consecutive variant indices — one runner per bundle. +matrix="$(printf '%s' "$apps" | "${PYTHON:-python3}" -m utils.github.variant_bundles)" +[[ -n "$matrix" ]] || matrix='[]' + +echo "apps=$matrix" >>"$GITHUB_OUTPUT" +echo "apps=$matrix" diff --git a/scripts/tests/deploy/ci/dedicated.sh b/scripts/tests/deploy/ci/dedicated.sh index 968891649e..afeda3dffe 100755 --- a/scripts/tests/deploy/ci/dedicated.sh +++ b/scripts/tests/deploy/ci/dedicated.sh @@ -21,7 +21,8 @@ set -euo pipefail # # Optional env: # PYTHON="python3" -# variant="" pin to one matrix round (skips the rest) +# variant="" pin to one or more matrix rounds, e.g. "2" or "0,1,2" +# (the runner-split bundle from CI discovery); empty = all PYTHON="${PYTHON:-python3}" diff --git a/tests/unit/cli/administration/deploy/development/inventory/test_planner.py b/tests/unit/cli/administration/deploy/development/inventory/test_planner.py index eea005757d..2bcdab7b1b 100644 --- a/tests/unit/cli/administration/deploy/development/inventory/test_planner.py +++ b/tests/unit/cli/administration/deploy/development/inventory/test_planner.py @@ -1,7 +1,7 @@ """Unit tests for `cli.administration.deploy.development.inventory.planner`. Covers ``plan_dev_inventory_matrix`` (mocking ``legacy_resolver``) and -``filter_plan_to_variant``. +``filter_plan_to_variants``. """ from __future__ import annotations @@ -11,7 +11,7 @@ from typing import ClassVar from unittest.mock import MagicMock, patch from cli.administration.deploy.development.inventory import ( - filter_plan_to_variant, + filter_plan_to_variants, plan_dev_inventory_matrix, ) @@ -220,36 +220,34 @@ class TestPlanDevInventoryMatrix(unittest.TestCase): ) -class TestFilterPlanToVariant(unittest.TestCase): +class TestFilterPlanToVariants(unittest.TestCase): PLAN: ClassVar[list[tuple]] = [ - ( - 0, - "/srv/inv-0", - {"web-app-multi": 0, "web-app-keycloak": 0}, - ("web-app-multi", "web-app-keycloak"), - ("web-app-multi", "web-app-keycloak"), - ), - ( - 1, - "/srv/inv-1", - {"web-app-multi": 1, "web-app-keycloak": 0}, - ("web-app-multi", "web-app-keycloak"), - ("web-app-multi", "web-app-keycloak"), - ), + (i, f"/srv/inv-{i}", {"web-app-multi": i}, ("web-app-multi",), ()) + for i in range(5) ] def test_none_returns_full_plan(self): - self.assertEqual(filter_plan_to_variant(self.PLAN, None), self.PLAN) + self.assertEqual(filter_plan_to_variants(self.PLAN, None), self.PLAN) - def test_pins_to_named_round(self): + def test_subset_keeps_only_listed_rounds_in_plan_order(self): self.assertEqual( - filter_plan_to_variant(self.PLAN, 1), - [self.PLAN[1]], + filter_plan_to_variants(self.PLAN, [0, 1, 2]), + self.PLAN[:3], + ) + self.assertEqual( + filter_plan_to_variants(self.PLAN, [3, 4]), + self.PLAN[3:], + ) + + def test_order_follows_plan_not_argument(self): + self.assertEqual( + filter_plan_to_variants(self.PLAN, [4, 0]), + [self.PLAN[0], self.PLAN[4]], ) def test_out_of_range_raises_value_error(self): - with self.assertRaisesRegex(ValueError, "variant 7 out of range"): - filter_plan_to_variant(self.PLAN, 7) + with self.assertRaisesRegex(ValueError, r"variants \[7\] out of range"): + filter_plan_to_variants(self.PLAN, [0, 7]) if __name__ == "__main__": # pragma: no cover diff --git a/tests/unit/cli/administration/deploy/development/test_matrix_deploy.py b/tests/unit/cli/administration/deploy/development/test_matrix_deploy.py index 4126c8d994..95b8713a0d 100644 --- a/tests/unit/cli/administration/deploy/development/test_matrix_deploy.py +++ b/tests/unit/cli/administration/deploy/development/test_matrix_deploy.py @@ -26,7 +26,7 @@ from cli.administration.deploy.development.deploy import handler # noqa: E402 def _args( *, apps: list[str] | None = None, - variant: int | None = None, + variant: list[int] | None = None, full_cycle: bool = False, ) -> argparse.Namespace: # `distro` is intentionally absent: deploy.handler no longer consumes @@ -367,7 +367,7 @@ class TestHandlerVariantPin(unittest.TestCase): ] run_deploy_mock.return_value = 0 - rc = handler(_args(apps=["web-app-multi"], variant=1)) + rc = handler(_args(apps=["web-app-multi"], variant=[1])) self.assertEqual(rc, 0) # Only the picked round runs; no cleanup because there is no @@ -401,8 +401,8 @@ class TestHandlerVariantPin(unittest.TestCase): _entry(1, "/srv/inv-1", {"web-app-multi": 1}), ] - with self.assertRaisesRegex(SystemExit, "variant 7 out of range"): - handler(_args(apps=["web-app-multi"], variant=7)) + with self.assertRaisesRegex(SystemExit, r"variants \[7\] out of range"): + handler(_args(apps=["web-app-multi"], variant=[7])) run_deploy_mock.assert_not_called() @@ -518,7 +518,7 @@ class TestHandlerFullCycle(unittest.TestCase): ] run_deploy_mock.return_value = 0 - rc = handler(_args(apps=["web-app-multi"], variant=1, full_cycle=True)) + rc = handler(_args(apps=["web-app-multi"], variant=[1], full_cycle=True)) self.assertEqual(rc, 0) self.assertEqual(run_deploy_mock.call_count, 2) @@ -536,5 +536,75 @@ class TestHandlerFullCycle(unittest.TestCase): purge_mock.assert_not_called() +class TestHandlerBudget(unittest.TestCase): + """The runtime-budget guard gates the round loop: `cut` mode stops early + and still returns success; `fail` mode propagates SystemExit.""" + + @patch("cli.administration.deploy.development.deploy.RuntimeBudget", autospec=True) + @patch( + "cli.administration.deploy.development.deploy._purge_app_entities", + autospec=True, + ) + @patch("cli.administration.deploy.development.deploy._run_deploy", autospec=True) + @patch( + "cli.administration.deploy.development.deploy.plan_dev_inventory_matrix", + autospec=True, + ) + @patch("cli.administration.deploy.development.deploy.make_compose", autospec=True) + def test_cut_stops_early_and_returns_success( + self, + make_compose_mock: MagicMock, + plan_mock: MagicMock, + run_deploy_mock: MagicMock, + purge_mock: MagicMock, + budget_cls_mock: MagicMock, + ) -> None: + make_compose_mock.return_value = _make_compose_mock() + plan_mock.return_value = [ + _entry(0, "/srv/inv-0", {"web-app-wordpress": 0}), + _entry(1, "/srv/inv-1", {"web-app-wordpress": 1}), + ] + run_deploy_mock.return_value = 0 + budget = budget_cls_mock.return_value + budget.exhausted.side_effect = [False, True] # round 1 over budget + + rc = handler(_args(apps=["web-app-wordpress"])) + + self.assertEqual(rc, 0) # cut is NOT a failure + run_deploy_mock.assert_called_once() # only round 0 ran + + @patch("cli.administration.deploy.development.deploy.RuntimeBudget", autospec=True) + @patch( + "cli.administration.deploy.development.deploy._purge_app_entities", + autospec=True, + ) + @patch("cli.administration.deploy.development.deploy._run_deploy", autospec=True) + @patch( + "cli.administration.deploy.development.deploy.plan_dev_inventory_matrix", + autospec=True, + ) + @patch("cli.administration.deploy.development.deploy.make_compose", autospec=True) + def test_fail_mode_propagates_systemexit( + self, + make_compose_mock: MagicMock, + plan_mock: MagicMock, + run_deploy_mock: MagicMock, + purge_mock: MagicMock, + budget_cls_mock: MagicMock, + ) -> None: + make_compose_mock.return_value = _make_compose_mock() + plan_mock.return_value = [ + _entry(0, "/srv/inv-0", {"web-app-wordpress": 0}), + _entry(1, "/srv/inv-1", {"web-app-wordpress": 1}), + ] + run_deploy_mock.return_value = 0 + budget = budget_cls_mock.return_value + budget.exhausted.side_effect = [False, SystemExit("budget exceeded")] + + with self.assertRaises(SystemExit): + handler(_args(apps=["web-app-wordpress"])) + run_deploy_mock.assert_called_once() # round 0 ran, then hard-fail + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/cli/administration/deploy/development/test_runtime_budget.py b/tests/unit/cli/administration/deploy/development/test_runtime_budget.py index 055177967b..3d8cebef29 100644 --- a/tests/unit/cli/administration/deploy/development/test_runtime_budget.py +++ b/tests/unit/cli/administration/deploy/development/test_runtime_budget.py @@ -108,5 +108,59 @@ class TestRuntimeBudget(unittest.TestCase): self.assertEqual(budget._longest_round, 1000) +class TestOverflowMode(unittest.TestCase): + def test_default_mode_is_cut(self) -> None: + with patch.dict(os.environ, {"INFINITO_VARIANT_TIME_OVERFLOW": ""}): + self.assertEqual(rb.RuntimeBudget().overflow_mode, "cut") + + def test_invalid_mode_raises_at_construction(self) -> None: + with ( + patch.dict(os.environ, {"INFINITO_VARIANT_TIME_OVERFLOW": "bogus"}), + self.assertRaises(SystemExit), + ): + rb.RuntimeBudget() + + def test_fail_mode_raises_instead_of_warning(self) -> None: + clock = _Clock() + with ( + patch.object(rb.time, "monotonic", clock), + patch.object(rb, "warning") as mock_warning, + patch.dict( + os.environ, + { + "INFINITO_MAX_RUNTIME": "3600", + "INFINITO_VARIANT_TIME_OVERFLOW": "fail", + }, + ), + ): + budget = rb.RuntimeBudget() + budget.start_round() + clock.t = 1000 + budget.end_round() + with self.assertRaises(SystemExit): + budget.exhausted(1, 3) + mock_warning.assert_not_called() + + def test_cut_mode_warns_and_returns_true(self) -> None: + clock = _Clock() + with ( + patch.object(rb.time, "monotonic", clock), + patch.object(rb, "warning") as mock_warning, + patch.dict( + os.environ, + { + "INFINITO_MAX_RUNTIME": "3600", + "INFINITO_VARIANT_TIME_OVERFLOW": "cut", + }, + ), + ): + budget = rb.RuntimeBudget() + budget.start_round() + clock.t = 1000 + budget.end_round() + self.assertTrue(budget.exhausted(1, 3)) + mock_warning.assert_called_once() + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/cli/administration/deploy/development/test_variant_select.py b/tests/unit/cli/administration/deploy/development/test_variant_select.py new file mode 100644 index 0000000000..6c4de282f4 --- /dev/null +++ b/tests/unit/cli/administration/deploy/development/test_variant_select.py @@ -0,0 +1,74 @@ +"""Unit tests for the shared variant-selection helpers.""" + +from __future__ import annotations + +import argparse +import os +import unittest +from typing import ClassVar +from unittest.mock import patch + +from cli.administration.deploy.development import variant_select as vs + + +class TestParseVariantCsv(unittest.TestCase): + def test_parses_and_drops_blank_tokens(self) -> None: + self.assertEqual(vs.parse_variant_csv("0,1,2"), [0, 1, 2]) + self.assertEqual(vs.parse_variant_csv(" 3 , 4 "), [3, 4]) + self.assertEqual(vs.parse_variant_csv("2"), [2]) + self.assertEqual(vs.parse_variant_csv(""), []) + self.assertEqual(vs.parse_variant_csv(","), []) + + def test_non_integer_raises_argument_type_error(self) -> None: + with self.assertRaises(argparse.ArgumentTypeError): + vs.parse_variant_csv("0,x") + + +class TestEnvVariant(unittest.TestCase): + def test_single_and_csv(self) -> None: + with patch.dict(os.environ, {"variant": "2"}): + self.assertEqual(vs.env_variant(), [2]) + with patch.dict(os.environ, {"variant": "0,1,2"}): + self.assertEqual(vs.env_variant(), [0, 1, 2]) + + def test_blank_is_none(self) -> None: + with patch.dict(os.environ, {"variant": ""}): + self.assertIsNone(vs.env_variant()) + with patch.dict(os.environ, {"variant": " "}): + self.assertIsNone(vs.env_variant()) + + def test_bad_value_exits(self) -> None: + with patch.dict(os.environ, {"variant": "0,x"}), self.assertRaises(SystemExit): + vs.env_variant() + + +class TestApplyVariantFilter(unittest.TestCase): + PLAN: ClassVar[list[tuple]] = [(i, f"inv-{i}", {}, (), ()) for i in range(5)] + + def _args(self, *, variant=None) -> argparse.Namespace: + return argparse.Namespace(variant=variant) + + def test_none_returns_full_plan(self) -> None: + self.assertEqual( + vs.apply_variant_filter(self.PLAN, self._args()), self.PLAN + ) + + def test_single_index_pins_one_round(self) -> None: + out = vs.apply_variant_filter(self.PLAN, self._args(variant=[1])) + self.assertEqual([e[0] for e in out], [1]) + + def test_subset_keeps_listed_rounds(self) -> None: + self.assertEqual( + vs.apply_variant_filter(self.PLAN, self._args(variant=[3, 4])), + self.PLAN[3:], + ) + + def test_empty_list_falls_back_to_full_matrix(self) -> None: + # Empty slice must NOT silently yield an empty plan (green no-op). + self.assertEqual( + vs.apply_variant_filter(self.PLAN, self._args(variant=[])), self.PLAN + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/utils/env/handlers/test_infinito_variant_time_overflow.py b/tests/unit/utils/env/handlers/test_infinito_variant_time_overflow.py new file mode 100644 index 0000000000..19b797c784 --- /dev/null +++ b/tests/unit/utils/env/handlers/test_infinito_variant_time_overflow.py @@ -0,0 +1,40 @@ +"""Unit tests for :mod:`utils.env.handlers.infinito_variant_time_overflow`.""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from unittest.mock import patch + +from utils.env.builder import BuildContext, EnvBuilder +from utils.env.handlers import infinito_variant_time_overflow as handler + + +def _ctx(*, on_gha: bool) -> BuildContext: + return BuildContext( + static={}, + static_comments={}, + repo_root=Path("/repo"), + on_gha=on_gha, + on_act=False, + ) + + +class TestApply(unittest.TestCase): + def test_defaults_to_cut(self) -> None: + for on_gha in (True, False): + with patch.dict("os.environ", {}, clear=True): + eb = EnvBuilder() + handler.apply(eb, _ctx(on_gha=on_gha)) + self.assertEqual(eb.values[handler.KEY], "cut") + self.assertEqual(eb.comments[handler.KEY], handler.COMMENT) + + def test_caller_env_wins_over_default(self) -> None: + with patch.dict("os.environ", {handler.KEY: "fail"}, clear=True): + eb = EnvBuilder() + handler.apply(eb, _ctx(on_gha=True)) + self.assertEqual(eb.values[handler.KEY], "fail") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/utils/github/test_variant_bundles.py b/tests/unit/utils/github/test_variant_bundles.py new file mode 100644 index 0000000000..55b0b0a294 --- /dev/null +++ b/tests/unit/utils/github/test_variant_bundles.py @@ -0,0 +1,114 @@ +"""Unit tests for :mod:`utils.github.variant_bundles`.""" + +from __future__ import annotations + +import json +import unittest +from unittest.mock import patch + +from utils.github import variant_bundles as vb + + +class TestChunkIndices(unittest.TestCase): + def test_splits_into_consecutive_bundles(self) -> None: + self.assertEqual(vb.chunk_indices(5, 3), [[0, 1, 2], [3, 4]]) + self.assertEqual(vb.chunk_indices(6, 3), [[0, 1, 2], [3, 4, 5]]) + self.assertEqual(vb.chunk_indices(3, 3), [[0, 1, 2]]) + self.assertEqual(vb.chunk_indices(1, 3), [[0]]) + + +class TestResolveBundleSize(unittest.TestCase): + def test_default_when_unset(self) -> None: + self.assertEqual(vb.resolve_bundle_size(""), vb.DEFAULT_BUNDLE_SIZE) + + def test_explicit_value(self) -> None: + self.assertEqual(vb.resolve_bundle_size("2"), 2) + + def test_zero_or_negative_rejected(self) -> None: + with self.assertRaises(ValueError): + vb.resolve_bundle_size("0") + + def test_non_numeric_rejected_cleanly(self) -> None: + with self.assertRaisesRegex(ValueError, "must be an integer"): + vb.resolve_bundle_size("three") + + +class TestExpandApps(unittest.TestCase): + VARIANTS = { # noqa: RUF012 + "web-app-single": [{}], + "web-app-three": [{}, {}, {}], + "web-app-five": [{}, {}, {}, {}, {}], + } + + def test_role_within_bundle_size_stays_full_matrix(self) -> None: + self.assertEqual( + vb.expand_apps(["web-app-three"], self.VARIANTS, 3), + [{"apps": "web-app-three", "variant": "", "variant_slug": ""}], + ) + + def test_missing_variants_treated_as_single(self) -> None: + self.assertEqual( + vb.expand_apps(["web-app-unknown"], self.VARIANTS, 3), + [{"apps": "web-app-unknown", "variant": "", "variant_slug": ""}], + ) + + def test_role_over_bundle_size_is_split(self) -> None: + self.assertEqual( + vb.expand_apps(["web-app-five"], self.VARIANTS, 3), + [ + {"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_mixed_list_preserves_app_order(self) -> None: + out = vb.expand_apps( + ["web-app-single", "web-app-five"], self.VARIANTS, 3 + ) + self.assertEqual( + out, + [ + {"apps": "web-app-single", "variant": "", "variant_slug": ""}, + {"apps": "web-app-five", "variant": "0,1,2", "variant_slug": "0-1-2"}, + {"apps": "web-app-five", "variant": "3,4", "variant_slug": "3-4"}, + ], + ) + + +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.dict("os.environ", {"INFINITO_VARIANT_BUNDLE_SIZE": "3"}), + patch("builtins.print") as mock_print, + ): + rc = vb.main(['["web-app-five"]']) + self.assertEqual(rc, 0) + printed = json.loads(mock_print.call_args.args[0]) + self.assertEqual( + printed, + [ + {"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_empty_input_yields_empty_list(self) -> None: + with ( + patch.object(vb, "get_variants", return_value={}), + patch("builtins.print") as mock_print, + ): + rc = vb.main([""]) + self.assertEqual(rc, 0) + self.assertEqual(json.loads(mock_print.call_args.args[0]), []) + + def test_non_list_json_rejected(self) -> None: + with ( + patch.object(vb, "get_variants", return_value={}), + self.assertRaises(SystemExit), + ): + vb.main(['"web-app-five"']) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/env/handlers/__init__.py b/utils/env/handlers/__init__.py index 445e5db7b7..65fdc931e1 100644 --- a/utils/env/handlers/__init__.py +++ b/utils/env/handlers/__init__.py @@ -27,6 +27,8 @@ from . import ( infinito_registry_cache_max_size, infinito_running_on_act, infinito_running_on_github, + infinito_variant_bundle_size, + infinito_variant_time_overflow, infinito_worker_cpu, infinito_worker_fetch, nix_config, @@ -41,6 +43,8 @@ ORDERED_HANDLERS = [ infinito_running_on_act, infinito_running_on_github, infinito_max_runtime, + infinito_variant_time_overflow, + infinito_variant_bundle_size, infinito_is_wsl2, infinito_outer_network_mtu, infinito_inventory, diff --git a/utils/env/handlers/infinito_variant_bundle_size.py b/utils/env/handlers/infinito_variant_bundle_size.py new file mode 100644 index 0000000000..11c004b9a7 --- /dev/null +++ b/utils/env/handlers/infinito_variant_bundle_size.py @@ -0,0 +1,20 @@ +"""INFINITO_VARIANT_BUNDLE_SIZE: how many matrix-deploy variants one CI runner +iterates before the discovery (utils.github.variant_bundles) splits a role into +another runner. Defaults to 3 everywhere.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from utils.env.builder import BuildContext, EnvBuilder + +KEY = "INFINITO_VARIANT_BUNDLE_SIZE" +COMMENT = ( + "Variants 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, "3", comment=COMMENT) diff --git a/utils/env/handlers/infinito_variant_time_overflow.py b/utils/env/handlers/infinito_variant_time_overflow.py new file mode 100644 index 0000000000..2903be88f5 --- /dev/null +++ b/utils/env/handlers/infinito_variant_time_overflow.py @@ -0,0 +1,21 @@ +"""INFINITO_VARIANT_TIME_OVERFLOW: how the variant-iteration guard reacts when +the remaining rounds no longer fit INFINITO_MAX_RUNTIME — ``cut`` (warn + skip) +or ``fail`` (abort the deploy). Defaults to ``cut`` everywhere.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from utils.env.builder import BuildContext, EnvBuilder + +KEY = "INFINITO_VARIANT_TIME_OVERFLOW" +COMMENT = ( + "Variant-iteration budget overflow policy " + "(cli.administration.deploy.development): cut = warn and skip the rounds " + "that no longer fit INFINITO_MAX_RUNTIME; fail = abort the deploy instead." +) + + +def apply(eb: EnvBuilder, ctx: BuildContext) -> None: + eb.setdefault(KEY, "cut", comment=COMMENT) diff --git a/utils/github/variant_bundles.py b/utils/github/variant_bundles.py new file mode 100644 index 0000000000..8ca812639b --- /dev/null +++ b/utils/github/variant_bundles.py @@ -0,0 +1,103 @@ +"""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. + +Each entry is ``{"apps": , "variant": "", "variant_slug": ""}``; +an empty ``variant`` means full-matrix mode. 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 +names (GitHub Actions expressions have no string-replace function). +""" + +from __future__ import annotations + +import json +import os +import sys +from typing import TYPE_CHECKING + +from utils.cache.applications import get_variants + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping, Sequence + from typing import Any + +DEFAULT_BUNDLE_SIZE = 3 + + +def resolve_bundle_size(raw: str | None = None) -> int: + if raw is None: + raw = os.environ.get("INFINITO_VARIANT_BUNDLE_SIZE") + value = (raw or "").strip() + if not value: + return DEFAULT_BUNDLE_SIZE + try: + size = int(value) + except ValueError: + raise ValueError( + f"INFINITO_VARIANT_BUNDLE_SIZE must be an integer, got {value!r}" + ) from None + if size < 1: + raise ValueError("INFINITO_VARIANT_BUNDLE_SIZE must be >= 1") + return size + + +def chunk_indices(count: int, bundle_size: int) -> list[list[int]]: + return [ + list(range(start, min(start + bundle_size, count))) + for start in range(0, count, bundle_size) + ] + + +def variant_count(variants_per_app: Mapping[str, Sequence[Any]], app: str) -> int: + return max(1, len(variants_per_app.get(app) or [])) + + +def _entry(app: str, variant_csv: str) -> dict[str, str]: + # `variant_slug` is a comma-free copy for artifact/job names: GitHub Actions + # expressions have no replace(), so the CSV cannot be sanitised in YAML. + return { + "apps": app, + "variant": variant_csv, + "variant_slug": variant_csv.replace(",", "-"), + } + + +def expand_apps( + apps: Iterable[str], + variants_per_app: Mapping[str, Sequence[Any]], + bundle_size: int = DEFAULT_BUNDLE_SIZE, +) -> list[dict[str, str]]: + entries: list[dict[str, str]] = [] + for app in apps: + count = variant_count(variants_per_app, app) + if count <= bundle_size: + entries.append({"apps": app, "variant": "", "variant_slug": ""}) + continue + entries.extend( + _entry(app, ",".join(map(str, chunk))) + for chunk in chunk_indices(count, bundle_size) + ) + return entries + + +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() + apps = json.loads(raw) if raw.strip() else [] + if not isinstance(apps, list): + raise SystemExit( + f"variant_bundles: expected a JSON array of app ids, got " + f"{type(apps).__name__}" + ) + entries = expand_apps(apps, get_variants(), resolve_bundle_size()) + print(json.dumps(entries)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())