From 357eb3bd328abb9f218895f46c73dd7cba3f31aa Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 13 Nov 2026 20:07:50 +0000 Subject: [PATCH] fix(codescan): break the runtime import cycles CodeQL reports and lint new ones MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeQL py/cyclic-import alerts #1023-#1029 and #1112-#1113 map to three cycles: utils.inventory.tools <-> libretranslate, utils.env.builder <-> its handlers, and utils.roles.applications.variants <-> the inventory legacy resolver. Each cycle loaded only because one side deferred an import into a function body. The shared piece now lives in a leaf module both sides import: utils/inventory/tools_vars.py, utils/env/context.py (BuildContext, EnvBuilder), and _resolve_round_include inside variants.py. The stricter lint found four more cycles, each broken the same way: compose <-> down (cli/administration/deploy/development/docker_root.py), the utils.cache package web (utils/cache/reset.py), utils.cache.carrier <-> users (utils/cache/tokens.py replaces users/store.py) and credentials -> provision (cli/administration/inventory/ruamel_io.py). tests/lint/repository/python/test_import_cycles.py fails on any runtime import cycle between the repository's own modules. It counts TYPE_CHECKING imports and implied parent-package edges, and skips only __main__ blocks and submodule-to-parent reads. Negative control: 3 of the 11 self-tests fail on the old logic. Whole repository: 12 passed. Targeted tests of every touched module: 4275 passed. Accepted security findings: 78 medusa findings, all on lines that exist verbatim in base 28d05e0183. They come from code moved unchanged into docker_root.py, tools_vars.py and tokens.py, or from untouched lines of touched files (compose.py, credentials_generator.py, credentials/reset/cli.py, users/__init__.py, yaml.py). Reviewed as by design or false positive: argv-list subprocess calls, dev docker-root teardown, NotASecret test-lane keys, SafeLoader yaml.load, md5 memo key, Jinja expression strings. 🎯 Fix: 90 % 💥 Break: 5 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 --- .../deploy/development/README.md | 2 +- .../deploy/development/compose.py | 9 +- .../deploy/development/docker_root.py | 47 +++ cli/administration/deploy/development/down.py | 57 +-- .../deploy/development/inventory/__init__.py | 15 +- .../development/inventory/legacy_resolver.py | 64 +-- .../deploy/development/inventory/planner.py | 3 +- .../inventory/credentials/__main__.py | 2 +- .../inventory/credentials/reset/cli.py | 2 +- .../inventory/mesh/inventory.py | 2 +- .../inventory/mesh/transport.py | 2 +- cli/administration/inventory/mesh/write.py | 2 +- .../provision/credentials_generator.py | 6 +- .../inventory/provision/host_vars.py | 6 +- .../inventory/provision/mirror_overrides.py | 7 +- .../inventory/provision/network_mode.py | 3 +- .../inventory/provision/reset.py | 2 +- .../inventory/provision/services/disabler.py | 2 +- .../inventory/provision/tor_node.py | 7 +- .../inventory/provision/users_generator.py | 7 +- .../inventory/{provision => }/ruamel_io.py | 4 +- .../artefact/files/plugins/lookup/users.md | 1 + docs/contributing/design/inventory.md | 2 +- docs/contributing/design/variants.md | 2 +- inventories/development/tools.yml.j2 | 2 +- plugins/lookup/applications.py | 3 +- plugins/lookup/domains.py | 3 +- plugins/lookup/users.py | 2 +- .../test_resource_in_applications_render.py | 2 +- .../test_disabled_provider_dependents.py | 2 +- .../variants/test_variant_pin_required.py | 8 +- .../test_body_filter_fold_render.py | 2 +- .../repository/python/test_import_cycles.py | 383 ++++++++++++++++++ tests/oracle/test_system_one.py | 3 +- tests/oracle/test_translation_score.py | 3 +- .../development/inventory/test_builder.py | 2 +- .../inventory/test_legacy_resolver.py | 4 +- .../development/inventory/test_planner.py | 12 +- .../deploy/development/test_down.py | 17 +- .../inventory/provision/test_host_vars.py | 4 +- .../inventory/provision/test_reset.py | 2 +- .../inventory/provision/test_ruamel_io.py | 2 +- .../provision/test_users_generator.py | 2 +- .../test_webserver_worker_limits.py | 2 +- .../plugins/filter/test_ca_trust_paths.py | 2 +- tests/unit/python/plugins/lookup/test_cert.py | 2 +- .../plugins/lookup/test_config_lookup.py | 2 +- .../unit/python/plugins/lookup/test_email.py | 8 +- .../python/plugins/lookup/test_tor_ports.py | 2 +- .../plugins/lookup/test_tor_reachable.py | 2 +- .../filter_plugins/test_compose_rehash.py | 2 +- .../test_oidc_addon_follows_sso.py | 2 +- .../test_talk_direct_media.py | 2 +- .../roles/web-app-wordpress/test_options.py | 2 +- .../python/utils/cache/test_applications.py | 2 +- tests/unit/python/utils/cache/test_base.py | 3 +- tests/unit/python/utils/cache/test_data.py | 2 +- tests/unit/python/utils/cache/test_domains.py | 2 +- .../unit/python/utils/cache/test_variants.py | 2 +- .../python/utils/cache/users/test_module.py | 44 +- .../handlers/infinito/gpu/test_only_tests.py | 3 +- .../utils/env/handlers/infinito/test_build.py | 2 +- .../env/handlers/infinito/test_cache_conf.py | 2 +- .../infinito/test_cache_host_pacman_path.py | 2 +- .../env/handlers/infinito/test_cache_stack.py | 2 +- .../env/handlers/infinito/test_domain.py | 2 +- .../env/handlers/infinito/test_ghcr_mirror.py | 2 +- .../env/handlers/infinito/test_ip_range.py | 3 +- .../infinito/test_outer_network_mtu.py | 2 +- tests/unit/python/utils/env/test_builder.py | 3 +- tests/unit/python/utils/env/test_writer.py | 2 +- .../utils/inventory/test_tools_address.py | 7 +- .../utils/inventory/test_tools_model.py | 3 +- .../utils/inventory/test_tools_render.py | 10 +- .../applications/test_variants_pin_scope.py | 5 +- utils/cache/README.md | 12 +- utils/cache/__init__.py | 26 +- utils/cache/carrier.py | 9 +- utils/cache/files.py | 2 +- utils/cache/gitignore.py | 2 +- utils/cache/reset.py | 20 + utils/cache/tokens.py | 147 +++++++ utils/cache/users/__init__.py | 97 +---- utils/cache/users/store.py | 68 ---- utils/cache/yaml.py | 2 +- utils/env/README.md | 3 +- utils/env/builder.py | 51 +-- utils/env/context.py | 54 +++ utils/env/handlers/README.md | 2 +- utils/env/handlers/__init__.py | 2 +- utils/env/handlers/act_platform_image.py | 2 +- utils/env/handlers/docker_platform.py | 2 +- utils/env/handlers/gha_passthrough.py | 2 +- utils/env/handlers/github_repository_owner.py | 2 +- utils/env/handlers/infinito/build.py | 2 +- .../handlers/infinito/ca/bundle_candidates.py | 2 +- utils/env/handlers/infinito/ca/cert_host.py | 2 +- utils/env/handlers/infinito/cache/conf.py | 2 +- .../infinito/cache/host_pacman_path.py | 2 +- utils/env/handlers/infinito/cache/hosts.py | 2 +- .../env/handlers/infinito/cache/http_hosts.py | 2 +- utils/env/handlers/infinito/cache/paths.py | 2 +- .../env/handlers/infinito/cache/registries.py | 2 +- utils/env/handlers/infinito/cache/stack.py | 2 +- utils/env/handlers/infinito/cache/tls.py | 2 +- .../env/handlers/infinito/cache/upstreams.py | 2 +- utils/env/handlers/infinito/container.py | 2 +- utils/env/handlers/infinito/dir/backups.py | 2 +- utils/env/handlers/infinito/dir/secrets.py | 2 +- utils/env/handlers/infinito/dir/var_lib.py | 2 +- utils/env/handlers/infinito/distros.py | 2 +- .../handlers/infinito/docker/embedded_dns.py | 2 +- utils/env/handlers/infinito/docker/volume.py | 2 +- utils/env/handlers/infinito/domain.py | 2 +- utils/env/handlers/infinito/fork/account.py | 2 +- .../handlers/infinito/fork/repository_url.py | 2 +- utils/env/handlers/infinito/ghcr_mirror.py | 2 +- utils/env/handlers/infinito/git_identity.py | 2 +- utils/env/handlers/infinito/gpu/count.py | 2 +- utils/env/handlers/infinito/gpu/only_tests.py | 2 +- utils/env/handlers/infinito/i18n/tuning.py | 2 +- utils/env/handlers/infinito/image.py | 2 +- .../env/handlers/infinito/image_repository.py | 2 +- utils/env/handlers/infinito/inventory.py | 2 +- utils/env/handlers/infinito/ip_range.py | 2 +- utils/env/handlers/infinito/is_wsl2.py | 2 +- .../handlers/infinito/outer_network_mtu.py | 2 +- .../infinito/package_cache/admin_password.py | 2 +- .../infinito/package_cache/blobstore_max.py | 2 +- .../infinito/package_cache/direct_mem.py | 2 +- .../handlers/infinito/package_cache/heap.py | 2 +- utils/env/handlers/infinito/parent_image.py | 2 +- .../infinito/playwright/reports_base_dir.py | 2 +- .../infinito/playwright/stage_base_dir.py | 2 +- utils/env/handlers/infinito/pull_policy.py | 2 +- .../infinito/registry_cache_max_size.py | 2 +- .../infinito/rescue/diagnostics_dir.py | 2 +- .../infinito/rescue/dns53_sampler_log.py | 2 +- .../infinito/rescue/local_dumps_dir.py | 2 +- utils/env/handlers/infinito/running_on/act.py | 2 +- .../handlers/infinito/running_on/github.py | 2 +- .../infinito/swarm_nfs/export_base.py | 2 +- .../handlers/infinito/swarm_nfs/state_path.py | 2 +- .../handlers/infinito/tools/libretranslate.py | 2 +- utils/env/handlers/infinito/tools/litellm.py | 2 +- utils/env/handlers/infinito/tools/models.py | 2 +- utils/env/handlers/infinito/tools/s1.py | 2 +- .../env/handlers/infinito/tools/translate.py | 2 +- utils/env/handlers/infinito/tor_socks_port.py | 2 +- utils/env/handlers/infinito/worker/cpu.py | 2 +- utils/env/handlers/infinito/worker/fetch.py | 2 +- utils/env/handlers/nix_config.py | 2 +- utils/env/handlers/passthrough.py | 2 +- utils/env/writer.py | 2 +- utils/i18n/libretranslate.py | 4 +- utils/inventory/tools.py | 96 +---- utils/inventory/tools_vars.py | 83 ++++ utils/roles/applications/variants.py | 52 ++- 158 files changed, 1065 insertions(+), 642 deletions(-) create mode 100644 cli/administration/deploy/development/docker_root.py rename cli/administration/inventory/{provision => }/ruamel_io.py (94%) create mode 100644 tests/lint/repository/python/test_import_cycles.py create mode 100644 utils/cache/reset.py create mode 100644 utils/cache/tokens.py delete mode 100644 utils/cache/users/store.py create mode 100644 utils/env/context.py create mode 100644 utils/inventory/tools_vars.py diff --git a/cli/administration/deploy/development/README.md b/cli/administration/deploy/development/README.md index 71dc1e3886..03fae57745 100644 --- a/cli/administration/deploy/development/README.md +++ b/cli/administration/deploy/development/README.md @@ -201,7 +201,7 @@ flowchart LR | ------------------------ | --------------- | --------------------------------- | | compose `initialize` / `reinstall` | yes | named roots + orphaned closure | | compose `update` | no | ansible extra-var only | -| compose CI matrix (`legacy_resolver` direct) | no | co-deploy superset, no prune | +| compose CI matrix (`_resolve_round_include` direct) | no | co-deploy superset, no prune | | swarm (`utils.tests.swarm.derive_includes`) | yes | named roots + orphaned closure | The swarm path applies the same cut through the `blocked` parameter of diff --git a/cli/administration/deploy/development/compose.py b/cli/administration/deploy/development/compose.py index 21aac747d7..91db369b4f 100644 --- a/cli/administration/deploy/development/compose.py +++ b/cli/administration/deploy/development/compose.py @@ -12,6 +12,7 @@ from utils.env.handlers.infinito.cache.conf import KEY as CACHE_CONF_KEY from utils.env.handlers.infinito.cache.conf import RELATIVE as CACHE_CONF from .coredns import CoreDNSCorefileRenderer +from .docker_root import cleanup_docker_root from .env import compose_file_args from .network import detect_outer_network_mtu from .proc import run_streaming @@ -310,9 +311,11 @@ class Compose: def down(self) -> None: """Tear down the stack.""" - from .down import down_stack - - down_stack(repo_root=self.repo_root, distro=self.distro) + print(">>> Stopping compose stack and removing volumes") + try: + self.run(["down", "--remove-orphans", "-v"]) + finally: + cleanup_docker_root() def exec( self, diff --git a/cli/administration/deploy/development/docker_root.py b/cli/administration/deploy/development/docker_root.py new file mode 100644 index 0000000000..c1f5d52a72 --- /dev/null +++ b/cli/administration/deploy/development/docker_root.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +from .profile import Profile + + +def _resolve_docker_root() -> Path: + raw = (os.environ.get("INFINITO_DOCKER_VOLUME") or "").strip().rstrip("/") + if not raw: + raise RuntimeError("INFINITO_DOCKER_VOLUME must be set") + return Path(raw) + + +def _wipe_docker_root(docker_root: Path) -> None: + if not docker_root.exists(): + print(f">>> Docker root does not exist, nothing to clean: {docker_root}") + return + print(f">>> CI cleanup: wiping Docker root: {docker_root}") + subprocess.run(["sudo", "rm", "-rf", str(docker_root)], check=True) + subprocess.run(["sudo", "mkdir", "-p", str(docker_root)], check=True) + subprocess.run( + ["sudo", "chown", f"{os.getuid()}:{os.getgid()}", str(docker_root)], + check=True, + ) + leftovers = sorted(entry.name for entry in docker_root.iterdir()) + if leftovers: + raise RuntimeError( + f"Docker root survived the wipe: {docker_root} still holds {leftovers}" + ) + + +def _should_wipe_docker_root() -> bool: + if not Profile().docker_root_ephemeral(): + return False + return os.environ.get("INFINITO_PRESERVE_DOCKER_CACHE") != "true" + + +def cleanup_docker_root() -> None: + if not _should_wipe_docker_root(): + docker_vol = os.environ.get("INFINITO_DOCKER_VOLUME") or "(unset)" + print(f">>> Skipping Docker root wipe: {docker_vol}") + return + docker_root = _resolve_docker_root() + _wipe_docker_root(docker_root) diff --git a/cli/administration/deploy/development/down.py b/cli/administration/deploy/development/down.py index 2bd29871d6..ef281a6a98 100644 --- a/cli/administration/deploy/development/down.py +++ b/cli/administration/deploy/development/down.py @@ -1,69 +1,18 @@ from __future__ import annotations -import os -import subprocess -from pathlib import Path from typing import TYPE_CHECKING from . import PROJECT_ROOT +from .compose import Compose from .env import resolve_distro if TYPE_CHECKING: import argparse - - -def _resolve_docker_root() -> Path: - raw = (os.environ.get("INFINITO_DOCKER_VOLUME") or "").strip().rstrip("/") - if not raw: - raise RuntimeError("INFINITO_DOCKER_VOLUME must be set") - return Path(raw) - - -def _wipe_docker_root(docker_root: Path) -> None: - if not docker_root.exists(): - print(f">>> Docker root does not exist, nothing to clean: {docker_root}") - return - print(f">>> CI cleanup: wiping Docker root: {docker_root}") - subprocess.run(["sudo", "rm", "-rf", str(docker_root)], check=True) - subprocess.run(["sudo", "mkdir", "-p", str(docker_root)], check=True) - subprocess.run( - ["sudo", "chown", f"{os.getuid()}:{os.getgid()}", str(docker_root)], - check=True, - ) - leftovers = sorted(entry.name for entry in docker_root.iterdir()) - if leftovers: - raise RuntimeError( - f"Docker root survived the wipe: {docker_root} still holds {leftovers}" - ) - - -def _should_wipe_docker_root() -> bool: - from .profile import Profile - - if not Profile().docker_root_ephemeral(): - return False - return os.environ.get("INFINITO_PRESERVE_DOCKER_CACHE") != "true" - - -def _cleanup_docker_root() -> None: - if not _should_wipe_docker_root(): - docker_vol = os.environ.get("INFINITO_DOCKER_VOLUME") or "(unset)" - print(f">>> Skipping Docker root wipe: {docker_vol}") - return - docker_root = _resolve_docker_root() - _wipe_docker_root(docker_root) + from pathlib import Path def down_stack(*, repo_root: Path, distro: str) -> None: - from .compose import Compose - - print(">>> Stopping compose stack and removing volumes") - try: - Compose(repo_root=repo_root, distro=distro).run( - ["down", "--remove-orphans", "-v"] - ) - finally: - _cleanup_docker_root() + Compose(repo_root=repo_root, distro=distro).down() def add_parser(sub: argparse._SubParsersAction) -> None: diff --git a/cli/administration/deploy/development/inventory/__init__.py b/cli/administration/deploy/development/inventory/__init__.py index 5fab98bf9d..a6d6c77983 100644 --- a/cli/administration/deploy/development/inventory/__init__.py +++ b/cli/administration/deploy/development/inventory/__init__.py @@ -20,14 +20,17 @@ Internal layout (one module per responsibility): * :mod:`.spec` — :class:`~.spec.DevInventorySpec` + ``PlanEntry`` type * :mod:`.payload` — variant payload pick + ``--vars`` bake -* :mod:`.legacy_resolver` — ``CombinedResolver``-driven include resolution +* :mod:`.legacy_resolver` - orphan pruning after ``disable`` * :mod:`.planner` — :func:`plan_dev_inventory_matrix` * :mod:`.builder` — :func:`build_dev_inventory` + matrix orchestrator -The private helpers (``_resolve_round_include`` and friends) are -re-exported below because unit tests historically patch them under this -package path. New tests SHOULD patch the submodule path directly -(e.g. ``inventory.legacy_resolver._resolve_round_include``). +The round's include set is resolved by +``utils.roles.applications.variants._resolve_round_include``. + +The private helpers (``_bake_overrides`` and friends) are re-exported +below because unit tests historically patch them under this package +path. New tests SHOULD patch the submodule path directly +(e.g. ``inventory.payload._bake_overrides``). ``DevInventorySpec`` and ``PlanEntry`` are imported but deliberately absent from ``__all__``: listing a re-exported class makes autodoc document it here @@ -40,7 +43,6 @@ from __future__ import annotations from .builder import build_dev_inventory, build_dev_inventory_matrix from .legacy_resolver import ( _build_services_overrides_for_round, - _resolve_round_include, prune_orphans_after_disable, ) from .payload import _bake_overrides, _resolve_variant_payloads @@ -51,7 +53,6 @@ from .spec import PlanEntry as PlanEntry __all__ = [ "_bake_overrides", "_build_services_overrides_for_round", - "_resolve_round_include", "_resolve_variant_payloads", "build_dev_inventory", "build_dev_inventory_matrix", diff --git a/cli/administration/deploy/development/inventory/legacy_resolver.py b/cli/administration/deploy/development/inventory/legacy_resolver.py index 77870a4a30..3f880466b8 100644 --- a/cli/administration/deploy/development/inventory/legacy_resolver.py +++ b/cli/administration/deploy/development/inventory/legacy_resolver.py @@ -1,15 +1,15 @@ -"""Default (non-variant) include resolution for the matrix planner. +"""Orphan pruning for the matrix planner's rounds after a `disable`. When NO primary app ships a `meta/variants.yml`, the planner falls back -to this path — the `CombinedResolver` walks `dependencies` and -`shared:`-edges in the variant-merged services map and Jinja flags are -evaluated at deploy time against `group_names`. `run_after` is NOT -followed for inclusion (it is a pure ordering hint), so a variant that -disables a service does not get the provider re-added through the -ordering edge. This module owns the include resolution that path needs -and nothing else; the round's variant-merged services maps come from +to the `CombinedResolver`, which walks `dependencies` and `shared:`-edges +in the variant-merged services map; Jinja flags are evaluated at deploy +time against `group_names`. `run_after` is NOT followed for inclusion (it +is a pure ordering hint), so a variant that disables a service does not +get the provider re-added through the ordering edge. The round's include +set and its variant-merged services maps come from `utils.roles.applications.variants`, which the CI selection resolves its -closure from as well. +closure from as well; this module cuts that include once `disable` drops +a provider. """ from __future__ import annotations @@ -24,52 +24,6 @@ if TYPE_CHECKING: _build_services_overrides_for_round = services_overrides_for_round -def _resolve_round_include( - *, - primary_apps: Sequence[str], - services_overrides: dict[str, dict], -) -> tuple[str, ...]: - """Resolve transitive prerequisites for each primary app under a - round's variant-merged services map. Returns the full include set - in stable order (deps first per primary, primary last; primaries - iterated in the user-provided order). - - A non-invokable prerequisite is dropped from the result. The include - set becomes an inventory group per entry and a deploy id the play - dispatches, and `utils.roles.stage` only ever loops over invokable - paths, so a non-invokable id could never be dispatched from one. - Keeping it would abort the round before ansible starts, which is - what `user-workstation` did to every desktop round, and inventing a - group for it instead would produce one nothing dispatches. The role - still reaches the host through whatever pulled it into the closure: - a meta dependency, or the service edge `sys-service-loader` reads. - - The resolver import is deferred so the host-side import surface - stays lean for callers that never need the variant-aware planner - (e.g. lint/validation). - """ - from cli.meta.roles.applications.resolution.combined.resolver import ( - CombinedResolver, - ) - from utils.roles.required_by_coverage import role_is_invokable - - resolver = CombinedResolver( - services_overrides=services_overrides, follow_run_after=False - ) - out: list[str] = [] - seen: set[str] = set() - for app_id in primary_apps: - deps = resolver.resolve(app_id) - for dep in deps: - if dep != app_id and dep not in seen and role_is_invokable(dep): - out.append(dep) - seen.add(dep) - if app_id not in seen: - out.append(app_id) - seen.add(app_id) - return tuple(out) - - def prune_orphans_after_disable( *, include: Sequence[str], diff --git a/cli/administration/deploy/development/inventory/planner.py b/cli/administration/deploy/development/inventory/planner.py index 5de21fe475..849b4d9389 100644 --- a/cli/administration/deploy/development/inventory/planner.py +++ b/cli/administration/deploy/development/inventory/planner.py @@ -2,7 +2,8 @@ Pure function — reads role metadata via cached YAML helpers and emits ``PlanEntry`` tuples; no filesystem side effects. The include set per -round is resolved by the ``CombinedResolver`` (see ``.legacy_resolver``): +round is resolved by the ``CombinedResolver`` (see +``utils.roles.applications.variants._resolve_round_include``): each role contributes its own pulled-in providers and the include is the union. A service-key is therefore pulled in as soon as ANY role in the round-aware closure says it should be (literal ``True`` OR the diff --git a/cli/administration/inventory/credentials/__main__.py b/cli/administration/inventory/credentials/__main__.py index fd0230bb9a..facdc7c2bb 100755 --- a/cli/administration/inventory/credentials/__main__.py +++ b/cli/administration/inventory/credentials/__main__.py @@ -28,7 +28,7 @@ from typing import Any from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap -from cli.administration.inventory.provision.ruamel_io import round_trip_yaml +from cli.administration.inventory.ruamel_io import round_trip_yaml from utils.manager.inventory import InventoryManager from .emit import ( diff --git a/cli/administration/inventory/credentials/reset/cli.py b/cli/administration/inventory/credentials/reset/cli.py index 74c7e0e913..299d9765c3 100644 --- a/cli/administration/inventory/credentials/reset/cli.py +++ b/cli/administration/inventory/credentials/reset/cli.py @@ -23,7 +23,7 @@ from cli.administration.inventory.provision.project import ( detect_project_root, ) from cli.administration.inventory.provision.reset import reset_credentials -from cli.administration.inventory.provision.ruamel_io import ( +from cli.administration.inventory.ruamel_io import ( dump_document, load_document, ) diff --git a/cli/administration/inventory/mesh/inventory.py b/cli/administration/inventory/mesh/inventory.py index 3f96985ea8..c4f2ac6966 100644 --- a/cli/administration/inventory/mesh/inventory.py +++ b/cli/administration/inventory/mesh/inventory.py @@ -5,7 +5,7 @@ import re from pathlib import Path from typing import Any -from cli.administration.inventory.provision.ruamel_io import load_document +from cli.administration.inventory.ruamel_io import load_document from utils import PROJECT_ROOT from utils.cache.yaml import load_yaml_any from utils.networks.mesh import ( diff --git a/cli/administration/inventory/mesh/transport.py b/cli/administration/inventory/mesh/transport.py index 69d23568da..39e2220575 100644 --- a/cli/administration/inventory/mesh/transport.py +++ b/cli/administration/inventory/mesh/transport.py @@ -4,7 +4,7 @@ import shlex from configparser import ConfigParser from typing import TYPE_CHECKING -from cli.administration.inventory.provision.ruamel_io import ( +from cli.administration.inventory.ruamel_io import ( dump_document, load_document, ) diff --git a/cli/administration/inventory/mesh/write.py b/cli/administration/inventory/mesh/write.py index 2b4cf4b214..f74406138a 100644 --- a/cli/administration/inventory/mesh/write.py +++ b/cli/administration/inventory/mesh/write.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING from ruamel.yaml.comments import CommentedMap, CommentedSeq -from cli.administration.inventory.provision.ruamel_io import ( +from cli.administration.inventory.ruamel_io import ( dump_document, ensure_map, load_document, diff --git a/cli/administration/inventory/provision/credentials_generator.py b/cli/administration/inventory/provision/credentials_generator.py index b0a3a4f826..61964959f8 100644 --- a/cli/administration/inventory/provision/credentials_generator.py +++ b/cli/administration/inventory/provision/credentials_generator.py @@ -12,9 +12,13 @@ from cli.administration.inventory.credentials.emit import ( credentials_map, declared_credentials, ) +from cli.administration.inventory.ruamel_io import ( + dump_document, + ensure_map, + load_document, +) from .role_resolver import resolve_role_path -from .ruamel_io import dump_document, ensure_map, load_document if TYPE_CHECKING: from pathlib import Path diff --git a/cli/administration/inventory/provision/host_vars.py b/cli/administration/inventory/provision/host_vars.py index 550f51aa6e..b35eb17bcb 100644 --- a/cli/administration/inventory/provision/host_vars.py +++ b/cli/administration/inventory/provision/host_vars.py @@ -6,10 +6,14 @@ from typing import TYPE_CHECKING, Any from ruamel.yaml.comments import CommentedMap +from cli.administration.inventory.ruamel_io import ( + dump_document, + load_document, + vault_value, +) from utils.cache.yaml import load_yaml_any from .passwords import generate_random_password -from .ruamel_io import dump_document, load_document, vault_value if TYPE_CHECKING: from pathlib import Path diff --git a/cli/administration/inventory/provision/mirror_overrides.py b/cli/administration/inventory/provision/mirror_overrides.py index fb59acacde..6d2c666032 100644 --- a/cli/administration/inventory/provision/mirror_overrides.py +++ b/cli/administration/inventory/provision/mirror_overrides.py @@ -2,10 +2,13 @@ from __future__ import annotations from typing import TYPE_CHECKING +from cli.administration.inventory.ruamel_io import ( + dump_document, + ensure_map, + load_document, +) from utils.cache.yaml import load_yaml_any -from .ruamel_io import dump_document, ensure_map, load_document - if TYPE_CHECKING: from pathlib import Path diff --git a/cli/administration/inventory/provision/network_mode.py b/cli/administration/inventory/provision/network_mode.py index dacd835ed4..b61a48625b 100644 --- a/cli/administration/inventory/provision/network_mode.py +++ b/cli/administration/inventory/provision/network_mode.py @@ -9,10 +9,9 @@ from __future__ import annotations import os from typing import TYPE_CHECKING +from cli.administration.inventory.ruamel_io import dump_document, load_document from utils.networks.reachability import NODE_MODES -from .ruamel_io import dump_document, load_document - if TYPE_CHECKING: from pathlib import Path diff --git a/cli/administration/inventory/provision/reset.py b/cli/administration/inventory/provision/reset.py index ea0f570aa5..3be98acd0a 100644 --- a/cli/administration/inventory/provision/reset.py +++ b/cli/administration/inventory/provision/reset.py @@ -16,11 +16,11 @@ from typing import TYPE_CHECKING from ruamel.yaml.comments import CommentedMap from cli.administration.inventory.credentials.vault import is_ruamel_vault +from cli.administration.inventory.ruamel_io import dump_document, load_document from utils.manager.credential_key import CREDENTIALS_KEY, SECRETS_KEY from utils.roles.mapping import ROLE_FILE_META_SECRETS, ROLE_FILE_VARS_MAIN from .credentials_generator import generate_credentials_for_roles -from .ruamel_io import dump_document, load_document from .users_generator import generate_user_passwords, required_user_policies if TYPE_CHECKING: diff --git a/cli/administration/inventory/provision/services/disabler.py b/cli/administration/inventory/provision/services/disabler.py index 26755c2995..bf19066264 100644 --- a/cli/administration/inventory/provision/services/disabler.py +++ b/cli/administration/inventory/provision/services/disabler.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING from ruamel.yaml.comments import CommentedMap -from cli.administration.inventory.provision.ruamel_io import ( +from cli.administration.inventory.ruamel_io import ( dump_document, load_document, round_trip_yaml, diff --git a/cli/administration/inventory/provision/tor_node.py b/cli/administration/inventory/provision/tor_node.py index 450a4290d2..f510cc45da 100644 --- a/cli/administration/inventory/provision/tor_node.py +++ b/cli/administration/inventory/provision/tor_node.py @@ -13,8 +13,11 @@ from __future__ import annotations from typing import TYPE_CHECKING from cli.administration.inventory.onion import ensure_node_onion - -from .ruamel_io import dump_document, ensure_map, load_document +from cli.administration.inventory.ruamel_io import ( + dump_document, + ensure_map, + load_document, +) if TYPE_CHECKING: from pathlib import Path diff --git a/cli/administration/inventory/provision/users_generator.py b/cli/administration/inventory/provision/users_generator.py index 4acd36ee76..203908019f 100644 --- a/cli/administration/inventory/provision/users_generator.py +++ b/cli/administration/inventory/provision/users_generator.py @@ -13,12 +13,17 @@ from __future__ import annotations from collections.abc import Mapping from typing import TYPE_CHECKING, Any +from cli.administration.inventory.ruamel_io import ( + dump_document, + ensure_map, + load_document, + vault_value, +) from utils.cache.users import get_user_defaults from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_META_USERS from .passwords import generate_declared_user_password -from .ruamel_io import dump_document, ensure_map, load_document, vault_value if TYPE_CHECKING: from pathlib import Path diff --git a/cli/administration/inventory/provision/ruamel_io.py b/cli/administration/inventory/ruamel_io.py similarity index 94% rename from cli/administration/inventory/provision/ruamel_io.py rename to cli/administration/inventory/ruamel_io.py index 79f4a6e02d..b138d2e748 100644 --- a/cli/administration/inventory/provision/ruamel_io.py +++ b/cli/administration/inventory/ruamel_io.py @@ -1,6 +1,6 @@ -"""Round-trip YAML access for the inventory files this package rewrites. +"""Round-trip YAML access for the inventory files the inventory CLIs rewrite. -The counterpart to :mod:`yaml_io`, which reads values. Everything here keeps +The counterpart to :mod:`.provision.yaml_io`, which reads values. Everything here keeps comments, quoting and vault tags intact, because host_vars is hand-edited as often as it is generated. """ diff --git a/docs/contributing/artefact/files/plugins/lookup/users.md b/docs/contributing/artefact/files/plugins/lookup/users.md index f01371fe64..4bc13b57c9 100644 --- a/docs/contributing/artefact/files/plugins/lookup/users.md +++ b/docs/contributing/artefact/files/plugins/lookup/users.md @@ -109,6 +109,7 @@ platform_administrator: | [users.py](../../../../../../plugins/lookup/users.py) | Runtime entry point for the `users` lookup. | | `utils/cache/users/` | Shared aggregation helper package that builds and caches defaults, handles reserved users, UID/GID allocation, and uniqueness validation. Placeholder substitution (DOMAIN_PRIMARY / ORGANIZATION / SOFTWARE_NAME) lives in [users/placeholders.py](../../../../../../utils/cache/users/placeholders.py), the validation of every `forward` in [users/forwards.py](../../../../../../utils/cache/users/forwards.py). | | [carrier.py](../../../../../../utils/cache/carrier.py) | The play-scoped carrier: fact name, `merged_users_cache_key`, and the reader that serves the carried payload. | +| [tokens.py](../../../../../../utils/cache/tokens.py) | The token store the users are hydrated from: the tokens file, the `sys_token_store_users` fact and the digest both cache keys share. | | [test_users.py](../../../../../../tests/unit/python/plugins/lookup/test_users.py) | Unit tests covering the full-dict, single-entry, override, strict missing, and non-strict missing cases. | For the related applications pattern see [applications.md](applications.md). diff --git a/docs/contributing/design/inventory.md b/docs/contributing/design/inventory.md index e37266dbbf..6cfdcf63e7 100644 --- a/docs/contributing/design/inventory.md +++ b/docs/contributing/design/inventory.md @@ -18,7 +18,7 @@ After stage 3 the inventory is fully variant-resolved on disk. Ansible loads it ## What decides which roles enter the inventory 🎯 -The include set passed to stage 2 is built per round by the matrix planner: [deploy/cli.py](../../../cli/administration/deploy/development/deploy/cli.py) and [init.py](../../../cli/administration/deploy/development/init.py) call `plan_dev_inventory_matrix` in [planner.py](../../../cli/administration/deploy/development/inventory/planner.py), which resolves each round's include via `_resolve_round_include` in [legacy_resolver.py](../../../cli/administration/deploy/development/inventory/legacy_resolver.py) using the [CombinedResolver](../../../cli/meta/roles/applications/resolution/combined/resolver.py) with `follow_run_after=False`. The swarm test path computes its include separately via [derive_includes.py](../../../utils/tests/swarm/derive_includes.py), reading the active variant map from `INFINITO_APP_VARIANTS`. Both expand the selection along two transitive paths: +The include set passed to stage 2 is built per round by the matrix planner: [deploy/cli.py](../../../cli/administration/deploy/development/deploy/cli.py) and [init.py](../../../cli/administration/deploy/development/init.py) call `plan_dev_inventory_matrix` in [planner.py](../../../cli/administration/deploy/development/inventory/planner.py), which resolves each round's include via `_resolve_round_include` in [variants.py](../../../utils/roles/applications/variants.py) using the [CombinedResolver](../../../cli/meta/roles/applications/resolution/combined/resolver.py) with `follow_run_after=False`. The swarm test path computes its include separately via [derive_includes.py](../../../utils/tests/swarm/derive_includes.py), reading the active variant map from `INFINITO_APP_VARIANTS`. Both expand the selection along two transitive paths: 1. **Ansible meta `dependencies:`** from each role's `meta/main.yml`. 2. **Shared-service auto-include** from each role's `meta/services.yml..` block, when both `enabled` AND `shared` pass `is_explicit_truth` in [registry.py](../../../utils/roles/applications/services/registry.py): the literal `True` or the dynamic form `"{{ '' in group_names }}"`. A literal `false` (as baked by a variant override) does NOT qualify. diff --git a/docs/contributing/design/variants.md b/docs/contributing/design/variants.md index e673872453..cddeb21622 100644 --- a/docs/contributing/design/variants.md +++ b/docs/contributing/design/variants.md @@ -62,7 +62,7 @@ Apps without a `meta/variants.yml` file collapse to a single empty overlay in `_ |---|---| | [variants.md](../artefact/files/role/variants.md) | File-structure rules for `roles//meta/variants.yml`. | | [applications.py (cache)](../../../utils/cache/applications.py) | Loader and cache for `_build_variants` (`get_variants` is the public Python entry point). The merged-applications path stays variant-agnostic; variant payloads reach it as inventory-level `applications.` overrides. | -| [inventory/](../../../cli/administration/deploy/development/inventory/__init__.py) | Dev inventory build package. Per-submodule split: [`spec.py`](../../../cli/administration/deploy/development/inventory/spec.py) (`DevInventorySpec`), [`builder.py`](../../../cli/administration/deploy/development/inventory/builder.py) (`build_dev_inventory` variant baking + `build_dev_inventory_matrix` per-round driver), [`planner.py`](../../../cli/administration/deploy/development/inventory/planner.py) (`plan_dev_inventory_matrix` pure planner shared with the deploy wrapper), [`legacy_resolver.py`](../../../cli/administration/deploy/development/inventory/legacy_resolver.py) (`CombinedResolver`-driven include resolution). | +| [inventory/](../../../cli/administration/deploy/development/inventory/__init__.py) | Dev inventory build package. Per-submodule split: [`spec.py`](../../../cli/administration/deploy/development/inventory/spec.py) (`DevInventorySpec`), [`builder.py`](../../../cli/administration/deploy/development/inventory/builder.py) (`build_dev_inventory` variant baking + `build_dev_inventory_matrix` per-round driver), [`planner.py`](../../../cli/administration/deploy/development/inventory/planner.py) (`plan_dev_inventory_matrix` pure planner shared with the deploy wrapper), [`legacy_resolver.py`](../../../cli/administration/deploy/development/inventory/legacy_resolver.py) (orphan pruning after `disable`; the include itself comes from [`variants.py`](../../../utils/roles/applications/variants.py)). | | [init.py](../../../cli/administration/deploy/development/init.py) | Dev CLI entry that drives `build_dev_inventory_matrix` to materialise `-` folders. | | [deploy/cli.py](../../../cli/administration/deploy/development/deploy/cli.py) | Dev CLI entry that re-derives the matrix plan and iterates one deploy per folder, with per-app cleanup between rounds. | | [entity.sh](../../../scripts/tests/deploy/local/purge/entity.sh) | Cleanup script invoked between rounds for every app in the previous round's include set. | diff --git a/inventories/development/tools.yml.j2 b/inventories/development/tools.yml.j2 index fa231e4418..ce212ca443 100644 --- a/inventories/development/tools.yml.j2 +++ b/inventories/development/tools.yml.j2 @@ -1,6 +1,6 @@ --- # Host vars the tools runner deploys its toolchain services with. -# Rendered by utils.inventory.tools with square-bracket delimiters, so the +# Rendered by utils.inventory.tools_vars with square-bracket delimiters, so the # curly-brace expressions below stay untouched for the deploy to resolve. TLS_MODE: self_signed diff --git a/plugins/lookup/applications.py b/plugins/lookup/applications.py index 74acce51c4..e0890168ee 100644 --- a/plugins/lookup/applications.py +++ b/plugins/lookup/applications.py @@ -5,11 +5,10 @@ from typing import Any from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase -from utils.cache import _reset_cache_for_tests as _reset_runtime_lookup_cache - # nocheck: lookup-cache-import (this lookup IS the applications SPOT provider) from utils.cache.applications import get_merged_applications from utils.cache.carrier import merged_applications_cache_key +from utils.cache.reset import _reset_cache_for_tests as _reset_runtime_lookup_cache def _reset_cache_for_tests() -> None: diff --git a/plugins/lookup/domains.py b/plugins/lookup/domains.py index 6a9a73108c..efb7b4a3ef 100644 --- a/plugins/lookup/domains.py +++ b/plugins/lookup/domains.py @@ -5,10 +5,9 @@ from typing import Any from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase -from utils.cache import _reset_cache_for_tests as _reset_runtime_lookup_cache - # nocheck: lookup-cache-import from utils.cache.domains import get_merged_domains +from utils.cache.reset import _reset_cache_for_tests as _reset_runtime_lookup_cache def _reset_cache_for_tests() -> None: diff --git a/plugins/lookup/users.py b/plugins/lookup/users.py index cedcf6516a..41a06c8fb8 100644 --- a/plugins/lookup/users.py +++ b/plugins/lookup/users.py @@ -5,8 +5,8 @@ from typing import Any from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase -from utils.cache import _reset_cache_for_tests as _reset_runtime_lookup_cache from utils.cache.carrier import merged_users_cache_key +from utils.cache.reset import _reset_cache_for_tests as _reset_runtime_lookup_cache # nocheck: lookup-cache-import (this lookup IS the users SPOT provider) from utils.cache.users import get_merged_users diff --git a/tests/integration/ansible/lookups/test_resource_in_applications_render.py b/tests/integration/ansible/lookups/test_resource_in_applications_render.py index a62a89a998..14f8af7a6a 100644 --- a/tests/integration/ansible/lookups/test_resource_in_applications_render.py +++ b/tests/integration/ansible/lookups/test_resource_in_applications_render.py @@ -24,9 +24,9 @@ import unittest from ansible.parsing.dataloader import DataLoader from ansible.template import Templar -from utils.cache import _reset_cache_for_tests from utils.cache.applications import get_merged_applications from utils.cache.errors import is_unresolvable +from utils.cache.reset import _reset_cache_for_tests from . import PROJECT_ROOT diff --git a/tests/integration/infrastructure/services/test_disabled_provider_dependents.py b/tests/integration/infrastructure/services/test_disabled_provider_dependents.py index 3d07d9770f..a7c081b6ed 100644 --- a/tests/integration/infrastructure/services/test_disabled_provider_dependents.py +++ b/tests/integration/infrastructure/services/test_disabled_provider_dependents.py @@ -39,8 +39,8 @@ from cli.administration.inventory.provision.services.disabler import ( parse_services_disabled, reconcile_services_disabled_from_env, ) -from utils.cache import _reset_cache_for_tests from utils.cache.applications import get_merged_applications +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import dump_yaml, load_yaml_any from utils.github.variant.network import TOR, disabled_services 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 bc39917893..ddf9dbdefb 100644 --- a/tests/integration/roles/meta/variants/test_variant_pin_required.py +++ b/tests/integration/roles/meta/variants/test_variant_pin_required.py @@ -36,13 +36,13 @@ import functools import re import unittest -from cli.administration.deploy.development.inventory.legacy_resolver import ( - _resolve_round_include, -) 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.variants import services_overrides_for_round +from utils.roles.applications.variants import ( + _resolve_round_include, + services_overrides_for_round, +) from utils.roles.guide import GUIDE_SERVICE_KEY, guide_off from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_VARIANTS diff --git a/tests/integration/roles/sys-stk-front-proxy/test_body_filter_fold_render.py b/tests/integration/roles/sys-stk-front-proxy/test_body_filter_fold_render.py index ac3471c066..292e1db787 100644 --- a/tests/integration/roles/sys-stk-front-proxy/test_body_filter_fold_render.py +++ b/tests/integration/roles/sys-stk-front-proxy/test_body_filter_fold_render.py @@ -22,8 +22,8 @@ from ansible.plugins.loader import filter_loader from ansible.template import Templar, trust_as_template from plugins.action.stack_host_template import ActionModule as StackHostTemplate -from utils.cache import _reset_cache_for_tests from utils.cache.files import PROJECT_ROOT, iter_project_files, read_text +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import load_yaml_any from utils.domains.default_primary import default_domain_primary from utils.roles.mapping import ( diff --git a/tests/lint/repository/python/test_import_cycles.py b/tests/lint/repository/python/test_import_cycles.py new file mode 100644 index 0000000000..0081935253 --- /dev/null +++ b/tests/lint/repository/python/test_import_cycles.py @@ -0,0 +1,383 @@ +from __future__ import annotations + +import ast +import unittest +from pathlib import Path + +from utils.cache.files import iter_non_ignored_files, read_text + +from . import PROJECT_ROOT + + +def _packages(root: Path) -> frozenset[str]: + """ + Args: + root: the repository root. + + Returns: + The top-level directories that are Python packages. + """ + return frozenset(init.parent.name for init in root.glob("*/__init__.py")) + + +def _module_name(rel: Path) -> tuple[str, bool]: + """ + Args: + rel: the file's path relative to the repository root. + + Returns: + The dotted name of a module and whether it is a package. + """ + parts = list(rel.with_suffix("").parts) + package = parts[-1] == "__init__" + if package: + parts.pop() + return ".".join(parts), package + + +def _guarded(node: ast.If) -> bool: + """ + Args: + node: the ``if`` statement. + + Returns: + Whether an ``if`` body runs only when the module executes as ``__main__``. + """ + test = node.test + return ( + isinstance(test, ast.Compare) + and isinstance(test.left, ast.Name) + and test.left.id == "__name__" + and any( + isinstance(c, ast.Constant) and c.value == "__main__" + for c in test.comparators + ) + ) + + +def _statements(tree: ast.AST) -> list[ast.Import | ast.ImportFrom]: + """ + Args: + tree: the parsed module. + + Returns: + Every import statement that can run, at any depth. + """ + found: list[ast.Import | ast.ImportFrom] = [] + pending: list[ast.AST] = [tree] + while pending: + node = pending.pop() + if isinstance(node, (ast.Import, ast.ImportFrom)): + found.append(node) + elif isinstance(node, ast.If) and _guarded(node): + pending.extend(node.orelse) + else: + pending.extend(ast.iter_child_nodes(node)) + return found + + +def _base(node: ast.ImportFrom, module: str, package: bool) -> str: + """ + Args: + node: the statement. + module: dotted name of the importing module. + package: whether the importing module is a package. + + Returns: + The dotted name, empty when a relative import climbs above the tree. + """ + if not node.level: + return node.module or "" + anchor = module.split(".") if package else module.split(".")[:-1] + keep = len(anchor) - (node.level - 1) + if keep <= 0: + return "" + return ".".join([*anchor[:keep], *([node.module] if node.module else [])]) + + +def _targets( + node: ast.Import | ast.ImportFrom, module: str, package: bool, known: set[str] +) -> list[str]: + """ + Args: + node: the statement. + module: dotted name of the importing module. + package: whether the importing module is a package. + known: every module of the tree. + + Returns: + Each module the statement names, plus every package above it, whose + ``__init__`` runs first. + """ + found: set[str] = set() + if isinstance(node, ast.Import): + found = {alias.name for alias in node.names if alias.name in known} + else: + base = _base(node, module, package) + for alias in node.names if base else (): + submodule = f"{base}.{alias.name}" + if submodule in known: + found.add(submodule) + elif base in known: + found.add(base) + parents = { + ".".join(parts[:depth]) + for parts in (target.split(".") for target in found) + for depth in range(1, len(parts)) + } + return sorted(found | (parents & known)) + + +def _edges( + sources: dict[str, tuple[str, bool, str]], +) -> list[tuple[str, str, str, int]]: + """ + Args: + sources: dotted module name to its path, package flag and text. + + Returns: + ``(importer, imported, path, line)`` per statement and target; a module + importing itself or one of its own parent packages adds nothing. + """ + known = set(sources) + edges: list[tuple[str, str, str, int]] = [] + for module, (rel, package, content) in sources.items(): + try: + tree = ast.parse(content) + except SyntaxError: + continue + for node in _statements(tree): + edges.extend( + (module, target, rel, node.lineno) + for target in _targets(node, module, package, known) + if target != module and not module.startswith(f"{target}.") + ) + return edges + + +def _components(graph: dict[str, set[str]]) -> list[set[str]]: + """ + Args: + graph: importer to the modules it imports. + + Returns: + The strongly connected components that hold more than one module. + """ + index: dict[str, int] = {} + low: dict[str, int] = {} + stack: list[str] = [] + on_stack: set[str] = set() + found: list[set[str]] = [] + for start in sorted(graph): + if start in index: + continue + index[start] = low[start] = len(index) + stack.append(start) + on_stack.add(start) + work = [(start, iter(sorted(graph[start])))] + while work: + node, children = work[-1] + child = next(children, None) + if child is not None: + if child not in index: + index[child] = low[child] = len(index) + stack.append(child) + on_stack.add(child) + work.append((child, iter(sorted(graph.get(child, ()))))) + elif child in on_stack: + low[node] = min(low[node], index[child]) + continue + work.pop() + if work: + parent = work[-1][0] + low[parent] = min(low[parent], low[node]) + if low[node] != index[node]: + continue + component: set[str] = set() + while True: + member = stack.pop() + on_stack.discard(member) + component.add(member) + if member == node: + break + if len(component) > 1: + found.append(component) + return found + + +def _cycles(sources: dict[str, tuple[str, bool, str]]) -> list[list[str]]: + """ + Args: + sources: dotted module name to its path, package flag and text. + + Returns: + One list per component: its members, then ``path:line: a -> b`` for + every import inside it. + """ + edges = _edges(sources) + graph: dict[str, set[str]] = {module: set() for module in sources} + for importer, imported, _rel, _line in edges: + graph[importer].add(imported) + report: list[list[str]] = [] + for component in _components(graph): + inside = sorted( + f"{rel}:{line}: {importer} -> {imported}" + for importer, imported, rel, line in edges + if importer in component and imported in component + ) + report.append([" <-> ".join(sorted(component)), *inside]) + return sorted(report) + + +def _sources(root: Path) -> dict[str, tuple[str, bool, str]]: + """ + Args: + root: the repository root. + + Returns: + Every module of the repository's own packages. + """ + packages = _packages(root) + sources: dict[str, tuple[str, bool, str]] = {} + for path in iter_non_ignored_files(extensions=(".py",)): + rel = Path(path).relative_to(root) + if rel.parts[0] not in packages: + continue + try: + content = read_text(str(path)) + except (OSError, UnicodeDecodeError): + continue + name, package = _module_name(rel) + sources[name] = (rel.as_posix(), package, content) + return sources + + +class TestImportCycles(unittest.TestCase): + def test_no_repository_module_imports_into_a_cycle(self) -> None: + cycles = _cycles(_sources(PROJECT_ROOT)) + statements = sum(len(cycle) - 1 for cycle in cycles) + report = "\n".join( + f" - {cycle[0]}\n" + "\n".join(f" {edge}" for edge in cycle[1:]) + for cycle in cycles + ) + self.assertFalse( + cycles, + f"{len(cycles)} import cycle(s) through {statements} import " + f"statement(s):\n{report}\n\n" + "Move what both sides need into the lower module, or into a new " + "module both import, so neither has to defer its import.", + ) + + +def _source(text: str, package: bool = False) -> tuple[str, bool, str]: + """ + Args: + text: the module's source. + package: whether the module is a package. + + Returns: + A test module entry. + """ + return ("m.py", package, text) + + +class TestCycleDetection(unittest.TestCase): + def test_a_module_level_pair_is_reported(self) -> None: + cycles = _cycles( + {"p.a": _source("import p.b"), "p.b": _source("from p.a import x")} + ) + + self.assertEqual( + [["p.a <-> p.b", "m.py:1: p.a -> p.b", "m.py:1: p.b -> p.a"]], cycles + ) + + def test_a_deferred_import_still_closes_the_cycle(self) -> None: + sources = { + "p.a": _source("import p.b"), + "p.b": _source("def f():\n from p.a import x"), + } + + self.assertEqual(["p.a <-> p.b"], [c[0] for c in _cycles(sources)]) + + def test_a_type_checking_import_closes_the_cycle(self) -> None: + sources = { + "p.a": _source("import p.b"), + "p.b": _source("if TYPE_CHECKING:\n from p.a import X"), + } + + self.assertEqual(["p.a <-> p.b"], [c[0] for c in _cycles(sources)]) + + def test_importing_a_submodule_also_imports_its_package(self) -> None: + sources = { + "pp": _source("from xx import f", package=True), + "pp.s": _source("G = 1"), + "xx": _source("from pp.s import G"), + } + + self.assertEqual( + [["pp <-> xx", "m.py:1: pp -> xx", "m.py:1: xx -> pp"]], _cycles(sources) + ) + + def test_a_plain_submodule_import_also_imports_its_package(self) -> None: + sources = { + "pp": _source("import xx", package=True), + "pp.s": _source("G = 1"), + "xx": _source("def f():\n import pp.s"), + } + + self.assertEqual(["pp <-> xx"], [c[0] for c in _cycles(sources)]) + + def test_a_main_guard_import_is_skipped(self) -> None: + sources = { + "p.a": _source("import p.b"), + "p.b": _source('if __name__ == "__main__":\n import p.a'), + } + + self.assertEqual([], _cycles(sources)) + + def test_a_relative_import_resolves_inside_the_package(self) -> None: + sources = { + "q.p.a": _source("from .b import x"), + "q.p.b": _source("from ..r import y"), + "q.r": _source("from .p.a import z"), + } + + self.assertEqual(["q.p.a <-> q.p.b <-> q.r"], [c[0] for c in _cycles(sources)]) + + def test_a_submodule_named_by_from_import_is_the_target(self) -> None: + sources = { + "p": _source("", package=True), + "p.a": _source("from p import b"), + "p.b": _source("from p.a import x"), + } + + self.assertEqual(["p.a <-> p.b"], [c[0] for c in _cycles(sources)]) + + def test_a_submodule_reading_its_parent_package_is_left_out(self) -> None: + sources = { + "p": _source("ROOT = 1\nfrom . import a", package=True), + "p.a": _source("from . import ROOT"), + } + + self.assertEqual([], _cycles(sources)) + + def test_a_longer_cycle_lists_every_member(self) -> None: + sources = { + "p.a": _source("import p.b"), + "p.b": _source("import p.c"), + "p.c": _source("import p.a"), + } + + self.assertEqual(["p.a <-> p.b <-> p.c"], [c[0] for c in _cycles(sources)]) + + def test_an_acyclic_graph_and_foreign_imports_pass(self) -> None: + sources = { + "p.a": _source("import os\nimport p.b"), + "p.b": _source("import yaml\nfrom p.c import x"), + } + + self.assertEqual([], _cycles(sources)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/oracle/test_system_one.py b/tests/oracle/test_system_one.py index 5bb3fcf73d..d1c9356212 100644 --- a/tests/oracle/test_system_one.py +++ b/tests/oracle/test_system_one.py @@ -31,7 +31,8 @@ from tests.utils.services import progress as _progress from utils.cache.yaml import load_yaml from utils.i18n.catalog import catalog_path, is_machine_translation, read_catalog from utils.i18n.spans import prose -from utils.inventory.tools import API_KEY, S1_ROLE, lane_url +from utils.inventory.tools import S1_ROLE, lane_url +from utils.inventory.tools_vars import API_KEY from utils.roles.mapping import ROLE_FILE_META_SERVICES from . import PROJECT_ROOT, SUITE diff --git a/tests/oracle/test_translation_score.py b/tests/oracle/test_translation_score.py index e3fd3128a6..a86e22ef3d 100644 --- a/tests/oracle/test_translation_score.py +++ b/tests/oracle/test_translation_score.py @@ -58,7 +58,8 @@ from utils.i18n.judge import MIDDLE, ChatJudge from utils.i18n.languages import DOMAINS, domain_languages, load_languages from utils.i18n.libretranslate import GATEWAY_ROLE, GATEWAY_SERVICE_KEY from utils.i18n.spans import prose -from utils.inventory.tools import LITELLM_KEY, lane_url +from utils.inventory.tools import lane_url +from utils.inventory.tools_vars import LITELLM_KEY from utils.roles.mapping import ROLE_FILE_META_SERVICES from . import PROJECT_ROOT, SUITE diff --git a/tests/unit/python/cli/administration/deploy/development/inventory/test_builder.py b/tests/unit/python/cli/administration/deploy/development/inventory/test_builder.py index 105ec385f9..0389388d89 100644 --- a/tests/unit/python/cli/administration/deploy/development/inventory/test_builder.py +++ b/tests/unit/python/cli/administration/deploy/development/inventory/test_builder.py @@ -255,7 +255,7 @@ class TestBuildDevInventoryMatrix(unittest.TestCase): self.compose.repo_root = Path("/tmp/infinito-nexus") @patch( - "cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include", + "utils.roles.applications.variants._resolve_round_include", autospec=True, ) @patch( diff --git a/tests/unit/python/cli/administration/deploy/development/inventory/test_legacy_resolver.py b/tests/unit/python/cli/administration/deploy/development/inventory/test_legacy_resolver.py index 04c2aaeaca..af961ebf2f 100644 --- a/tests/unit/python/cli/administration/deploy/development/inventory/test_legacy_resolver.py +++ b/tests/unit/python/cli/administration/deploy/development/inventory/test_legacy_resolver.py @@ -90,9 +90,7 @@ class TestRoundIncludeIsDispatchable(unittest.TestCase): """ def _include(self, primary: str) -> tuple[str, ...]: - from cli.administration.deploy.development.inventory.legacy_resolver import ( - _resolve_round_include, - ) + from utils.roles.applications.variants import _resolve_round_include return _resolve_round_include(primary_apps=[primary], services_overrides={}) diff --git a/tests/unit/python/cli/administration/deploy/development/inventory/test_planner.py b/tests/unit/python/cli/administration/deploy/development/inventory/test_planner.py index 516fc2b762..1d1fefcca1 100644 --- a/tests/unit/python/cli/administration/deploy/development/inventory/test_planner.py +++ b/tests/unit/python/cli/administration/deploy/development/inventory/test_planner.py @@ -1,6 +1,6 @@ """Unit tests for `cli.administration.deploy.development.inventory.planner`. -Covers ``plan_dev_inventory_matrix`` (mocking ``legacy_resolver``) and +Covers ``plan_dev_inventory_matrix`` (mocking the round include) and ``filter_plan_to_variants``. """ @@ -18,7 +18,7 @@ from cli.administration.deploy.development.inventory import ( class TestPlanDevInventoryMatrix(unittest.TestCase): @patch( - "cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include", + "utils.roles.applications.variants._resolve_round_include", autospec=True, ) @patch( @@ -54,7 +54,7 @@ class TestPlanDevInventoryMatrix(unittest.TestCase): ) @patch( - "cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include", + "utils.roles.applications.variants._resolve_round_include", autospec=True, ) @patch( @@ -100,7 +100,7 @@ class TestPlanDevInventoryMatrix(unittest.TestCase): ) @patch( - "cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include", + "utils.roles.applications.variants._resolve_round_include", autospec=True, ) @patch( @@ -154,7 +154,7 @@ class TestPlanDevInventoryMatrix(unittest.TestCase): ) @patch( - "cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include", + "utils.roles.applications.variants._resolve_round_include", autospec=True, ) @patch( @@ -238,7 +238,7 @@ class TestPlanBakesPinnedVariant(unittest.TestCase): return_value={"web-app-bar": 1}, ) @patch( - "cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include", + "utils.roles.applications.variants._resolve_round_include", autospec=True, return_value=("web-app-bar", "web-app-foo"), ) diff --git a/tests/unit/python/cli/administration/deploy/development/test_down.py b/tests/unit/python/cli/administration/deploy/development/test_down.py index bf878fa5d9..282676d687 100644 --- a/tests/unit/python/cli/administration/deploy/development/test_down.py +++ b/tests/unit/python/cli/administration/deploy/development/test_down.py @@ -7,11 +7,14 @@ import unittest from pathlib import Path from unittest.mock import MagicMock, patch -from cli.administration.deploy.development.down import _wipe_docker_root +from cli.administration.deploy.development.docker_root import _wipe_docker_root class TestWipeDockerRoot(unittest.TestCase): - @patch("cli.administration.deploy.development.down.subprocess.run", autospec=True) + @patch( + "cli.administration.deploy.development.docker_root.subprocess.run", + autospec=True, + ) def test_the_wipe_escalates(self, run_mock: MagicMock) -> None: with tempfile.TemporaryDirectory() as tmp: docker_root = Path(tmp) / "docker" @@ -23,7 +26,10 @@ class TestWipeDockerRoot(unittest.TestCase): self.assertEqual(commands[0], ["sudo", "rm", "-rf", str(docker_root)]) self.assertTrue(all(cmd[0] == "sudo" for cmd in commands)) - @patch("cli.administration.deploy.development.down.subprocess.run", autospec=True) + @patch( + "cli.administration.deploy.development.docker_root.subprocess.run", + autospec=True, + ) def test_a_surviving_docker_root_is_a_hard_error(self, run_mock: MagicMock) -> None: with tempfile.TemporaryDirectory() as tmp: docker_root = Path(tmp) / "docker" @@ -36,7 +42,10 @@ class TestWipeDockerRoot(unittest.TestCase): self.assertIn("containers", str(ctx.exception)) self.assertTrue(run_mock.called) - @patch("cli.administration.deploy.development.down.subprocess.run", autospec=True) + @patch( + "cli.administration.deploy.development.docker_root.subprocess.run", + autospec=True, + ) def test_a_missing_docker_root_is_not_wiped(self, run_mock: MagicMock) -> None: with tempfile.TemporaryDirectory() as tmp: _wipe_docker_root(Path(tmp) / "absent") diff --git a/tests/unit/python/cli/administration/inventory/provision/test_host_vars.py b/tests/unit/python/cli/administration/inventory/provision/test_host_vars.py index d55382d907..30184d8b5f 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_host_vars.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_host_vars.py @@ -146,9 +146,7 @@ ansible_become_password: !vault | ENCRYPTEDVALUE """ - with patch( - "cli.administration.inventory.provision.ruamel_io.VaultHandler" - ) as vh: + with patch("cli.administration.inventory.ruamel_io.VaultHandler") as vh: inst = vh.return_value inst.encrypt_string.return_value = vaulted_snippet diff --git a/tests/unit/python/cli/administration/inventory/provision/test_reset.py b/tests/unit/python/cli/administration/inventory/provision/test_reset.py index 4995e6059f..671bd6eded 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_reset.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_reset.py @@ -7,7 +7,7 @@ from unittest.mock import patch from ruamel.yaml import YAML from cli.administration.inventory.provision.reset import reset_credentials -from cli.administration.inventory.provision.ruamel_io import load_document +from cli.administration.inventory.ruamel_io import load_document from utils.roles.mapping import ROLE_FILE_META_USERS MODULE = "cli.administration.inventory.provision.reset" diff --git a/tests/unit/python/cli/administration/inventory/provision/test_ruamel_io.py b/tests/unit/python/cli/administration/inventory/provision/test_ruamel_io.py index 603897edef..67cd569209 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_ruamel_io.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_ruamel_io.py @@ -4,7 +4,7 @@ from pathlib import Path from ruamel.yaml.comments import CommentedMap, CommentedSeq -from cli.administration.inventory.provision.ruamel_io import ( +from cli.administration.inventory.ruamel_io import ( as_commented_map, dump_document, ensure_map, diff --git a/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py b/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py index 5b24e5e66b..a021b057ca 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py @@ -31,7 +31,7 @@ from utils.roles.mapping import ROLE_FILE_META_USERS MODULE = "cli.administration.inventory.provision.users_generator" CREDENTIALS_MODULE = "cli.administration.inventory.provision.credentials_generator" -RUAMEL_MODULE = "cli.administration.inventory.provision.ruamel_io" +RUAMEL_MODULE = "cli.administration.inventory.ruamel_io" REALISTIC_HOST_VARS = """\ --- diff --git a/tests/unit/python/group_vars/test_webserver_worker_limits.py b/tests/unit/python/group_vars/test_webserver_worker_limits.py index 4491023780..afeac3d26f 100644 --- a/tests/unit/python/group_vars/test_webserver_worker_limits.py +++ b/tests/unit/python/group_vars/test_webserver_worker_limits.py @@ -17,12 +17,12 @@ from typing import Any, ClassVar from ansible.parsing.dataloader import DataLoader from ansible.template import Templar, trust_as_template -from utils.cache import _reset_cache_for_tests from utils.cache.carrier import ( APPLICATIONS_RENDERED_FACT, merged_applications_cache_key, ) from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import load_yaml, load_yaml_str from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_TEMPL_COMPOSE diff --git a/tests/unit/python/plugins/filter/test_ca_trust_paths.py b/tests/unit/python/plugins/filter/test_ca_trust_paths.py index 447bd64a45..c7e99d6077 100644 --- a/tests/unit/python/plugins/filter/test_ca_trust_paths.py +++ b/tests/unit/python/plugins/filter/test_ca_trust_paths.py @@ -41,7 +41,7 @@ class TestCaTrustPaths(unittest.TestCase): ) def test_env_handler_exports_the_host_spot(self): - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers.infinito.ca import cert_host as handler eb = EnvBuilder() diff --git a/tests/unit/python/plugins/lookup/test_cert.py b/tests/unit/python/plugins/lookup/test_cert.py index 1e9dd89bd4..78b2542f6c 100644 --- a/tests/unit/python/plugins/lookup/test_cert.py +++ b/tests/unit/python/plugins/lookup/test_cert.py @@ -7,7 +7,7 @@ from ansible.errors import AnsibleError import utils.tls_common as _tls_common from plugins.lookup.cert import LookupModule -from utils.cache import _reset_cache_for_tests +from utils.cache.reset import _reset_cache_for_tests sys.modules.setdefault("ansible.module_utils.tls_common", _tls_common) diff --git a/tests/unit/python/plugins/lookup/test_config_lookup.py b/tests/unit/python/plugins/lookup/test_config_lookup.py index 75ef8c8786..3aeae2be9d 100644 --- a/tests/unit/python/plugins/lookup/test_config_lookup.py +++ b/tests/unit/python/plugins/lookup/test_config_lookup.py @@ -9,8 +9,8 @@ from pathlib import Path from ansible.errors import AnsibleError from plugins.lookup.config import LookupModule -from utils.cache import _reset_cache_for_tests from utils.cache import base as cache_base +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import dump_yaml_str from utils.roles.applications.config import AppConfigKeyError, ConfigEntryNotSetError from utils.roles.mapping import ( diff --git a/tests/unit/python/plugins/lookup/test_email.py b/tests/unit/python/plugins/lookup/test_email.py index a1191449af..73fc945444 100644 --- a/tests/unit/python/plugins/lookup/test_email.py +++ b/tests/unit/python/plugins/lookup/test_email.py @@ -12,11 +12,11 @@ from ansible.errors import AnsibleError from plugins.lookup.applications import LookupModule as ApplicationsLookup from plugins.lookup.email import RESOLUTION_ORDER, LookupModule, provider_view_carrier -from utils.cache import _reset_cache_for_tests from utils.cache import applications as cache_applications from utils.cache import base as cache_base -from utils.cache import users as cache_users +from utils.cache import tokens as cache_tokens from utils.cache.carrier import APPLICATIONS_RENDERED_FACT, PROVIDER_VIEW_RENDERED_FACT +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import dump_yaml_str from utils.roles.mapping import ROLE_FILE_META_DOMAINS, ROLE_FILE_META_SERVICES @@ -43,7 +43,7 @@ class TestEmailLookup(unittest.TestCase): (self._tmp / "roles").mkdir(parents=True, exist_ok=True) os.chdir(self._tmp) self._tokens_store_patcher = patch.object( - cache_users, "_load_store_users", return_value={} + cache_tokens, "load_store_users", return_value={} ) self._tokens_store_patcher.start() @@ -472,7 +472,7 @@ class TestProviderOnionIsClusterWide(unittest.TestCase): (self._tmp / "roles").mkdir(parents=True, exist_ok=True) os.chdir(self._tmp) self._tokens_store_patcher = patch.object( - cache_users, "_load_store_users", return_value={} + cache_tokens, "load_store_users", return_value={} ) self._tokens_store_patcher.start() diff --git a/tests/unit/python/plugins/lookup/test_tor_ports.py b/tests/unit/python/plugins/lookup/test_tor_ports.py index 7b825b652f..fc3d057b37 100644 --- a/tests/unit/python/plugins/lookup/test_tor_ports.py +++ b/tests/unit/python/plugins/lookup/test_tor_ports.py @@ -11,7 +11,7 @@ from plugins.lookup.tor_ports import ( collect_exposed_ports, collect_onion_ports, ) -from utils.cache import _reset_cache_for_tests +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import dump_yaml_str from utils.roles.mapping import ROLE_FILE_META_SERVICES diff --git a/tests/unit/python/plugins/lookup/test_tor_reachable.py b/tests/unit/python/plugins/lookup/test_tor_reachable.py index 2c86e9462d..4d97187ab5 100644 --- a/tests/unit/python/plugins/lookup/test_tor_reachable.py +++ b/tests/unit/python/plugins/lookup/test_tor_reachable.py @@ -7,7 +7,7 @@ from pathlib import Path from ansible.errors import AnsibleError from plugins.lookup.tor_reachable import LookupModule, is_reachable -from utils.cache import _reset_cache_for_tests +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import dump_yaml_str from utils.roles.mapping import ROLE_FILE_META_SERVICES diff --git a/tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_rehash.py b/tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_rehash.py index 2570e24b2e..ac214bf1a8 100644 --- a/tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_rehash.py +++ b/tests/unit/python/roles/sys-svc-compose/filter_plugins/test_compose_rehash.py @@ -7,7 +7,7 @@ from pathlib import Path from plugins.lookup.compose_volumes import compose_volumes from utils import PROJECT_ROOT -from utils.cache import _reset_cache_for_tests +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import dump_yaml_str, load_yaml_str _spec = importlib.util.spec_from_file_location( diff --git a/tests/unit/python/roles/web-app-nextcloud/test_oidc_addon_follows_sso.py b/tests/unit/python/roles/web-app-nextcloud/test_oidc_addon_follows_sso.py index 3fa9e82bee..ea17731f0d 100644 --- a/tests/unit/python/roles/web-app-nextcloud/test_oidc_addon_follows_sso.py +++ b/tests/unit/python/roles/web-app-nextcloud/test_oidc_addon_follows_sso.py @@ -17,8 +17,8 @@ from __future__ import annotations import unittest -from utils.cache import _reset_cache_for_tests from utils.cache.applications import get_merged_applications +from utils.cache.reset import _reset_cache_for_tests def _templar(variables: dict): diff --git a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py index a29156a622..3df9077bfc 100644 --- a/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py +++ b/tests/unit/python/roles/web-app-nextcloud/test_talk_direct_media.py @@ -15,8 +15,8 @@ from jinja2 import ( import plugins.lookup.container_ports as container_ports_lookup from plugins.lookup.container_volumes import container_volumes -from utils.cache import _reset_cache_for_tests from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ( ROLE_FILE_META_SERVICES, diff --git a/tests/unit/python/roles/web-app-wordpress/test_options.py b/tests/unit/python/roles/web-app-wordpress/test_options.py index fa2c6cbf09..df848a41c4 100644 --- a/tests/unit/python/roles/web-app-wordpress/test_options.py +++ b/tests/unit/python/roles/web-app-wordpress/test_options.py @@ -27,9 +27,9 @@ from ansible.plugins.lookup import LookupBase from ansible.template import Templar from plugins.lookup.config import LookupModule -from utils.cache import _reset_cache_for_tests from utils.cache import base as cache_base from utils.cache.files import iter_project_files_with_content, read_text +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import load_yaml_any from utils.roles.applications.config import AppConfigKeyError from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_VARS_MAIN diff --git a/tests/unit/python/utils/cache/test_applications.py b/tests/unit/python/utils/cache/test_applications.py index c9c757eb8a..9b4f5c6c0a 100644 --- a/tests/unit/python/utils/cache/test_applications.py +++ b/tests/unit/python/utils/cache/test_applications.py @@ -18,12 +18,12 @@ import unittest import unittest.mock as mock from pathlib import Path -from utils.cache import _reset_cache_for_tests from utils.cache import applications as cache_apps from utils.cache.carrier import ( APPLICATIONS_RENDERED_FACT, merged_applications_cache_key, ) +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ( ROLE_DIR_META_ADDONS, diff --git a/tests/unit/python/utils/cache/test_base.py b/tests/unit/python/utils/cache/test_base.py index 1d06d73671..c8c59fa2b0 100644 --- a/tests/unit/python/utils/cache/test_base.py +++ b/tests/unit/python/utils/cache/test_base.py @@ -17,7 +17,8 @@ import unittest import unittest.mock as mock from pathlib import Path -from utils.cache import _reset_cache_for_tests, base +from utils.cache import base +from utils.cache.reset import _reset_cache_for_tests from utils.domains.default_primary import default_domain_primary from utils.paths import FILE_TOKENS diff --git a/tests/unit/python/utils/cache/test_data.py b/tests/unit/python/utils/cache/test_data.py index 463b4aa8ac..6f6fe07330 100644 --- a/tests/unit/python/utils/cache/test_data.py +++ b/tests/unit/python/utils/cache/test_data.py @@ -5,7 +5,6 @@ import textwrap import unittest from pathlib import Path -from utils.cache import _reset_cache_for_tests from utils.cache.applications import get_application_defaults from utils.cache.base import ( PROJECT_ROOT, @@ -14,6 +13,7 @@ from utils.cache.base import ( _fingerprint_mapping, _stable_variables_signature, ) +from utils.cache.reset import _reset_cache_for_tests from utils.cache.users import ( _build_users, _compute_reserved_usernames, diff --git a/tests/unit/python/utils/cache/test_domains.py b/tests/unit/python/utils/cache/test_domains.py index cc550bb5a8..a1c42c1032 100644 --- a/tests/unit/python/utils/cache/test_domains.py +++ b/tests/unit/python/utils/cache/test_domains.py @@ -16,9 +16,9 @@ import unittest from pathlib import Path from unittest.mock import patch -from utils.cache import _reset_cache_for_tests from utils.cache import domains as cache_domains from utils.cache.base import _RENDER_GUARD +from utils.cache.reset import _reset_cache_for_tests from utils.domains.default_primary import default_domain_primary from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_USERS diff --git a/tests/unit/python/utils/cache/test_variants.py b/tests/unit/python/utils/cache/test_variants.py index cfe566aa81..af1e06a5b8 100644 --- a/tests/unit/python/utils/cache/test_variants.py +++ b/tests/unit/python/utils/cache/test_variants.py @@ -15,7 +15,6 @@ from . import PROJECT_ROOT if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) -from utils.cache import _reset_cache_for_tests from utils.cache.applications import ( _build_variants, get_application_defaults, @@ -25,6 +24,7 @@ from utils.cache.applications import ( from utils.cache.applications import ( _load_variants_overrides as _load_yaml_variant_list, ) +from utils.cache.reset import _reset_cache_for_tests from utils.roles.mapping import ( ROLE_FILE_META_SERVER, ROLE_FILE_META_SERVICES, diff --git a/tests/unit/python/utils/cache/users/test_module.py b/tests/unit/python/utils/cache/users/test_module.py index b1d99e36fe..3beb23e96e 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -2,8 +2,8 @@ Pins the public API (`get_user_defaults`, `get_merged_users`) plus the internal helpers that only this module owns: `_load_user_defs`, -`_build_users`, `_validate_forwards`, `_compute_reserved_usernames`, `_load_store_users`, -`_resolve_tokens_file`, `_hydrate_users_tokens`, `_merge_users`, +`_build_users`, `_validate_forwards`, `_compute_reserved_usernames`, +`_hydrate_users_tokens`, `_merge_users`, `_materialize_domain_label_reservations`. Module name is `test_users_module` to disambiguate from the existing `tests/unit/python/plugins/lookup/test_users.py` which targets the lookup plugin. @@ -18,11 +18,11 @@ import unittest.mock as mock from collections import OrderedDict from pathlib import Path -from utils.cache import _reset_cache_for_tests from utils.cache import base as cache_base +from utils.cache import tokens as cache_tokens from utils.cache import users as cache_users from utils.cache.carrier import USERS_RENDERED_FACT, merged_users_cache_key -from utils.cache.users import store as cache_users_store +from utils.cache.reset import _reset_cache_for_tests from utils.cache.yaml import dump_yaml_str from utils.domains.default_primary import default_domain_primary from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_USERS @@ -345,7 +345,7 @@ class TestResolveTokensFile(unittest.TestCase): sentinel.write_text("users: {}\n", encoding="utf-8") cache_base.DEFAULT_TOKENS_FILE = sentinel try: - result = cache_users._resolve_tokens_file(variables={}) + result = cache_tokens.resolve_tokens_file(variables={}) self.assertEqual(result, sentinel) finally: cache_base.DEFAULT_TOKENS_FILE = previous @@ -354,7 +354,7 @@ class TestResolveTokensFile(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: explicit = Path(tmp) / "tokens.yml" explicit.write_text("users: {}\n", encoding="utf-8") - result = cache_users._resolve_tokens_file( + result = cache_tokens.resolve_tokens_file( variables={"FILE_TOKENS": str(explicit)} ) self.assertEqual(result, explicit) @@ -362,8 +362,8 @@ class TestResolveTokensFile(unittest.TestCase): class TestLoadStoreUsers(unittest.TestCase): def test_missing_path_returns_empty(self): - self.assertEqual(cache_users._load_store_users(None), {}) - self.assertEqual(cache_users._load_store_users(""), {}) + self.assertEqual(cache_tokens.load_store_users(None), {}) + self.assertEqual(cache_tokens.load_store_users(""), {}) def test_yaml_users_block_passes_through(self): with tempfile.TemporaryDirectory() as tmp: @@ -372,7 +372,7 @@ class TestLoadStoreUsers(unittest.TestCase): dump_yaml_str({"users": {"alice": {"tokens": {"x": "y"}}}}), encoding="utf-8", ) - result = cache_users._load_store_users(path) + result = cache_tokens.load_store_users(path) self.assertEqual(result, {"alice": {"tokens": {"x": "y"}}}) @@ -574,9 +574,7 @@ class TestGetMergedUsersCarrierFact(unittest.TestCase): return { "inventory_hostname": host, "users": {"foo": {"email": "foo@example.org"}}, - cache_users_store.STORE_FACT: { - "foo": {"tokens": {"web-app-foo": "minted"}} - }, + cache_tokens.STORE_FACT: {"foo": {"tokens": {"web-app-foo": "minted"}}}, } @staticmethod @@ -650,7 +648,7 @@ class TestGetMergedUsersCarrierFact(unittest.TestCase): roles = _seed_minimal_user_role(Path(tmp)) variables = self._variables() self._park(roles, variables, {"foo": {"carried": True}}) - variables[cache_users_store.STORE_FACT] = { + variables[cache_tokens.STORE_FACT] = { "foo": {"tokens": {"web-app-foo": "rotated"}} } merged, renders = self._merged(roles, variables) @@ -667,7 +665,7 @@ class TestGetMergedUsersCarrierFact(unittest.TestCase): encoding="utf-8", ) variables = self._variables() - del variables[cache_users_store.STORE_FACT] + del variables[cache_tokens.STORE_FACT] variables["FILE_TOKENS"] = str(tokens) carried = self._park(roles, variables, {"foo": {"carried": True}}) return roles, variables, tokens, carried @@ -692,7 +690,7 @@ class TestGetMergedUsersCarrierFact(unittest.TestCase): roles, variables, _, carried = self._park_from_the_tokens_file( Path(tmp), "minted" ) - variables[cache_users_store.STORE_FACT] = { + variables[cache_tokens.STORE_FACT] = { "foo": {"tokens": {"web-app-foo": "minted"}} } merged, renders = self._merged(roles, variables) @@ -749,8 +747,8 @@ class TestStoreSignature(unittest.TestCase): @staticmethod def _signature(store: dict) -> tuple: with tempfile.TemporaryDirectory() as tmp: - return cache_users._store_signature( - {cache_users_store.STORE_FACT: store}, Path(tmp) / "tokens.yml" + return cache_tokens.store_signature( + {cache_tokens.STORE_FACT: store}, Path(tmp) / "tokens.yml" ) @staticmethod @@ -764,9 +762,9 @@ class TestStoreSignature(unittest.TestCase): tokens_file = Path(tmp) / "tokens.yml" tokens_file.write_text(dump_yaml_str({"users": store}), encoding="utf-8") self.assertEqual( - cache_users._store_signature({}, tokens_file), - cache_users._store_signature( - {cache_users_store.STORE_FACT: store}, tokens_file + cache_tokens.store_signature({}, tokens_file), + cache_tokens.store_signature( + {cache_tokens.STORE_FACT: store}, tokens_file ), ) @@ -774,10 +772,8 @@ class TestStoreSignature(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: absent = Path(tmp) / "tokens.yml" self.assertEqual( - cache_users._store_signature({}, absent), - cache_users._store_signature( - {cache_users_store.STORE_FACT: {}}, absent - ), + cache_tokens.store_signature({}, absent), + cache_tokens.store_signature({cache_tokens.STORE_FACT: {}}, absent), ) def test_fields_and_padding_the_hydration_ignores_keep_the_signature(self): diff --git a/tests/unit/python/utils/env/handlers/infinito/gpu/test_only_tests.py b/tests/unit/python/utils/env/handlers/infinito/gpu/test_only_tests.py index 437b13bbcc..8430c391df 100644 --- a/tests/unit/python/utils/env/handlers/infinito/gpu/test_only_tests.py +++ b/tests/unit/python/utils/env/handlers/infinito/gpu/test_only_tests.py @@ -6,7 +6,8 @@ import unittest from pathlib import Path from unittest.mock import patch -from utils.env.builder import BuildContext, EnvBuilder, apply_custom_env +from utils.env.builder import apply_custom_env +from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers.infinito.gpu import only_tests as handler _BLANK = {handler.KEY: ""} diff --git a/tests/unit/python/utils/env/handlers/infinito/test_build.py b/tests/unit/python/utils/env/handlers/infinito/test_build.py index 81ad302ed5..f554ce6cb9 100644 --- a/tests/unit/python/utils/env/handlers/infinito/test_build.py +++ b/tests/unit/python/utils/env/handlers/infinito/test_build.py @@ -5,7 +5,7 @@ import unittest from pathlib import Path from unittest.mock import patch -from utils.env.builder import BuildContext, EnvBuilder +from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers.infinito import build as handler _BLANK = {handler.KEY: ""} diff --git a/tests/unit/python/utils/env/handlers/infinito/test_cache_conf.py b/tests/unit/python/utils/env/handlers/infinito/test_cache_conf.py index f4f9f27eaa..f983586be4 100644 --- a/tests/unit/python/utils/env/handlers/infinito/test_cache_conf.py +++ b/tests/unit/python/utils/env/handlers/infinito/test_cache_conf.py @@ -8,7 +8,7 @@ from pathlib import Path from tempfile import TemporaryDirectory from unittest.mock import patch -from utils.env.builder import BuildContext, EnvBuilder +from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers.infinito.cache import conf as handler diff --git a/tests/unit/python/utils/env/handlers/infinito/test_cache_host_pacman_path.py b/tests/unit/python/utils/env/handlers/infinito/test_cache_host_pacman_path.py index 912861d763..568bd8b28d 100644 --- a/tests/unit/python/utils/env/handlers/infinito/test_cache_host_pacman_path.py +++ b/tests/unit/python/utils/env/handlers/infinito/test_cache_host_pacman_path.py @@ -8,7 +8,7 @@ import unittest from pathlib import Path from unittest.mock import patch -from utils.env.builder import BuildContext, EnvBuilder +from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers.infinito.cache import host_pacman_path as handler HELPER = "utils.env.handlers.infinito.cache.host_pacman_path.run_helper" diff --git a/tests/unit/python/utils/env/handlers/infinito/test_cache_stack.py b/tests/unit/python/utils/env/handlers/infinito/test_cache_stack.py index 2ec5db4cdf..b228239000 100644 --- a/tests/unit/python/utils/env/handlers/infinito/test_cache_stack.py +++ b/tests/unit/python/utils/env/handlers/infinito/test_cache_stack.py @@ -7,7 +7,7 @@ import unittest from pathlib import Path from unittest.mock import patch -from utils.env.builder import BuildContext, EnvBuilder +from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers.infinito.cache import stack as handler _BLANK = {"CI": "", handler.KEY: ""} diff --git a/tests/unit/python/utils/env/handlers/infinito/test_domain.py b/tests/unit/python/utils/env/handlers/infinito/test_domain.py index 7991528ba7..a471894142 100644 --- a/tests/unit/python/utils/env/handlers/infinito/test_domain.py +++ b/tests/unit/python/utils/env/handlers/infinito/test_domain.py @@ -12,7 +12,7 @@ from tempfile import TemporaryDirectory from unittest.mock import patch from utils.domains.default_primary import default_domain_primary -from utils.env.builder import BuildContext, EnvBuilder +from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers.infinito import domain as handler DOMAIN = default_domain_primary() diff --git a/tests/unit/python/utils/env/handlers/infinito/test_ghcr_mirror.py b/tests/unit/python/utils/env/handlers/infinito/test_ghcr_mirror.py index 3242ff25c1..acfac2c46b 100644 --- a/tests/unit/python/utils/env/handlers/infinito/test_ghcr_mirror.py +++ b/tests/unit/python/utils/env/handlers/infinito/test_ghcr_mirror.py @@ -5,7 +5,7 @@ import unittest from pathlib import Path from unittest.mock import patch -from utils.env.builder import BuildContext, EnvBuilder +from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers.infinito import ghcr_mirror as handler _BLANK = {handler.KEY: ""} diff --git a/tests/unit/python/utils/env/handlers/infinito/test_ip_range.py b/tests/unit/python/utils/env/handlers/infinito/test_ip_range.py index 2b2a6c3d99..534244016e 100644 --- a/tests/unit/python/utils/env/handlers/infinito/test_ip_range.py +++ b/tests/unit/python/utils/env/handlers/infinito/test_ip_range.py @@ -6,7 +6,8 @@ import unittest from pathlib import Path from unittest.mock import patch -from utils.env.builder import EnvBuilder, build_env +from utils.env.builder import build_env +from utils.env.context import EnvBuilder from utils.env.handlers.infinito import ip_range as handler diff --git a/tests/unit/python/utils/env/handlers/infinito/test_outer_network_mtu.py b/tests/unit/python/utils/env/handlers/infinito/test_outer_network_mtu.py index 5fbdae61e0..40f088a70e 100644 --- a/tests/unit/python/utils/env/handlers/infinito/test_outer_network_mtu.py +++ b/tests/unit/python/utils/env/handlers/infinito/test_outer_network_mtu.py @@ -6,7 +6,7 @@ import unittest from pathlib import Path from unittest.mock import patch -from utils.env.builder import BuildContext, EnvBuilder +from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers.infinito import outer_network_mtu as handler diff --git a/tests/unit/python/utils/env/test_builder.py b/tests/unit/python/utils/env/test_builder.py index 0b96f93338..a83e91aaa1 100644 --- a/tests/unit/python/utils/env/test_builder.py +++ b/tests/unit/python/utils/env/test_builder.py @@ -17,7 +17,8 @@ import unittest from pathlib import Path from unittest.mock import patch -from utils.env.builder import BuildContext, EnvBuilder, build_env +from utils.env.builder import build_env +from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers import ORDERED_HANDLERS, PASSTHROUGH_STATIC_KEYS diff --git a/tests/unit/python/utils/env/test_writer.py b/tests/unit/python/utils/env/test_writer.py index fa8e12b9dd..8d16bdadb1 100644 --- a/tests/unit/python/utils/env/test_writer.py +++ b/tests/unit/python/utils/env/test_writer.py @@ -12,7 +12,7 @@ from pathlib import Path from tempfile import TemporaryDirectory from utils.cache.files import read_text -from utils.env.builder import EnvBuilder +from utils.env.context import EnvBuilder from utils.env.writer import quote_for_dotenv, write_dotenv diff --git a/tests/unit/python/utils/inventory/test_tools_address.py b/tests/unit/python/utils/inventory/test_tools_address.py index 3da2030d69..11349152fd 100644 --- a/tests/unit/python/utils/inventory/test_tools_address.py +++ b/tests/unit/python/utils/inventory/test_tools_address.py @@ -15,7 +15,8 @@ from tempfile import TemporaryDirectory from unittest.mock import patch from utils.inventory import tools -from utils.inventory.tools import ADDRESS, LANE_SERVICE, lane_address, lane_ip +from utils.inventory.tools import ADDRESS, lane_address, lane_ip +from utils.inventory.tools_vars import LANE_SERVICE NETWORKS = { "infinito-nexus-core_default": {"IPAddress": "172.30.0.9"}, @@ -32,9 +33,7 @@ class TestLaneIp(unittest.TestCase): environment = {"INFINITO_SUBNET": "172.30.5.0/24", "INFINITO_CONTAINER": "c"} with ( patch.object(tools.subprocess, "run", return_value=found), - patch( - "utils.i18n.libretranslate.environment", return_value=env or environment - ), + patch.object(tools, "environment", return_value=env or environment), ): return lane_ip(Path("/nowhere")) diff --git a/tests/unit/python/utils/inventory/test_tools_model.py b/tests/unit/python/utils/inventory/test_tools_model.py index d12048afbe..fe15980084 100644 --- a/tests/unit/python/utils/inventory/test_tools_model.py +++ b/tests/unit/python/utils/inventory/test_tools_model.py @@ -9,7 +9,8 @@ from pathlib import Path from utils import PROJECT_ROOT from utils.cache.yaml import load_yaml_any -from utils.inventory.tools import LANE_MODEL_ALIAS, TEMPLATE, render +from utils.inventory.tools import LANE_MODEL_ALIAS +from utils.inventory.tools_vars import TEMPLATE, render OLLAMA_ROLE = "svc-ai-ollama" diff --git a/tests/unit/python/utils/inventory/test_tools_render.py b/tests/unit/python/utils/inventory/test_tools_render.py index 0c3ac9dd19..1c87085e46 100644 --- a/tests/unit/python/utils/inventory/test_tools_render.py +++ b/tests/unit/python/utils/inventory/test_tools_render.py @@ -6,7 +6,7 @@ from pathlib import Path from unittest.mock import patch from utils.cache.files import read_text -from utils.inventory import tools +from utils.inventory import tools_vars MARKUP = "/models/\"" TEMPLATE = ( @@ -21,14 +21,14 @@ class TestRender(unittest.TestCase): def test_the_yaml_lane_renders_without_html_escaping(self) -> None: with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) - template = root / tools.TEMPLATE + template = root / tools_vars.TEMPLATE template.parent.mkdir(parents=True) template.write_text(TEMPLATE, encoding="utf-8") - with patch.object(tools, "models_dir", return_value=MARKUP): - rendered = read_text(str(tools.render(root, ["en", "de"]))) + with patch.object(tools_vars, "models_dir", return_value=MARKUP): + rendered = read_text(str(tools_vars.render(root, ["en", "de"]))) self.assertIn(f'models: "{MARKUP}"', rendered) self.assertIn("languages: de,en", rendered) - self.assertIn(f"key: {tools.API_KEY}", rendered) + self.assertIn(f"key: {tools_vars.API_KEY}", rendered) self.assertIn("{{ ansible_expression }}", rendered) self.assertNotIn("<", rendered) self.assertNotIn("&", rendered) diff --git a/tests/unit/python/utils/roles/applications/test_variants_pin_scope.py b/tests/unit/python/utils/roles/applications/test_variants_pin_scope.py index 429ef79d2a..ae0ffcb2b7 100644 --- a/tests/unit/python/utils/roles/applications/test_variants_pin_scope.py +++ b/tests/unit/python/utils/roles/applications/test_variants_pin_scope.py @@ -20,10 +20,7 @@ CARRIER = "web-app-carrier" PARTNER = "web-app-partner" SUBJECT = "web-app-subject" -_INCLUDE = ( - "cli.administration.deploy.development.inventory.legacy_resolver." - "_resolve_round_include" -) +_INCLUDE = "utils.roles.applications.variants._resolve_round_include" class TestPinScope(unittest.TestCase): diff --git a/utils/cache/README.md b/utils/cache/README.md index b4e1bb6ae4..8761b449ee 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -11,14 +11,16 @@ This package contains the in-process cache layers Infinito.Nexus uses to keep CL | [base.py](base.py) | Cross-cutting helpers: filesystem constants (`PROJECT_ROOT`, `ROLES_DIR`, `DEFAULT_TOKENS_FILE`), `_deep_merge`, cache-key + content-fingerprint signatures, the cross-domain re-entry guard, and the templar-render machinery. The only ansible-coupled symbol is `_render_with_templar`, which lazy-imports its dependency. | | [applications.py](applications.py) | Per-app variants + defaults + `get_merged_applications`. **Strictly ansible-free at import time** so the GitHub Actions runner-host CLI path (`cli.administration.deploy.development.init` → `plan_dev_inventory_matrix` → `get_variants`) keeps working without ansible installed. | | [carrier.py](carrier.py) | The play-scoped carriers of the rendered applications and users payloads: the fact names `_INFINITO_APPLICATIONS_RENDERED` and `_INFINITO_USERS_RENDERED`, `merged_applications_cache_key`, `merged_users_cache_key`, and the readers `get_merged_applications` and `get_merged_users` consult before they render. | -| `users/` | User definitions, token store hydration, alias materialization, `get_user_defaults`, `get_merged_users` (package; `users/placeholders.py` substitutes `DOMAIN_PRIMARY` / `ORGANIZATION` / `SOFTWARE_NAME` ahead of the templar render pass; `users/store.py` reads the `sys_token_store_users` fact and digests the tokens the users are hydrated from, the digest the users cache and users carrier keys share). | +| [tokens.py](tokens.py) | The token store the users are hydrated from: `resolve_tokens_file`, `load_store_users`, the `sys_token_store_users` fact and the digest the users cache and users carrier keys share (`store_signature`). | +| `users/` | User definitions, token store hydration, alias materialization, `get_user_defaults`, `get_merged_users` (package; `users/placeholders.py` substitutes `DOMAIN_PRIMARY` / `ORGANIZATION` / `SOFTWARE_NAME` ahead of the templar render pass). | | [domains.py](domains.py) | Canonical-domains map derived from the merged applications view: `get_merged_domains`. A read issued while the applications render is in progress (the re-entry guard is set) sees the unrendered view, so it is cached under its own key and never answers a later read. | -| [`__init__.py`](__init__.py) | Owns the package-level `_reset_cache_for_tests()` orchestrator that clears every cache plus the shared fingerprint memo in one call. | +| [`__init__.py`](__init__.py) | Owns `PROJECT_ROOT` and `ROLES_DIR` and imports nothing, so every module can read them without importing a cache. | +| [reset.py](reset.py) | Owns the `_reset_cache_for_tests()` orchestrator that clears every cache plus the shared fingerprint memo in one call. | ## When To Use Which 🎯 - Use `utils.cache.yaml.load_yaml(path)` (or `load_yaml_any(path)` when the YAML root is a list or scalar) whenever a CLI tool, filter, or library reads individual YAML files where the same path MAY be touched repeatedly within a single invocation. -- Import the cached getters directly from the domain module that owns them: `utils.cache.applications` for `get_application_defaults` / `get_variants` / `get_merged_applications`, `utils.cache.users` for `get_user_defaults` / `get_merged_users`, and `utils.cache.domains` for `get_merged_domains`. The package's `_reset_cache_for_tests` is exposed at `from utils.cache import _reset_cache_for_tests`. +- Import the cached getters directly from the domain module that owns them: `utils.cache.applications` for `get_application_defaults` / `get_variants` / `get_merged_applications`, `utils.cache.users` for `get_user_defaults` / `get_merged_users`, and `utils.cache.domains` for `get_merged_domains`. The cache-wide `_reset_cache_for_tests` is exposed at `from utils.cache.reset import _reset_cache_for_tests`. The layers are orthogonal: `yaml.py` caches "this file's parsed root", the `applications`/`users`/`domains` modules cache "this aggregated, rendered payload". They do not invalidate each other and MAY both be active at the same time. @@ -32,7 +34,7 @@ While one render runs, the re-entry guard also holds that render's unrendered vi ## Test-Only Helpers 🧪 -Each module owns a private `_reset()` that clears its own cache dicts. The package-level `utils.cache._reset_cache_for_tests()` orchestrates all six (`base`, `applications`, `users`, `domains`, `yaml`, `files`) plus the shared fingerprint memo. Unit tests that exercise the cached paths MUST call it in `setUp` to guarantee clean state across test cases. +Each module owns a private `_reset()` that clears its own cache dicts. `utils.cache.reset._reset_cache_for_tests()` orchestrates all six (`base`, `applications`, `users`, `domains`, `yaml`, `files`) plus the shared fingerprint memo. Unit tests that exercise the cached paths MUST call it in `setUp` to guarantee clean state across test cases. ## Design Guidelines 📐 @@ -55,7 +57,7 @@ from utils.cache.users import get_merged_users, get_user_defaults from utils.cache.domains import get_merged_domains # Tests -from utils.cache import _reset_cache_for_tests +from utils.cache.reset import _reset_cache_for_tests ``` ## Schema 🗺️ diff --git a/utils/cache/__init__.py b/utils/cache/__init__.py index 92c01e2977..176af80b28 100644 --- a/utils/cache/__init__.py +++ b/utils/cache/__init__.py @@ -18,10 +18,9 @@ Domain modules: + path matcher used by lint/integration tests that need a "files git would track" view without spawning git. -Use the domain module directly. The package-level -``_reset_cache_for_tests`` clears every domain's caches plus the shared -fingerprint memo in one call — preferred over hand-rolling N -``_reset()`` calls per test fixture. +Use the domain module directly. ``utils.cache.reset._reset_cache_for_tests`` +clears every domain's caches plus the shared fingerprint memo in one +call, preferred over hand-rolling N ``_reset()`` calls per test fixture. ``PROJECT_ROOT`` is the single source of truth for the repository root. Every callsite that needs it — CLI tools, plugins, tests — MUST import @@ -36,22 +35,3 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[2] ROLES_DIR: Path = PROJECT_ROOT / "roles" - - -def _reset_cache_for_tests() -> None: - """Orchestrate per-domain cache resets plus the shared fingerprint - memo. Test fixtures rely on a single entry point so they can stay - agnostic of how the cache is partitioned across modules.""" - from utils.domains import application_domain_index - - from . import applications, base, domains, files, gitignore, users - from . import yaml as _yaml_cache - - application_domain_index._reset() - applications._reset() - users._reset() - domains._reset() - base._reset() - _yaml_cache._reset() - files._reset() - gitignore._reset() diff --git a/utils/cache/carrier.py b/utils/cache/carrier.py index c77d26071f..bfd97dfd70 100644 --- a/utils/cache/carrier.py +++ b/utils/cache/carrier.py @@ -20,6 +20,7 @@ from .base import ( _revalidate_tokens_file, _stable_variables_signature, ) +from .tokens import resolve_tokens_file, store_signature if TYPE_CHECKING: import os @@ -70,10 +71,8 @@ def merged_users_cache_key( ``(resolved roles dir, applications key signature extended by the token store signature and the host the payload was rendered for)``. """ - from .users import _resolve_tokens_file, _store_signature - roles_key, signature = merged_applications_cache_key(variables, roles_dir=roles_dir) - tokens = _store_signature(variables, _resolve_tokens_file(variables)) + tokens = store_signature(variables, resolve_tokens_file(variables)) host = (variables or {}).get("inventory_hostname") return ( roles_key, @@ -87,9 +86,7 @@ def revalidate_tokens_file(variables: Mapping[str, Any] | None) -> None: Args: variables: The play's variable scope the tokens file resolves from. """ - from .users import _resolve_tokens_file - - _revalidate_tokens_file(_resolve_tokens_file(variables)) + _revalidate_tokens_file(resolve_tokens_file(variables)) def _carried( diff --git a/utils/cache/files.py b/utils/cache/files.py index 3a7c27e3dd..b63d906344 100644 --- a/utils/cache/files.py +++ b/utils/cache/files.py @@ -256,7 +256,7 @@ def _reset() -> None: """Test-only helper: clear the project-walk and file-content caches. Named ``_reset`` for parity with the per-domain reset helpers in - sibling modules; ``utils.cache._reset_cache_for_tests`` orchestrates + sibling modules; ``utils.cache.reset._reset_cache_for_tests`` orchestrates calls to all of them. """ _all_project_files.cache_clear() diff --git a/utils/cache/gitignore.py b/utils/cache/gitignore.py index ea5355ae62..1f908798e4 100644 --- a/utils/cache/gitignore.py +++ b/utils/cache/gitignore.py @@ -108,7 +108,7 @@ def _reset() -> None: """Test-only helper: clear the cached gitignore patterns. Named ``_reset`` for parity with the per-domain reset helpers in - sibling modules; ``utils.cache._reset_cache_for_tests`` orchestrates + sibling modules; ``utils.cache.reset._reset_cache_for_tests`` orchestrates calls to all of them. """ load_gitignore_patterns.cache_clear() diff --git a/utils/cache/reset.py b/utils/cache/reset.py new file mode 100644 index 0000000000..be8416c6c8 --- /dev/null +++ b/utils/cache/reset.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from utils.domains import application_domain_index + +from . import applications, base, domains, files, gitignore, users +from . import yaml as _yaml_cache + + +def _reset_cache_for_tests() -> None: + """Orchestrate per-domain cache resets plus the shared fingerprint + memo. Test fixtures rely on a single entry point so they can stay + agnostic of how the cache is partitioned across modules.""" + application_domain_index._reset() + applications._reset() + users._reset() + domains._reset() + base._reset() + _yaml_cache._reset() + files._reset() + gitignore._reset() diff --git a/utils/cache/tokens.py b/utils/cache/tokens.py new file mode 100644 index 0000000000..35db4dff19 --- /dev/null +++ b/utils/cache/tokens.py @@ -0,0 +1,147 @@ +from __future__ import annotations + +import hashlib +import json +import os +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from utils.cache import base as _base +from utils.cache.yaml import load_yaml as _load_yaml_cached + +STORE_FACT = "sys_token_store_users" + +_DIGESTS: dict[str, str] = {} + + +def snapshot(variables: Mapping[str, Any] | None) -> Mapping[str, Any] | None: + """Return the token store the play read from the stack host. + + Args: + variables: the play's variable scope. + + Returns: + The ``sys_token_store_users`` fact, or None outside a play that loaded + ``sys-token-store``. + """ + value = (variables or {}).get(STORE_FACT) + return value if isinstance(value, Mapping) else None + + +def _tagged(value: Any) -> list: + return [True, str(value)] if isinstance(value, str) else [False, repr(value)] + + +def tokens_digest(store_users: Mapping[str, Any]) -> str: + """Digest exactly the part of a store that `_hydrate_users_tokens` reads. + + Args: + store_users: the store's ``users`` mapping. + + Returns: + The SHA-256 of every user entry with a tokens mapping, in store order, + and its non-empty stripped tokens, memoised per store content. + """ + memo_key = hashlib.md5( + repr(list(store_users.items())).encode("utf-8"), usedforsecurity=False + ).hexdigest() + digest = _DIGESTS.get(memo_key) + if digest is not None: + return digest + entries: list = [] + for user_key, user_data in store_users.items(): + if not isinstance(user_data, Mapping): + continue + tokens = user_data.get("tokens", {}) + if not isinstance(tokens, Mapping): + continue + kept = [] + for app_id, token in tokens.items(): + text = "" if token is None else str(token).strip() + if text: + kept.append([_tagged(app_id), text]) + entries.append([_tagged(user_key), kept]) + digest = hashlib.sha256(json.dumps(entries).encode("utf-8")).hexdigest() + _DIGESTS[memo_key] = digest + return digest + + +def load_store_users(file_tokens: str | os.PathLike[str] | None) -> dict[str, Any]: + if not file_tokens: + return {} + + path = Path(file_tokens) + if not path.exists(): + return {} + + data = _load_yaml_cached(path, default_if_missing={}) + users = data.get("users", {}) if isinstance(data, dict) else {} + return users if isinstance(users, dict) else {} + + +def store_signature(variables: Mapping[str, Any] | None, tokens_file: Path) -> tuple: + """Return the cache-key part of the store the users are hydrated from. + + Args: + variables: the play's variable scope. + tokens_file: the controller's tokens file, used when no snapshot exists. + + Returns: + ``(STORE_FACT, digest)``, equal for the tokens file and the + ``sys_token_store_users`` fact when both hold the same tokens. + """ + current = snapshot(variables) + store = current if current is not None else load_store_users(tokens_file) + return (STORE_FACT, tokens_digest(store)) + + +def resolve_tokens_file(variables: Mapping[str, Any] | None) -> Path: + candidates: list[Path] = [] + + def _add_candidate(value: Any) -> None: + if value is None: + return + text = str(value).strip() + if text: + candidates.append(Path(text)) + + variables = variables or {} + _add_candidate(variables.get("FILE_TOKENS")) + + tokens_name = _base.DEFAULT_TOKENS_FILE.name + secrets_name = _base.DEFAULT_TOKENS_FILE.parent.name + + dir_secrets = variables.get("DIR_SECRETS") + if dir_secrets: + _add_candidate(Path(str(dir_secrets)) / tokens_name) + + dir_var_lib = variables.get("DIR_VAR_LIB") + if dir_var_lib: + _add_candidate(Path(str(dir_var_lib)) / secrets_name / tokens_name) + + _add_candidate(os.environ.get("FILE_TOKENS")) + + env_dir_secrets = os.environ.get("DIR_SECRETS") + if env_dir_secrets: + _add_candidate(Path(env_dir_secrets) / tokens_name) + + env_dir_var_lib = os.environ.get("DIR_VAR_LIB") + if env_dir_var_lib: + _add_candidate(Path(env_dir_var_lib) / secrets_name / tokens_name) + + candidates.append(_base.DEFAULT_TOKENS_FILE) + + seen: set[Path] = set() + for candidate in candidates: + if candidate in seen: + continue + seen.add(candidate) + if candidate.exists(): + return candidate + + return candidates[0] + + +def _reset() -> None: + _DIGESTS.clear() diff --git a/utils/cache/users/__init__.py b/utils/cache/users/__init__.py index 30f8518801..d08a335a25 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -10,14 +10,13 @@ from __future__ import annotations import copy import glob -import os from collections import OrderedDict from collections.abc import Mapping from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from urllib.parse import urlparse -from utils.cache import base as _base +from utils.cache import tokens as _tokens from utils.cache.base import ( _RENDER_GUARD, _cache_key, @@ -28,7 +27,6 @@ from utils.cache.base import ( _stable_variables_signature, ) from utils.cache.carrier import _carried_users, merged_users_cache_key -from utils.cache.users import store as _store from utils.cache.users.forwards import validate_forwards as _validate_forwards from utils.cache.users.placeholders import ( substitute_primary_domain_placeholder as _substitute_primary_domain_placeholder, @@ -39,6 +37,9 @@ from utils.cache.users.placeholders import ( from utils.cache.yaml import load_yaml as _load_yaml_cached from utils.roles.mapping import ROLE_FILE_META_USERS +if TYPE_CHECKING: + import os + _USERS_DEFAULTS_CACHE: dict[str, dict[str, Any]] = {} _MERGED_USERS_CACHE: dict[tuple, dict[str, Any]] = {} @@ -213,82 +214,6 @@ def _build_users( return users -def _load_store_users(file_tokens: str | os.PathLike[str] | None) -> dict[str, Any]: - if not file_tokens: - return {} - - path = Path(file_tokens) - if not path.exists(): - return {} - - data = _load_yaml_cached(path, default_if_missing={}) - users = data.get("users", {}) if isinstance(data, dict) else {} - return users if isinstance(users, dict) else {} - - -def _store_signature(variables: Mapping[str, Any] | None, tokens_file: Path) -> tuple: - """Return the cache-key part of the store the users are hydrated from. - - Args: - variables: the play's variable scope. - tokens_file: the controller's tokens file, used when no snapshot exists. - - Returns: - ``(STORE_FACT, digest)``, equal for the tokens file and the - ``sys_token_store_users`` fact when both hold the same tokens. - """ - snapshot = _store.snapshot(variables) - store = snapshot if snapshot is not None else _load_store_users(tokens_file) - return (_store.STORE_FACT, _store.tokens_digest(store)) - - -def _resolve_tokens_file(variables: Mapping[str, Any] | None) -> Path: - candidates: list[Path] = [] - - def _add_candidate(value: Any) -> None: - if value is None: - return - text = str(value).strip() - if text: - candidates.append(Path(text)) - - variables = variables or {} - _add_candidate(variables.get("FILE_TOKENS")) - - tokens_name = _base.DEFAULT_TOKENS_FILE.name - secrets_name = _base.DEFAULT_TOKENS_FILE.parent.name - - dir_secrets = variables.get("DIR_SECRETS") - if dir_secrets: - _add_candidate(Path(str(dir_secrets)) / tokens_name) - - dir_var_lib = variables.get("DIR_VAR_LIB") - if dir_var_lib: - _add_candidate(Path(str(dir_var_lib)) / secrets_name / tokens_name) - - _add_candidate(os.environ.get("FILE_TOKENS")) - - env_dir_secrets = os.environ.get("DIR_SECRETS") - if env_dir_secrets: - _add_candidate(Path(env_dir_secrets) / tokens_name) - - env_dir_var_lib = os.environ.get("DIR_VAR_LIB") - if env_dir_var_lib: - _add_candidate(Path(env_dir_var_lib) / secrets_name / tokens_name) - - candidates.append(_base.DEFAULT_TOKENS_FILE) - - seen: set[Path] = set() - for candidate in candidates: - if candidate in seen: - continue - seen.add(candidate) - if candidate.exists(): - return candidate - - return candidates[0] - - def _hydrate_users_tokens( users: Mapping[str, Any] | None, store_users: Mapping[str, Any] | None, @@ -422,12 +347,12 @@ def get_merged_users( variables["DOMAIN_PRIMARY"] = variables["SYSTEM_EMAIL_DOMAIN"] resolved_roles_dir = _resolve_roles_dir(roles_dir=roles_dir) - tokens_file = _resolve_tokens_file(variables) - snapshot = _store.snapshot(variables) + tokens_file = _tokens.resolve_tokens_file(variables) + snapshot = _tokens.snapshot(variables) cache_key = ( _cache_key(resolved_roles_dir), _stable_variables_signature(source_variables), - _store_signature(variables, tokens_file), + _tokens.store_signature(variables, tokens_file), templar is not None, ) cached = _MERGED_USERS_CACHE.get(cache_key) @@ -450,7 +375,9 @@ def get_merged_users( _validate_forwards(merged) hydrated = _hydrate_users_tokens( merged, - dict(snapshot) if snapshot is not None else _load_store_users(tokens_file), + dict(snapshot) + if snapshot is not None + else _tokens.load_store_users(tokens_file), ) if getattr(_RENDER_GUARD, "users", False): @@ -485,4 +412,4 @@ def get_merged_users( def _reset() -> None: _USERS_DEFAULTS_CACHE.clear() _MERGED_USERS_CACHE.clear() - _store._reset() + _tokens._reset() diff --git a/utils/cache/users/store.py b/utils/cache/users/store.py deleted file mode 100644 index b779c0f698..0000000000 --- a/utils/cache/users/store.py +++ /dev/null @@ -1,68 +0,0 @@ -"""The token store the users are hydrated from: the play fact and its digest.""" - -from __future__ import annotations - -import hashlib -import json -from collections.abc import Mapping -from typing import Any - -STORE_FACT = "sys_token_store_users" - -_DIGESTS: dict[str, str] = {} - - -def snapshot(variables: Mapping[str, Any] | None) -> Mapping[str, Any] | None: - """Return the token store the play read from the stack host. - - Args: - variables: the play's variable scope. - - Returns: - The ``sys_token_store_users`` fact, or None outside a play that loaded - ``sys-token-store``. - """ - value = (variables or {}).get(STORE_FACT) - return value if isinstance(value, Mapping) else None - - -def _tagged(value: Any) -> list: - return [True, str(value)] if isinstance(value, str) else [False, repr(value)] - - -def tokens_digest(store_users: Mapping[str, Any]) -> str: - """Digest exactly the part of a store that `_hydrate_users_tokens` reads. - - Args: - store_users: the store's ``users`` mapping. - - Returns: - The SHA-256 of every user entry with a tokens mapping, in store order, - and its non-empty stripped tokens, memoised per store content. - """ - memo_key = hashlib.md5( - repr(list(store_users.items())).encode("utf-8"), usedforsecurity=False - ).hexdigest() - digest = _DIGESTS.get(memo_key) - if digest is not None: - return digest - entries: list = [] - for user_key, user_data in store_users.items(): - if not isinstance(user_data, Mapping): - continue - tokens = user_data.get("tokens", {}) - if not isinstance(tokens, Mapping): - continue - kept = [] - for app_id, token in tokens.items(): - text = "" if token is None else str(token).strip() - if text: - kept.append([_tagged(app_id), text]) - entries.append([_tagged(user_key), kept]) - digest = hashlib.sha256(json.dumps(entries).encode("utf-8")).hexdigest() - _DIGESTS[memo_key] = digest - return digest - - -def _reset() -> None: - _DIGESTS.clear() diff --git a/utils/cache/yaml.py b/utils/cache/yaml.py index 33e1e614a4..1992f66140 100644 --- a/utils/cache/yaml.py +++ b/utils/cache/yaml.py @@ -332,7 +332,7 @@ def _reset() -> None: Named ``_reset`` for parity with the per-domain reset helpers in sibling modules (``applications._reset``, ``users._reset``, - ``domains._reset``, ``base._reset``); ``utils.cache._reset_cache_for_tests`` + ``domains._reset``, ``base._reset``); ``utils.cache.reset._reset_cache_for_tests`` orchestrates calls to all of them. """ _CACHE.clear() diff --git a/utils/env/README.md b/utils/env/README.md index e2b5012e31..aa146e4930 100644 --- a/utils/env/README.md +++ b/utils/env/README.md @@ -15,7 +15,8 @@ Every module here belongs to one of four roles: parse, resolve, orchestrate, wri |---|---| | `parser.py` | Read [default.env](../../default.env) into `(values, comments)` tuples. | | `runtime.py` | Resolve host-context lookups (disk, RAM, hostname, GHA/Act flags, `/proc/version`, helper-script invocation). | -| `builder.py` | Thin orchestrator that defines `EnvBuilder`, `BuildContext`, and `build_env()`. Walks the handler registry. | +| `context.py` | Defines `EnvBuilder` and `BuildContext`, the two objects every handler is handed. | +| `builder.py` | Thin orchestrator that defines `build_env()`. Walks the handler registry. | | `writer.py` | Serialise an `EnvBuilder` into a docker-compose-compatible `.env` on disk. | | [`handlers/`](handlers/) | One module per dynamically-computed variable. See [handlers README](handlers/README.md). | diff --git a/utils/env/builder.py b/utils/env/builder.py index 27658e0045..2c82bb7946 100644 --- a/utils/env/builder.py +++ b/utils/env/builder.py @@ -3,15 +3,14 @@ Thin orchestrator: each variable's mapping/computation lives in its own module under :mod:`utils.env.handlers`. ``build_env`` walks the ``ORDERED_HANDLERS`` registry, letting each handler read/write through -an :class:`EnvBuilder`. +an :class:`~utils.env.context.EnvBuilder`. """ from __future__ import annotations -import os -from dataclasses import dataclass from typing import TYPE_CHECKING +from utils.env.context import BuildContext, EnvBuilder from utils.env.handlers import ORDERED_HANDLERS, docker_platform, ip_range from utils.env.runtime import detect_gha_act @@ -19,52 +18,6 @@ if TYPE_CHECKING: from pathlib import Path -@dataclass(frozen=True) -class BuildContext: - """Per-build inputs passed to every handler. - - Attributes are read-only; per-handler scratch state lives on the - :class:`EnvBuilder` instead. - """ - - static: dict[str, str] - static_comments: dict[str, str] - repo_root: Path - on_gha: bool - on_act: bool - - -class EnvBuilder: - """Mirror bash ``: "${KEY:=value}"`` semantics with per-key comments. - - ``setdefault`` falls back to the supplied value only when the - process env has no non-empty value for the key. ``set`` is - unconditional. ``get`` reads from the builder, falling back to the - process env so derived values (e.g. ``INFINITO_CONTAINER``) can be - composed off previously-set keys. - """ - - def __init__(self) -> None: - self.values: dict[str, str] = {} - self.comments: dict[str, str] = {} - - def setdefault(self, key: str, value: str, *, comment: str = "") -> str: - existing = os.environ.get(key, "").strip() - self.values[key] = existing or value - if comment: - self.comments.setdefault(key, comment) - return self.values[key] - - def set(self, key: str, value: str, *, comment: str = "") -> str: - self.values[key] = value - if comment: - self.comments.setdefault(key, comment) - return value - - def get(self, key: str) -> str: - return self.values.get(key, os.environ.get(key, "")) - - def apply_custom_env(eb: EnvBuilder, repo_root: Path) -> None: """Overwrite every key found in ``/custom.env``. diff --git a/utils/env/context.py b/utils/env/context.py new file mode 100644 index 0000000000..9299b87f85 --- /dev/null +++ b/utils/env/context.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import os +from dataclasses import dataclass +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from pathlib import Path + + +@dataclass(frozen=True) +class BuildContext: + """Per-build inputs passed to every handler. + + Attributes are read-only; per-handler scratch state lives on the + :class:`EnvBuilder` instead. + """ + + static: dict[str, str] + static_comments: dict[str, str] + repo_root: Path + on_gha: bool + on_act: bool + + +class EnvBuilder: + """Mirror bash ``: "${KEY:=value}"`` semantics with per-key comments. + + ``setdefault`` falls back to the supplied value only when the + process env has no non-empty value for the key. ``set`` is + unconditional. ``get`` reads from the builder, falling back to the + process env so derived values (e.g. ``INFINITO_CONTAINER``) can be + composed off previously-set keys. + """ + + def __init__(self) -> None: + self.values: dict[str, str] = {} + self.comments: dict[str, str] = {} + + def setdefault(self, key: str, value: str, *, comment: str = "") -> str: + existing = os.environ.get(key, "").strip() + self.values[key] = existing or value + if comment: + self.comments.setdefault(key, comment) + return self.values[key] + + def set(self, key: str, value: str, *, comment: str = "") -> str: + self.values[key] = value + if comment: + self.comments.setdefault(key, comment) + return value + + def get(self, key: str) -> str: + return self.values.get(key, os.environ.get(key, "")) diff --git a/utils/env/handlers/README.md b/utils/env/handlers/README.md index b8fa6c6127..f981634cad 100644 --- a/utils/env/handlers/README.md +++ b/utils/env/handlers/README.md @@ -30,7 +30,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_..." COMMENT = "" diff --git a/utils/env/handlers/__init__.py b/utils/env/handlers/__init__.py index 34ede20e61..df51dd1dbf 100644 --- a/utils/env/handlers/__init__.py +++ b/utils/env/handlers/__init__.py @@ -1,7 +1,7 @@ """Handler registry. ``ORDERED_HANDLERS`` is iterated by ``build_env()``. Each handler module exposes ``apply(eb, ctx) -> None``. Cross-handler -data flows via :class:`utils.env.builder.EnvBuilder`; handlers must not +data flows via :class:`utils.env.context.EnvBuilder`; handlers must not import each other. """ diff --git a/utils/env/handlers/act_platform_image.py b/utils/env/handlers/act_platform_image.py index 08e153b8e8..08d856c9f9 100644 --- a/utils/env/handlers/act_platform_image.py +++ b/utils/env/handlers/act_platform_image.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.env.runtime import run_helper if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "ACT_PLATFORM_IMAGE" COMMENT = ( diff --git a/utils/env/handlers/docker_platform.py b/utils/env/handlers/docker_platform.py index be6ddcc2dd..d50190a0af 100644 --- a/utils/env/handlers/docker_platform.py +++ b/utils/env/handlers/docker_platform.py @@ -5,7 +5,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_DOCKER_PLATFORM" COMMENT = "Platform the deploy creates app containers for; empty: the host's own." diff --git a/utils/env/handlers/gha_passthrough.py b/utils/env/handlers/gha_passthrough.py index a91c272984..4c02b5e101 100644 --- a/utils/env/handlers/gha_passthrough.py +++ b/utils/env/handlers/gha_passthrough.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder STATIC_KEYS = ("INFINITO_GHCR_MIRROR_PREFIX",) diff --git a/utils/env/handlers/github_repository_owner.py b/utils/env/handlers/github_repository_owner.py index 6ae58b930f..7b3f1c9db7 100644 --- a/utils/env/handlers/github_repository_owner.py +++ b/utils/env/handlers/github_repository_owner.py @@ -9,7 +9,7 @@ import sys from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "GITHUB_REPOSITORY_OWNER" COMMENT = "Lowercased GHA repository owner used to compose INFINITO_IMAGE." diff --git a/utils/env/handlers/infinito/build.py b/utils/env/handlers/infinito/build.py index 22b5ab141b..aa8e5afc32 100644 --- a/utils/env/handlers/infinito/build.py +++ b/utils/env/handlers/infinito/build.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_BUILD" diff --git a/utils/env/handlers/infinito/ca/bundle_candidates.py b/utils/env/handlers/infinito/ca/bundle_candidates.py index 165b152e64..79dd15fad6 100644 --- a/utils/env/handlers/infinito/ca/bundle_candidates.py +++ b/utils/env/handlers/infinito/ca/bundle_candidates.py @@ -9,7 +9,7 @@ from typing import TYPE_CHECKING from utils.paths import read_group_paths if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CA_BUNDLE_CANDIDATES" COMMENT = "Extracted CA bundle per distro layout, first readable one wins (SPOT: group_vars/all/05_paths.yml CA_BUNDLE_CANDIDATES)." diff --git a/utils/env/handlers/infinito/ca/cert_host.py b/utils/env/handlers/infinito/ca/cert_host.py index 2af3149a52..aac7c9151c 100644 --- a/utils/env/handlers/infinito/ca/cert_host.py +++ b/utils/env/handlers/infinito/ca/cert_host.py @@ -15,7 +15,7 @@ from utils import PROJECT_ROOT from utils.cache.files import read_text if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CA_CERT_HOST" COMMENT = "Host path of the self-signed root CA cert (ca_trust_paths SPOT)." diff --git a/utils/env/handlers/infinito/cache/conf.py b/utils/env/handlers/infinito/cache/conf.py index 742b9626a6..e6d84d98a9 100644 --- a/utils/env/handlers/infinito/cache/conf.py +++ b/utils/env/handlers/infinito/cache/conf.py @@ -16,7 +16,7 @@ from pathlib import Path from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_PACKAGE_FRONTEND_CONF" COMMENT = "Upstream map the cache frontend mounts, rendered by this checkout." diff --git a/utils/env/handlers/infinito/cache/host_pacman_path.py b/utils/env/handlers/infinito/cache/host_pacman_path.py index dc4482cc8c..73d080d714 100644 --- a/utils/env/handlers/infinito/cache/host_pacman_path.py +++ b/utils/env/handlers/infinito/cache/host_pacman_path.py @@ -10,7 +10,7 @@ from utils.env.parser import parse_static_env from utils.env.runtime import run_helper if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_HOST_PACMAN_PATH" COMMENT = "Pacman cache of an Arch Linux host an arch stack mounts read-only at the same path; empty on every other host or stack." diff --git a/utils/env/handlers/infinito/cache/hosts.py b/utils/env/handlers/infinito/cache/hosts.py index 505a88a31b..cbced45dee 100644 --- a/utils/env/handlers/infinito/cache/hosts.py +++ b/utils/env/handlers/infinito/cache/hosts.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.cache.hosts import declarations if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_HOSTS" COMMENT = ( diff --git a/utils/env/handlers/infinito/cache/http_hosts.py b/utils/env/handlers/infinito/cache/http_hosts.py index 7d4d1ac23f..65f97a7cf0 100644 --- a/utils/env/handlers/infinito/cache/http_hosts.py +++ b/utils/env/handlers/infinito/cache/http_hosts.py @@ -14,7 +14,7 @@ from typing import TYPE_CHECKING from utils.cache.hosts import HTTP_PORT, declarations if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_HTTP_HOSTS" COMMENT = "Hostnames the cache frontend serves over plain HTTP; safe to hijack in any image build." diff --git a/utils/env/handlers/infinito/cache/paths.py b/utils/env/handlers/infinito/cache/paths.py index 3d3dee5c6d..1a6500bd12 100644 --- a/utils/env/handlers/infinito/cache/paths.py +++ b/utils/env/handlers/infinito/cache/paths.py @@ -18,7 +18,7 @@ from typing import TYPE_CHECKING from utils.paths import read_group_path if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder ENTRIES: tuple[tuple[str, tuple[str, ...], str], ...] = ( ( diff --git a/utils/env/handlers/infinito/cache/registries.py b/utils/env/handlers/infinito/cache/registries.py index 1cddaf91f3..1de58bbfc0 100644 --- a/utils/env/handlers/infinito/cache/registries.py +++ b/utils/env/handlers/infinito/cache/registries.py @@ -31,7 +31,7 @@ from utils.docker.image.ref import DOCKER_HUB_REGISTRIES, split_registry_and_nam from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_REGISTRIES" COMMENT = "Registries the pull-through proxy SSL-bumps and caches; derived from every role image, Docker Hub is implicit." diff --git a/utils/env/handlers/infinito/cache/stack.py b/utils/env/handlers/infinito/cache/stack.py index 4f143e9fa6..9d9b684153 100644 --- a/utils/env/handlers/infinito/cache/stack.py +++ b/utils/env/handlers/infinito/cache/stack.py @@ -6,7 +6,7 @@ import os from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_STACK" COMMENT = "True where a persistent pull-through cache stack pays off (local dev)." diff --git a/utils/env/handlers/infinito/cache/tls.py b/utils/env/handlers/infinito/cache/tls.py index f7eda17e22..2f6567c395 100644 --- a/utils/env/handlers/infinito/cache/tls.py +++ b/utils/env/handlers/infinito/cache/tls.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.cache.hosts import HTTPS_PORT, declarations if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_TLS_HOSTS" COMMENT = "Hostnames the cache frontend needs a leaf cert for; derived from the roles' cache: declarations." diff --git a/utils/env/handlers/infinito/cache/upstreams.py b/utils/env/handlers/infinito/cache/upstreams.py index 199aa188e1..c9423fc6f1 100644 --- a/utils/env/handlers/infinito/cache/upstreams.py +++ b/utils/env/handlers/infinito/cache/upstreams.py @@ -14,7 +14,7 @@ from typing import TYPE_CHECKING from utils.cache.records import records if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_UPSTREAMS" MIRRORS_KEY = "INFINITO_APT_UBUNTU_MIRRORS" diff --git a/utils/env/handlers/infinito/container.py b/utils/env/handlers/infinito/container.py index fe6c2712fb..d497aedbac 100644 --- a/utils/env/handlers/infinito/container.py +++ b/utils/env/handlers/infinito/container.py @@ -10,7 +10,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CONTAINER" COMMENT = "Compose service container name derived from INFINITO_DISTRO." diff --git a/utils/env/handlers/infinito/dir/backups.py b/utils/env/handlers/infinito/dir/backups.py index b446a2ebc9..f2041bf387 100644 --- a/utils/env/handlers/infinito/dir/backups.py +++ b/utils/env/handlers/infinito/dir/backups.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_DIR_BACKUPS" COMMENT = "Local backup root (derived from INFINITO_DIR_VAR_LIB)." diff --git a/utils/env/handlers/infinito/dir/secrets.py b/utils/env/handlers/infinito/dir/secrets.py index bddc48a8d5..13f3cdb07f 100644 --- a/utils/env/handlers/infinito/dir/secrets.py +++ b/utils/env/handlers/infinito/dir/secrets.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_DIR_SECRETS" COMMENT = "Host secrets dir (derived from INFINITO_DIR_VAR_LIB)." diff --git a/utils/env/handlers/infinito/dir/var_lib.py b/utils/env/handlers/infinito/dir/var_lib.py index 4ff7323535..97784259f0 100644 --- a/utils/env/handlers/infinito/dir/var_lib.py +++ b/utils/env/handlers/infinito/dir/var_lib.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.paths import read_group_path if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_DIR_VAR_LIB" COMMENT = "Base state dir; env build derives paths from it (SPOT: group_vars/all/05_paths.yml DIR_VAR_LIB)." diff --git a/utils/env/handlers/infinito/distros.py b/utils/env/handlers/infinito/distros.py index 3e2571288c..2a55727a8d 100644 --- a/utils/env/handlers/infinito/distros.py +++ b/utils/env/handlers/infinito/distros.py @@ -11,7 +11,7 @@ from typing import TYPE_CHECKING from utils.distros import FILE_META_DISTROS, distro_names if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_DISTROS" COMMENT = f"Space-separated distro ids, derived from {FILE_META_DISTROS}." diff --git a/utils/env/handlers/infinito/docker/embedded_dns.py b/utils/env/handlers/infinito/docker/embedded_dns.py index 51425086fb..709639ff62 100644 --- a/utils/env/handlers/infinito/docker/embedded_dns.py +++ b/utils/env/handlers/infinito/docker/embedded_dns.py @@ -10,7 +10,7 @@ from utils import PROJECT_ROOT from utils.paths import read_group_value if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder NETWORKS = str(PROJECT_ROOT / "group_vars" / "all" / "08_networks.yml") KEY = "INFINITO_DOCKER_EMBEDDED_DNS_IP" diff --git a/utils/env/handlers/infinito/docker/volume.py b/utils/env/handlers/infinito/docker/volume.py index 80347dd5a2..57f96d3725 100644 --- a/utils/env/handlers/infinito/docker/volume.py +++ b/utils/env/handlers/infinito/docker/volume.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_DOCKER_VOLUME" diff --git a/utils/env/handlers/infinito/domain.py b/utils/env/handlers/infinito/domain.py index b6eb58bc06..e1cf70673a 100644 --- a/utils/env/handlers/infinito/domain.py +++ b/utils/env/handlers/infinito/domain.py @@ -14,7 +14,7 @@ from typing import TYPE_CHECKING from utils.cache.files import read_text if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_DOMAIN" COMMENT = "Domain of this stack: .INFINITO_DNS_DOMAIN." diff --git a/utils/env/handlers/infinito/fork/account.py b/utils/env/handlers/infinito/fork/account.py index c499e1b250..f92f9cb26d 100644 --- a/utils/env/handlers/infinito/fork/account.py +++ b/utils/env/handlers/infinito/fork/account.py @@ -7,7 +7,7 @@ import getpass from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_FORK_ACCOUNT" COMMENT = ( diff --git a/utils/env/handlers/infinito/fork/repository_url.py b/utils/env/handlers/infinito/fork/repository_url.py index aa2e3f2c6a..b78e0217e2 100644 --- a/utils/env/handlers/infinito/fork/repository_url.py +++ b/utils/env/handlers/infinito/fork/repository_url.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_FORK_REPOSITORY_URL" COMMENT = ( diff --git a/utils/env/handlers/infinito/ghcr_mirror.py b/utils/env/handlers/infinito/ghcr_mirror.py index 136c370ba7..4da5b39e6e 100644 --- a/utils/env/handlers/infinito/ghcr_mirror.py +++ b/utils/env/handlers/infinito/ghcr_mirror.py @@ -5,7 +5,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_GHCR_MIRROR" COMMENT = "True where images come from the GHCR mirror instead of their upstream registry (real GitHub Actions)." diff --git a/utils/env/handlers/infinito/git_identity.py b/utils/env/handlers/infinito/git_identity.py index a247b97b32..bc31f153e1 100644 --- a/utils/env/handlers/infinito/git_identity.py +++ b/utils/env/handlers/infinito/git_identity.py @@ -9,7 +9,7 @@ import subprocess from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder NAME_KEY = "INFINITO_GIT_AUTHOR_NAME" EMAIL_KEY = "INFINITO_GIT_AUTHOR_EMAIL" diff --git a/utils/env/handlers/infinito/gpu/count.py b/utils/env/handlers/infinito/gpu/count.py index 0c452636b6..4a5a813950 100644 --- a/utils/env/handlers/infinito/gpu/count.py +++ b/utils/env/handlers/infinito/gpu/count.py @@ -7,7 +7,7 @@ import subprocess from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_GPU_COUNT" COMMENT = "GPUs the compose services reserve: 'all' on an NVIDIA host, else 0." diff --git a/utils/env/handlers/infinito/gpu/only_tests.py b/utils/env/handlers/infinito/gpu/only_tests.py index ffbe2f92c1..b0482d0e05 100644 --- a/utils/env/handlers/infinito/gpu/only_tests.py +++ b/utils/env/handlers/infinito/gpu/only_tests.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_TEST_GPU" GPU_COUNT_KEY = "INFINITO_GPU_COUNT" diff --git a/utils/env/handlers/infinito/i18n/tuning.py b/utils/env/handlers/infinito/i18n/tuning.py index 014c63cbb9..451aa4bb4a 100644 --- a/utils/env/handlers/infinito/i18n/tuning.py +++ b/utils/env/handlers/infinito/i18n/tuning.py @@ -11,7 +11,7 @@ from utils.cache.files import read_text from utils.i18n.limits import BATCH_SIZE if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder TUNING_FILE = Path("build") / "i18n-tuning.json" BATCH_KEY = "INFINITO_I18N_BATCH_SIZE" diff --git a/utils/env/handlers/infinito/image.py b/utils/env/handlers/infinito/image.py index 810b4eab0d..4a1d3ab175 100644 --- a/utils/env/handlers/infinito/image.py +++ b/utils/env/handlers/infinito/image.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.distros import environment_image if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_IMAGE" COMMENT = ( diff --git a/utils/env/handlers/infinito/image_repository.py b/utils/env/handlers/infinito/image_repository.py index aff0c7356c..3f7bfdb421 100644 --- a/utils/env/handlers/infinito/image_repository.py +++ b/utils/env/handlers/infinito/image_repository.py @@ -9,7 +9,7 @@ from typing import TYPE_CHECKING from utils.env.runtime import run_helper if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_IMAGE_REPOSITORY" COMMENT = ( diff --git a/utils/env/handlers/infinito/inventory.py b/utils/env/handlers/infinito/inventory.py index 41a0ab01e2..282b33e68d 100644 --- a/utils/env/handlers/infinito/inventory.py +++ b/utils/env/handlers/infinito/inventory.py @@ -10,7 +10,7 @@ from typing import TYPE_CHECKING from utils.env.runtime import run_helper if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder INVENTORY_DIR_KEY = "INFINITO_INVENTORY_DIR" INVENTORY_FILE_KEY = "INFINITO_INVENTORY_FILE" diff --git a/utils/env/handlers/infinito/ip_range.py b/utils/env/handlers/infinito/ip_range.py index 1c02ebaf48..69fd8c03b5 100644 --- a/utils/env/handlers/infinito/ip_range.py +++ b/utils/env/handlers/infinito/ip_range.py @@ -13,7 +13,7 @@ import ipaddress from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import EnvBuilder + from utils.env.context import EnvBuilder KEY = "INFINITO_IP_RANGE" SUBNET_KEY = "INFINITO_SUBNET" diff --git a/utils/env/handlers/infinito/is_wsl2.py b/utils/env/handlers/infinito/is_wsl2.py index 08f74b2a35..27d3bf4b96 100644 --- a/utils/env/handlers/infinito/is_wsl2.py +++ b/utils/env/handlers/infinito/is_wsl2.py @@ -7,7 +7,7 @@ from typing import TYPE_CHECKING from utils.env.runtime import is_wsl2 if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_IS_WSL2" COMMENT = "True when /proc/version identifies the host as WSL2." diff --git a/utils/env/handlers/infinito/outer_network_mtu.py b/utils/env/handlers/infinito/outer_network_mtu.py index e4117ba790..95b3881980 100644 --- a/utils/env/handlers/infinito/outer_network_mtu.py +++ b/utils/env/handlers/infinito/outer_network_mtu.py @@ -15,7 +15,7 @@ from pathlib import Path from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_OUTER_NETWORK_MTU" STATIC_READS = (KEY,) diff --git a/utils/env/handlers/infinito/package_cache/admin_password.py b/utils/env/handlers/infinito/package_cache/admin_password.py index 8dce998746..57f30f4072 100644 --- a/utils/env/handlers/infinito/package_cache/admin_password.py +++ b/utils/env/handlers/infinito/package_cache/admin_password.py @@ -10,7 +10,7 @@ from typing import TYPE_CHECKING from utils.env.runtime import hostname if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_PACKAGE_ADMIN_PASSWORD" COMMENT = ( diff --git a/utils/env/handlers/infinito/package_cache/blobstore_max.py b/utils/env/handlers/infinito/package_cache/blobstore_max.py index fcec790ba5..b0b9508397 100644 --- a/utils/env/handlers/infinito/package_cache/blobstore_max.py +++ b/utils/env/handlers/infinito/package_cache/blobstore_max.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.env.runtime import df_avail_gb if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_PACKAGE_BLOBSTORE_MAX" COMMENT = ( diff --git a/utils/env/handlers/infinito/package_cache/direct_mem.py b/utils/env/handlers/infinito/package_cache/direct_mem.py index f2d1734ef9..1c38d82ac0 100644 --- a/utils/env/handlers/infinito/package_cache/direct_mem.py +++ b/utils/env/handlers/infinito/package_cache/direct_mem.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_PACKAGE_DIRECT_MEM" COMMENT = "Nexus direct-memory budget; tied to INFINITO_CACHE_PACKAGE_HEAP." diff --git a/utils/env/handlers/infinito/package_cache/heap.py b/utils/env/handlers/infinito/package_cache/heap.py index bb6c20e5c1..b9e0f7542b 100644 --- a/utils/env/handlers/infinito/package_cache/heap.py +++ b/utils/env/handlers/infinito/package_cache/heap.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.env.runtime import mem_available_mb if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_PACKAGE_HEAP" COMMENT = "Nexus JVM heap size (half of MemAvailable, cap 2g, floor 1g)." diff --git a/utils/env/handlers/infinito/parent_image.py b/utils/env/handlers/infinito/parent_image.py index c37a13715e..e317eb89ca 100644 --- a/utils/env/handlers/infinito/parent_image.py +++ b/utils/env/handlers/infinito/parent_image.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.distros import base_image if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_PARENT_IMAGE" COMMENT = ( diff --git a/utils/env/handlers/infinito/playwright/reports_base_dir.py b/utils/env/handlers/infinito/playwright/reports_base_dir.py index 22d462836e..d309b9c13b 100644 --- a/utils/env/handlers/infinito/playwright/reports_base_dir.py +++ b/utils/env/handlers/infinito/playwright/reports_base_dir.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_PLAYWRIGHT_REPORTS_BASE_DIR" COMMENT = ( diff --git a/utils/env/handlers/infinito/playwright/stage_base_dir.py b/utils/env/handlers/infinito/playwright/stage_base_dir.py index 1a5583e91a..c80eff636d 100644 --- a/utils/env/handlers/infinito/playwright/stage_base_dir.py +++ b/utils/env/handlers/infinito/playwright/stage_base_dir.py @@ -11,7 +11,7 @@ from utils.cache.files import read_text from utils.roles.mapping import ROLE_FILE_VARS_MAIN if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_PLAYWRIGHT_STAGE_BASE_DIR" COMMENT = ( diff --git a/utils/env/handlers/infinito/pull_policy.py b/utils/env/handlers/infinito/pull_policy.py index 8f0b3db864..e3ad5a59df 100644 --- a/utils/env/handlers/infinito/pull_policy.py +++ b/utils/env/handlers/infinito/pull_policy.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_PULL_POLICY" diff --git a/utils/env/handlers/infinito/registry_cache_max_size.py b/utils/env/handlers/infinito/registry_cache_max_size.py index 7afa5bbf48..008ae43720 100644 --- a/utils/env/handlers/infinito/registry_cache_max_size.py +++ b/utils/env/handlers/infinito/registry_cache_max_size.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.env.runtime import df_avail_gb if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_CACHE_REGISTRY_MAX_SIZE" COMMENT = ( diff --git a/utils/env/handlers/infinito/rescue/diagnostics_dir.py b/utils/env/handlers/infinito/rescue/diagnostics_dir.py index 56dee73a8b..df5643e526 100644 --- a/utils/env/handlers/infinito/rescue/diagnostics_dir.py +++ b/utils/env/handlers/infinito/rescue/diagnostics_dir.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.paths import read_group_path if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_RESCUE_DIAGNOSTICS_DIR" COMMENT = "Where rescue: blocks write their failure snapshot; CI uploads it (SPOT: group_vars/all/05_paths.yml DIR_RESCUE_DIAGNOSTICS)." diff --git a/utils/env/handlers/infinito/rescue/dns53_sampler_log.py b/utils/env/handlers/infinito/rescue/dns53_sampler_log.py index 0fc4a6fb74..95c8465c92 100644 --- a/utils/env/handlers/infinito/rescue/dns53_sampler_log.py +++ b/utils/env/handlers/infinito/rescue/dns53_sampler_log.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from utils.paths import read_group_path if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_DNS53_SAMPLER_LOG" COMMENT = "Where the :53 sampler appends its ticks and the rescue collector reads them (SPOT: group_vars/all/05_paths.yml FILE_DNS53_SAMPLER_LOG)." diff --git a/utils/env/handlers/infinito/rescue/local_dumps_dir.py b/utils/env/handlers/infinito/rescue/local_dumps_dir.py index e470438cdc..4399b2e563 100644 --- a/utils/env/handlers/infinito/rescue/local_dumps_dir.py +++ b/utils/env/handlers/infinito/rescue/local_dumps_dir.py @@ -12,7 +12,7 @@ from typing import TYPE_CHECKING from utils.paths import read_group_path if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_RESCUE_LOCAL_DUMPS_DIR" COMMENT = "Where in-play role dumps land; the rescue collector ships them as local-dumps (SPOT: group_vars/all/05_paths.yml DIR_RESCUE_DIAGNOSTICS)." diff --git a/utils/env/handlers/infinito/running_on/act.py b/utils/env/handlers/infinito/running_on/act.py index 343224cb70..41f82ce6c9 100644 --- a/utils/env/handlers/infinito/running_on/act.py +++ b/utils/env/handlers/infinito/running_on/act.py @@ -5,7 +5,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_RUNNING_ON_ACT" COMMENT = "True when running under nektos/act locally." diff --git a/utils/env/handlers/infinito/running_on/github.py b/utils/env/handlers/infinito/running_on/github.py index 852e6b7833..6126e98162 100644 --- a/utils/env/handlers/infinito/running_on/github.py +++ b/utils/env/handlers/infinito/running_on/github.py @@ -6,7 +6,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_RUNNING_ON_GITHUB" COMMENT = "True when running on real GitHub Actions (not act)." diff --git a/utils/env/handlers/infinito/swarm_nfs/export_base.py b/utils/env/handlers/infinito/swarm_nfs/export_base.py index 1f3b68585c..a507efcc40 100644 --- a/utils/env/handlers/infinito/swarm_nfs/export_base.py +++ b/utils/env/handlers/infinito/swarm_nfs/export_base.py @@ -9,7 +9,7 @@ from typing import TYPE_CHECKING from utils.storage.nfs import get_export_base if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_SWARM_NFS_EXPORT_BASE" COMMENT = "NFS export base path inside the NFS-server sidecar (SPOT: svc-storage-nfs-server services.yml)." diff --git a/utils/env/handlers/infinito/swarm_nfs/state_path.py b/utils/env/handlers/infinito/swarm_nfs/state_path.py index 282b13b02e..dcf41c1ee0 100644 --- a/utils/env/handlers/infinito/swarm_nfs/state_path.py +++ b/utils/env/handlers/infinito/swarm_nfs/state_path.py @@ -9,7 +9,7 @@ from typing import TYPE_CHECKING from utils.storage.nfs import STATE_SUBDIR, state_path if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_SWARM_NFS_STATE_PATH" COMMENT = "Cluster-shared NFS state dir on the act-swarm test nodes." diff --git a/utils/env/handlers/infinito/tools/libretranslate.py b/utils/env/handlers/infinito/tools/libretranslate.py index 6c10f522d2..8b099fe66f 100644 --- a/utils/env/handlers/infinito/tools/libretranslate.py +++ b/utils/env/handlers/infinito/tools/libretranslate.py @@ -10,7 +10,7 @@ from utils.cache.files import read_text from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_TOOLS_LIBRETRANSLATE_PORT" COMMENT = "Loopback port the tools runner forwards to its LibreTranslate." diff --git a/utils/env/handlers/infinito/tools/litellm.py b/utils/env/handlers/infinito/tools/litellm.py index 9dead26eb2..364ec21a38 100644 --- a/utils/env/handlers/infinito/tools/litellm.py +++ b/utils/env/handlers/infinito/tools/litellm.py @@ -10,7 +10,7 @@ from utils.cache.files import read_text from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_TOOLS_LITELLM_PORT" COMMENT = "Loopback port the tools runner forwards to its model gateway." diff --git a/utils/env/handlers/infinito/tools/models.py b/utils/env/handlers/infinito/tools/models.py index 8b6fe05c59..7236210e65 100644 --- a/utils/env/handlers/infinito/tools/models.py +++ b/utils/env/handlers/infinito/tools/models.py @@ -18,7 +18,7 @@ from typing import TYPE_CHECKING from utils.env.handlers.infinito.cache.paths import base if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_TOOLS_MODELS_HOST_PATH" COMMENT = "Node-local directory the tools lane keeps its downloaded models in." diff --git a/utils/env/handlers/infinito/tools/s1.py b/utils/env/handlers/infinito/tools/s1.py index f9889afc47..46a7046f7c 100644 --- a/utils/env/handlers/infinito/tools/s1.py +++ b/utils/env/handlers/infinito/tools/s1.py @@ -10,7 +10,7 @@ from utils.cache.files import read_text from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_TOOLS_S1_PORT" COMMENT = "Loopback port the tools runner forwards to its System One." diff --git a/utils/env/handlers/infinito/tools/translate.py b/utils/env/handlers/infinito/tools/translate.py index 449200c83f..46db093dc5 100644 --- a/utils/env/handlers/infinito/tools/translate.py +++ b/utils/env/handlers/infinito/tools/translate.py @@ -10,7 +10,7 @@ from utils.cache.files import read_text from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_TOOLS_TRANSLATE_PORT" COMMENT = "Loopback port the tools runner forwards to its translation gateway." diff --git a/utils/env/handlers/infinito/tor_socks_port.py b/utils/env/handlers/infinito/tor_socks_port.py index 54280ce001..756b5cea8a 100644 --- a/utils/env/handlers/infinito/tor_socks_port.py +++ b/utils/env/handlers/infinito/tor_socks_port.py @@ -15,7 +15,7 @@ from utils.cache.files import read_text from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_TOR_SOCKS_PORT" COMMENT = "Node Tor SOCKS port (SPOT: svc-net-tor services.tor.ports.local.socks)." diff --git a/utils/env/handlers/infinito/worker/cpu.py b/utils/env/handlers/infinito/worker/cpu.py index 0e24e09602..ffee8ca05b 100644 --- a/utils/env/handlers/infinito/worker/cpu.py +++ b/utils/env/handlers/infinito/worker/cpu.py @@ -10,7 +10,7 @@ import os from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_WORKER_CPU" COMMENT = "Host CPU count when INFINITO_WORKER_ENABLED truthy, else 1 (sequential)." diff --git a/utils/env/handlers/infinito/worker/fetch.py b/utils/env/handlers/infinito/worker/fetch.py index bfafbfe30d..b437c28b94 100644 --- a/utils/env/handlers/infinito/worker/fetch.py +++ b/utils/env/handlers/infinito/worker/fetch.py @@ -10,7 +10,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "INFINITO_WORKER_FETCH" COMMENT = "Workers for network-bound bulk fetches (INFINITO_WORKER_CPU * 20)." diff --git a/utils/env/handlers/nix_config.py b/utils/env/handlers/nix_config.py index 97267afa8e..a56d12f4c7 100644 --- a/utils/env/handlers/nix_config.py +++ b/utils/env/handlers/nix_config.py @@ -13,7 +13,7 @@ import os from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder KEY = "NIX_CONFIG" COMMENT = "Pass-through of the caller's NIX_CONFIG access-tokens line, when present." diff --git a/utils/env/handlers/passthrough.py b/utils/env/handlers/passthrough.py index e121a6f2dd..3b8c3d62b4 100644 --- a/utils/env/handlers/passthrough.py +++ b/utils/env/handlers/passthrough.py @@ -7,7 +7,7 @@ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: - from utils.env.builder import BuildContext, EnvBuilder + from utils.env.context import BuildContext, EnvBuilder STATIC_KEYS = ( "INFINITO_SRC_DIR", diff --git a/utils/env/writer.py b/utils/env/writer.py index 494f7ea338..7ca5fde0d5 100644 --- a/utils/env/writer.py +++ b/utils/env/writer.py @@ -18,7 +18,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from pathlib import Path - from utils.env.builder import EnvBuilder + from utils.env.context import EnvBuilder _SAFE_VALUE_RE = re.compile(r"^[A-Za-z0-9_/.@:%+=-]+$") diff --git a/utils/i18n/libretranslate.py b/utils/i18n/libretranslate.py index 009d754f2f..dee28632fd 100644 --- a/utils/i18n/libretranslate.py +++ b/utils/i18n/libretranslate.py @@ -14,7 +14,7 @@ from utils.cache.yaml import load_yaml from utils.i18n.client import LibreTranslate as LibreTranslate from utils.i18n.client import Outcome as Outcome from utils.i18n.client import merge -from utils.inventory.tools import LANE_SERVICE +from utils.inventory.tools_vars import LANE_SERVICE, render from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: @@ -246,8 +246,6 @@ def _vars_file(root: Path) -> Path: Returns: The rendered file, beside the template so the container sees it. """ - from utils.inventory.tools import render - return render(root, baked_languages(root)) diff --git a/utils/inventory/tools.py b/utils/inventory/tools.py index ea07e6f0c1..3270d9c3fd 100644 --- a/utils/inventory/tools.py +++ b/utils/inventory/tools.py @@ -1,36 +1,17 @@ -"""The tools lane: the host vars its services deploy with, and bringing it up. +"""The tools lane: bringing it up and reaching its services. The lane holds the toolchain services the repository's own targets and tests call: the translation engine behind the ``i18n`` targets, and the System One classifier the semantic suite asks for a verdict. A caller names the roles it needs and gets them running, so a check is never skipped merely because -nothing happened to be up. - -The template carries Ansible expressions the deploy resolves later, so it is -rendered with the Ansible parts inside ``raw`` blocks; everything this module -fills is an ordinary Jinja expression. The rendered file lands beside the -template so the runner's bind mount of the repository exposes it inside the -container. +nothing happened to be up. The host vars those services deploy with are +rendered by :mod:`utils.inventory.tools_vars`. Nothing here deploys a cache: the runner extends ``compose.cache-consumer.yml`` from the outer stack, so its image pulls already traverse ``registry-cache`` and its package and model downloads resolve to ``package-cache-frontend`` through that file's ``extra_hosts``. -System One authenticates its callers, and its key is an -``algorithm: alphanumeric`` credential the provisioner would otherwise -generate into a vault the caller cannot read back. :data:`API_KEY` pins one -instead, so the lane and the checks that call it agree without reading a vault -or passing a secret on a command line. It is a fixed literal because the lane -serves the repository's own tooling on a developer machine and reaches no -deployment that holds data, the same standing as the dummy authorized key the -template already carries. Never reuse it anywhere a real caller could reach. - -:data:`LITELLM_KEY` pins the model gateway's master key for the same reason -and under the same standing. A deployment hands each consumer a virtual key -instead, which is what the role's secret description asks for; the oracle -judge is not a deployed consumer and has no vault to read one from. - The lane pins its own model in the template, rather than taking the repository's ``AI_LOCAL_MODELS`` default: the oracle needs a judge that can tell a faithful rendering from an unrelated text, a demand no deployment @@ -42,42 +23,30 @@ two are held together by a test that renders the template. from __future__ import annotations -import os import subprocess from pathlib import Path -from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape - from utils.cache.yaml import load_yaml +from utils.i18n.libretranslate import ( + baked_languages, + deploy, + deploying, + environment, + lane_container, +) +from utils.inventory.tools_vars import LANE_SERVICE, LITELLM_KEY from utils.roles.mapping import ROLE_FILE_META_SERVICES -TEMPLATE = Path("inventories") / "development" / "tools.yml.j2" -RENDERED = Path("inventories") / "development" / "tools.rendered.yml" ADDRESS = Path("inventories") / "development" / "tools.address" -API_KEY = "toolsLaneTestKeyNotASecret0000000000" -LITELLM_KEY = "toolsLaneLiteLlmMasterKeyNotASecret000000000000000000" LIBRETRANSLATE_ROLE = "svc-ai-libretranslate-engine" S1_ROLE = "svc-ai-s1" LITELLM_ROLE = "svc-ai-litellm" OLLAMA_ROLE = "svc-ai-ollama" GATEWAY_ROLE = "web-svc-translate" -LANE_SERVICE = "tools" LANE_MODEL_ALIAS = "qwen2.5:3b" PROBE_TIMEOUT_SECONDS = 10 -def models_dir() -> str: - """Return the node-local directory the lane keeps its models in. - - Reads the same value ``compose/tools.override.yml`` mounts into the - runner, so a bind the inventory writes resolves to the host directory - rather than to something inside the runner that a rebuild discards. - """ - from utils.env.handlers.infinito.tools.models import KEY, default - - return (os.environ.get(KEY) or "").strip() or default() - - def lane_ip(root: Path) -> str: """Return the runner's address inside the stack's own subnet, or ''. @@ -94,8 +63,6 @@ def lane_ip(root: Path) -> str: import ipaddress import json - from utils.i18n.libretranslate import environment, lane_container - env = environment(root) found = subprocess.run( [ @@ -181,8 +148,6 @@ def host_url(root: Path, role: str, service_key: str) -> str: role: application id owning the service. service_key: key under ``meta/services.yml``. """ - from utils.i18n.libretranslate import environment - services = load_yaml(root / "roles" / role / ROLE_FILE_META_SERVICES) port = services[service_key]["ports"]["local"]["http"] return f"http://{environment(root)['INFINITO_BIND_IP']}:{port}" @@ -334,42 +299,6 @@ def serving(root: Path, load_only: list[str], roles: tuple[str, ...]) -> bool: return {_base_subtag(code) for code in load_only} <= served -def render(root: Path, load_only: list[str]) -> Path: - """Write the tools lane host vars and return the rendered file. - - Args: - root: repository root. - load_only: every language code the lane's image prefetches models for. - Pinning the whole set keeps the build ARG constant, so the prefetch - layer is not rebuilt once per batch. - - Returns: - The rendered file. - """ - template_path = root / TEMPLATE - env = Environment( - loader=FileSystemLoader(str(template_path.parent)), - undefined=StrictUndefined, - keep_trailing_newline=True, - trim_blocks=True, - lstrip_blocks=True, - variable_start_string="[[", - variable_end_string="]]", - block_start_string="[%", - block_end_string="%]", - autoescape=select_autoescape(default_for_string=False), - ) - body = env.get_template(template_path.name).render( - load_only=sorted(load_only), - s1_api_key=API_KEY, - litellm_master_key=LITELLM_KEY, - models_dir=models_dir(), - ) - rendered = root / RENDERED - rendered.write_text(body, encoding="utf-8") - return rendered - - def ensure(root: Path, roles: tuple[str, ...]) -> None: """Bring the named lane roles up, unless they already serve. @@ -394,8 +323,6 @@ def ensure(root: Path, roles: tuple[str, ...]) -> None: RuntimeError: a deploy already holds the container stack this one would touch. """ - from utils.i18n.libretranslate import baked_languages, deploy, deploying - if serving(root, baked_languages(root), roles): print( f"tools lane already serves {', '.join(roles)}; not deploying", flush=True @@ -437,7 +364,6 @@ def main(argv: list[str] | None = None) -> int: import argparse from utils import PROJECT_ROOT - from utils.i18n.libretranslate import baked_languages default_roles = [ LIBRETRANSLATE_ROLE, diff --git a/utils/inventory/tools_vars.py b/utils/inventory/tools_vars.py new file mode 100644 index 0000000000..29207584d7 --- /dev/null +++ b/utils/inventory/tools_vars.py @@ -0,0 +1,83 @@ +"""The tools lane's host vars: the inventory its services deploy with. + +The template carries Ansible expressions the deploy resolves later, so it is +rendered with the Ansible parts inside ``raw`` blocks; everything this module +fills is an ordinary Jinja expression. The rendered file lands beside the +template so the runner's bind mount of the repository exposes it inside the +container. + +System One authenticates its callers, and its key is an +``algorithm: alphanumeric`` credential the provisioner would otherwise +generate into a vault the caller cannot read back. :data:`API_KEY` pins one +instead, so the lane and the checks that call it agree without reading a vault +or passing a secret on a command line. It is a fixed literal because the lane +serves the repository's own tooling on a developer machine and reaches no +deployment that holds data, the same standing as the dummy authorized key the +template already carries. Never reuse it anywhere a real caller could reach. + +:data:`LITELLM_KEY` pins the model gateway's master key for the same reason +and under the same standing. A deployment hands each consumer a virtual key +instead, which is what the role's secret description asks for; the oracle +judge is not a deployed consumer and has no vault to read one from. +""" + +from __future__ import annotations + +import os +from pathlib import Path + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +TEMPLATE = Path("inventories") / "development" / "tools.yml.j2" +RENDERED = Path("inventories") / "development" / "tools.rendered.yml" +API_KEY = "toolsLaneTestKeyNotASecret0000000000" +LITELLM_KEY = "toolsLaneLiteLlmMasterKeyNotASecret000000000000000000" +LANE_SERVICE = "tools" + + +def models_dir() -> str: + """Return the node-local directory the lane keeps its models in. + + Reads the same value ``compose/tools.override.yml`` mounts into the + runner, so a bind the inventory writes resolves to the host directory + rather than to something inside the runner that a rebuild discards. + """ + from utils.env.handlers.infinito.tools.models import KEY, default + + return (os.environ.get(KEY) or "").strip() or default() + + +def render(root: Path, load_only: list[str]) -> Path: + """Write the tools lane host vars and return the rendered file. + + Args: + root: repository root. + load_only: every language code the lane's image prefetches models for. + Pinning the whole set keeps the build ARG constant, so the prefetch + layer is not rebuilt once per batch. + + Returns: + The rendered file. + """ + template_path = root / TEMPLATE + env = Environment( + loader=FileSystemLoader(str(template_path.parent)), + undefined=StrictUndefined, + keep_trailing_newline=True, + trim_blocks=True, + lstrip_blocks=True, + variable_start_string="[[", + variable_end_string="]]", + block_start_string="[%", + block_end_string="%]", + autoescape=select_autoescape(default_for_string=False), + ) + body = env.get_template(template_path.name).render( + load_only=sorted(load_only), + s1_api_key=API_KEY, + litellm_master_key=LITELLM_KEY, + models_dir=models_dir(), + ) + rendered = root / RENDERED + rendered.write_text(body, encoding="utf-8") + return rendered diff --git a/utils/roles/applications/variants.py b/utils/roles/applications/variants.py index ede3b8ed50..cce54e902e 100644 --- a/utils/roles/applications/variants.py +++ b/utils/roles/applications/variants.py @@ -14,7 +14,7 @@ resolves its closure on a runner that has no inventory, no container and no from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from dataclasses import dataclass from pathlib import Path from typing import Any @@ -260,6 +260,52 @@ def clamped_assignment( } +def _resolve_round_include( + *, + primary_apps: Sequence[str], + services_overrides: dict[str, dict], +) -> tuple[str, ...]: + """Resolve transitive prerequisites for each primary app under a + round's variant-merged services map. Returns the full include set + in stable order (deps first per primary, primary last; primaries + iterated in the user-provided order). + + A non-invokable prerequisite is dropped from the result. The include + set becomes an inventory group per entry and a deploy id the play + dispatches, and `utils.roles.stage` only ever loops over invokable + paths, so a non-invokable id could never be dispatched from one. + Keeping it would abort the round before ansible starts, which is + what `user-workstation` did to every desktop round, and inventing a + group for it instead would produce one nothing dispatches. The role + still reaches the host through whatever pulled it into the closure: + a meta dependency, or the service edge `sys-service-loader` reads. + + The resolver import is deferred so the host-side import surface + stays lean for callers that never need the variant-aware planner + (e.g. lint/validation). + """ + from cli.meta.roles.applications.resolution.combined.resolver import ( + CombinedResolver, + ) + from utils.roles.required_by_coverage import role_is_invokable + + resolver = CombinedResolver( + services_overrides=services_overrides, follow_run_after=False + ) + out: list[str] = [] + seen: set[str] = set() + for app_id in primary_apps: + deps = resolver.resolve(app_id) + for dep in deps: + if dep != app_id and dep not in seen and role_is_invokable(dep): + out.append(dep) + seen.add(dep) + if app_id not in seen: + out.append(app_id) + seen.add(app_id) + return tuple(out) + + def round_under( active_index: Mapping[str, int], *, @@ -283,8 +329,6 @@ def round_under( The round under ``active_index``, and ``{role: index}`` for every non-primary role a pin in force moves. """ - from cli.administration.deploy.development.inventory import legacy_resolver - overrides = _overrides_for_assignment( active_index, roles_dir=roles_dir, @@ -292,7 +336,7 @@ def round_under( variants_per_app=variants_per_app, ) include = tuple( - legacy_resolver._resolve_round_include( + _resolve_round_include( primary_apps=list(primary_app_variants), services_overrides=overrides, )