From f1635e6a592a2f7ca019a97a70a5af07b6b5ddf4 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 1 Sep 2026 21:08:08 +0200 Subject: [PATCH] feat(variants): let a variant dictate the config of the providers it pulls in A round deploys a provider once, so the role that pulls it in is the only place that can say how lean it has to be. A variant entry may now carry any application config topic under a service it depends on: a mapping deep-merges, so naming one key changes that key alone, and null empties the topic. Empty was the case that needed a marker of its own, because merging an empty mapping is a no-op and would leave exactly the services the round was trying to shed. The topic vocabulary and the merge semantics live in utils.roles.applications.topics, which is also where resources.py now gets them rather than spelling the same null-or-merge out a second time. Collecting who demands what stays in the inventory tree, refuses two roles demanding different values for one provider in the same round, and skips a role's own entity entry so the existing services..users declarations are not read as overrides. The CI set-cover learns the same fact. Its greedy cover retires a role's variant-0 row when an earlier row of another role embeds it, on the stated premise that embedding pulls the provider's variant 0. A variant that dictates that provider's config breaks the premise from the other side: whatever ran, it was not the provider as the provider declares it. Such a pair now covers nothing, so the retired row keeps its job, its artefact and its verdict. Measured on the current tree: 20 override pairs, 41 covered rows before and after, so nothing is revoked today. The rule bites the moment an override lands in a row that covers. Co-Authored-By: Claude Opus 5 (1M context) --- .../development/inventory/legacy_resolver.py | 23 +++ .../development/inventory/nested_overrides.py | 90 ++++++++++ .../deploy/development/inventory/payload.py | 16 ++ cli/meta/roles/applications/complexity/cli.py | 37 +++- roles/svc-db-qdrant/meta/variants.yml | 4 + roles/web-app-baserow/meta/variants.yml | 3 + roles/web-app-checkmk/meta/variants.yml | 3 + roles/web-app-fider/meta/variants.yml | 3 + roles/web-app-gitea/meta/variants.yml | 3 + roles/web-app-gitlab/meta/variants.yml | 3 + roles/web-app-homeassistant/meta/variants.yml | 4 + roles/web-app-jellyfin/meta/variants.yml | 3 + roles/web-app-jenkins/meta/variants.yml | 3 + roles/web-app-listmonk/meta/variants.yml | 3 + roles/web-app-mattermost/meta/variants.yml | 3 + roles/web-app-moodle/meta/variants.yml | 32 ++-- roles/web-app-n8n/meta/variants.yml | 3 + roles/web-app-nextcloud/meta/variants.yml | 7 +- roles/web-app-pretix/meta/variants.yml | 3 + roles/web-app-prometheus/meta/variants.yml | 4 + roles/web-app-snipe-it/meta/variants.yml | 3 + roles/web-app-wordpress/meta/variants.yml | 2 + roles/web-app-zammad/meta/variants.yml | 3 + .../web-svc-libretranslate/meta/variants.yml | 3 + .../integration/roles/meta/test_non_empty.py | 10 ++ .../variants/test_mcp_consumer_variant.py | 164 ++++++++++++++++++ .../inventory/test_nested_overrides.py | 91 ++++++++++ .../complexity/test_complexity.py | 15 ++ .../utils/roles/applications/test_topics.py | 66 +++++++ .../roles/applications/services/resources.py | 15 +- utils/roles/applications/topics.py | 115 ++++++++++++ 31 files changed, 712 insertions(+), 25 deletions(-) create mode 100644 cli/administration/deploy/development/inventory/nested_overrides.py create mode 100644 tests/integration/roles/meta/variants/test_mcp_consumer_variant.py create mode 100644 tests/unit/python/cli/administration/deploy/development/inventory/test_nested_overrides.py create mode 100644 tests/unit/python/utils/roles/applications/test_topics.py create mode 100644 utils/roles/applications/topics.py diff --git a/cli/administration/deploy/development/inventory/legacy_resolver.py b/cli/administration/deploy/development/inventory/legacy_resolver.py index 1dff1fa170..5b70ba0698 100644 --- a/cli/administration/deploy/development/inventory/legacy_resolver.py +++ b/cli/administration/deploy/development/inventory/legacy_resolver.py @@ -20,6 +20,8 @@ from utils.cache.base import _deep_merge from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_META_SERVICES +from .nested_overrides import apply_topic, collect_provider_overrides + def _build_services_overrides_for_round( *, @@ -72,9 +74,30 @@ def _build_services_overrides_for_round( merged = _deep_merge(dict(base_services), dict(variant_services)) if isinstance(merged, dict): overrides[role_name] = merged + _apply_nested_service_maps(overrides, roles_dir=roles_dir) return overrides +def _apply_nested_service_maps(overrides: dict[str, dict], *, roles_dir: str) -> None: + """Replace a pulled-in provider's services map with what the round demands. + + Only the ``services`` topic reaches this path: the closure walks service + edges, so the other config topics a variant may override are the inventory + bake's business. + + Args: + overrides: ``{role: services map}``, mutated in place. + roles_dir: roles directory the service registry is built from. + """ + payloads = {role: {"services": services} for role, services in overrides.items()} + for provider, topics in collect_provider_overrides( + payloads, roles_dir=roles_dir + ).items(): + if "services" not in topics: + continue + overrides[provider] = apply_topic(overrides.get(provider), topics["services"]) + + def _resolve_round_include( *, primary_apps: Sequence[str], diff --git a/cli/administration/deploy/development/inventory/nested_overrides.py b/cli/administration/deploy/development/inventory/nested_overrides.py new file mode 100644 index 0000000000..b17a362b13 --- /dev/null +++ b/cli/administration/deploy/development/inventory/nested_overrides.py @@ -0,0 +1,90 @@ +"""Collect the provider config a round's variants dictate. + +The topic vocabulary and merge semantics live in +``utils.roles.applications.topics``; this module resolves which role demands +what, and refuses two roles demanding different things for one provider. + +Only a config topic counts, and only on an entry naming another role's +service. A role's own entity entry is skipped, which is what keeps the two +existing `services..users` / `services..domains` declarations from +being read as overrides. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from utils.roles.applications.services.registry import ( + build_service_registry_from_roles_dir, +) +from utils.roles.applications.topics import CONFIG_TOPICS, apply_topic, provider_of + +__all__ = ["CONFIG_TOPICS", "NestedOverrideConflictError", "apply_topic"] + + +class NestedOverrideConflictError(RuntimeError): + """Two roles in one round demand different config for one provider.""" + + +def _claims(payloads: Mapping[str, Any]) -> list[tuple[str, str, str, Any]]: + """Return the ``(role, service_key, topic, value)`` a round's payloads carry. + + Args: + payloads: ``{role: variant payload}`` for one round. + + Reading this before the service registry keeps a round whose variants + override nothing from paying for the registry at all. + """ + claims: list[tuple[str, str, str, Any]] = [] + for role_name, payload in payloads.items(): + if not isinstance(payload, Mapping): + continue + services = payload.get("services") + if not isinstance(services, Mapping): + continue + for service_key, entry in services.items(): + if not isinstance(entry, Mapping): + continue + claims.extend( + (role_name, service_key, topic, entry[topic]) + for topic in sorted(CONFIG_TOPICS & set(entry)) + ) + return claims + + +def collect_provider_overrides( + payloads: Mapping[str, Any], *, roles_dir: str +) -> dict[str, dict[str, Any]]: + """Return ``{provider: {topic: value}}`` demanded by the round's payloads. + + Args: + payloads: ``{role: variant payload}`` for one round. + roles_dir: roles directory the service registry is built from. + + Raises: + NestedOverrideConflictError: two roles demand different values for the + same topic of the same provider. + """ + claims = _claims(payloads) + if not claims: + return {} + + registry = build_service_registry_from_roles_dir(Path(roles_dir)) + demanded: dict[str, dict[str, Any]] = {} + claimed_by: dict[tuple[str, str], str] = {} + for role_name, service_key, topic, value in claims: + provider = provider_of(service_key, registry) + if not provider or provider == role_name: + continue + previous = claimed_by.get((provider, topic)) + if previous and demanded[provider][topic] != value: + raise NestedOverrideConflictError( + f"{role_name} and {previous} demand different " + f"{topic!r} for {provider!r} in the same round; a " + f"round deploys it once, so the two cannot both hold" + ) + demanded.setdefault(provider, {})[topic] = value + claimed_by[(provider, topic)] = role_name + return demanded diff --git a/cli/administration/deploy/development/inventory/payload.py b/cli/administration/deploy/development/inventory/payload.py index 588decaec3..6421739441 100644 --- a/cli/administration/deploy/development/inventory/payload.py +++ b/cli/administration/deploy/development/inventory/payload.py @@ -15,6 +15,8 @@ from typing import Any from utils.cache.applications import get_variant_overrides_only +from .nested_overrides import apply_topic, collect_provider_overrides + def _resolve_variant_payloads( *, @@ -32,6 +34,10 @@ def _resolve_variant_payloads( Apps without `meta/variants.yml` collapse to a single empty override `{}`. Out-of-range indices clamp to 0. + + A config topic a variant declares under a service it depends on is + finally moved onto that service's provider, so the role pulling a + dependency in is what decides how lean the dependency runs. """ overrides_per_app = get_variant_overrides_only(roles_dir=roles_dir) resolved: dict[str, Any] = {} @@ -43,6 +49,16 @@ def _resolve_variant_payloads( if not 0 <= index < len(variant_list): index = 0 resolved[app_id] = variant_list[index] + for provider, topics in collect_provider_overrides( + resolved, roles_dir=roles_dir + ).items(): + if provider not in resolved: + continue + payload = resolved[provider] + payload = dict(payload) if isinstance(payload, Mapping) else {} + for topic, value in topics.items(): + payload[topic] = apply_topic(payload.get(topic), value) + resolved[provider] = payload return resolved diff --git a/cli/meta/roles/applications/complexity/cli.py b/cli/meta/roles/applications/complexity/cli.py index 8d1ea4b3e9..9e7249e371 100644 --- a/cli/meta/roles/applications/complexity/cli.py +++ b/cli/meta/roles/applications/complexity/cli.py @@ -5,9 +5,13 @@ from __future__ import annotations import argparse import re import sys -from typing import Any +from typing import TYPE_CHECKING, Any from utils import PROJECT_ROOT +from utils.roles.applications.topics import overridden_providers + +if TYPE_CHECKING: + from collections.abc import Mapping from .filter import FilterError, compile_predicate from .model import ( @@ -272,7 +276,10 @@ def _apply_sort(rows: list[ComplexityRow], sort_spec: list[tuple[str, bool]]) -> rows.sort(key=_SORT_KEYS[column], reverse=reverse) -def _mark_covered(rows: list[ComplexityRow]) -> list[ComplexityRow]: +def _mark_covered( + rows: list[ComplexityRow], + overridden: Mapping[tuple[str, int], set[str]] | None = None, +) -> list[ComplexityRow]: """Assign each sorted row its numeric ``id`` (its position in sort order) and its ``covered_by`` via a greedy set-cover: the first row is green, and every later row's ``covered_by`` is the (1-based) ``id`` of the first @@ -287,8 +294,20 @@ def _mark_covered(rows: list[ComplexityRow]) -> list[ComplexityRow]: Coverage is variant-aware: when a service.yml declares another service enabled+shared it always pulls that provider's variant 0, so only a row's variant-0 (or whole-role) form can be covered. A variant > 0 row is never - covered and is always green; it may still cover other roles' rows.""" - green: list[tuple[int, str, set[str]]] = [] + covered and is always green; it may still cover other roles' rows. + + A variant that dictates a provider's own config is not evidence about that + provider in any variant: the deploy ran a configuration the provider does + not declare. ``overridden`` maps ``(role, variant)`` to the providers it + overrides, and such a pair never covers those providers. + + Args: + rows: the complexity rows, in ranking order. + overridden: ``{(role, variant): {provider role, ...}}``, or None when + no variant dictates anything. + """ + demands = overridden or {} + green: list[tuple[int, str, int | None, set[str]]] = [] out: list[ComplexityRow] = [] for index, row in enumerate(rows, start=1): coverable = row.variant in (None, 0) @@ -296,8 +315,10 @@ def _mark_covered(rows: list[ComplexityRow]) -> list[ComplexityRow]: next( ( gid - for gid, gname, gset in green - if gname != row.name and row.name in gset + for gid, gname, gvariant, gset in green + if gname != row.name + and row.name in gset + and row.name not in demands.get((gname, gvariant or 0), ()) ), None, ) @@ -305,7 +326,7 @@ def _mark_covered(rows: list[ComplexityRow]) -> list[ComplexityRow]: else None ) if coverer is None: - green.append((index, row.name, set(row.services))) + green.append((index, row.name, row.variant, set(row.services))) out.append(row._replace(id=index, covered_by=coverer or 0)) return out @@ -353,7 +374,7 @@ def main(argv: list[str] | None = None) -> int: rows = attach_siblings(rows) _apply_sort(rows, sort_spec) - rows = _mark_covered(rows) + rows = _mark_covered(rows, overridden_providers(roles_dir)) _apply_sort(rows, sort_spec) rows = [r._replace(row=line) for line, r in enumerate(rows, start=1)] diff --git a/roles/svc-db-qdrant/meta/variants.yml b/roles/svc-db-qdrant/meta/variants.yml index 0546253d99..85878423d4 100644 --- a/roles/svc-db-qdrant/meta/variants.yml +++ b/roles/svc-db-qdrant/meta/variants.yml @@ -23,12 +23,16 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: flowise: enabled: true shared: true + services: diff --git a/roles/web-app-baserow/meta/variants.yml b/roles/web-app-baserow/meta/variants.yml index 9037a469d0..032260691f 100644 --- a/roles/web-app-baserow/meta/variants.yml +++ b/roles/web-app-baserow/meta/variants.yml @@ -83,9 +83,12 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: diff --git a/roles/web-app-checkmk/meta/variants.yml b/roles/web-app-checkmk/meta/variants.yml index 7f02bdf42c..ea78be6498 100644 --- a/roles/web-app-checkmk/meta/variants.yml +++ b/roles/web-app-checkmk/meta/variants.yml @@ -72,12 +72,15 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: - services: container_backup: enabled: false diff --git a/roles/web-app-fider/meta/variants.yml b/roles/web-app-fider/meta/variants.yml index 3af4570eeb..837322f47e 100644 --- a/roles/web-app-fider/meta/variants.yml +++ b/roles/web-app-fider/meta/variants.yml @@ -78,9 +78,12 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: diff --git a/roles/web-app-gitea/meta/variants.yml b/roles/web-app-gitea/meta/variants.yml index 5da73eb89a..8d2ed419cf 100644 --- a/roles/web-app-gitea/meta/variants.yml +++ b/roles/web-app-gitea/meta/variants.yml @@ -89,12 +89,15 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: - services: container_backup: enabled: false diff --git a/roles/web-app-gitlab/meta/variants.yml b/roles/web-app-gitlab/meta/variants.yml index 96606d26fd..fc409d21ea 100644 --- a/roles/web-app-gitlab/meta/variants.yml +++ b/roles/web-app-gitlab/meta/variants.yml @@ -83,9 +83,12 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: diff --git a/roles/web-app-homeassistant/meta/variants.yml b/roles/web-app-homeassistant/meta/variants.yml index 50ff180866..64421bc9a7 100644 --- a/roles/web-app-homeassistant/meta/variants.yml +++ b/roles/web-app-homeassistant/meta/variants.yml @@ -41,12 +41,16 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: flowise: enabled: true shared: true + services: diff --git a/roles/web-app-jellyfin/meta/variants.yml b/roles/web-app-jellyfin/meta/variants.yml index 71c2ab67a0..51bf9ff461 100644 --- a/roles/web-app-jellyfin/meta/variants.yml +++ b/roles/web-app-jellyfin/meta/variants.yml @@ -66,12 +66,15 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: - services: container_backup: enabled: false diff --git a/roles/web-app-jenkins/meta/variants.yml b/roles/web-app-jenkins/meta/variants.yml index 72b1bead94..e741b63b9e 100644 --- a/roles/web-app-jenkins/meta/variants.yml +++ b/roles/web-app-jenkins/meta/variants.yml @@ -71,12 +71,15 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: - services: container_backup: enabled: false diff --git a/roles/web-app-listmonk/meta/variants.yml b/roles/web-app-listmonk/meta/variants.yml index 61308c1211..fbdbdb2d85 100644 --- a/roles/web-app-listmonk/meta/variants.yml +++ b/roles/web-app-listmonk/meta/variants.yml @@ -80,9 +80,12 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: diff --git a/roles/web-app-mattermost/meta/variants.yml b/roles/web-app-mattermost/meta/variants.yml index 4207624f41..ed775be250 100644 --- a/roles/web-app-mattermost/meta/variants.yml +++ b/roles/web-app-mattermost/meta/variants.yml @@ -89,12 +89,15 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: - services: container_backup: diff --git a/roles/web-app-moodle/meta/variants.yml b/roles/web-app-moodle/meta/variants.yml index dfbf366bc6..38ad4dfa31 100644 --- a/roles/web-app-moodle/meta/variants.yml +++ b/roles/web-app-moodle/meta/variants.yml @@ -37,8 +37,8 @@ enabled: true shared: true litellm: - enabled: true - shared: true + enabled: false + shared: false tor: enabled: true @@ -88,14 +88,14 @@ tor: enabled: true openwebui: - enabled: true - shared: true + enabled: false + shared: false hermes: - enabled: true - shared: true + enabled: false + shared: false openclaw: - enabled: true - shared: true + enabled: false + shared: false - services: container_backup: enabled: false @@ -129,14 +129,18 @@ litellm: enabled: true shared: true + services: tor: enabled: true openwebui: - enabled: false - shared: false + enabled: true + shared: true + services: hermes: - enabled: false - shared: false + enabled: true + shared: true + services: openclaw: - enabled: false - shared: false + enabled: true + shared: true + services: diff --git a/roles/web-app-n8n/meta/variants.yml b/roles/web-app-n8n/meta/variants.yml index adf775c880..3bcc556118 100644 --- a/roles/web-app-n8n/meta/variants.yml +++ b/roles/web-app-n8n/meta/variants.yml @@ -75,9 +75,12 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: diff --git a/roles/web-app-nextcloud/meta/variants.yml b/roles/web-app-nextcloud/meta/variants.yml index 6c49ffbb46..10d5a4f763 100644 --- a/roles/web-app-nextcloud/meta/variants.yml +++ b/roles/web-app-nextcloud/meta/variants.yml @@ -189,8 +189,9 @@ enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true openwebui: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true + enabled: true + shared: true + services: litellm: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -205,9 +206,11 @@ hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: addons: &addons_static_off appointments: enabled: false diff --git a/roles/web-app-pretix/meta/variants.yml b/roles/web-app-pretix/meta/variants.yml index 14d24d0757..ca3d40d1ee 100644 --- a/roles/web-app-pretix/meta/variants.yml +++ b/roles/web-app-pretix/meta/variants.yml @@ -77,9 +77,12 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: diff --git a/roles/web-app-prometheus/meta/variants.yml b/roles/web-app-prometheus/meta/variants.yml index 7fb470edd3..a2f43d14f1 100644 --- a/roles/web-app-prometheus/meta/variants.yml +++ b/roles/web-app-prometheus/meta/variants.yml @@ -67,12 +67,16 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: flowise: enabled: true shared: true + services: diff --git a/roles/web-app-snipe-it/meta/variants.yml b/roles/web-app-snipe-it/meta/variants.yml index cd0b18b92a..6bbfde59fd 100644 --- a/roles/web-app-snipe-it/meta/variants.yml +++ b/roles/web-app-snipe-it/meta/variants.yml @@ -89,12 +89,15 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: - services: container_backup: enabled: false diff --git a/roles/web-app-wordpress/meta/variants.yml b/roles/web-app-wordpress/meta/variants.yml index aeb0a46fac..0e59d2b295 100644 --- a/roles/web-app-wordpress/meta/variants.yml +++ b/roles/web-app-wordpress/meta/variants.yml @@ -91,9 +91,11 @@ hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: addons: activitypub: enabled: false diff --git a/roles/web-app-zammad/meta/variants.yml b/roles/web-app-zammad/meta/variants.yml index 225c028f71..c9629385c9 100644 --- a/roles/web-app-zammad/meta/variants.yml +++ b/roles/web-app-zammad/meta/variants.yml @@ -94,12 +94,15 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: - services: container_backup: enabled: false diff --git a/roles/web-svc-libretranslate/meta/variants.yml b/roles/web-svc-libretranslate/meta/variants.yml index 998cdc6080..f5b7b94d00 100644 --- a/roles/web-svc-libretranslate/meta/variants.yml +++ b/roles/web-svc-libretranslate/meta/variants.yml @@ -51,9 +51,12 @@ openwebui: enabled: true shared: true + services: hermes: enabled: true shared: true + services: openclaw: enabled: true shared: true + services: diff --git a/tests/integration/roles/meta/test_non_empty.py b/tests/integration/roles/meta/test_non_empty.py index 7397e78691..5d68de05d7 100644 --- a/tests/integration/roles/meta/test_non_empty.py +++ b/tests/integration/roles/meta/test_non_empty.py @@ -1,13 +1,20 @@ import os +import re import unittest import yaml from utils.cache.files import iter_project_files from utils.cache.yaml import load_yaml_any +from utils.roles.applications.topics import CONFIG_TOPICS +from utils.roles.mapping import ROLE_FILE_META_VARIANTS from . import PROJECT_ROOT +_CLEARED_TOPIC = re.compile( + rf"^\[\d+\]\.services\.[^.]+\.(?:{'|'.join(sorted(CONFIG_TOPICS))})$" +) + def find_none_values(data, prefix=None): """ @@ -56,8 +63,11 @@ class TestConfigurationNoNone(unittest.TestCase): data = load_yaml_any(filepath) except yaml.YAMLError as e: self.fail(f"Failed to parse YAML in {filepath}: {e}") + is_variants = filepath.endswith(ROLE_FILE_META_VARIANTS) errors = find_none_values(data) for path, _value in errors: + if is_variants and _CLEARED_TOPIC.match(path): + continue all_errors.append(f"{filepath}: Key '{path}' is None") if all_errors: diff --git a/tests/integration/roles/meta/variants/test_mcp_consumer_variant.py b/tests/integration/roles/meta/variants/test_mcp_consumer_variant.py new file mode 100644 index 0000000000..da8da1d61a --- /dev/null +++ b/tests/integration/roles/meta/variants/test_mcp_consumer_variant.py @@ -0,0 +1,164 @@ +"""Integration guard: an MCP provider ships one round that is only MCP. + +A provider's clients cost a full application stack each, so the round that +proves the MCP pairing must not also carry the role's SSO, mail, metrics and +dashboard surfaces. Every role with a ``meta/mcp.yml`` that admits at least +one consumer therefore needs one variant that is exactly that pairing: + +* every admitted consumer pinned ``enabled: true`` with ``services: null``, + so the client is deployed but drags none of its own dependencies along, +* every other service pinned ``enabled: false``. + +``tor`` is exempt because the onion round is a deploy axis rather than a +feature of the role, ``litellm`` because the gateway is what the clients +answer prompts through, and so are the role's own entity and any service its +``meta/services.yml`` pins to a literal ``true`` — the datastores, which a +variant cannot switch off without taking the application with them. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-consumer-variant`` in the head of the role's + ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.applications import get_application_defaults, get_variants +from utils.cache.files import read_text +from utils.roles.applications.mcp import derive_allowed_consumers +from utils.roles.entity.name import get_entity_name +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +_RULE = "mcp-consumer-variant" +_SERVER_DIRECTIONS = frozenset({"server", "both"}) +_ALWAYS_ALLOWED = frozenset({"tor", "litellm"}) + +ROLES_DIR = PROJECT_ROOT / "roles" + + +def _statically_on(base_services: Mapping) -> set[str]: + """Return service keys a variant cannot switch off. + + Args: + base_services: the role's ``meta/services.yml`` mapping. + + A literal ``enabled: true`` in the base is the datastore shape: it states + a fact about what the application needs, not a per-round choice. + """ + return { + key + for key, entry in base_services.items() + if isinstance(entry, Mapping) and entry.get("enabled") is True + } + + +def _variant_findings( + role: str, consumers: set[str], variant: Mapping, allowed: set[str] +) -> list[str]: + """Return why one variant is not the role's MCP-only round. + + Args: + role: the provider role id. + consumers: entity keys of every admitted consumer. + variant: one ``meta/variants.yml`` entry. + allowed: keys that may stay on besides the consumers. + """ + services = variant.get("services") + if not isinstance(services, Mapping): + return [f"{role}: variant declares no services"] + findings: list[str] = [] + for key in sorted(consumers): + entry = services.get(key) + if not isinstance(entry, Mapping) or entry.get("enabled") is not True: + findings.append(f"{role}: {key} is not enabled") + elif "services" not in entry or entry["services"] is not None: + findings.append(f"{role}: {key} lacks `services: null`") + findings.extend( + f"{role}: {key} stays enabled" + for key, entry in sorted(services.items()) + if isinstance(entry, Mapping) + and entry.get("enabled") is True + and key not in consumers + and key not in allowed + ) + return findings + + +def offenders() -> list[str]: + """Return one finding per provider without an MCP-only variant.""" + defaults = get_application_defaults(roles_dir=ROLES_DIR) + services_by_role = { + role: (config or {}).get("services") + for role, config in defaults.items() + if isinstance(config, dict) + } + variants = get_variants(roles_dir=ROLES_DIR) + findings: list[str] = [] + for meta in sorted(ROLES_DIR.glob(f"*/{ROLE_FILE_META_MCP}")): + role = meta.parent.parent.name + block = (defaults.get(role) or {}).get("mcp") + if not isinstance(block, Mapping): + continue + if str(block.get("direction") or "").strip().lower() not in _SERVER_DIRECTIONS: + continue + if is_suppressed_in_head(read_text(str(meta)).splitlines(), _RULE): + continue + consumers = { + get_entity_name(c) for c in derive_allowed_consumers(role, services_by_role) + } + if not consumers: + continue + base = services_by_role.get(role) + allowed = ( + _ALWAYS_ALLOWED + | {get_entity_name(role)} + | (_statically_on(base) if isinstance(base, Mapping) else set()) + ) + per_variant = [ + _variant_findings(role, consumers, v, allowed) + for v in variants.get(role, []) + if isinstance(v, Mapping) + ] + if any(not f for f in per_variant): + continue + closest = min(per_variant, key=len) if per_variant else [f"{role}: no variants"] + findings.append( + f"{role}: no variant is the MCP-only round; the closest one still " + f"reports: {'; '.join(closest)}" + ) + return findings + + +class TestMcpConsumerVariant(unittest.TestCase): + def test_every_provider_ships_an_mcp_only_variant(self) -> None: + findings = offenders() + self.assertEqual( + [], + findings, + f"MCP provider(s) without an MCP-only variant ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_finds_providers(self) -> None: + defaults = get_application_defaults(roles_dir=ROLES_DIR) + seen = sum( + 1 + for meta in ROLES_DIR.glob(f"*/{ROLE_FILE_META_MCP}") + if isinstance( + (defaults.get(meta.parent.parent.name) or {}).get("mcp"), Mapping + ) + ) + self.assertTrue( + seen, + "no role ships meta/mcp.yml, so the rule would pass vacuously", + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/unit/python/cli/administration/deploy/development/inventory/test_nested_overrides.py b/tests/unit/python/cli/administration/deploy/development/inventory/test_nested_overrides.py new file mode 100644 index 0000000000..a473f1031d --- /dev/null +++ b/tests/unit/python/cli/administration/deploy/development/inventory/test_nested_overrides.py @@ -0,0 +1,91 @@ +"""Unit tests for `cli.administration.deploy.development.inventory.nested_overrides`. + +The service registry is stubbed: what matters is which role a claim is +attributed to, not how a service key resolves to its provider. +""" + +from __future__ import annotations + +import unittest +from unittest.mock import patch + +from cli.administration.deploy.development.inventory.nested_overrides import ( + NestedOverrideConflictError, + collect_provider_overrides, +) + +_REGISTRY = { + "openwebui": {"role": "web-app-openwebui"}, + "gitea": {"role": "web-app-gitea"}, +} + +_PATCH = ( + "cli.administration.deploy.development.inventory.nested_overrides" + ".build_service_registry_from_roles_dir" +) + + +class TestCollectProviderOverrides(unittest.TestCase): + def _collect(self, payloads, registry=None): + with patch(_PATCH, autospec=True) as build: + build.return_value = _REGISTRY if registry is None else registry + return collect_provider_overrides(payloads, roles_dir="/roles") + + def test_a_named_topic_reaches_its_provider(self) -> None: + payloads = { + "web-app-moodle": {"services": {"openwebui": {"services": None}}}, + } + self.assertEqual( + {"web-app-openwebui": {"services": None}}, self._collect(payloads) + ) + + def test_several_topics_of_one_provider_are_collected_together(self) -> None: + payloads = { + "web-app-moodle": { + "services": { + "openwebui": {"services": None, "addons": {"whisper": False}}, + }, + }, + } + self.assertEqual( + {"web-app-openwebui": {"services": None, "addons": {"whisper": False}}}, + self._collect(payloads), + ) + + def test_a_roles_own_entry_is_not_an_override(self) -> None: + payloads = {"web-app-gitea": {"services": {"gitea": {"users": {"a": 1}}}}} + self.assertEqual({}, self._collect(payloads)) + + def test_an_unregistered_service_key_is_skipped(self) -> None: + payloads = {"web-app-moodle": {"services": {"nowhere": {"services": None}}}} + self.assertEqual({}, self._collect(payloads)) + + def test_two_roles_agreeing_is_not_a_conflict(self) -> None: + payloads = { + "web-app-moodle": {"services": {"openwebui": {"services": None}}}, + "web-app-gitea": {"services": {"openwebui": {"services": None}}}, + } + self.assertEqual( + {"web-app-openwebui": {"services": None}}, self._collect(payloads) + ) + + def test_two_roles_demanding_different_values_raises(self) -> None: + payloads = { + "web-app-moodle": {"services": {"openwebui": {"services": None}}}, + "web-app-gitea": {"services": {"openwebui": {"services": {"a": 1}}}}, + } + with self.assertRaises(NestedOverrideConflictError): + self._collect(payloads) + + def test_a_round_without_overrides_never_builds_the_registry(self) -> None: + payloads = {"web-app-moodle": {"services": {"openwebui": {"enabled": True}}}} + with patch(_PATCH, autospec=True) as build: + build.return_value = _REGISTRY + self.assertEqual( + {}, collect_provider_overrides(payloads, roles_dir="/roles") + ) + build.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py b/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py index 33d461b1a2..ec2d862733 100644 --- a/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py +++ b/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py @@ -954,6 +954,21 @@ class TestCoveredBy(unittest.TestCase): ) self.assertEqual([m.covered_by for m in marked], [0, 0, 2]) + def test_a_variant_that_overrides_a_provider_does_not_cover_it(self) -> None: + rows = [_row("A", ["B", "C"], variant=1), _row("B", []), _row("C", [])] + marked = _mark_covered(rows, {("A", 1): {"B"}}) + self.assertEqual([m.covered_by for m in marked], [0, 0, 1]) + + def test_the_override_only_bars_the_provider_it_names(self) -> None: + rows = [_row("A", ["B"], variant=1), _row("B", [])] + marked = _mark_covered(rows, {("A", 1): {"C"}}) + self.assertEqual([m.covered_by for m in marked], [0, 1]) + + def test_an_override_in_another_variant_leaves_coverage_alone(self) -> None: + rows = [_row("A", ["B"], variant=0), _row("B", [])] + marked = _mark_covered(rows, {("A", 2): {"B"}}) + self.assertEqual([m.covered_by for m in marked], [0, 1]) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/roles/applications/test_topics.py b/tests/unit/python/utils/roles/applications/test_topics.py new file mode 100644 index 0000000000..80d2fc625f --- /dev/null +++ b/tests/unit/python/utils/roles/applications/test_topics.py @@ -0,0 +1,66 @@ +"""Unit tests for ``utils/roles/applications/topics.py``. + +The three override shapes have to stay distinguishable: ``null`` empties, +``{}`` is a no-op, and a mapping changes the keys it names and nothing else. +""" + +from __future__ import annotations + +import unittest + +from utils.cache.files import PROJECT_ROOT +from utils.roles.applications.topics import ( + CONFIG_TOPICS, + apply_topic, + overridden_providers, +) + + +class TestApplyTopic(unittest.TestCase): + def test_null_empties_the_topic(self): + self.assertEqual({}, apply_topic({"a": {"enabled": True}}, None)) + + def test_an_empty_mapping_changes_nothing(self): + base = {"a": {"enabled": True}} + self.assertEqual(base, apply_topic(base, {})) + + def test_a_mapping_merges_the_named_keys_only(self): + base = {"a": {"enabled": True}, "b": {"enabled": True}} + self.assertEqual( + {"a": {"enabled": False}, "b": {"enabled": True}}, + apply_topic(base, {"a": {"enabled": False}}), + ) + + def test_a_missing_base_still_takes_the_override(self): + self.assertEqual({"a": 1}, apply_topic(None, {"a": 1})) + + def test_the_vocabulary_covers_the_topics_a_variant_can_name(self): + self.assertIn("services", CONFIG_TOPICS) + self.assertIn("addons", CONFIG_TOPICS) + self.assertNotIn("enabled", CONFIG_TOPICS) + + +class TestOverriddenProviders(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.found = overridden_providers(PROJECT_ROOT / "roles") + + def test_the_scan_finds_the_declared_overrides(self) -> None: + self.assertTrue(self.found) + + def test_a_role_never_records_itself(self) -> None: + self.assertEqual( + [], + [(role, i) for (role, i), targets in self.found.items() if role in targets], + ) + + def test_every_target_is_a_role_that_exists(self) -> None: + roles = {p.name for p in (PROJECT_ROOT / "roles").iterdir() if p.is_dir()} + missing = sorted( + {target for targets in self.found.values() for target in targets} - roles + ) + self.assertEqual([], missing) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/roles/applications/services/resources.py b/utils/roles/applications/services/resources.py index a3da6b8ee2..e6e61978bf 100644 --- a/utils/roles/applications/services/resources.py +++ b/utils/roles/applications/services/resources.py @@ -15,6 +15,7 @@ from typing import Any from humanfriendly import parse_size +from utils.roles.applications.topics import apply_topic from utils.roles.entity.name import get_entity_name _RESOURCE_KEYS = ("mem_reservation", "mem_limit", "pids_limit", "cpus") @@ -166,6 +167,7 @@ def collect_role_resources( ) shared_dependencies: list[str] = [] + nested_maps: dict[str, dict[str, Any]] = {} for service_key, raw_service_conf in services.items(): if service_key == entity_name: continue @@ -185,6 +187,8 @@ def collect_role_resources( add(service_key, service_conf) elif provider_role and provider_role != role_name: shared_dependencies.append(provider_role) + if "services" in service_conf: + nested_maps[provider_role] = service_conf["services"] elif _is_shared(service_conf): warnings.append( f"{role_name}: shared service '{service_key}' has no registered provider" @@ -196,9 +200,18 @@ def collect_role_resources( return for provider_role in shared_dependencies: + scoped = applications + if provider_role in nested_maps: + demanded = nested_maps[provider_role] + provider_conf = dict(_as_mapping(applications.get(provider_role))) + provider_conf["services"] = apply_topic( + provider_conf.get("services"), demanded + ) + scoped = dict(applications) + scoped[provider_role] = provider_conf collect_role_resources( provider_role, - applications, + scoped, service_registry, visited, rows, diff --git a/utils/roles/applications/topics.py b/utils/roles/applications/topics.py new file mode 100644 index 0000000000..3603e29efd --- /dev/null +++ b/utils/roles/applications/topics.py @@ -0,0 +1,115 @@ +"""The config topics a variant may dictate for the providers it pulls in. + +A round deploys a provider once, so the role that pulls it in is the only +place that can say how lean it has to be. A variant entry may therefore carry +any application config topic under the service it depends on: + + services: + openwebui: + enabled: true + shared: true + services: null # brings nothing along + addons: + whisper: + enabled: false # everything else in addons survives + +A mapping deep-merges, so naming one key changes that key and nothing else. +``null`` empties the topic, which is the only way to say "bring nothing": +merged, an empty mapping is a no-op and would leave exactly the services the +round was trying to shed. + +YAML writes null three ways - ``null``, ``~``, and a key with nothing after +it - so a half-typed line empties a topic rather than being ignored. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from utils.cache.base import _deep_merge +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.services.registry import ( + build_service_registry_from_roles_dir, +) +from utils.roles.mapping import ROLE_FILE_META_VARIANTS + +CONFIG_TOPICS = frozenset( + { + "addons", + "csp", + "domains", + "group_id", + "info", + "mcp", + "networks", + "packages", + "rbac", + "secrets", + "server", + "services", + "tests", + "users", + } +) + + +def apply_topic(base_value: Any, override_value: Any) -> Any: + """Return a provider's topic after one override is applied. + + Args: + base_value: what the provider declares for the topic today. + override_value: what the pulling role demands. + + ``None`` empties the topic and is normalised to ``{}``: the closure + resolver skips a non-mapping payload, so leaving the bare ``None`` would + silently keep the services it was meant to drop. + """ + if override_value is None: + return {} + return _deep_merge(base_value, override_value) + + +def provider_of(service_key: str, service_registry: Mapping) -> str: + """Return the role providing ``service_key``, or "" when unregistered. + + Args: + service_key: a first-level key of a role's services map. + service_registry: the project-wide service registry. + """ + entry = service_registry.get(service_key) + if not isinstance(entry, Mapping): + return "" + role = entry.get("role") + return str(role).strip() if role else "" + + +def overridden_providers(roles_dir: str | Path) -> dict[tuple[str, int], set[str]]: + """Return ``{(role, variant index): {provider role, ...}}`` across every variant. + + Args: + roles_dir: roles directory the variants and service registry are read from. + + A variant that dictates a provider's config does not deploy that provider as + the provider declares it, so nothing about that run states what the provider + does on its own. Callers that reason about coverage need to know which pairs + those are before they credit one role's deploy to another. + """ + roles_root = Path(roles_dir) + registry = build_service_registry_from_roles_dir(roles_root) + found: dict[tuple[str, int], set[str]] = {} + for path in sorted(roles_root.glob(f"*/{ROLE_FILE_META_VARIANTS}")): + role = path.parent.parent.name + variants = load_yaml_any(str(path), default_if_missing=[]) or [] + for index, variant in enumerate(variants): + services = (variant or {}).get("services") or {} + if not isinstance(services, Mapping): + continue + for service_key, entry in services.items(): + if not isinstance(entry, Mapping) or not CONFIG_TOPICS & set(entry): + continue + target = provider_of(str(service_key), registry) + if target and target != role: + found.setdefault((role, index), set()).add(target) + return found