diff --git a/cli/meta/ci/variant_split/compare.py b/cli/meta/ci/variant_split/compare.py index 50f16140ae..aff350907a 100644 --- a/cli/meta/ci/variant_split/compare.py +++ b/cli/meta/ci/variant_split/compare.py @@ -159,7 +159,7 @@ def pin_check(before: Mapping[str, Any], after: Mapping[str, Any]) -> dict[str, p for p in new_pins if not isinstance(p["reciprocal"], int) - or (p["target"] != "reciprocal" and int(p["target"]) != p["reciprocal"]) + or (p["target"].isdigit() and int(p["target"]) != p["reciprocal"]) ] def faults(snap: Mapping[str, Any], field: str) -> set[str]: diff --git a/cli/meta/ci/variant_split/rounds.py b/cli/meta/ci/variant_split/rounds.py index 21880448e0..d23701ee70 100644 --- a/cli/meta/ci/variant_split/rounds.py +++ b/cli/meta/ci/variant_split/rounds.py @@ -19,8 +19,8 @@ from utils.roles.applications.topics import overridden_providers, provider_of from utils.roles.applications.variant_pins import ( PIN, VariantPinError, - _reciprocal_index, _service_key_lines, + intended_index, ) from utils.roles.mapping import ( ROLE_FILE_META_MCP, @@ -131,7 +131,7 @@ def pinned_keys(role: str, roles_dir: str) -> dict[int, dict[str, tuple[str, str def pin_findings( role: str, *, roles_dir: str, variants_per_app: Mapping[str, list] ) -> list[dict[str, Any]]: - """Every pin *role* declares, with the variant that reciprocates it. + """Every pin *role* declares, with the variant its target is written to select. Args: role: the carrier role. @@ -142,9 +142,10 @@ def pin_findings( for index, pins in sorted(pinned_keys(role, roles_dir).items()): for partner, (target, key) in sorted(pins.items()): try: - reciprocal: int | str = _reciprocal_index( + reciprocal: int | str = intended_index( partner, role, + target, roles_dir=roles_dir, variants_per_app=variants_per_app, ) diff --git a/docs/contributing/actions/testing/suppression.md b/docs/contributing/actions/testing/suppression.md index d43c429589..d46aae8437 100644 --- a/docs/contributing/actions/testing/suppression.md +++ b/docs/contributing/actions/testing/suppression.md @@ -153,6 +153,16 @@ Some Python files use Ruff-compatible uppercase `# noqa` codes. Ruff and related | `F401` | Imported but unused | Re-export modules or import-probe tests where import success is the assertion. | | `SLF001` | Private member access | Test-only introspection of parser or object internals when the public surface does not expose the needed state. | +## Addon-Carrier Variant 🧩 + +[test_addons_variant_pinning.py](../../../../tests/lint/ansible/services/test_addons_variant_pinning.py) makes every variant from 2 on alias variant 1's static-off addon set. One variant per role MAY keep the static addons on instead, for example when they move off variant 0 into their own round to fit the job budget. It carries `# nocheck: addons-variant-pinning ` on its own `addons:` line, the only line the lint reads the marker from, and is then exempt from that rule: + +```yaml + addons: {} # nocheck: addons-variant-pinning v15 carries the static addons moved off v0 for the job budget +``` + +The reason MUST be at least `MIN_REASON_CHARS` (10) characters long. The marker fails on variant 0 or 1, because variant 1 owns the static-off set; on a second marked variant in the same role; while variant 0 still installs the static addons, because variant 0 then carries them already; and on a variant that pins every static addon off, because such a carrier carries nothing. The per-addon opt-out in the head of `meta/addons/.yml` is a separate placement of the same key. + ## Adding a new rule 🆕 1. Pick a kebab-case `` identifier. diff --git a/docs/contributing/artefact/files/role/variants.md b/docs/contributing/artefact/files/role/variants.md index 2803c84c92..f6653341f1 100644 --- a/docs/contributing/artefact/files/role/variants.md +++ b/docs/contributing/artefact/files/role/variants.md @@ -49,6 +49,14 @@ The token follows the `role#variant` form used by the priority slots. `#reciproc # variant-pin: web-app-nextcloud#reciprocal ``` +`#without-` resolves to the partner's one variant whose `services..enabled` is the literal `false`. Use it to cut a transitive chain the carrier does not need, where the partner never gates on the carrier and `#reciprocal` therefore has nothing to find. It needs no reciprocity, only exactly one matching variant; none or several raise `VariantPinError`. Unlike a bare index it keeps working when the partner gains a variant: + +```yaml + # variant-pin: web-svc-mirror#without-prometheus + tor: + enabled: true +``` + The marker is a comment, so it never reaches the merged services map or `host_vars`. It applies only to the variant entry it stands in; the same role's other variants are unaffected. A primary app keeps the index the sweep assigned it and no pin overrides it. A pin is in force only while the role carrying it is part of the round's include and runs the variant the marker stands in. A pin in a role the round does not deploy changes nothing. The round starts every role on its clamped index and recomputes the include and the pins in force until the assignment no longer changes; pins that never settle raise `VariantPinError`. [test_variant_pin_fixed_point.py](../../../../../tests/integration/roles/meta/variants/test_variant_pin_fixed_point.py) settles every round the matrix plans (each role as the only primary, in each of its variants) and fails when a round raises `VariantPinError`, or when a pin in force stands above a service entry the carrier runs with `enabled: false` in that round. Place a pin only above an entry the variant keeps enabled: the guide host `docs` stays on for the primary app alone, so a pin above `docs` fails the guard in any round that pulls the role in as a dependency running that variant. @@ -83,7 +91,7 @@ flowchart LR outside -.->|pin: not in force| partner ``` -Two roles pinning the same partner to different variants in one round raises `VariantPinConflictError` before an inventory is written. An index that no longer points at the reciprocating variant is caught by [test_variant_pins.py](../../../../../tests/integration/roles/meta/variants/test_variant_pins.py); `#reciprocal` needs exactly one candidate variant on the partner or it raises. +Two roles pinning the same partner to different variants in one round raises `VariantPinConflictError` before an inventory is written. An index that no longer points at the reciprocating variant is caught by [test_variant_pins.py](../../../../../tests/integration/roles/meta/variants/test_variant_pins.py); `#reciprocal` and `#without-` each need exactly one candidate variant on the partner or they raise. ## Credentials Interaction 🔐 diff --git a/roles/web-app-nextcloud/meta/variants.yml b/roles/web-app-nextcloud/meta/variants.yml index bb99356dc2..ca9e6bb659 100644 --- a/roles/web-app-nextcloud/meta/variants.yml +++ b/roles/web-app-nextcloud/meta/variants.yml @@ -1493,8 +1493,8 @@ enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true sso: - enabled: true - shared: true + enabled: false + shared: false coturn: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -1502,8 +1502,8 @@ enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true ldap: - enabled: true - shared: true + enabled: false + shared: false dashboard: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -1572,6 +1572,7 @@ peertube: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true + # variant-pin: web-svc-mirror#without-prometheus tor: enabled: true hermes: @@ -1580,3 +1581,4 @@ openclaw: enabled: false shared: false + addons: {} # nocheck: addons-variant-pinning v15 carries the static addons moved off v0 for the job budget diff --git a/tests/integration/roles/meta/variants/test_variant_pin_required.py b/tests/integration/roles/meta/variants/test_variant_pin_required.py index ddf9dbdefb..626d149c09 100644 --- a/tests/integration/roles/meta/variants/test_variant_pin_required.py +++ b/tests/integration/roles/meta/variants/test_variant_pin_required.py @@ -35,10 +35,11 @@ from __future__ import annotations import functools import re import unittest +from unittest.mock import patch from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any -from utils.roles.applications.variant_pins import pins_of +from utils.roles.applications.variant_pins import RECIPROCAL, pins_of from utils.roles.applications.variants import ( _resolve_round_include, services_overrides_for_round, @@ -120,7 +121,8 @@ def _exempt(role: str) -> bool: def _pins_partner(role: str, index: int, partner: str) -> bool: - return partner in pins_of(role, roles_dir=str(ROLES_DIR)).get(index, {}) + target = pins_of(role, roles_dir=str(ROLES_DIR)).get(index, {}).get(partner) + return target is not None and (target.isdigit() or target == RECIPROCAL) def mutual_pairs() -> list[tuple[str, str, str, str]]: @@ -182,5 +184,18 @@ class TestVariantPinRequired(unittest.TestCase): ) +class TestPinsPartner(unittest.TestCase): + def _pins(self, target: str) -> bool: + with patch(f"{__name__}.pins_of", return_value={0: {"web-app-b": target}}): + return _pins_partner("web-app-a", 0, "web-app-b") + + def test_an_index_or_reciprocal_pin_states_the_pairing(self) -> None: + self.assertTrue(self._pins("3")) + self.assertTrue(self._pins(RECIPROCAL)) + + def test_negative_control_a_without_pin_does_not_state_the_pairing(self) -> None: + self.assertFalse(self._pins("without-prometheus")) + + if __name__ == "__main__": unittest.main() diff --git a/tests/integration/roles/meta/variants/test_variant_pins.py b/tests/integration/roles/meta/variants/test_variant_pins.py index 673bd6527b..23bdac63c8 100644 --- a/tests/integration/roles/meta/variants/test_variant_pins.py +++ b/tests/integration/roles/meta/variants/test_variant_pins.py @@ -13,8 +13,9 @@ and the inventory is written without complaint. This guard checks the index still means what it was written to mean, by comparing it against the variant ``#reciprocal`` would have found. A pin -written as ``#reciprocal`` carries no index, so for those the guard only -confirms the symbolic form resolves to exactly one variant. +written as ``#reciprocal`` or ``#without-`` carries no index, so for +those the guard only confirms the symbolic form resolves to exactly one +variant; ``#without-`` needs no reciprocity. """ from __future__ import annotations @@ -25,7 +26,7 @@ from utils.cache.applications import get_variants from utils.roles.applications.variant_pins import ( RECIPROCAL, VariantPinError, - _reciprocal_index, + intended_index, pins_of, ) @@ -49,13 +50,17 @@ class TestVariantPins(unittest.TestCase): findings = [] for role, index, partner, target in _pinning_roles(): try: - reciprocal = _reciprocal_index( - partner, role, roles_dir=str(ROLES_DIR), variants_per_app=variants + reciprocal = intended_index( + partner, + role, + target, + roles_dir=str(ROLES_DIR), + variants_per_app=variants, ) except VariantPinError as exc: findings.append(f" - {role}#{index} -> {partner}#{target}: {exc}") continue - if target != RECIPROCAL and int(target) != reciprocal: + if target.isdigit() and int(target) != reciprocal: findings.append( f" - {role}#{index} pins {partner}#{target}, but the variant " f"that switches {role} back on is {partner}#{reciprocal}" @@ -68,7 +73,7 @@ class TestVariantPins(unittest.TestCase): "that leaves the pairing dark:\n" + "\n".join(findings) + "\n\nPoint the pin at the reciprocating variant, or write it as " - "'#reciprocal' so it follows the partner automatically.", + f"'#{RECIPROCAL}' so it follows the partner automatically.", ) def test_the_scan_reads_the_marker(self) -> None: diff --git a/tests/lint/ansible/services/test_addons_variant_pinning.py b/tests/lint/ansible/services/test_addons_variant_pinning.py index d9a40a7139..d50097646f 100644 --- a/tests/lint/ansible/services/test_addons_variant_pinning.py +++ b/tests/lint/ansible/services/test_addons_variant_pinning.py @@ -90,6 +90,126 @@ def _variants(role_dir: Path) -> list: return data if isinstance(data, list) else [] +def _pinned_enabled(variant, addon_id: str): + """ + Args: + variant: one entry of the variant list. + addon_id: the addon to look up. + + Returns: + The ``enabled`` value the variant pins for *addon_id*, None when it + pins none. + """ + entry = _pinned_addons(variant).get(addon_id) + return entry.get("enabled") if isinstance(entry, Mapping) else None + + +def _addons_line_reason(lines: list[str]) -> str | None: + """ + Args: + lines: the lines of one variant entry, its ``- `` line first. + + Returns: + The reason the marker on the entry's own ``addons:`` line states, + empty when it states none, None when that line carries no marker. + """ + from utils.annotations.suppress import marker_reason + + own = next( + ( + line + for line in lines + if line[:2] in ("- ", " ") and line[2:].startswith("addons:") + ), + None, + ) + return None if own is None else marker_reason(own, _RULE) + + +def _addon_carriers( + text: str, variants: list, required: list[str] +) -> tuple[set[int], list[str]]: + """ + Args: + text: the role's ``meta/variants.yml``. + variants: the parsed variant list of that file. + required: the ids of the role's statically enabled addons. + + Returns: + The indices of the variants whose own ``addons:`` line carries + ``# nocheck: addons-variant-pinning``, and one finding per marker on + variant 0 or 1, per reason shorter than ``MIN_REASON_CHARS``, per + carrier while variant 0 still installs the static addons, per carrier + that leaves none of them on, and for more than one marked variant. + """ + from cli.administration.inventory.validate.open_subtrees import ( + MIN_REASON_CHARS, + ) + + lines = text.splitlines() + starts = [n for n, line in enumerate(lines) if line.startswith("- ")] + baseline_off = all( + _pinned_enabled(variants[0] if variants else {}, a) is False for a in required + ) + carriers: set[int] = set() + findings: list[str] = [] + for index, (start, end) in enumerate( + zip(starts, [*starts[1:], len(lines)], strict=True) + ): + reason = _addons_line_reason(lines[start:end]) + if reason is None: + continue + carriers.add(index) + variant = variants[index] if index < len(variants) else {} + if index < 2: + findings.append( + f"variant {index} carries the marker, but variant 1 owns the " + "static-off set" + ) + if len(reason) < MIN_REASON_CHARS: + findings.append( + f"variant {index} carries the marker without a reason of at " + f"least {MIN_REASON_CHARS} characters" + ) + if not baseline_off: + findings.append( + f"variant {index} carries the marker, but v0 already carries the " + "static addons" + ) + if all(_pinned_enabled(variant, a) is False for a in required): + findings.append( + f"variant {index}: carrier marker on a variant that carries nothing" + ) + if len(carriers) > 1: + findings.append( + f"variants {sorted(carriers)} carry the marker; a role has at most " + "one addon-carrier variant" + ) + return carriers, findings + + +def _uncarried_static_addons( + variants: list, required: list[str], carriers: set[int] +) -> list[tuple[int, str, object]]: + """ + Args: + variants: the role's parsed variant list. + required: the ids of the statically enabled addons. + carriers: the addon-carrier variants, exempt from the check. + + Returns: + ``(variant index, addon id, pinned value)`` per variant from 2 on + that does not pin a statically enabled addon to ``false``. + """ + return [ + (index, addon_id, value) + for index in range(2, len(variants)) + if index not in carriers + for addon_id in required + if (value := _pinned_enabled(variants[index], addon_id)) is not False + ] + + def _pinned_addons(variant) -> Mapping: """Return a variant entry's ``addons`` map, empty when it declares none. @@ -156,17 +276,16 @@ class TestAddonsVariantPinning(unittest.TestCase): if len(variants) < 3: continue required = sorted(f.stem for f in addon_files if _base_enabled(f) is True) - for index in range(2, len(variants)): - pinned = _pinned_addons(variants[index]) - for addon_id in required: - entry = pinned.get(addon_id) - value = entry.get("enabled") if isinstance(entry, Mapping) else None - if value is False: - continue - findings.append( - f"- {role}/{ROLE_FILE_META_VARIANTS}: variant {index} pins " - f"{addon_id!r} as {value!r}, variant 1 disables it" - ) + carriers, _ = _addon_carriers( + read_text(str(role_dir / ROLE_FILE_META_VARIANTS)), variants, required + ) + findings.extend( + f"- {role}/{ROLE_FILE_META_VARIANTS}: variant {index} pins " + f"{addon_id!r} as {value!r}, variant 1 disables it" + for index, addon_id, value in _uncarried_static_addons( + variants, required, carriers + ) + ) if not findings: return @@ -181,9 +300,164 @@ class TestAddonsVariantPinning(unittest.TestCase): " enabled: false\n" " # variant 2 and later\n" " addons: *addons_static_off\n\n" + "\n".join(findings) + "\n\n" - f"Per-addon opt-out: `# nocheck: {_RULE}` with a reason." + f"Per-addon opt-out: `# nocheck: {_RULE}` with a reason. The role's " + f"one addon-carrier variant keeps them on with `# nocheck: {_RULE} " + "` on its `addons:` line." ) + def test_every_addon_carrier_marker_is_valid(self) -> None: + findings: list[str] = [] + for role, addon_files in sorted(self._roles().items()): + role_dir = PROJECT_ROOT / "roles" / role + path = role_dir / ROLE_FILE_META_VARIANTS + if not path.is_file(): + continue + required = sorted(f.stem for f in addon_files if _base_enabled(f) is True) + _, problems = _addon_carriers( + read_text(str(path)), _variants(role_dir), required + ) + findings.extend( + f"- {role}/{ROLE_FILE_META_VARIANTS}: {p}" for p in problems + ) + + if not findings: + return + + self.fail( + f"`# nocheck: {_RULE}` on a variant's own `addons:` line names the " + "role's one addon-carrier variant, which keeps the static addons on. " + "It needs a reason, marks one variant only and never variant 0 or 1, " + "requires variant 0 to keep the static addons off, and must leave at " + "least one of them on:\n\n" + "\n".join(findings) + ) + + def _carriers( + self, marked: Mapping[int, str], variants: list + ) -> tuple[set[int], list[str]]: + return _addon_carriers( + "".join(f"- addons: {{}}{marked.get(index, '')}\n" for index in range(5)), + variants, + ["calendar"], + ) + + def _five_variants(self) -> list: + off = {"calendar": {"enabled": False}} + return [ + {"addons": off}, + {"addons": off}, + {"addons": off}, + {"addons": {}}, + {"addons": off}, + ] + + def test_a_marked_carrier_keeps_the_static_addons(self) -> None: + carriers, problems = self._carriers( + {3: f" # nocheck: {_RULE} budget split"}, self._five_variants() + ) + self.assertEqual((carriers, problems), ({3}, [])) + self.assertEqual( + _uncarried_static_addons(self._five_variants(), ["calendar"], carriers), + [], + ) + + def test_negative_control_an_unmarked_carrier_fails(self) -> None: + carriers, _ = self._carriers({}, self._five_variants()) + self.assertEqual( + _uncarried_static_addons(self._five_variants(), ["calendar"], carriers), + [(3, "calendar", None)], + ) + + def test_negative_control_a_second_marked_variant_fails(self) -> None: + variants = self._five_variants() + variants[4] = {"addons": {}} + _, problems = self._carriers( + { + 3: f" # nocheck: {_RULE} budget split", + 4: f" # nocheck: {_RULE} another split", + }, + variants, + ) + self.assertEqual( + problems, + [ + ( + "variants [3, 4] carry the marker; a role has at most one " + "addon-carrier variant" + ) + ], + ) + + def test_negative_control_a_marker_without_a_reason_fails(self) -> None: + _, problems = self._carriers({3: f" # nocheck: {_RULE}"}, self._five_variants()) + self.assertEqual( + problems, + ["variant 3 carries the marker without a reason of at least 10 characters"], + ) + + def test_negative_control_a_too_short_reason_fails(self) -> None: + _, problems = self._carriers( + {3: f" # nocheck: {_RULE} split"}, self._five_variants() + ) + self.assertEqual( + problems, + ["variant 3 carries the marker without a reason of at least 10 characters"], + ) + + def test_negative_control_a_marker_on_variant_1_fails(self) -> None: + variants = self._five_variants() + variants[1] = {"addons": {}} + _, problems = self._carriers({1: f" # nocheck: {_RULE} owns the set"}, variants) + self.assertEqual( + problems, + ["variant 1 carries the marker, but variant 1 owns the static-off set"], + ) + + def test_negative_control_a_carrier_beside_a_static_on_baseline_fails( + self, + ) -> None: + variants = self._five_variants()[:3] + variants[0] = {} + variants[2] = {"addons": {}} + _, problems = self._carriers({2: f" # nocheck: {_RULE} budget split"}, variants) + self.assertEqual( + problems, + ["variant 2 carries the marker, but v0 already carries the static addons"], + ) + + def test_negative_control_a_stale_carrier_marker_fails(self) -> None: + _, problems = self._carriers( + {4: f" # nocheck: {_RULE} budget split"}, self._five_variants() + ) + self.assertEqual( + problems, + ["variant 4: carrier marker on a variant that carries nothing"], + ) + + def test_negative_control_a_marker_off_the_addons_line_counts_nothing( + self, + ) -> None: + text = ( + "- addons: {}\n- addons: {}\n- addons: {}\n" + f"# Variant 3: heading # nocheck: {_RULE} budget split\n" + "- services:\n" + f" tor: # nocheck: {_RULE} budget split\n" + " enabled: true\n" + " addons: {}\n" + ) + variants = self._five_variants()[:4] + self.assertEqual(_addon_carriers(text, variants, ["calendar"]), (set(), [])) + + def test_a_marker_on_a_block_variants_addons_line_counts(self) -> None: + text = ( + "- addons: {}\n- addons: {}\n- addons: {}\n" + "- services:\n" + " tor:\n" + " enabled: true\n" + f" addons: {{}} # nocheck: {_RULE} budget split\n" + ) + variants = self._five_variants()[:4] + self.assertEqual(_addon_carriers(text, variants, ["calendar"]), ({3}, [])) + def test_dynamic_addons_are_never_pinned_in_a_variant(self) -> None: findings: list[str] = [] for role, addon_files in sorted(self._roles().items()): diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_compare.py b/tests/unit/python/cli/meta/ci/variant_split/test_compare.py index d230d72a51..b8d875e766 100644 --- a/tests/unit/python/cli/meta/ci/variant_split/test_compare.py +++ b/tests/unit/python/cli/meta/ci/variant_split/test_compare.py @@ -137,6 +137,19 @@ class TestVerdict(unittest.TestCase): ) self.assertEqual(result["pins"]["unreciprocated"], []) + def test_a_resolving_without_pin_passes(self) -> None: + pin = { + "carrier": "app#3", + "partner": "pa", + "target": "without-a", + "key": "a", + "reciprocal": 0, + } + result = compare.verdict( + _before(), _after(pin=pin), old=["app#0"], split=["app#0", "app#3"] + ) + self.assertEqual(result["pins"]["unreciprocated"], []) + def test_the_render_names_the_verdict(self) -> None: text = compare.render( compare.verdict( diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py b/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py index db5eb45c58..1f2d334477 100644 --- a/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py +++ b/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py @@ -76,6 +76,15 @@ class TestPins(unittest.TestCase): ) self.assertTrue(str(finding["reciprocal"]).startswith("error:")) + def test_a_without_pin_names_the_variant_switching_the_key_off(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + [finding] = rounds.pin_findings( + "web-app-a", + roles_dir=_tree(tmp, "without-a", gate=False), + variants_per_app=VARIANTS, + ) + self.assertEqual((finding["target"], finding["reciprocal"]), ("without-a", 0)) + class TestToken(unittest.TestCase): def test_a_whole_role_row_is_variant_0(self) -> None: diff --git a/tests/unit/python/utils/roles/applications/test_variant_pins.py b/tests/unit/python/utils/roles/applications/test_variant_pins.py index 7620f24113..86b064d76a 100644 --- a/tests/unit/python/utils/roles/applications/test_variant_pins.py +++ b/tests/unit/python/utils/roles/applications/test_variant_pins.py @@ -180,6 +180,57 @@ class VariantPinTestCase(unittest.TestCase): {"web-app-nextcloud": 3}, ) + def switch_matomo_off(self, *indices: int) -> None: + for index in indices: + self.variants["web-app-nextcloud"][index]["services"]["matomo"] = { + "enabled": False + } + + def test_a_without_target_keeps_dashes_and_underscores(self) -> None: + self.pin_openproject("without-mail_relay-v2") + self.assertEqual( + pins_of("web-app-openproject", roles_dir=self.roles_dir), + {1: {"web-app-nextcloud": "without-mail_relay-v2"}}, + ) + + def test_without_finds_the_one_variant_switching_the_key_off(self) -> None: + self.pin_openproject("without-matomo") + self.switch_matomo_off(2) + self.assertEqual( + self.resolve({"web-app-openproject": 1}), {"web-app-nextcloud": 2} + ) + + def test_without_and_no_candidate_raises(self) -> None: + self.pin_openproject("without-matomo") + with self.assertRaises(VariantPinError) as caught: + self.resolve({"web-app-openproject": 1}) + self.assertIn( + "web-app-nextcloud pins services.matomo to literal false in 0 variants " + "(none)", + str(caught.exception), + ) + + def test_without_and_two_candidates_raises(self) -> None: + self.pin_openproject("without-matomo") + self.switch_matomo_off(1, 2) + with self.assertRaises(VariantPinError) as caught: + self.resolve({"web-app-openproject": 1}) + self.assertIn( + "web-app-nextcloud pins services.matomo to literal false in 2 variants " + "([1, 2])", + str(caught.exception), + ) + + def test_a_without_pin_conflicting_with_an_index_pin_raises(self) -> None: + self.pin_openproject("without-matomo") + self.switch_matomo_off(2) + self.pin_gitlab("3") + with self.assertRaises(VariantPinConflictError) as caught: + self.resolve({"web-app-openproject": 1, "web-app-gitlab": 0}) + self.assertIn( + "cannot deploy web-app-nextcloud in two variants", str(caught.exception) + ) + def test_an_index_pin_and_a_reciprocal_pin_agreeing_do_not_conflict(self) -> None: self.pin_openproject("reciprocal") self.pin_gitlab("3") diff --git a/utils/roles/applications/variant_pins.py b/utils/roles/applications/variant_pins.py index 43eaef1fb5..31a0da7a27 100644 --- a/utils/roles/applications/variant_pins.py +++ b/utils/roles/applications/variant_pins.py @@ -1,4 +1,4 @@ -"""Variant pins: ``# variant-pin: #``. +"""Variant pins: ``# variant-pin: #>``. A matrix round hands every role the round index, clamping to variant 0 when the role has fewer entries (:func:`services_overrides_for_round`). A pairing @@ -40,12 +40,14 @@ from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_VARIANTS PIN = re.compile( - r"#\s*variant-pin:\s*([a-z0-9][a-z0-9-]*)\s*#\s*(\d+|reciprocal)\b", + r"#\s*variant-pin:\s*([a-z0-9][a-z0-9-]*)\s*#\s*" + r"(\d+|reciprocal|without-[a-z0-9_-]+)\b", re.IGNORECASE, ) _GROUP_MEMBERSHIP = re.compile(r"'([a-z0-9][a-z0-9-]*)'\s+in\s+group_names") RECIPROCAL = "reciprocal" +WITHOUT = "without-" class VariantPinError(ValueError): @@ -115,6 +117,18 @@ def _reciprocal_key(partner: str, role: str, *, roles_dir: str) -> str | None: return None +def _variants_setting( + partner: str, key: str, enabled: bool, *, variants_per_app: Mapping[str, list] +) -> list[int]: + return [ + index + for index, variant in enumerate(variants_per_app.get(partner) or []) + if isinstance(variant, Mapping) + and isinstance((variant.get("services") or {}).get(key), Mapping) + and (variant["services"][key]).get("enabled") is enabled + ] + + def _reciprocal_index( partner: str, role: str, @@ -128,13 +142,7 @@ def _reciprocal_index( f"{role} pins {partner}#reciprocal, but {partner}'s " f"{ROLE_FILE_META_SERVICES} declares no service gating on {role}" ) - hits = [ - index - for index, variant in enumerate(variants_per_app.get(partner) or []) - if isinstance(variant, Mapping) - and isinstance((variant.get("services") or {}).get(key), Mapping) - and (variant["services"][key]).get("enabled") is True - ] + hits = _variants_setting(partner, key, True, variants_per_app=variants_per_app) if len(hits) != 1: raise VariantPinError( f"{role} pins {partner}#reciprocal, but {partner} pins " @@ -144,6 +152,54 @@ def _reciprocal_index( return hits[0] +def _without_index( + partner: str, key: str, role: str, *, variants_per_app: Mapping[str, list] +) -> int: + hits = _variants_setting(partner, key, False, variants_per_app=variants_per_app) + if len(hits) != 1: + raise VariantPinError( + f"{role} pins {partner}#{WITHOUT}{key}, but {partner} pins " + f"services.{key} to literal false in {len(hits)} variants " + f"({hits or 'none'}); {WITHOUT} needs exactly one" + ) + return hits[0] + + +def intended_index( + partner: str, + role: str, + target: str, + *, + roles_dir: str, + variants_per_app: Mapping[str, list], +) -> int: + """ + Args: + partner: the pinned role. + role: the carrier role. + target: the pin target, an index, ``reciprocal`` or ``without-``. + roles_dir: the roles tree the partner's services are read from. + variants_per_app: parsed variants per role. + + Returns: + The single variant ``without-`` resolves to; for every other + target, the variant that switches *role* back on. + + Raises: + VariantPinError: the target resolves to no variant or to several. + """ + if target.startswith(WITHOUT): + return _without_index( + partner, + target.removeprefix(WITHOUT), + role, + variants_per_app=variants_per_app, + ) + return _reciprocal_index( + partner, role, roles_dir=roles_dir, variants_per_app=variants_per_app + ) + + def resolve_pins( active_index: Mapping[str, int], *, @@ -171,20 +227,21 @@ def resolve_pins( pins_of(role, roles_dir=roles_dir).get(index, {}).items() ): count = len(variants_per_app.get(partner) or []) - if target == RECIPROCAL: - wanted = _reciprocal_index( - partner, - role, - roles_dir=roles_dir, - variants_per_app=variants_per_app, - ) - else: + if target.isdigit(): wanted = int(target) if not 0 <= wanted < count: raise VariantPinError( f"{role}#{index} pins {partner}#{wanted}, but {partner} " f"declares {count} variant(s)" ) + else: + wanted = intended_index( + partner, + role, + target, + roles_dir=roles_dir, + variants_per_app=variants_per_app, + ) if partner in resolved and resolved[partner] != wanted: raise VariantPinConflictError( f"{source[partner]} pins {partner}#{resolved[partner]} while "