From 1539bb6698e60bda43e57cb22cfde14b3337fbb6 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 24 Nov 2026 22:43:42 +0000 Subject: [PATCH] fix(ci): select only the roles whose rounds really deploy a changed role MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR 2846 changed only web-app-n8n and CI deployed every variant of ten unrelated roles: the disk closure linked each matrix consumer to n8n through matrix's dynamic n8n flag, and a role none of whose variant rounds deploys the seed fell back to all of its variants. The selection now drops such roles and keeps every other role only with the variants whose round deploys a seed. Its prefilter is built from the union of each role's disk, variant and nested services, so service keys only a variant declares (web-app-lam in moodle and openbao) are no longer missed. run_after no longer counts as an include, and a seed without application_id falls back to a full deploy. Checked against the planner's rounds for all 198 app seeds: exact. MEDUSA acceptances: RH005 on both existing raise SystemExit lines (exit contract, the caller maps any non-zero exit to __ALL__). 🎯 Fix: 95 % 💥 Break: 4 % 💸 Tokens: 100 % ⏱️ Velocity: 100 % 🛡️ Security: 100 % 🏆 Score: 91 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../resolution/affected/__main__.py | 240 ++++++++++++------ docs/contributing/artefact/git/pipeline.md | 4 +- scripts/meta/resolve/diff/affected_roles.sh | 4 - .../resolution/affected/test_main.py | 105 +++++++- 4 files changed, 263 insertions(+), 90 deletions(-) diff --git a/cli/meta/roles/applications/resolution/affected/__main__.py b/cli/meta/roles/applications/resolution/affected/__main__.py index 55feeac633..36a1aefe7b 100755 --- a/cli/meta/roles/applications/resolution/affected/__main__.py +++ b/cli/meta/roles/applications/resolution/affected/__main__.py @@ -2,27 +2,25 @@ """ Resolve the set of roles affected by a change to a given set of seed roles. -A role R is "affected" by seed S iff S appears in R's transitive prerequisite -closure (run_after + dependencies + services), as defined by -:class:`cli.meta.roles.applications.resolution.combined.resolver.CombinedResolver`. - Usage: python -m cli.meta.roles.applications.resolution.affected --changed-roles ROLE [ROLE ...] Output: Whitespace-separated, sorted list of selection tokens (single line), - including the seed roles themselves. A role whose variants do not all - reach a seed is narrowed to the ones that do (``role#0,2``, - :mod:`utils.github.variant.selection`): a variant that switches its - provider off does not inherit the seed's change, so deploying it verifies - nothing. The narrowing is transitive over the whole chain, because each - round's closure is walked on that round's variant-merged services maps. + including the seed roles themselves. Every other role is kept only with + the variants whose round really deploys a seed (``role#0,2``, + :mod:`utils.github.variant.selection`), and dropped when none does: a + variant that switches its provider off, or reaches the seed only over a + ``run_after`` ordering hint, does not inherit the seed's change, so + deploying it verifies nothing. The narrowing is transitive over the whole + chain, because each round's closure is walked on that round's + variant-merged services maps. Exit codes: 0 Success. The closure was computed and printed. 1 Resolver error or unknown seed. 2 At least one seed role is non-modellable in the resolver - (no application_id and not referenced by any role's run_after). + (no application_id, so no round closure can contain it). Callers MUST treat this as "fall back to a full deploy" because the resolver cannot guarantee that downstream consumers are enumerated for that seed. @@ -32,23 +30,32 @@ from __future__ import annotations import argparse import sys +from collections.abc import Mapping from typing import TYPE_CHECKING from cli.meta.roles.applications.resolution.combined.errors import ( CombinedResolutionError, ) -from cli.meta.roles.applications.resolution.combined.repo_paths import roles_dir +from cli.meta.roles.applications.resolution.combined.repo_paths import ( + role_config_path, + roles_dir, +) from cli.meta.roles.applications.resolution.combined.resolver import CombinedResolver from cli.meta.roles.applications.resolution.combined.role_introspection import ( has_application_id, - load_run_after, ) +from cli.meta.roles.applications.resolution.combined.yaml_utils import load_yaml_file from utils.cache.applications import get_variants +from utils.roles.applications.services.registry import ( + build_service_registry_from_roles_dir, + is_explicit_truth, +) +from utils.roles.applications.topics import provider_of from utils.roles.applications.variants import resolve_round from utils.roles.display import VARIANT_SEPARATOR if TYPE_CHECKING: - from collections.abc import Iterable, Mapping + from collections.abc import Iterable from pathlib import Path EXIT_NON_MODELLABLE_SEED = 2 @@ -61,40 +68,109 @@ def _list_role_names() -> list[str]: return sorted(p.name for p in rdir.iterdir() if p.is_dir()) -def _non_modellable_seeds(seeds: set[str], all_roles: list[str]) -> list[str]: - """Return seeds that the resolver cannot reach as a downstream prereq. +def _non_modellable_seeds(seeds: set[str]) -> list[str]: + """ + Args: + seeds: the changed roles. - A seed is reachable iff at least one of: - * it has ``application_id`` (then app-deps and shared-service edges - from any consumer can include it), or - * some role lists it in its ``run_after`` (then a run_after edge - from that consumer includes it). + Returns: + Every seed without ``application_id``, sorted. A round pulls a role + in only over app-only ``dependencies`` and ``services`` edges, never + over ``run_after``, so the resolver cannot enumerate who deploys + such a seed and the caller MUST fall back to a full deploy. + """ + return sorted(role for role in seeds if not has_application_id(role)) - Any other seed (e.g. a non-app helper role only pulled in via - ``include_role`` from tasks) is invisible to the resolver. Returning - a partial closure for such a seed silently shrinks the deploy - matrix. Callers MUST fall back to a full deploy in that case. + +def _switched_on(blocks: list[Mapping]) -> dict[str, dict]: + """ + Args: + blocks: services maps of one role. + + Returns: + ``{key: enabled and shared}`` for each key some block marks + ``enabled`` and some block marks ``shared`` with an explicit truth, + which every deep merge of those blocks needs before it pulls the + key's provider in. """ - if not seeds: - return [] + def flagged(flag: str) -> set[str]: + return { + str(key) + for block in blocks + for key, entry in block.items() + if isinstance(entry, Mapping) and is_explicit_truth(entry.get(flag)) + } - run_after_index: set[str] = set() - for role in all_roles: - try: - for target in load_run_after(role): - run_after_index.add(target) - except CombinedResolutionError: - continue + return { + key: {"enabled": True, "shared": True} + for key in flagged("enabled") & flagged("shared") + } - out: list[str] = [] - for seed in sorted(seeds): - if has_application_id(seed): - continue - if seed in run_after_index: - continue - out.append(seed) - return out + +def _own_blocks(name: str, variants: Mapping[str, list]) -> list[Mapping]: + """ + Args: + name: a role. + variants: parsed variants per role. + + Returns: + The role's ``meta/services.yml`` and each of its variants' + ``services`` blocks, the mappings among them. + """ + path = role_config_path(name) + blocks = [ + load_yaml_file(path) if path.exists() else {}, + *( + payload.get("services") + for payload in variants.get(name) or () + if isinstance(payload, Mapping) + ), + ] + return [block for block in blocks if isinstance(block, Mapping)] + + +def _nested_demands( + sources: Mapping[str, list[Mapping]], registry: Mapping +) -> list[tuple[str, Mapping]]: + """ + Args: + sources: services blocks per role. + registry: the service registry of the roles tree. + + Returns: + ``(provider, demand)`` for every nested ``services`` map a block + places on one of its keys, with the provider of that key. + """ + return [ + (provider_of(str(key), registry), entry["services"]) + for blocks in sources.values() + for block in blocks + for key, entry in block.items() + if isinstance(entry, Mapping) and isinstance(entry.get("services"), Mapping) + ] + + +def _union_services( + names: list[str], variants: Mapping[str, list] +) -> dict[str, dict[str, dict]]: + """ + Args: + names: every role. + variants: parsed variants per role. + + Returns: + ``{role: services map}`` built by :func:`_switched_on` from the + role's ``meta/services.yml``, each variant's ``services`` block, and + every nested ``services`` demand another role's block makes of it, + the three sources a round deep-merges its map from. + """ + sources = {name: _own_blocks(name, variants) for name in names} + registry = build_service_registry_from_roles_dir(roles_dir()) + for provider, demand in _nested_demands(sources, registry): + if provider in sources: + sources[provider].append(demand) + return {name: _switched_on(blocks) for name, blocks in sources.items()} def affected_roles(changed: Iterable[str]) -> list[str]: @@ -109,7 +185,7 @@ def affected_roles(changed: Iterable[str]) -> list[str]: f"Unknown role(s) passed via --changed-roles: {sorted(unknown)}" ) - non_modellable = _non_modellable_seeds(seeds, all_roles) + non_modellable = _non_modellable_seeds(seeds) if non_modellable: print( "non-modellable seed(s) for resolver: " @@ -118,17 +194,20 @@ def affected_roles(changed: Iterable[str]) -> list[str]: ) raise SystemExit(EXIT_NON_MODELLABLE_SEED) - resolver = CombinedResolver() - affected: set[str] = set(seeds) - - for role in all_roles: - if role in affected: - continue - prereqs = resolver.resolve(role) - if any(p in seeds for p in prereqs): - affected.add(role) - - return sorted(affected) + resolver = CombinedResolver( + services_overrides=_union_services( + all_roles, get_variants(roles_dir=str(roles_dir()), readonly=True) + ), + follow_run_after=False, + ) + return sorted( + seeds + | { + role + for role in all_roles + if role not in seeds and seeds.intersection(resolver.resolve(role)) + } + ) def _round_resolver( @@ -167,14 +246,19 @@ def _pinned( count: int, roles_path: Path, variants: Mapping[str, list], -) -> str: - """*role*, narrowed to the variants whose own closure reaches a seed. +) -> str | None: + """ + Args: + role: an affected role that is not a seed. + seeds: the changed roles. + count: the variants *role* runs in, at least one. + roles_path: the roles tree. + variants: parsed variants per role. - Returns the bare role id whenever the narrowing cannot be trusted: no - variant reaching a seed means the role is affected through an edge the - round closure does not model (a ``run_after`` hint, or a resolution the - variant merge refused), and verifying none of it is worse than verifying - all of it. + Returns: + ``None`` when no round deploys a seed; the bare role id when every + round does, or when a round's resolution fails, because the + narrowing cannot be trusted then; else the ``role#i,j`` token. """ try: hits = [ @@ -186,36 +270,44 @@ def _pinned( ] except CombinedResolutionError: return role - if not hits or len(hits) == count: + if not hits: + return None + if len(hits) == count: return role return role + VARIANT_SEPARATOR + ",".join(str(index) for index in hits) def affected_selection(changed: Iterable[str]) -> list[str]: - """:func:`affected_roles` as selection tokens, variant-narrowed. + """ + Args: + changed: the changed roles. - A seed role keeps every variant: its own files changed, so each of them - has to redeploy regardless of which providers it pulls. + Returns: + Every seed with all its variants, because its own files changed, and + every other affected role with only the variants whose round deploys + a seed; a role none of whose rounds does is left out. """ seeds: set[str] = {r.strip() for r in changed if r and r.strip()} affected = affected_roles(changed) variants = get_variants(roles_dir=str(roles_dir()), readonly=True) - counts = {role: len(variants.get(role) or ()) for role in affected} - return [ + tokens = ( role - if role in seeds or counts[role] < 2 - else _pinned(role, seeds, counts[role], roles_dir(), variants) + if role in seeds + else _pinned( + role, seeds, max(1, len(variants.get(role) or ())), roles_dir(), variants + ) for role in affected - ] + ) + return [token for token in tokens if token] def main() -> None: parser = argparse.ArgumentParser( description=( - "Print all roles whose transitive prerequisite closure " - "(run_after + dependencies + services) contains any of the " - "given seed roles, each narrowed to the variants that reach one. " - "Seed roles themselves are included, with every variant." + "Print every role with a variant whose round deploys one of the " + "given seed roles over dependencies or services, narrowed to " + "those variants. Seed roles themselves are included, with every " + "variant." ) ) parser.add_argument( diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index b1f7633b57..df6a103aaf 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -79,11 +79,11 @@ The two deploy-test workflows listed in the `Infrastructure tests` table of [wor 3. **Diff vs `origin/main`**, applied only when the `whitelist` input is empty: - **Skipped paths:** `.md` and `.rst` files and everything under `tests/` outside `roles//...` neither seed a role nor widen the deploy. - **No diff at all**, OR **any other changed path outside `roles//...`**, OR **only skipped paths**: no whitelist is set, so the full deploy across the workflow's scope runs. - - **All remaining changed paths under `roles//...`**: the changed roles become the seed set, and the whitelist is the transitive closure of those seeds expanded upwards over `run_after`, `dependencies`, and shared services. In other words, every role whose prerequisite set as defined by [combined resolver](../../../../cli/meta/roles/applications/resolution/combined/resolver.py) contains one of the seeds is included, together with the seeds themselves. + - **All remaining changed paths under `roles//...`**: the changed roles become the seed set, and the candidates are the transitive closure of those seeds expanded upwards over `dependencies` and shared services. In other words, every role whose prerequisite set as defined by [combined resolver](../../../../cli/meta/roles/applications/resolution/combined/resolver.py) contains one of the seeds is a candidate, together with the seeds themselves. The closure reads each role's services as the union of `meta/services.yml`, every `meta/variants.yml` entry, and every nested `services` demand another role makes of it, so it contains every round's closure. Each role in that closure is then narrowed to the variants that actually reach a seed: variant `i` of a role is kept only when round `i`'s closure — walked on the same variant-merged services maps [the matrix planner](../../../../cli/administration/deploy/development/inventory/planner.py) builds its rounds from, and therefore variant-aware at every generation of the chain — contains one of the seeds. A role whose variants do not all qualify enters the whitelist as a `role#0,2` selection token, so an image bump in a provider no longer redeploys the variants that switch that provider off. This applies to every auto-derived whitelist — the weekly update PRs, Dependabot, and any other diff-driven run — because they all resolve through this one path. -The reverse closure is fail-safe: any seed that is not modellable in the resolver (no `application_id` and not referenced by any role's `run_after`) MUST trigger a fall-back to a full deploy, as MUST any resolver runtime error. The closure MUST NOT silently shrink the deploy matrix on partial information. The variant narrowing follows the same rule: a role reached only through a `run_after` edge (which the round closure does not follow) keeps every variant, and so does a seed role itself, whose own files changed. +The reverse closure is fail-safe: any seed that is not modellable in the resolver (no `application_id`, so no round closure can contain it) MUST trigger a fall-back to a full deploy, as MUST any resolver runtime error. The closure MUST NOT silently shrink the deploy matrix on partial information. A seed role keeps every variant, because its own files changed. Every other role none of whose rounds contains a seed is left out of the whitelist, including one reached only through a `run_after` edge: `run_after` is an ordering hint the planner never follows, so no round of that role deploys the seed's change. The PR-scope short-circuits in [scope.sh](../../../../scripts/meta/resolve/pr/scope.sh) (documentation-only, agent-only) still apply at the entry layer. They skip the orchestrator entirely and are independent of the diff-driven whitelist resolution above. diff --git a/scripts/meta/resolve/diff/affected_roles.sh b/scripts/meta/resolve/diff/affected_roles.sh index 273869c759..356c1969c8 100755 --- a/scripts/meta/resolve/diff/affected_roles.sh +++ b/scripts/meta/resolve/diff/affected_roles.sh @@ -1,9 +1,5 @@ #!/usr/bin/env bash # -# Compute which roles are affected by the current branch's diff against -# `origin/main`, expanded transitively over run_after + dependencies + -# services edges via cli.meta.roles.applications.resolution.affected. -# # Output (single line on stdout): # __ALL__ full deploy needed. Emitted when: # * the diff is empty, OR diff --git a/tests/unit/python/cli/meta/roles/applications/resolution/affected/test_main.py b/tests/unit/python/cli/meta/roles/applications/resolution/affected/test_main.py index 0b8acce987..711674753b 100644 --- a/tests/unit/python/cli/meta/roles/applications/resolution/affected/test_main.py +++ b/tests/unit/python/cli/meta/roles/applications/resolution/affected/test_main.py @@ -75,7 +75,7 @@ class TestAffected(unittest.TestCase): ["leaf"], ) - def test_run_after_consumer_is_included(self) -> None: + def test_a_run_after_consumer_is_not_affected(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) _mk_app_role(root, "leaf", "leaf") @@ -83,10 +83,8 @@ class TestAffected(unittest.TestCase): _write_run_after(root, "consumer", ["leaf"]) with patch.object(repo_paths, "PROJECT_ROOT", root): - self.assertEqual( - affected_main.affected_roles(["leaf"]), - ["consumer", "leaf"], - ) + self.assertEqual(affected_main.affected_roles(["leaf"]), ["leaf"]) + self.assertEqual(affected_main.affected_selection(["leaf"]), ["leaf"]) def test_dependencies_consumer_is_included_transitively(self) -> None: with tempfile.TemporaryDirectory() as td: @@ -218,6 +216,90 @@ class TestAffected(unittest.TestCase): got = affected_main.affected_selection(["web-app-keycloak"]) self.assertIn("web-app-consumer#0,1", got) + def test_a_role_no_round_of_which_deploys_the_seed_is_left_out(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + for role in ("web-app-n8n", "web-app-matrix", "web-app-discourse"): + _mk_app_role(root, role, role) + off = {"enabled": False, "shared": False} + on = {"enabled": True, "shared": True} + dynamic = "{{ 'web-app-n8n' in group_names }}" + dump_yaml( + root / "roles" / "web-app-matrix" / ROLE_FILE_META_SERVICES, + {"matrix": {}, "n8n": {"enabled": dynamic, "shared": dynamic}}, + ) + dump_yaml( + root / "roles" / "web-app-matrix" / ROLE_FILE_META_VARIANTS, + [{"services": {"n8n": off}}, {"services": {"n8n": on}}], + ) + dump_yaml( + root / "roles" / "web-app-discourse" / ROLE_FILE_META_SERVICES, + {"discourse": {}, "matrix": on}, + ) + dump_yaml( + root / "roles" / "web-app-discourse" / ROLE_FILE_META_VARIANTS, + [{}, {"services": {"matrix": off}}], + ) + + with patch.object(repo_paths, "PROJECT_ROOT", root): + self.assertIn( + "web-app-discourse", affected_main.affected_roles(["web-app-n8n"]) + ) + got = affected_main.affected_selection(["web-app-n8n"]) + self.assertEqual(got, ["web-app-matrix#1", "web-app-n8n"]) + + def test_a_service_key_a_variant_switches_on_reaches_the_seed(self) -> None: + shapes = { + "only the variant declares it": ( + {"moodle": {}}, + {"enabled": True, "shared": True}, + ), + "disk shares it, the variant enables it": ( + {"moodle": {}, "lam": {"shared": True}}, + {"enabled": True}, + ), + } + for label, (disk, variant) in shapes.items(): + with self.subTest(label), tempfile.TemporaryDirectory() as td: + root = Path(td) + _mk_app_role(root, "web-app-lam", "web-app-lam") + _mk_app_role(root, "web-app-moodle", "web-app-moodle") + dump_yaml( + root / "roles" / "web-app-moodle" / ROLE_FILE_META_SERVICES, disk + ) + dump_yaml( + root / "roles" / "web-app-moodle" / ROLE_FILE_META_VARIANTS, + [{"services": {"lam": variant}}, {}], + ) + + with patch.object(repo_paths, "PROJECT_ROOT", root): + got = affected_main.affected_selection(["web-app-lam"]) + self.assertEqual(got, ["web-app-lam", "web-app-moodle#0"]) + + def test_a_nested_services_demand_on_a_provider_reaches_the_seed(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + for role in ("web-app-keycloak", "web-app-matomo", "web-app-consumer"): + _mk_app_role(root, role, role) + off = {"enabled": False, "shared": False} + on = {"enabled": True, "shared": True} + dump_yaml( + root / "roles" / "web-app-matomo" / ROLE_FILE_META_SERVICES, + {"matomo": {"shared": True}, "sso": off}, + ) + dump_yaml( + root / "roles" / "web-app-consumer" / ROLE_FILE_META_SERVICES, + {"consumer": {}, "matomo": on}, + ) + dump_yaml( + root / "roles" / "web-app-consumer" / ROLE_FILE_META_VARIANTS, + [{"services": {"matomo": {**on, "services": {"sso": on}}}}, {}], + ) + + with patch.object(repo_paths, "PROJECT_ROOT", root): + got = affected_main.affected_selection(["web-app-keycloak"]) + self.assertIn("web-app-consumer#0", got) + def test_a_seed_keeps_every_variant_of_its_own_role(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) @@ -253,7 +335,7 @@ class TestAffected(unittest.TestCase): affected_main.EXIT_NON_MODELLABLE_SEED, ) - def test_non_app_seed_reachable_via_run_after_is_modellable(self) -> None: + def test_a_non_app_seed_behind_run_after_is_still_non_modellable(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) _mk_non_app_role(root, "sys-helper") @@ -261,16 +343,19 @@ class TestAffected(unittest.TestCase): _write_run_after(root, "consumer", ["sys-helper"]) with patch.object(repo_paths, "PROJECT_ROOT", root): - got = affected_main.affected_roles(["sys-helper"]) - self.assertIn("sys-helper", got) - self.assertIn("consumer", got) + with self.assertRaises(SystemExit) as ctx: + affected_main.affected_roles(["sys-helper"]) + self.assertEqual( + ctx.exception.code, + affected_main.EXIT_NON_MODELLABLE_SEED, + ) def test_main_prints_space_separated_sorted(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) _mk_app_role(root, "leaf", "leaf") _mk_app_role(root, "consumer", "consumer") - _write_run_after(root, "consumer", ["leaf"]) + _write_dependencies(root, "consumer", ["leaf"]) with patch.object(repo_paths, "PROJECT_ROOT", root): buf = io.StringIO()