From 3541c473baded554626330a1dec84d45761c9247 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:33:08 +0000 Subject: [PATCH 01/65] update(versions): update pins with a declared source (web-app-mattermost) --- .../meta/addons/mattermost-plugin-gitlab.yml | 4 ++-- .../web-app-mattermost/meta/addons/mattermost-plugin-jira.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/roles/web-app-mattermost/meta/addons/mattermost-plugin-gitlab.yml b/roles/web-app-mattermost/meta/addons/mattermost-plugin-gitlab.yml index 7a6ed98f70..bd696ac467 100644 --- a/roles/web-app-mattermost/meta/addons/mattermost-plugin-gitlab.yml +++ b/roles/web-app-mattermost/meta/addons/mattermost-plugin-gitlab.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-mattermost', 'services.gitlab.enabled') | required: false mechanism: plugin source: upstream -version: "v1.13.1" +version: "v2.0.0" bridges: - gitlab update: @@ -12,5 +12,5 @@ update: upstream_id: mattermost/mattermost-plugin-gitlab config: plugin_id: com.github.manland.mattermost-plugin-gitlab - archive: https://github.com/mattermost/mattermost-plugin-gitlab/releases/download/v1.13.1/mattermost-plugin-gitlab-v1.13.1.tar.gz + archive: https://github.com/mattermost/mattermost-plugin-gitlab/releases/download/v2.0.0/mattermost-plugin-gitlab-v2.0.0.tar.gz partner_url: "{{ lookup('tls', 'web-app-gitlab', 'url.base') }}" diff --git a/roles/web-app-mattermost/meta/addons/mattermost-plugin-jira.yml b/roles/web-app-mattermost/meta/addons/mattermost-plugin-jira.yml index 402382a048..571fab4070 100644 --- a/roles/web-app-mattermost/meta/addons/mattermost-plugin-jira.yml +++ b/roles/web-app-mattermost/meta/addons/mattermost-plugin-jira.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-mattermost', 'services.jira.enabled') | b required: false mechanism: plugin source: upstream -version: "v4.8.3" +version: "v5.1.0" bridges: - jira update: From 2fd480d2db24c3768faffab8f1309a302952b55b Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Wed, 18 Nov 2026 21:29:02 +0400 Subject: [PATCH 02/65] perf(applications_carrier): park the carriers outside the fact cache Co-Authored-By: Claude Opus 5.5 --- .../files/plugins/lookup/applications.md | 7 +- .../artefact/files/plugins/lookup/users.md | 2 +- docs/contributing/design/inventory.md | 2 +- plugins/action/applications_carrier.py | 37 +-- .../test_applications_carrier.py | 238 ++++++++++++++++++ .../action/test_applications_carrier.py | 68 ++--- .../python/utils/cache/test_applications.py | 31 +++ .../python/utils/cache/users/test_module.py | 17 +- utils/cache/README.md | 8 +- utils/cache/carrier.py | 23 +- 10 files changed, 372 insertions(+), 61 deletions(-) create mode 100644 tests/integration/ansible/action_plugins/test_applications_carrier.py diff --git a/docs/contributing/artefact/files/plugins/lookup/applications.md b/docs/contributing/artefact/files/plugins/lookup/applications.md index 3fd16109cf..46a1fe1630 100644 --- a/docs/contributing/artefact/files/plugins/lookup/applications.md +++ b/docs/contributing/artefact/files/plugins/lookup/applications.md @@ -33,15 +33,16 @@ No other source is consulted. Ansible forks a fresh worker process for every task. The in-process cache inside `get_merged_applications` therefore never survives from one task to the next, and every task that touches the lookup would render the full tree again (about 16 to 23 seconds per task on a CI runner, measured on the workspace jobs). -The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN` or `group_names`). +The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the non-persistent host variable `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that variable at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN` or `group_names`). - `tasks/stages/01_constructor.yml` renders once for the bootstrap section, in every deploy mode, right after the `networks` and `service_provider` merges and the `add_host` placements, so the `update` role, the pre-flight checks and the package batch share one render with the `group_names` and `groups` a role sees. Moving it before the placements bakes stale values into the play. The stage-wide task after the token store serves that render while its key still matches, so the carried user records can predate the token store (see the token rule below). - The carrier is parked again after every role in `tasks/utils/setup/role.yml`, after every nested application load in `tasks/utils/load/app.yml`, and after every store write in `roles/sys-token-store/tasks/write_many.yml`, which `write.yml` runs for a single token. The first two run on every host of the include, also on hosts the loaded role skips. A re-park whose key still matches serves the carried payload without rendering. - The action renders with `application_id` removed from its variables, so the carried tree holds the play-scope result of every consumer-aligned `lookup('tls', ...)`, whichever role parks it. - The token store is not part of the key: a store write keeps the applications carrier and re-renders only the users carrier (see [users.md](users.md)). -- The action masks its own result: the fact is the whole rendered tree with every application's credentials, so it never reaches a log regardless of `MASK_CREDENTIALS_IN_LOGS`. +- The action registers the carriers in the layer `set_fact` writes, never as `ansible_facts`: `get_vars` deep-copies the fact cache before every task, and the carrier is the whole rendered tree. A reader that finds a carrier in `ansible_facts` but not among the variables raises `CarrierInvisibleError` instead of rendering again. +- The action masks its own result: the carrier is the whole rendered tree with every application's credentials, so it never reaches a log regardless of `MASK_CREDENTIALS_IN_LOGS`. - User records inside the payload are the token store's state at render time, which can predate every store write of the play. Readers of tokens MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which key the users on the current token store. Application config MUST NOT derive a value from a token. -- The action parks the users carrier `_INFINITO_USERS_RENDERED` at the same points, after the applications render; `clear: true` drops every carrier fact. See [users.md](users.md). +- The action parks the users carrier `_INFINITO_USERS_RENDERED` at the same points, after the applications render; `clear: true` drops every carrier. See [users.md](users.md). - With `provider_view: true` (the stage-wide park only), a host that is not the onion-serving mail provider host also parks `_INFINITO_PROVIDER_VIEW_RENDERED`: the applications tree of its own variables under the provider host's `group_names` and `NETWORK_MODE`, keyed like the applications carrier plus `[provider host, NETWORK_MODE]`. It is kept while the parked one or the provider host's own carrier still matches. - The carriers are private to the lookups. Consumers MUST NOT read `_INFINITO_APPLICATIONS_RENDERED`; they keep going through `lookup('applications')`, which is what makes the carrier transparent. Only `lookup('email')` reads the provider host's `_INFINITO_APPLICATIONS_RENDERED` and its own `_INFINITO_PROVIDER_VIEW_RENDERED`, and only to hand the matching one to `lookup('domains')`. - These carriers are the only materialised merged views a play MAY hold. The rule against a top-level `applications` fact above is unchanged. diff --git a/docs/contributing/artefact/files/plugins/lookup/users.md b/docs/contributing/artefact/files/plugins/lookup/users.md index 4bc13b57c9..fe2d2bd816 100644 --- a/docs/contributing/artefact/files/plugins/lookup/users.md +++ b/docs/contributing/artefact/files/plugins/lookup/users.md @@ -22,7 +22,7 @@ The `users` lookup is the ONLY supported runtime entry point for merged user con ## Play-Scoped Carrier 🧊 -The [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action parks the rendered users next to the applications in the host fact `_INFINITO_USERS_RENDERED`, at every point listed in [applications.md](applications.md), and `clear: true` drops both facts. `get_merged_users` serves the fact to a templated read when its key matches and renders otherwise. +The [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action parks the rendered users next to the applications in the non-persistent host variable `_INFINITO_USERS_RENDERED`, at every point listed in [applications.md](applications.md), and `clear: true` drops both carriers. `get_merged_users` serves the carrier to a templated read when its key matches and renders otherwise. - The key is the applications carrier key plus the token store and `inventory_hostname`: a changed `applications`, `users`, `DOMAIN_PRIMARY`, `SYSTEM_EMAIL_DOMAIN`, `group_names`, token store or host rejects the carrier. - The token store enters the key as the SHA-256 of exactly the tokens the users are hydrated from: the controller's tokens file until `sys-token-store` loads, the `sys_token_store_users` fact after. Both sources key alike when they hold the same tokens, so loading an unchanged store keeps the carrier, and a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. diff --git a/docs/contributing/design/inventory.md b/docs/contributing/design/inventory.md index 6cfdcf63e7..2091208331 100644 --- a/docs/contributing/design/inventory.md +++ b/docs/contributing/design/inventory.md @@ -47,7 +47,7 @@ Rendering happens at **play runtime**, never during the build pipeline above. Th `get_merged_applications` is invoked transitively by `lookup('applications', ...)` and by `lookup('config', application_id, 'services..')`. Tasks that read service flags through these lookups always see real Python values, never raw Jinja strings. -The render runs once per play. The constructor stage parks the payload and its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED`, and every task's worker process (Ansible forks one per task) serves that payload instead of rendering again. See [applications.md](../artefact/files/plugins/lookup/applications.md) for the carrier contract. +The render runs once per play. The constructor stage parks the payload and its cache key in the non-persistent host variable `_INFINITO_APPLICATIONS_RENDERED`, and every task's worker process (Ansible forks one per task) serves that payload instead of rendering again. See [applications.md](../artefact/files/plugins/lookup/applications.md) for the carrier contract. A role's task that reads its own service flag therefore picks up the runtime-resolved value, even when the inventory carried a Jinja string for that flag: the conditional evaluates against the play's actual `group_names`, which reflects which other application groups the host joined. diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index d67b2064ec..51bbf87770 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -1,12 +1,14 @@ -"""Render the applications and users SPOTs once and park them as play-scoped carrier facts. +"""Render the applications and users SPOTs once and park them as play-scoped carrier variables. Ansible forks a fresh worker per task, so the in-process render caches of ``lookup('applications')`` and ``lookup('users')`` are cold in every task until something renders in a place all later workers inherit. This action -renders in the worker of one constructor task and returns both payloads as -host facts; every later worker inherits them at fork time and -``get_merged_applications`` / ``get_merged_users`` serve them instead of -rendering. The users carrier is keyed like the applications carrier plus +renders in the worker of one constructor task and registers both payloads +as non-persistent host variables, the layer ``set_fact`` writes; every later +worker inherits them at fork time and ``get_merged_applications`` / +``get_merged_users`` serve them instead of rendering. They stay out of the +fact cache on purpose: ``get_vars`` deep-copies every fact before every task, +and these are the whole rendered trees. The users carrier is keyed like the applications carrier plus the token store digest and ``inventory_hostname``:: - name: 🧊 Render the applications SPOT once and carry it into every task's worker @@ -33,12 +35,12 @@ where the key still matches they serve the carried payload without rendering, and a users carrier that still matches is left in place instead of being returned again. A store write therefore re-renders the users alone. -The result is masked by the action itself: the facts are the whole rendered +The result is masked by the action itself: the carriers are the whole rendered trees, about 0.4 MB with every application's and user's credentials, and printing them at ``-v`` is neither credential debugging nor readable. Args: - clear: drop every carrier fact instead of rendering. Defaults to false. + clear: drop every carrier instead of rendering. Defaults to false. provider_view: on a host that does not run the onion-serving mail provider, also park the applications payload of the provider host's view in ``_INFINITO_PROVIDER_VIEW_RENDERED`` (see @@ -53,7 +55,7 @@ from typing import Any from ansible.errors import AnsibleActionFail from ansible.module_utils.parsing.convert_bool import boolean -from ansible.plugins.action import ActionBase +from ansible.plugins.action import ActionBase, VariableLayer from ansible.plugins.loader import lookup_loader from plugins.lookup.email import provider_view_carrier @@ -83,14 +85,14 @@ class ActionModule(ActionBase): ) if boolean(args.get("clear", False)): - result.update( - changed=False, - ansible_facts={ + self._park( + { APPLICATIONS_RENDERED_FACT: None, USERS_RENDERED_FACT: None, PROVIDER_VIEW_RENDERED_FACT: None, - }, + } ) + result.update(changed=False) return result revalidate_tokens_file(task_vars) @@ -120,9 +122,10 @@ class ActionModule(ActionBase): if view_carrier is not None: carriers[PROVIDER_VIEW_RENDERED_FACT] = view_carrier - result.update( - changed=False, - ansible_facts=carriers, - _ansible_no_log=True, - ) + self._park(carriers) + result.update(changed=False, _ansible_no_log=True) return result + + def _park(self, carriers: dict[str, Any]) -> None: + self.register_host_variables({}, VariableLayer.CACHEABLE_FACT) + self.register_host_variables(carriers, VariableLayer.EPHEMERAL_FACT) diff --git a/tests/integration/ansible/action_plugins/test_applications_carrier.py b/tests/integration/ansible/action_plugins/test_applications_carrier.py new file mode 100644 index 0000000000..cc1fe173aa --- /dev/null +++ b/tests/integration/ansible/action_plugins/test_applications_carrier.py @@ -0,0 +1,238 @@ +"""The applications carrier must reach every later worker without the fact cache. + +``get_vars`` deep-copies every fact before every task, twice while facts are +injected as top-level variables, so a carrier parked as a fact makes every +task pay for the whole rendered applications tree. With fact injection off, +a carrier parked as a fact also disappears from the top-level variables the +readers consult, and every lookup renders the payload again. + +These cases run real Ansible with fake ``applications`` and ``users`` lookups +in front of the real ``applications_carrier`` action: the carrier must be +visible to a later task's worker with injection on and off and never sit in +``ansible_facts``. The hazard case parks a carrier the old way, as a fact, so +the reader guard is shown to turn the invisible carrier into a failed task. +""" + +import json +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.carrier import ( + APPLICATIONS_RENDERED_FACT, + USERS_RENDERED_FACT, +) +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +APPLICATIONS_KEY = ["roles", ["signature"]] +USERS_KEY = ["roles", ["signature", "localhost"]] + +FAKE_APPLICATIONS = f""" +from ansible.plugins.lookup import LookupBase + + +class LookupModule(LookupBase): + def run(self, terms, variables=None, **kwargs): + return [{{"key": {APPLICATIONS_KEY!r}, "applications": {{"web-app-x": {{}}}}}}] +""" + +FAKE_USERS = f""" +from ansible.plugins.lookup import LookupBase + + +class LookupModule(LookupBase): + def run(self, terms, variables=None, **kwargs): + return [{{"key": {USERS_KEY!r}, "users": {{"alice": {{}}}}}}] +""" + +PROBE = f""" +from ansible.plugins.lookup import LookupBase + +from utils.cache.carrier import _carried_applications, _carried_users + + +class LookupModule(LookupBase): + def run(self, terms, variables=None, **kwargs): + variables = variables or {{}} + facts = variables.get("ansible_facts") or {{}} + return [{{ + "applications": _carried_applications( + variables, ({APPLICATIONS_KEY[0]!r}, tuple({APPLICATIONS_KEY[1]!r})) + ) is not None, + "users": _carried_users( + variables, ({USERS_KEY[0]!r}, tuple({USERS_KEY[1]!r})) + ) is not None, + "fact_cache": sorted( + name for name in ({APPLICATIONS_RENDERED_FACT!r}, {USERS_RENDERED_FACT!r}) + if name in facts + ), + }}] +""" + +FACT_CARRIER = f""" +from ansible.plugins.action import ActionBase + + +class ActionModule(ActionBase): + def run(self, tmp=None, task_vars=None): + result = super().run(tmp, task_vars) + result.update( + changed=False, + ansible_facts={{ + {APPLICATIONS_RENDERED_FACT!r}: {{ + "key": {APPLICATIONS_KEY!r}, + "applications": {{"web-app-x": {{}}}}, + }} + }}, + ) + return result +""" + +CARRIER_PLAY = """--- +- name: Park the carrier and read it from later workers + hosts: localhost + gather_facts: false + tasks: + - name: Park the carrier + applications_carrier: {} + + - name: Read the parked carrier in a later worker + ansible.builtin.set_fact: + probe_parked: "{{ lookup('carrier_probe') }}" + + - name: Drop the carrier + applications_carrier: + clear: true + + - name: Read after the drop + ansible.builtin.set_fact: + probe_cleared: "{{ lookup('carrier_probe') }}" + + - name: Report both reads + ansible.builtin.copy: + dest: "{{ probe_out }}" + content: "{{ {'parked': probe_parked, 'cleared': probe_cleared} | to_json }}" + mode: "0644" +""" + +HAZARD_PLAY = """--- +- name: Park the carrier as a fact and read it + hosts: localhost + gather_facts: false + tasks: + - name: Park the carrier in the fact cache + fact_carrier: {} + + - name: Read the fact-parked carrier + ansible.builtin.copy: + dest: "{{ probe_out }}" + content: "{{ lookup('carrier_probe') | to_json }}" + mode: "0644" +""" + + +def _run(workdir: Path, play: str, inject: bool) -> tuple[int, str, dict | None]: + """Run *play* once with fact injection set to *inject*. + + Args: + workdir: an empty directory to build the plugins and the play in. + play: the playbook text. + inject: the value of ``ANSIBLE_INJECT_FACT_VARS``. + + Returns: + ``(exit code, combined output, probe report or None)``. + """ + lookups = workdir / "lookup" + actions = workdir / "action" + for directory, name, body in ( + (lookups, "applications.py", FAKE_APPLICATIONS), + (lookups, "users.py", FAKE_USERS), + (lookups, "carrier_probe.py", PROBE), + (actions, "fact_carrier.py", FACT_CARRIER), + ): + directory.mkdir(parents=True, exist_ok=True) + (directory / name).write_text(body, encoding="utf-8") + (workdir / "play.yml").write_text(play, encoding="utf-8") + probe_out = workdir / "probe.json" + + env = os.environ.copy() + env.update( + ANSIBLE_CONFIG=str(PROJECT_ROOT / "ansible.cfg"), + ANSIBLE_LOCAL_TEMP=str(workdir / "ansible-local"), + ANSIBLE_LOOKUP_PLUGINS=str(lookups), + ANSIBLE_ACTION_PLUGINS=f"{actions}:{PROJECT_ROOT / 'plugins/action'}", + ANSIBLE_INJECT_FACT_VARS=str(inject), + PYTHONPATH=os.pathsep.join( + part for part in (str(PROJECT_ROOT), env.get("PYTHONPATH")) if part + ), + ) + result = subprocess.run( + [ + "ansible-playbook", + "-i", + "localhost,", + "-c", + "local", + str(workdir / "play.yml"), + "-e", + f"probe_out={probe_out}", + ], + cwd=str(PROJECT_ROOT), + env=env, + capture_output=True, + text=True, + check=False, + ) + report = json.loads(read_text(str(probe_out))) if probe_out.exists() else None + return result.returncode, result.stdout + result.stderr, report + + +@unittest.skipUnless(shutil.which("ansible-playbook"), "ansible-playbook not found") +class TestApplicationsCarrierReachesLaterWorkers(unittest.TestCase): + def _play(self, play: str, inject: bool) -> tuple[int, str, dict | None]: + with tempfile.TemporaryDirectory() as tmp: + return _run(Path(tmp), play, inject) + + def test_the_carrier_reaches_later_workers_outside_the_fact_cache(self): + for inject in (True, False): + with self.subTest(inject=inject): + code, output, report = self._play(CARRIER_PLAY, inject) + self.assertEqual(code, 0, output) + self.assertNotIn("template error", output) + self.assertEqual( + report["parked"], + {"applications": True, "users": True, "fact_cache": []}, + ) + self.assertEqual( + report["cleared"], + {"applications": False, "users": False, "fact_cache": []}, + ) + + def test_a_fact_parked_carrier_is_visible_only_while_facts_are_injected(self): + code, output, report = self._play(HAZARD_PLAY, True) + self.assertEqual(code, 0, output) + self.assertEqual( + report, + { + "applications": True, + "users": False, + "fact_cache": [APPLICATIONS_RENDERED_FACT], + }, + "the hazard must be reproducible with injection on, or the case " + "below proves nothing", + ) + + def test_the_reader_fails_on_a_fact_parked_carrier_without_injection(self): + code, output, report = self._play(HAZARD_PLAY, False) + self.assertNotEqual(code, 0, output) + self.assertIsNone(report) + self.assertIn("not visible as a variable", output) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/action/test_applications_carrier.py b/tests/unit/python/plugins/action/test_applications_carrier.py index ad0c1c387d..ea555f9af3 100644 --- a/tests/unit/python/plugins/action/test_applications_carrier.py +++ b/tests/unit/python/plugins/action/test_applications_carrier.py @@ -2,6 +2,7 @@ import unittest from unittest.mock import patch from ansible.errors import AnsibleActionFail +from ansible.plugins.action import VariableLayer from plugins.action.applications_carrier import ActionModule from utils.cache.carrier import ( @@ -50,9 +51,17 @@ def _make_action(task: _FakeTask, templar=None) -> ActionModule: action._task = task action._loader = None action._templar = _FakeTemplar() if templar is None else templar + action.registered = {} + action.register_host_variables = lambda variables, layer: ( + action.registered.__setitem__(layer, variables) + ) return action +def _parked(action: ActionModule) -> dict: + return action.registered[VariableLayer.EPHEMERAL_FACT] + + def _lookups(templar=None): applications = _FakeLookup( {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}}, templar @@ -64,7 +73,7 @@ def _lookups(templar=None): class TestApplicationsCarrierActionPlugin(unittest.TestCase): - def test_parks_both_carriers_as_masked_facts(self): + def test_parks_both_carriers_outside_the_fact_cache(self): applications, users, loader = _lookups() action = _make_action(_FakeTask()) with ( @@ -80,10 +89,10 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ): result = action.run(task_vars={"applications": {}}) - self.assertIs( - result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier - ) - self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier) + self.assertIs(_parked(action)[APPLICATIONS_RENDERED_FACT], applications.carrier) + self.assertIs(_parked(action)[USERS_RENDERED_FACT], users.carrier) + self.assertEqual(action.registered[VariableLayer.CACHEABLE_FACT], {}) + self.assertNotIn("ansible_facts", result) self.assertTrue(result["_ansible_no_log"]) self.assertFalse(result["changed"]) for lookup in (applications, users): @@ -107,22 +116,21 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ), patch("plugins.action.applications_carrier.revalidate_tokens_file"), ): - return action.run(task_vars=task_vars), applications, users + action.run(task_vars=task_vars) + return _parked(action), applications, users def test_a_users_carrier_that_still_matches_stays_in_place(self): parked = {"key": ["roles", ["a", "b", "c", "d", "h"]], "users": {"u": {}}} - result, applications, _ = self._park({USERS_RENDERED_FACT: parked}) + carriers, applications, _ = self._park({USERS_RENDERED_FACT: parked}) - self.assertNotIn(USERS_RENDERED_FACT, result["ansible_facts"]) - self.assertIs( - result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier - ) + self.assertNotIn(USERS_RENDERED_FACT, carriers) + self.assertIs(carriers[APPLICATIONS_RENDERED_FACT], applications.carrier) def test_a_stale_users_carrier_is_replaced(self): parked = {"key": ["roles", ["a", "b", "c", "d", "h2"]], "users": {"u": {}}} - result, _, users = self._park({USERS_RENDERED_FACT: parked}) + carriers, _, users = self._park({USERS_RENDERED_FACT: parked}) - self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier) + self.assertIs(carriers[USERS_RENDERED_FACT], users.carrier) def test_renders_the_applications_before_the_users(self): _, _, loader = _lookups() @@ -227,7 +235,7 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ): action.run(task_vars={}) - def test_clear_drops_both_facts_without_rendering(self): + def test_clear_drops_every_carrier_without_rendering(self): applications, users, loader = _lookups() action = _make_action(_FakeTask(args={"clear": True})) with ( @@ -244,13 +252,15 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): result = action.run(task_vars={"applications": {}}) self.assertEqual( - result["ansible_facts"], + _parked(action), { APPLICATIONS_RENDERED_FACT: None, USERS_RENDERED_FACT: None, PROVIDER_VIEW_RENDERED_FACT: None, }, ) + self.assertEqual(action.registered[VariableLayer.CACHEABLE_FACT], {}) + self.assertNotIn("ansible_facts", result) self.assertFalse(result["changed"]) self.assertEqual(applications.calls, []) self.assertEqual(users.calls, []) @@ -269,12 +279,10 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): side_effect=loader.get, ), ): - result = action.run(task_vars={"applications": {}}) + action.run(task_vars={"applications": {}}) - self.assertIs( - result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier - ) - self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier) + self.assertIs(_parked(action)[APPLICATIONS_RENDERED_FACT], applications.carrier) + self.assertIs(_parked(action)[USERS_RENDERED_FACT], users.carrier) self.assertEqual(len(applications.calls), 1) self.assertEqual(len(users.calls), 1) @@ -297,32 +305,32 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): return_value=view_carrier, ) as probe, ): - result = action.run(task_vars=task_vars) - return result, probe, action, task_vars + action.run(task_vars=task_vars) + return _parked(action), probe, action, task_vars def test_provider_view_parks_the_provider_view_carrier(self): view_carrier = {"key": ["roles", []], "applications": {}, "view": ["mgr", ""]} - result, probe, action, task_vars = self._run_with_view_carrier( + carriers, probe, action, task_vars = self._run_with_view_carrier( {"provider_view": True}, view_carrier ) probe.assert_called_once_with(task_vars, templar=action._templar) - self.assertIs( - result["ansible_facts"][PROVIDER_VIEW_RENDERED_FACT], view_carrier - ) + self.assertIs(carriers[PROVIDER_VIEW_RENDERED_FACT], view_carrier) def test_a_provider_view_carrier_that_still_matches_stays_in_place(self): - result, probe, _, _ = self._run_with_view_carrier({"provider_view": True}, None) + carriers, probe, _, _ = self._run_with_view_carrier( + {"provider_view": True}, None + ) probe.assert_called_once() - self.assertNotIn(PROVIDER_VIEW_RENDERED_FACT, result["ansible_facts"]) + self.assertNotIn(PROVIDER_VIEW_RENDERED_FACT, carriers) def test_without_provider_view_the_view_is_not_rendered(self): - result, probe, _, _ = self._run_with_view_carrier({}, {"key": []}) + carriers, probe, _, _ = self._run_with_view_carrier({}, {"key": []}) probe.assert_not_called() - self.assertNotIn(PROVIDER_VIEW_RENDERED_FACT, result["ansible_facts"]) + self.assertNotIn(PROVIDER_VIEW_RENDERED_FACT, carriers) if __name__ == "__main__": diff --git a/tests/unit/python/utils/cache/test_applications.py b/tests/unit/python/utils/cache/test_applications.py index 9b4f5c6c0a..6b52f57555 100644 --- a/tests/unit/python/utils/cache/test_applications.py +++ b/tests/unit/python/utils/cache/test_applications.py @@ -21,6 +21,7 @@ from pathlib import Path from utils.cache import applications as cache_apps from utils.cache.carrier import ( APPLICATIONS_RENDERED_FACT, + CarrierInvisibleError, merged_applications_cache_key, ) from utils.cache.reset import _reset_cache_for_tests @@ -490,6 +491,36 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): merged["web-app-foo"]["services"]["foo"]["image"], "override" ) + def test_a_carrier_parked_only_in_the_fact_cache_fails_loudly(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_roles(Path(tmp)) + variables = self._variables() + key = merged_applications_cache_key(variables, roles_dir=roles) + variables["ansible_facts"] = { + APPLICATIONS_RENDERED_FACT: { + "key": [key[0], list(key[1])], + "applications": {"web-app-foo": {"carried": True}}, + } + } + with self.assertRaises(CarrierInvisibleError): + cache_apps.get_merged_applications( + variables=variables, roles_dir=roles, templar=None + ) + + def test_a_carrier_visible_as_a_variable_ignores_the_fact_cache(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_roles(Path(tmp)) + variables = self._variables() + key = merged_applications_cache_key(variables, roles_dir=roles) + carried = {"web-app-foo": {"carried": True}} + carrier = {"key": [key[0], list(key[1])], "applications": carried} + variables[APPLICATIONS_RENDERED_FACT] = carrier + variables["ansible_facts"] = {APPLICATIONS_RENDERED_FACT: carrier} + merged = cache_apps.get_merged_applications( + variables=variables, roles_dir=roles, templar=None + ) + self.assertIs(merged, carried) + class TestNestedLookupsReuseTheUnrenderedView(unittest.TestCase): def setUp(self) -> None: diff --git a/tests/unit/python/utils/cache/users/test_module.py b/tests/unit/python/utils/cache/users/test_module.py index 3beb23e96e..32cc63a073 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -21,7 +21,11 @@ from pathlib import Path 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.carrier import ( + USERS_RENDERED_FACT, + CarrierInvisibleError, + merged_users_cache_key, +) 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 @@ -739,6 +743,17 @@ class TestGetMergedUsersCarrierFact(unittest.TestCase): merged["rendered"]["foo"]["email"], "foo@example.org" ) + def test_a_carrier_parked_only_in_the_fact_cache_fails_loudly(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_user_role(Path(tmp)) + variables = self._variables() + self._park(roles, variables, {"foo": {"carried": True}}) + variables["ansible_facts"] = { + USERS_RENDERED_FACT: variables.pop(USERS_RENDERED_FACT) + } + with self.assertRaises(CarrierInvisibleError): + self._merged(roles, variables) + class TestStoreSignature(unittest.TestCase): def setUp(self) -> None: diff --git a/utils/cache/README.md b/utils/cache/README.md index 8761b449ee..eda1e48f4d 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -10,7 +10,7 @@ This package contains the in-process cache layers Infinito.Nexus uses to keep CL | [files.py](files.py) | The project tree's full path list (one walk per process) and per-file UTF-8 contents (`read_text`). Used by lint/integration tests and CLI tools that scan the repo. | | [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. | +| [carrier.py](carrier.py) | The play-scoped carriers of the rendered applications and users payloads: the non-persistent variable 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. | | [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. | @@ -28,7 +28,7 @@ The layers are orthogonal: `yaml.py` caches "this file's parsed root", the `appl Both layers are process-wide in-process caches. They intentionally do NOT track on-disk file mtimes; CLI tools are short-lived and the assumption "the on-disk file does not change while my process runs" holds. The single exception is `utils.cache.yaml.dump_yaml`, which writes through and evicts the cached entry for the path it just wrote so a tool that edits a file mid-run sees the new content on the next read. -Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` and `_MERGED_USERS_CACHE` start empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked by the constructor stage and again after every role, every nested application load and every persisted token) and serves it when the key matches. The same action parks `_INFINITO_USERS_RENDERED`, which `get_merged_users` serves to templated reads under the applications key plus the token store digest and `inventory_hostname`. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) and [users.md](../../docs/contributing/artefact/files/plugins/lookup/users.md) for the contract. +Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` and `_MERGED_USERS_CACHE` start empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier variable `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, registered in the `set_fact` layer and never in the fact cache, which `get_vars` deep-copies before every task; parked by the constructor stage and again after every role, every nested application load and every persisted token) and serves it when the key matches. The same action parks `_INFINITO_USERS_RENDERED`, which `get_merged_users` serves to templated reads under the applications key plus the token store digest and `inventory_hostname`. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) and [users.md](../../docs/contributing/artefact/files/plugins/lookup/users.md) for the contract. While one render runs, the re-entry guard also holds that render's unrendered view and its cache key. A nested `get_merged_applications` call from a lookup inside a role template (`config`, `tls`, `domain`, ...) with the same key returns that view instead of copying and merging the role defaults again. The view is shared by every nested call of the render, so callers MUST NOT mutate it. The guard drops it when the render ends. @@ -66,7 +66,7 @@ from utils.cache.reset import _reset_cache_for_tests flowchart TD decl["meta/services.yml
a flag reading group_names
114 role files"] ctor["01_constructor.yml:191
applications_carrier"] - fact["_INFINITO_APPLICATIONS_RENDERED
per-host fact"] + fact["_INFINITO_APPLICATIONS_RENDERED
per-host set_fact variable"] lookup["lookup('database', ...)
and every applications consumer"] key["base.py:103
_stable_variables_signature"] proc["_MERGED_APPLICATIONS_CACHE
process-global dict"] @@ -84,7 +84,7 @@ flowchart TD render --> consumer consumer -->|"selects"| name - proc -.->|"TRIP-WIRE: read BEFORE the
host's own fact, so an inherited
entry outranks it"| fact + proc -.->|"TRIP-WIRE: read BEFORE the
host's own carrier, so an inherited
entry outranks it"| fact render -.->|"TRIP-WIRE: main process renders
task names for one host; forked
workers inherit that entry"| proc key -.->|"TRIP-WIRE: carrier.py:121 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact ``` diff --git a/utils/cache/carrier.py b/utils/cache/carrier.py index bfd97dfd70..7090bb85b4 100644 --- a/utils/cache/carrier.py +++ b/utils/cache/carrier.py @@ -3,8 +3,9 @@ Ansible forks a fresh worker process per task, so the in-process `_MERGED_APPLICATIONS_CACHE` and `_MERGED_USERS_CACHE` start empty in every worker. The constructor stage renders once and parks each payload plus its -cache key in the host facts named by `APPLICATIONS_RENDERED_FACT` and -`USERS_RENDERED_FACT`; every later worker inherits those facts at fork time +cache key in the non-persistent host variables named by +`APPLICATIONS_RENDERED_FACT` and `USERS_RENDERED_FACT` (the `set_fact` layer, +outside the fact cache); every later worker inherits those variables at fork time and `get_merged_applications` / `get_merged_users` serve them instead of rendering. Ansible-free at import time like the rest of the package. """ @@ -30,6 +31,10 @@ USERS_RENDERED_FACT = "_INFINITO_USERS_RENDERED" PROVIDER_VIEW_RENDERED_FACT = "_INFINITO_PROVIDER_VIEW_RENDERED" +class CarrierInvisibleError(RuntimeError): + """A carrier parked where the variable readers cannot see it.""" + + def merged_applications_cache_key( variables: Mapping[str, Any] | None, *, @@ -99,12 +104,22 @@ def _carried( else ``None``. Args: - variables: The play's variable scope, read for the carrier fact. - fact: The carrier fact's name. + variables: The play's variable scope, read for the carrier variable. + fact: The carrier variable's name. field: The carrier's payload field. cache_key: The key the caller would render under. + + Raises: + CarrierInvisibleError: when *fact* sits in ``ansible_facts`` but not + among the variables, so every reader would miss it and render. """ carrier = variables.get(fact) + if fact not in variables and fact in (variables.get("ansible_facts") or {}): + raise CarrierInvisibleError( + f"{fact} is parked in the fact cache but not visible as a variable; " + "park it with applications_carrier, which registers it outside the " + "fact cache, or every lookup renders the payload again" + ) if not isinstance(carrier, Mapping): return None key = carrier.get("key") From 7c22e0ac6e86b15b7fd2a0b63b2df615c196303d Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Wed, 18 Nov 2026 21:29:30 +0400 Subject: [PATCH 03/65] perf(ansible): stop injecting facts as top-level variables Co-Authored-By: Claude Opus 5.5 --- ansible.cfg | 1 + roles/svc-net-tor/tasks/00_core.yml | 2 +- .../test_no_deprecated_ansible_patterns.py | 221 ++++++++++++------ 3 files changed, 155 insertions(+), 69 deletions(-) diff --git a/ansible.cfg b/ansible.cfg index e11d4fa469..f0b0645392 100644 --- a/ansible.cfg +++ b/ansible.cfg @@ -4,6 +4,7 @@ pipelining = True forks = 25 strategy = linear gathering = smart +inject_facts_as_vars = False timeout = 120 retry_files_enabled = False host_key_checking = True diff --git a/roles/svc-net-tor/tasks/00_core.yml b/roles/svc-net-tor/tasks/00_core.yml index aaa1701da2..33ebcb1ab5 100644 --- a/roles/svc-net-tor/tasks/00_core.yml +++ b/roles/svc-net-tor/tasks/00_core.yml @@ -53,7 +53,7 @@ - "!all" - network filter: - - ansible_docker0 + - ansible_docker0 # nocheck: deprecated-ansible (setup filter, not a fact read) - name: "📝 Render torrc" ansible.builtin.template: # nocheck: stack-host-template (per-host torrc under DIR_VAR_LIB; tor is a node-local host-network sidecar) diff --git a/tests/lint/ansible/test_no_deprecated_ansible_patterns.py b/tests/lint/ansible/test_no_deprecated_ansible_patterns.py index 5d466a63a9..efaf737124 100644 --- a/tests/lint/ansible/test_no_deprecated_ansible_patterns.py +++ b/tests/lint/ansible/test_no_deprecated_ansible_patterns.py @@ -1,8 +1,9 @@ -"""Lint: forbid Ansible constructs that emit [DEPRECATION WARNING] at deploy. +"""Lint: forbid Ansible constructs that are deprecated or break with fact injection off. -Each pattern below triggered a deprecation in CI and has a non-deprecated -replacement. Keeping them out of the tree means the compose deploy's -deprecation gate (assert_no_deprecation_warnings.sh) stays green. +Each pattern below has a non-deprecated replacement. Keeping them out of the +tree means the compose deploy's deprecation gate +(assert_no_deprecation_warnings.sh) stays green and ``inject_facts_as_vars = +False`` in ``ansible.cfg`` stays safe. Forbidden (with fix): @@ -14,16 +15,19 @@ Forbidden (with fix): runs is MariaDB, which ``ansible.mysql`` warns about and drops in 6.0.0. Use ``ansible.mariadb.mariadb_`` and keep ``ansible.mariadb`` in both requirements files. -* top-level injected gathered facts (``ansible_os_family`` and friends) -- - ``INJECT_FACTS_AS_VARS`` default is deprecated. Use ``ansible_facts['']``. - Only gathered facts are denied; magic/connection vars (ansible_version, host, - user, connection, python_interpreter, become_*, failed_result, ...) are not - facts and stay allowed. The ``(?!=)`` guard skips a literal log label such as - ``ansible_virtualization_type={{ ... }}`` (name glued to ``=``) while still - flagging a comparison like ``ansible_os_family == 'X'`` (space before ``==``). +* top-level injected facts (``ansible_os_family``, ``ansible_eth0`` and every + other ``ansible_``) -- ``ansible.cfg`` turns fact injection off, so a + top-level fact is undefined. Use ``ansible_facts['']``. Every + ``ansible_`` that is not a magic or connection variable + (``ALLOWED_NAMES``, ``ALLOWED_PREFIXES``) counts as a fact. The ``(?!=)`` + guard skips a literal log label such as ``ansible_virtualization_type={{ ... + }}`` (name glued to ``=``) while still flagging a comparison like + ``ansible_os_family == 'X'`` (space before ``==``). In Python the rule reads + only subscript and ``.get`` keys, the shape of a variable read. -Scans ``.yml`` / ``.yaml`` / ``.j2`` under roles/, tasks/, group_vars/. Mark a -genuine exception with ``# nocheck: deprecated-ansible`` same-or-above the line. +Scans ``.yml`` / ``.yaml`` / ``.j2`` under roles/, tasks/, group_vars/, +playbooks/ and the playbook, and ``.py`` outside tests/ and role ``files/``. Mark a genuine +exception with ``# nocheck: deprecated-ansible`` same-or-above the line. """ from __future__ import annotations @@ -38,47 +42,67 @@ from utils.cache.files import iter_project_files, read_text from . import PROJECT_ROOT _RULE = "deprecated-ansible" -SCAN_SUFFIXES = (".yml", ".yaml", ".j2") -_SCAN_PREFIXES = ("roles/", "tasks/", "group_vars/") +SCAN_SUFFIXES = (".yml", ".yaml", ".j2", ".py") +_YAML_PREFIXES = ("roles/", "tasks/", "group_vars/", "playbooks/", "playbook.yml") +_PY_EXCLUDED_PREFIXES = ("tests/",) +_PY_EXCLUDED_PARTS = ("/files/",) -_FACT_NAMES = ( - "os_family", - "distribution", - "distribution_release", - "distribution_version", - "distribution_major_version", - "distribution_file_variety", - "architecture", - "machine", - "system", - "kernel", - "kernel_version", - "default_ipv4", - "default_ipv6", - "all_ipv4_addresses", - "all_ipv6_addresses", - "virtualization_type", - "virtualization_role", - "processor", - "processor_cores", - "processor_count", - "processor_vcpus", - "memtotal_mb", - "memfree_mb", - "mounts", - "devices", - "interfaces", - "hostname", - "nodename", - "fqdn", - "domain", - "pkg_mgr", - "service_mgr", - "selinux", - "date_time", - "lsb", - "dns", +ALLOWED_NAMES = frozenset( + { + "ansible_facts", + "ansible_local", + "ansible_check_mode", + "ansible_config_file", + "ansible_collection_name", + "ansible_dependent_role_names", + "ansible_diff_mode", + "ansible_forks", + "ansible_index_var", + "ansible_inventory_sources", + "ansible_limit", + "ansible_loop", + "ansible_loop_var", + "ansible_parent_role_names", + "ansible_parent_role_paths", + "ansible_play_batch", + "ansible_play_hosts", + "ansible_play_hosts_all", + "ansible_play_name", + "ansible_play_role_names", + "ansible_playbook_python", + "ansible_role_name", + "ansible_role_names", + "ansible_run_tags", + "ansible_search_path", + "ansible_skip_tags", + "ansible_verbosity", + "ansible_version", + "ansible_failed_task", + "ansible_failed_result", + "ansible_job_id", + "ansible_host", + "ansible_port", + "ansible_user", + "ansible_password", + "ansible_connection", + "ansible_private_key_file", + "ansible_pipelining", + "ansible_timeout", + "ansible_remote_tmp", + "ansible_docker_extra_args", + } ) +ALLOWED_PREFIXES = ( + "ansible_become", + "ansible_ssh_", + "ansible_shell_", + "ansible_winrm_", + "ansible_paramiko_", +) +ALLOWED_SUFFIXES = ("_interpreter",) + +_YAML_NAME = re.compile(r"\bansible_[A-Za-z0-9_]+\b(?!=)") +_PY_NAME = re.compile(r"(?:\[\s*|\.get\(\s*)[\"'](ansible_[A-Za-z0-9_]+)[\"']") _PATTERNS: tuple[tuple[str, re.Pattern[str], str], ...] = ( ( @@ -91,38 +115,73 @@ _PATTERNS: tuple[tuple[str, re.Pattern[str], str], ...] = ( re.compile(r"\b(?:community|ansible)\.mysql\."), "MariaDB leaves the mysql collection in 6.0.0 -> use ansible.mariadb.mariadb_ (ansible.mariadb in both requirements files)", ), - ( - "injected-fact", - re.compile(rf"\bansible_(?:{'|'.join(_FACT_NAMES)})\b(?!=)"), - "top-level injected fact -> use ansible_facts['']", - ), ) +_FACT_FIX = "top-level injected fact, undefined with fact injection off -> use ansible_facts['']" -def _scan_file(path: Path) -> list[str]: - try: - text = read_text(str(path)) - except (OSError, UnicodeDecodeError): - return [] +def is_fact_name(name: str) -> bool: + """Tell whether *name* is a fact rather than a magic or connection variable. + + Args: + name: an ``ansible_`` identifier. + + Returns: + ``True`` when the name is neither allowed explicitly nor by prefix or suffix. + """ + return not ( + name in ALLOWED_NAMES + or name.startswith(ALLOWED_PREFIXES) + or name.endswith(ALLOWED_SUFFIXES) + ) + + +def scan_text(text: str, python: bool) -> list[str]: + """Return one issue line per forbidden construct in *text*. + + Args: + text: the file content. + python: read *text* as Python (subscript and ``.get`` keys only) instead + of YAML or Jinja. + """ lines = text.splitlines() out: list[str] = [] + fact_pattern = _PY_NAME if python else _YAML_NAME + patterns = () if python else _PATTERNS for idx, line in enumerate(lines, start=1): - for kind, pattern, fix in _PATTERNS: - if pattern.search(line) and not is_suppressed_at( - lines, idx, _RULE, mode="same-or-above" - ): + if is_suppressed_at(lines, idx, _RULE, mode="same-or-above"): + continue + for kind, pattern, fix in patterns: + if pattern.search(line): out.append(f"line {idx}: [{kind}] {line.strip()} -> {fix}") + for match in fact_pattern.finditer(line): + name = match.group(1) if python else match.group(0) + if is_fact_name(name): + out.append( + f"line {idx}: [injected-fact] {line.strip()} -> {_FACT_FIX}" + ) return out +def _in_scope(rel: str) -> bool: + if rel.endswith(".py"): + return not rel.startswith(_PY_EXCLUDED_PREFIXES) and not any( + part in f"/{rel}" for part in _PY_EXCLUDED_PARTS + ) + return rel.startswith(_YAML_PREFIXES) + + class TestNoDeprecatedAnsiblePatterns(unittest.TestCase): def test_no_deprecated_patterns(self) -> None: offenders: dict[Path, list[str]] = {} for abs_path in iter_project_files(extensions=SCAN_SUFFIXES): rel = Path(abs_path).relative_to(PROJECT_ROOT).as_posix() - if not rel.startswith(_SCAN_PREFIXES): + if not _in_scope(rel): continue - issues = _scan_file(Path(abs_path)) + try: + text = read_text(str(abs_path)) + except (OSError, UnicodeDecodeError): + continue + issues = scan_text(text, python=rel.endswith(".py")) if issues: offenders[Path(abs_path)] = issues @@ -135,6 +194,32 @@ class TestNoDeprecatedAnsiblePatterns(unittest.TestCase): lines.extend(f" * {i}" for i in issues) self.fail("\n".join(lines)) + def test_a_planted_top_level_fact_read_is_caught(self) -> None: + planted = { + "when: ansible_os_family == 'Debian'": False, + "{{ ansible_eth0.ipv4.address }}": False, + "{{ hostvars[h]['ansible_default_ipv4'] }}": False, + 'distro = task_vars.get("ansible_distribution")': True, + 'facts = task_vars["ansible_mounts"]': True, + } + for line, python in planted.items(): + with self.subTest(line=line): + self.assertTrue(scan_text(line, python=python), line) + + def test_magic_connection_and_namespaced_reads_pass(self) -> None: + clean = { + "when: ansible_facts['os_family'] == 'Debian'": False, + "{{ ansible_host }} {{ ansible_become_password }}": False, + "{{ ansible_python_interpreter }} {{ ansible_loop_var }}": False, + "msg: ansible_virtualization_type={{ x }}": False, + 'facts = task_vars.get("ansible_facts") or {}': True, + 'host = hostvars[h].get("ansible_host")': True, + "ansible_playbook = shutil.which('ansible-playbook')": True, + } + for line, python in clean.items(): + with self.subTest(line=line): + self.assertEqual(scan_text(line, python=python), [], line) + if __name__ == "__main__": unittest.main() From 312435975e89e3a9d98c25b42014d00d662eb01e Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Wed, 18 Nov 2026 21:29:51 +0400 Subject: [PATCH 04/65] perf(sys-svc-container): query docker.service instead of gathering every unit Co-Authored-By: Claude Opus 5.5 --- .../sys-svc-container/tasks/01_assert_requirements.yml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/roles/sys-svc-container/tasks/01_assert_requirements.yml b/roles/sys-svc-container/tasks/01_assert_requirements.yml index b8661ddbcf..dc5c78b9e1 100644 --- a/roles/sys-svc-container/tasks/01_assert_requirements.yml +++ b/roles/sys-svc-container/tasks/01_assert_requirements.yml @@ -1,6 +1,9 @@ --- -- name: 📊 Gather service facts - ansible.builtin.service_facts: +- name: 📊 Query the docker unit + ansible.builtin.systemd_service: + name: docker.service + register: sys_svc_container_docker_unit + failed_when: false - name: 🔎 Check docker socket ansible.builtin.stat: @@ -10,7 +13,8 @@ - name: ✅ Assert docker service exists ansible.builtin.assert: that: - - "'docker.service' in ansible_facts.services" + - sys_svc_container_docker_unit.status is defined + - sys_svc_container_docker_unit.status.LoadState != 'not-found' fail_msg: > docker.service is not registered in systemd. Docker engine does not appear to be installed. From f6a40c4618e93321402df295be4005eae0444d89 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Wed, 18 Nov 2026 21:30:30 +0400 Subject: [PATCH 05/65] perf(swarm-lab): ask the Docker CLI for its version once per run Co-Authored-By: Claude Opus 5.5 --- ansible.cfg | 1 + plugins/README.md | 8 +- plugins/connection/docker_cached.py | 135 +++++++++++ tests/integration/ansible/README.md | 2 +- .../ansible/connection_plugins/README.md | 7 + .../ansible/connection_plugins/__init__.py | 5 + .../connection_plugins/test_docker_cached.py | 219 ++++++++++++++++++ utils/tests/swarm/extend_inventory.py | 2 +- 8 files changed, 374 insertions(+), 5 deletions(-) create mode 100644 plugins/connection/docker_cached.py create mode 100644 tests/integration/ansible/connection_plugins/README.md create mode 100644 tests/integration/ansible/connection_plugins/__init__.py create mode 100644 tests/integration/ansible/connection_plugins/test_docker_cached.py mode change 100755 => 100644 utils/tests/swarm/extend_inventory.py diff --git a/ansible.cfg b/ansible.cfg index f0b0645392..ca8daa338b 100644 --- a/ansible.cfg +++ b/ansible.cfg @@ -23,6 +23,7 @@ callbacks_enabled = profile_tasks,profile_roles,timer # --- Plugin paths --- action_plugins = ./plugins/action +connection_plugins = ./plugins/connection filter_plugins = ./plugins/filter lookup_plugins = ./plugins/lookup library = ./library diff --git a/plugins/README.md b/plugins/README.md index 69025524bc..95d0753f24 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -12,14 +12,16 @@ This document is the central reference for plugin types and plugin placement in ```text plugins/ -├── action/ # custom action plugins -├── filter/ # custom Jinja2 filters -└── lookup/ # custom lookup plugins +├── action/ # custom action plugins +├── connection/ # custom connection plugins +├── filter/ # custom Jinja2 filters +└── lookup/ # custom lookup plugins ``` Configured plugin paths in this repository are defined in `ansible.cfg`: - `action_plugins = ./plugins/action` +- `connection_plugins = ./plugins/connection` - `filter_plugins = ./plugins/filter` - `lookup_plugins = ./plugins/lookup` diff --git a/plugins/connection/docker_cached.py b/plugins/connection/docker_cached.py new file mode 100644 index 0000000000..63676db22a --- /dev/null +++ b/plugins/connection/docker_cached.py @@ -0,0 +1,135 @@ +"""The community.docker docker connection, asking the Docker CLI for its version once per run. + +The stock plugin builds a fresh connection in every forked worker, and with a +remote user set it runs ``docker version`` twice before every module run (the +first probe never matches a current Docker). This subclass keeps the answer in +a file under the run's ``DEFAULT_LOCAL_TMP``, which every worker inherits from +the ``ansible-playbook`` process and which Ansible removes when the run ends, +so only the first task-host of a run pays for the version query. Everything +else (user, become, file transfer, timeouts, environment) is the stock plugin's. +""" + +from __future__ import annotations + +import hashlib +import os +from pathlib import Path + +from ansible import constants +from ansible_collections.community.docker.plugins.connection.docker import ( + Connection as DockerConnection, +) + +DOCUMENTATION = r""" +name: docker_cached +short_description: Run tasks in docker containers, with the Docker version cached per run +description: + - The community.docker docker connection, except that the Docker CLI version is queried once per + ansible-playbook run and shared by every forked worker. +options: + remote_addr: + description: + - The name of the container you want to access. + default: inventory_hostname + vars: + - name: inventory_hostname + - name: ansible_host + - name: ansible_docker_host + remote_user: + description: + - The user to execute as inside the container. + vars: + - name: ansible_user + - name: ansible_docker_user + ini: + - section: defaults + key: remote_user + env: + - name: ANSIBLE_REMOTE_USER + cli: + - name: user + keyword: + - name: remote_user + docker_extra_args: + description: + - Extra arguments to pass to the docker command line. + default: '' + vars: + - name: ansible_docker_extra_args + ini: + - section: docker_connection + key: extra_cli_args + container_timeout: + default: 10 + description: + - Controls how long we can wait to access reading output from the container once execution started. + env: + - name: ANSIBLE_TIMEOUT + - name: ANSIBLE_DOCKER_TIMEOUT + ini: + - key: timeout + section: defaults + - key: timeout + section: docker_connection + vars: + - name: ansible_docker_timeout + cli: + - name: timeout + type: integer + extra_env: + description: + - Extra environment variables to set when running commands in the Docker container. + vars: + - name: ansible_docker_extra_env + type: dict + working_dir: + description: + - The directory inside the container to run commands in. + env: + - name: ANSIBLE_DOCKER_WORKING_DIR + ini: + - key: working_dir + section: docker_connection + vars: + - name: ansible_docker_working_dir + type: string + privileged: + description: + - Whether commands should be run with extended privileges. + env: + - name: ANSIBLE_DOCKER_PRIVILEGED + ini: + - key: privileged + section: docker_connection + vars: + - name: ansible_docker_privileged + type: boolean + default: false +""" + + +class Connection(DockerConnection): + transport = "docker_cached" + + def _version_cache_path(self) -> Path: + scope = "\0".join( + [self.docker_cmd, *self._docker_args, os.environ.get("DOCKER_HOST") or ""] + ) + digest = hashlib.sha256(scope.encode("utf-8")).hexdigest()[:16] + return Path(constants.DEFAULT_LOCAL_TMP) / f"docker-version-{digest}" + + def _get_docker_version(self) -> str: + path = self._version_cache_path() + try: + cached = path.read_text( + encoding="utf-8" # nocheck: cache-read (per-run file the first worker writes) + ).strip() + except FileNotFoundError: + cached = "" + if cached: + return cached + version = super()._get_docker_version() + staging = path.with_name(f"{path.name}.{os.getpid()}") + staging.write_text(version, encoding="utf-8") + staging.replace(path) + return version diff --git a/tests/integration/ansible/README.md b/tests/integration/ansible/README.md index 54477c9d93..6413a98452 100644 --- a/tests/integration/ansible/README.md +++ b/tests/integration/ansible/README.md @@ -1,6 +1,6 @@ # Ansible Integration Tests 🧩 -Integration tests for Ansible-native artefacts: action plugins, filter plugins, lookup plugins, handlers, group_vars, inventory, Jinja templates, playbooks, and role-local [`vars/`](vars/) / `defaults/`. +Integration tests for Ansible-native artefacts: action plugins, connection plugins, filter plugins, lookup plugins, handlers, group_vars, inventory, Jinja templates, playbooks, and role-local [`vars/`](vars/) / `defaults/`. Each child directory pins one Ansible surface; see the per-directory README for scope. Topical concerns that are not Ansible-specific (compose/docker/networks, OAuth2/OIDC, service registry, role-meta layout) live under [`infrastructure/`](../infrastructure/), [`iam/`](../iam/), [`meta/`](../meta/), or [`roles/`](../roles/). diff --git a/tests/integration/ansible/connection_plugins/README.md b/tests/integration/ansible/connection_plugins/README.md new file mode 100644 index 0000000000..5248ec3527 --- /dev/null +++ b/tests/integration/ansible/connection_plugins/README.md @@ -0,0 +1,7 @@ +# Connection Plugin Tests 🔌 + +Integration tests that exercise custom Ansible connection plugins end-to-end through real playbook runs against a stand-in `docker` executable, so no real container is involved. + +Tests in this directory MUST only cover connection plugins shipped under `plugins/connection/`. Tests that validate action, filter or lookup plugins MUST live elsewhere under `tests/integration/`. + +For framework, directory layout, and `make test-integration` usage see [integration.md](../../../../docs/contributing/actions/testing/integration.md). diff --git a/tests/integration/ansible/connection_plugins/__init__.py b/tests/integration/ansible/connection_plugins/__init__.py new file mode 100644 index 0000000000..eec6d4835a --- /dev/null +++ b/tests/integration/ansible/connection_plugins/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/integration/ansible/connection_plugins/test_docker_cached.py b/tests/integration/ansible/connection_plugins/test_docker_cached.py new file mode 100644 index 0000000000..4a59ee58f1 --- /dev/null +++ b/tests/integration/ansible/connection_plugins/test_docker_cached.py @@ -0,0 +1,219 @@ +"""The cached docker connection must ask the Docker CLI for its version once per run. + +The stock ``community.docker.docker`` connection runs ``docker version`` twice +before every module run once a remote user is set, because every task-host +gets a fresh connection in a fresh worker. ``docker_cached`` keeps the answer +for the run. These cases run the same play through both plugins against a +stand-in ``docker`` executable that logs every call and runs the exec payload +locally: the cached plugin must make the same exec calls with the same +results, and only the first task-host may query the version. +""" + +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from typing import ClassVar + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +SHIM = f"""#!{sys.executable} +import json +import os +import subprocess +import sys + +args = sys.argv[1:] +with open(os.environ["DOCKER_SHIM_LOG"], "a", encoding="utf-8") as log: + log.write(json.dumps(args) + "\\n") +if args[:1] == ["version"]: + print("29.1.3" if "--format" in args else "Client:\\n Version: 29.1.3") + sys.exit(0) +if args[:1] != ["exec"]: + sys.exit(2) +rest = args[1:] +env = dict(os.environ) +cwd = None +while rest and rest[0].startswith("-"): + flag = rest.pop(0) + if flag in ("-u", "-e", "-w"): + value = rest.pop(0) + if flag == "-e": + key, _, val = value.partition("=") + env[key] = val + if flag == "-w": + cwd = value +rest.pop(0) +sys.exit(subprocess.run(rest, env=env, cwd=cwd, check=False).returncode) +""" + +PLAY = """--- +- name: Run module, copy and template tasks over a docker connection + hosts: node1 + gather_facts: false + tasks: + - name: Run a command + ansible.builtin.command: echo hello + register: command_result + changed_when: false + + - name: Stat the work directory + ansible.builtin.stat: + path: "{{ work_dir }}" + register: stat_result + + - name: Copy a file + ansible.builtin.copy: + content: "copied\\n" + dest: "{{ work_dir }}/copied.txt" + mode: "0644" + register: copy_result + + - name: Template a file + ansible.builtin.template: + src: "{{ template_src }}" + dest: "{{ work_dir }}/templated.txt" + mode: "0644" + register: template_result + + - name: Report the results + ansible.builtin.copy: + dest: "{{ report }}" + content: "{{ {'command': command_result.stdout, 'stat': stat_result.stat.isdir, 'copy': copy_result.changed, 'template': template_result.changed} | to_json }}" + mode: "0644" + delegate_to: localhost +""" + + +def _run(workdir: Path, connection: str) -> tuple[dict, list[list[str]], Path]: + """Run the play once through *connection*. + + Args: + workdir: an empty directory for the shim, the play and its outputs. + connection: the ``ansible_connection`` of the node. + + Returns: + ``(reported results, logged docker calls, work directory of the node)``. + + Raises: + RuntimeError: when ansible-playbook exits non-zero. + """ + shim_dir = workdir / "bin" + shim_dir.mkdir() + shim = shim_dir / "docker" + shim.write_text(SHIM, encoding="utf-8") + shim.chmod(0o755) + node_dir = workdir / "node" + node_dir.mkdir() + template = workdir / "template.j2" + template.write_text("templated {{ inventory_hostname }}\n", encoding="utf-8") + (workdir / "play.yml").write_text(PLAY, encoding="utf-8") + (workdir / "inventory.yml").write_text( + json.dumps( + { + "all": { + "hosts": { + "node1": { + "ansible_connection": connection, + "ansible_user": "root", + "ansible_python_interpreter": sys.executable, + "ansible_remote_tmp": str(workdir / "remote-tmp"), + } + } + } + } + ), + encoding="utf-8", + ) + log = workdir / "docker-calls.log" + report = workdir / "report.json" + env = os.environ.copy() + env.update( + ANSIBLE_CONFIG=str(PROJECT_ROOT / "ansible.cfg"), + ANSIBLE_LOCAL_TEMP=str(workdir / "ansible-local"), + DOCKER_SHIM_LOG=str(log), + PATH=os.pathsep.join([str(shim_dir), env["PATH"]]), + ) + result = subprocess.run( + [ + "ansible-playbook", + "-i", + str(workdir / "inventory.yml"), + str(workdir / "play.yml"), + "-e", + f"work_dir={node_dir}", + "-e", + f"template_src={template}", + "-e", + f"report={report}", + ], + cwd=str(PROJECT_ROOT), + env=env, + capture_output=True, + text=True, + check=False, + ) + if result.returncode != 0: + raise RuntimeError( + f"ansible-playbook failed\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}" + ) + calls = [json.loads(line) for line in read_text(str(log)).splitlines() if line] + return json.loads(read_text(str(report))), calls, node_dir + + +@unittest.skipUnless(shutil.which("ansible-playbook"), "ansible-playbook not found") +class TestDockerCachedConnection(unittest.TestCase): + runs: ClassVar[dict[str, tuple[dict, list[list[str]], dict[str, str]]]] = {} + + @classmethod + def setUpClass(cls) -> None: + for connection in ("community.docker.docker", "docker_cached"): + with tempfile.TemporaryDirectory() as tmp: + report, calls, node_dir = _run(Path(tmp), connection) + files = { + name: read_text(str(node_dir / name)) + for name in ("copied.txt", "templated.txt") + } + cls.runs[connection] = (report, calls, files) + + @staticmethod + def _kinds(calls: list[list[str]], kind: str) -> list[list[str]]: + return [call for call in calls if call[:1] == [kind]] + + def test_the_stock_plugin_queries_the_version_before_every_module_run(self): + _, calls, _ = self.runs["community.docker.docker"] + self.assertEqual( + len(self._kinds(calls, "version")), + 8, + "the stand-in must reproduce the two version calls per task-host, " + "or the case below proves nothing", + ) + + def test_only_the_first_task_host_queries_the_version(self): + _, calls, _ = self.runs["docker_cached"] + self.assertEqual(len(self._kinds(calls, "version")), 2) + self.assertEqual(calls[0][:1], ["version"]) + + def test_the_exec_calls_and_results_match_the_stock_plugin(self): + stock_report, stock_calls, stock_files = self.runs["community.docker.docker"] + report, calls, files = self.runs["docker_cached"] + self.assertEqual( + len(self._kinds(calls, "exec")), len(self._kinds(stock_calls, "exec")) + ) + self.assertEqual(report, stock_report) + self.assertEqual( + report, + {"command": "hello", "stat": True, "copy": True, "template": True}, + ) + self.assertEqual(files, stock_files) + self.assertEqual(files["templated.txt"], "templated node1\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/tests/swarm/extend_inventory.py b/utils/tests/swarm/extend_inventory.py old mode 100755 new mode 100644 index 0e235ad9e1..bcaadbc065 --- a/utils/tests/swarm/extend_inventory.py +++ b/utils/tests/swarm/extend_inventory.py @@ -35,7 +35,7 @@ from utils.tests.swarm.backup_repos import repo_placements from utils.tests.swarm.derive_includes import applications_for_round, derive_includes _DOCKER_VARS: dict[str, str] = { - "ansible_connection": "docker", + "ansible_connection": "docker_cached", "ansible_python_interpreter": "/usr/bin/python3", "ansible_user": "root", } From 6ab25c9c29bea22188fc08bc0a46c75247b8e56f Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Wed, 18 Nov 2026 21:30:54 +0400 Subject: [PATCH 06/65] perf(playbook): render the play environment once per host Co-Authored-By: Claude Opus 5.5 --- playbook.yml | 35 +++-- tasks/utils/play/environment/check.yml | 12 ++ tasks/utils/play/environment/freeze.yml | 5 + .../playbooks/test_play_environment_frozen.py | 124 ++++++++++++++++++ 4 files changed, 163 insertions(+), 13 deletions(-) create mode 100644 tasks/utils/play/environment/check.yml create mode 100644 tasks/utils/play/environment/freeze.yml create mode 100644 tests/integration/ansible/playbooks/test_play_environment_frozen.py diff --git a/playbook.yml b/playbook.yml index 934372d224..b445f627fd 100644 --- a/playbook.yml +++ b/playbook.yml @@ -2,21 +2,27 @@ - name: "Execute Infinito.Nexus Play" hosts: all any_errors_fatal: true - environment: - CA_TRUST_CERT_HOST: "{{ CA_TRUST.cert_host }}" - CA_TRUST_WRAPPER_HOST: "{{ CA_TRUST.wrapper_host }}" - CA_TRUST_NAME: "{{ CA_TRUST.trust_name }}" - CA_TRUST_CERT_CONTAINER: "{{ CA_TRUST.inject_cert_container }}" - CA_TRUST_WRAPPER_CONTAINER: "{{ CA_TRUST.inject_wrapper_container }}" - CA_CONTAINER_ENABLED: "{{ CA_CONTAINER_ENABLED | int }}" - COMPOSE_HTTP_TIMEOUT: "600" - DOCKER_CLIENT_TIMEOUT: "600" - DOCKER_BUILDKIT: "{{ BUILDKIT_ENABLED | int }}" - COMPOSE_DOCKER_CLI_BUILD: "{{ BUILDKIT_ENABLED | int }}" - INFINITO_RESCUE_DIAGNOSTICS_DIR: "{{ DIR_RESCUE_DIAGNOSTICS }}" - CONTAINER_EXEC_TIMEOUT: "{{ SYS_TIMEOUT_CONTAINER_EXEC }}" + vars: + PLAY_ENVIRONMENT_SOURCE: + CA_TRUST_CERT_HOST: "{{ CA_TRUST.cert_host }}" + CA_TRUST_WRAPPER_HOST: "{{ CA_TRUST.wrapper_host }}" + CA_TRUST_NAME: "{{ CA_TRUST.trust_name }}" + CA_TRUST_CERT_CONTAINER: "{{ CA_TRUST.inject_cert_container }}" + CA_TRUST_WRAPPER_CONTAINER: "{{ CA_TRUST.inject_wrapper_container }}" + CA_CONTAINER_ENABLED: "{{ CA_CONTAINER_ENABLED | int }}" + COMPOSE_HTTP_TIMEOUT: "600" + DOCKER_CLIENT_TIMEOUT: "600" + DOCKER_BUILDKIT: "{{ BUILDKIT_ENABLED | int }}" + COMPOSE_DOCKER_CLI_BUILD: "{{ BUILDKIT_ENABLED | int }}" + INFINITO_RESCUE_DIAGNOSTICS_DIR: "{{ DIR_RESCUE_DIAGNOSTICS }}" + CONTAINER_EXEC_TIMEOUT: "{{ SYS_TIMEOUT_CONTAINER_EXEC }}" + PLAY_ENVIRONMENT: "{{ PLAY_ENVIRONMENT_SOURCE }}" + environment: "{{ PLAY_ENVIRONMENT }}" gather_facts: false pre_tasks: + - name: "🧊 Render the play environment once for this host" + ansible.builtin.include_tasks: tasks/utils/play/environment/freeze.yml + - name: "🐍 Link the managed Python interpreter before any module needs it" ansible.builtin.script: scripts/system/python/managed_interpreter.sh register: managed_interpreter @@ -37,4 +43,7 @@ - name: "Load 'destructor' tasks" include_tasks: "tasks/stages/03_destructor.yml" + post_tasks: + - name: "✅ Check the play environment against its sources" + ansible.builtin.include_tasks: tasks/utils/play/environment/check.yml become: true diff --git a/tasks/utils/play/environment/check.yml b/tasks/utils/play/environment/check.yml new file mode 100644 index 0000000000..7c1660d484 --- /dev/null +++ b/tasks/utils/play/environment/check.yml @@ -0,0 +1,12 @@ +--- +# Param: PLAY_ENVIRONMENT_SOURCE - mapping of environment variable to its templated source +# Param: PLAY_ENVIRONMENT - the mapping freeze.yml rendered at play start +- name: "✅ Assert the frozen play environment still equals its sources" + ansible.builtin.assert: + that: + - PLAY_ENVIRONMENT == PLAY_ENVIRONMENT_SOURCE + fail_msg: >- + A source of the play environment changed during the play, so every task after the change + ran with a stale value. Sources now: {{ PLAY_ENVIRONMENT_SOURCE | dict2items + | difference(PLAY_ENVIRONMENT | dict2items) | items2dict | to_json }} + quiet: true diff --git a/tasks/utils/play/environment/freeze.yml b/tasks/utils/play/environment/freeze.yml new file mode 100644 index 0000000000..feb5b42e21 --- /dev/null +++ b/tasks/utils/play/environment/freeze.yml @@ -0,0 +1,5 @@ +--- +# Param: PLAY_ENVIRONMENT_SOURCE - mapping of environment variable to its templated source +- name: "🧊 Render the play environment once for this host" + ansible.builtin.set_fact: + PLAY_ENVIRONMENT: "{{ PLAY_ENVIRONMENT_SOURCE }}" diff --git a/tests/integration/ansible/playbooks/test_play_environment_frozen.py b/tests/integration/ansible/playbooks/test_play_environment_frozen.py new file mode 100644 index 0000000000..90de1f4279 --- /dev/null +++ b/tests/integration/ansible/playbooks/test_play_environment_frozen.py @@ -0,0 +1,124 @@ +"""The play environment is rendered once per host and checked against its sources. + +``playbook.yml`` passes its environment as the ``PLAY_ENVIRONMENT`` mapping +that ``tasks/utils/play/environment/freeze.yml`` renders once, so no task +compiles the source templates again. ``environment/check.yml`` runs at the +end of the play and fails when a source changed after the freeze, because +every task after the change ran with the stale value. + +These cases run real Ansible with the two shared task files: the frozen value +reaches a module's environment, and a source changed mid-play fails the check. +""" + +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +FREEZE = PROJECT_ROOT / "tasks/utils/play/environment/freeze.yml" +CHECK = PROJECT_ROOT / "tasks/utils/play/environment/check.yml" +PLAYBOOK = PROJECT_ROOT / "playbook.yml" + +PLAY = f"""--- +- name: Freeze the play environment and check it at the end + hosts: localhost + gather_facts: false + vars: + probe_source: frozen + PLAY_ENVIRONMENT_SOURCE: + PROBE_VALUE: "{{{{ probe_source }}}}" + PLAY_ENVIRONMENT: "{{{{ PLAY_ENVIRONMENT_SOURCE }}}}" + environment: "{{{{ PLAY_ENVIRONMENT }}}}" + pre_tasks: + - name: Freeze + ansible.builtin.include_tasks: {FREEZE} + tasks: + - name: Report the value a module sees + ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_out }}}}" + changed_when: false + + - name: Change the source mid-play + ansible.builtin.set_fact: + probe_source: changed + when: change_source | bool + post_tasks: + - name: Check + ansible.builtin.include_tasks: {CHECK} +""" + + +def _run(change_source: bool) -> tuple[int, str, str]: + """Run the play once. + + Args: + change_source: whether the play changes the source after the freeze. + + Returns: + ``(exit code, combined output, value the module saw)``. + """ + with tempfile.TemporaryDirectory() as tmp: + workdir = Path(tmp) + (workdir / "play.yml").write_text(PLAY, encoding="utf-8") + probe_out = workdir / "probe.txt" + result = subprocess.run( + [ + "ansible-playbook", + "-i", + "localhost,", + "-c", + "local", + str(workdir / "play.yml"), + "-e", + f"probe_out={probe_out}", + "-e", + f"change_source={change_source}", + ], + cwd=str(workdir), + capture_output=True, + text=True, + check=False, + ) + seen = read_text(str(probe_out)) if probe_out.exists() else "" + return result.returncode, result.stdout + result.stderr, seen + + +@unittest.skipUnless(shutil.which("ansible-playbook"), "ansible-playbook not found") +class TestPlayEnvironmentFrozen(unittest.TestCase): + def test_a_module_sees_the_frozen_value_and_the_check_passes(self): + code, output, seen = _run(change_source=False) + self.assertEqual(code, 0, output) + self.assertEqual(seen, "frozen") + + def test_a_source_changed_mid_play_fails_the_check(self): + code, output, seen = _run(change_source=True) + self.assertNotEqual(code, 0, output) + self.assertEqual(seen, "frozen") + self.assertIn("A source of the play environment changed", output) + + +class TestPlaybookUsesTheFrozenEnvironment(unittest.TestCase): + def test_the_playbook_freezes_first_and_checks_last(self): + text = read_text(str(PLAYBOOK)) + self.assertIn('environment: "{{ PLAY_ENVIRONMENT }}"', text) + self.assertIn('PLAY_ENVIRONMENT: "{{ PLAY_ENVIRONMENT_SOURCE }}"', text) + pre_tasks = text.index("pre_tasks:") + self.assertLess( + pre_tasks, text.index("tasks/utils/play/environment/freeze.yml") + ) + self.assertLess( + text.index("tasks/utils/play/environment/freeze.yml"), + text.index("ansible.builtin.script: scripts/system/python"), + ) + self.assertLess( + text.index("post_tasks:"), + text.index("tasks/utils/play/environment/check.yml"), + ) + + +if __name__ == "__main__": + unittest.main() From 066a84d0a6172c5e71c9de10c462d238b7d3bee5 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Thu, 19 Nov 2026 08:36:37 +0400 Subject: [PATCH 07/65] fix(swarm-lab): keep extend_inventory.py executable Co-Authored-By: Claude Opus 5.5 --- utils/tests/swarm/extend_inventory.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 utils/tests/swarm/extend_inventory.py diff --git a/utils/tests/swarm/extend_inventory.py b/utils/tests/swarm/extend_inventory.py old mode 100644 new mode 100755 From 37e5381fab12ce9dce45b823ef19b55f8ee322bb Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 19 Nov 2026 09:15:19 +0000 Subject: [PATCH 08/65] fix(ci): cut MediaWiki#0 to budget with honest coverage credits MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit web-app-mediawiki#0 died on the deploy cap in PR #1456 (run 44360158737: pass 2 killed at 19334 s). Its round pulled Jitsi through Matrix#0 and Weblate through Translate#0. The cut: Matrix variant 0 turns Jitsi off (bond 1 -> 0.5, like mattermost, moodle and discourse), and Weblate moves from Translate variant 0 to variant 3 with a reciprocal pin. The model puts mw#0 at 23267 -> 19695 s (extrapolated pass 2); the trivy report reuse already on main (6f1daf9c3d) covers the rest. Without an honest credit the cut lost the edge weblate#0 -> translate#0, because openproject#3 was credited with Weblate it never deploys. This brings over the credit fix from the IAM line, commit 36deb3e6f4 (cli, reach.py and its tests; the workflow warning stays on IAM). A row now counts as covered only if its coverer deploys it at variant 0 in every mode and network. False credits drop from 23 to 0. Coverage: all 547 Playwright specs keep their trigger (527 triggered, 0 never, 20 outside lifecycles, the same list as main). jenkins#0, n8n#0 and web-svc-html#0 become rows of their own and displace espocrm#2, openbao#2 and opencloud#2 from the 204-row head. One variant edge, weblate#0 -> translate#0 shared, is lost, because the IAM rule does not compare provider variants. Goldens: wordpress#0 and nextcloud#7 drop from 29 to 27 roles. Not run: unit and integration tests (per order, MEDUSA only; the suite runs on main). MEDUSA: 100 %, three accepted findings carried over from 36deb3e6f4. 🎯 Fix: 80 % 💥 Break: 10 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 72 🚦 Gate: ⛔ fix 80 % < 90, break 10 % > 5 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- cli/meta/ci/query.py | 8 +- cli/meta/roles/applications/complexity/cli.py | 46 +++- .../roles/applications/complexity/reach.py | 150 ++++++++++ roles/web-app-matrix/meta/services.yml | 3 +- roles/web-app-matrix/meta/variants.yml | 3 +- roles/web-svc-translate/meta/variants.yml | 9 +- .../test_covered_rows_are_deployed.py | 259 ++++++++++++++++++ .../roles/meta/variants/test_variant_tree.py | 6 +- tests/unit/python/cli/meta/ci/test_query.py | 23 ++ .../complexity/test_complexity.py | 146 +++++++++- .../applications/complexity/test_reach.py | 140 ++++++++++ 11 files changed, 761 insertions(+), 32 deletions(-) create mode 100644 cli/meta/roles/applications/complexity/reach.py create mode 100644 tests/integration/meta/workflows/test_covered_rows_are_deployed.py create mode 100644 tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py diff --git a/cli/meta/ci/query.py b/cli/meta/ci/query.py index 84e94ef8f0..96441350de 100644 --- a/cli/meta/ci/query.py +++ b/cli/meta/ci/query.py @@ -123,7 +123,11 @@ def discover_rows( lifecycles: str = "", ) -> list[dict]: """The ordered candidate rows, each the complexity payload of one - ``role#variant``. Uncapped: the chunker decides what a sweep spends.""" + ``role#variant``. Uncapped: the chunker decides what a sweep spends. + + Only stdout is captured: a planner error in the subprocess (an unsettled + variant pin, a provider-override conflict) reaches the caller's stderr by + name instead of collapsing into ``exit status 1``.""" out = subprocess.run( _query_argv( modes, @@ -133,7 +137,7 @@ def discover_rows( fmt=["--format", "json"], ), cwd=PROJECT_ROOT, - capture_output=True, + stdout=subprocess.PIPE, text=True, check=True, ).stdout diff --git a/cli/meta/roles/applications/complexity/cli.py b/cli/meta/roles/applications/complexity/cli.py index ee60cde3c3..5df068d901 100644 --- a/cli/meta/roles/applications/complexity/cli.py +++ b/cli/meta/roles/applications/complexity/cli.py @@ -14,6 +14,8 @@ from utils.roles.applications.topics import overridden_providers if TYPE_CHECKING: from collections.abc import Mapping + from .reach import Rounds + from .filter import FilterError, compile_predicate from .model import ( TESTED_LIFECYCLES, @@ -22,6 +24,7 @@ from .model import ( compute_complexity_rows, compute_variant_complexity_rows, ) +from .reach import rounds from .render import render_json, render_string, render_table, render_yaml _SORT_KEYS = { @@ -281,6 +284,8 @@ def _mark_covered( rows: list[ComplexityRow], overridden: Mapping[tuple[str, int], set[str]] | None = None, variant_counts: Mapping[str, int] | None = None, + *, + planner: Rounds, ) -> list[ComplexityRow]: """Assign each sorted row its numeric ``id`` (its position in sort order) and its ``covered_by`` via a greedy set-cover: the first row is green, and @@ -288,10 +293,21 @@ def _mark_covered( already-green predecessor OF A DIFFERENT ROLE that actually embeds this row (its role name is in the predecessor's transitive ``services``); a row with no such predecessor becomes green itself, leaving ``covered_by`` at the - sentinel ``0`` (no real ``id`` is 0). Because ``services`` is the - transitive closure, embedding the row pulls its whole subtree, so the - coverer's deploy genuinely brings this row up. Two variants of the same - role never cover each other (a role never embeds itself). + sentinel ``0`` (no real ``id`` is 0). Two variants of the same role never + cover each other (a role never embeds itself). + + ``services`` alone does not prove the coverer's deploy brings the row up: + the closure walks every provider's base ``meta/services.yml``, while the + round runs each provider in a variant that may switch the edge off, and + leaves the primary-only guide and Semaphore edges off for every provider, so + a coverer can name a role its round never deploys. ``planner`` is the deploy + planner's answer, and a coverer must run the row's role in variant 0 there + too, in every network mode the sweep may rotate the coverer to: the deploy + and network axes are assigned after this cut, and a network's ``disable`` + drops the Tor provider from a clearnet node and a clearnet-only partner from + a Tor node. A coverer must also offer every deploy mode and network mode the + row offers, or the sweep never deploys the row in the ones it lacks; such a + row stays green. Coverage is variant-aware: only a row's variant-0 (or whole-role) form can be covered, because a coverer only ever brings a provider up at variant 0. @@ -314,6 +330,7 @@ def _mark_covered( no variant dictates anything. variant_counts: ``{role: how many variants it declares}``. A role missing from it counts as one, which is the whole-role case. + planner: the deploy planner's :class:`~.reach.Rounds` (:func:`rounds`). """ demands = overridden or {} counts = variant_counts or {} @@ -322,7 +339,14 @@ def _mark_covered( index = coverer_variant or 0 return index == 0 or index >= counts.get(provider, 1) - green: list[tuple[int, str, int | None, set[str]]] = [] + def deploys_at_zero(coverer: ComplexityRow, row: ComplexityRow) -> bool: + return ( + planner.modes(row) <= planner.modes(coverer) + and planner.networks(row) <= planner.networks(coverer) + and planner.runs(coverer).get(row.name) == 0 + ) + + green: list[tuple[int, ComplexityRow, set[str]]] = [] out: list[ComplexityRow] = [] for index, row in enumerate(rows, start=1): coverable = row.variant in (None, 0) @@ -330,11 +354,12 @@ def _mark_covered( next( ( gid - for gid, gname, gvariant, gset in green - if gname != row.name + for gid, grow, gset in green + if grow.name != row.name and row.name in gset - and row.name not in demands.get((gname, gvariant or 0), ()) - and pulls_at_zero(gvariant, row.name) + and row.name not in demands.get((grow.name, grow.variant or 0), ()) + and pulls_at_zero(grow.variant, row.name) + and deploys_at_zero(grow, row) ), None, ) @@ -342,7 +367,7 @@ def _mark_covered( else None ) if coverer is None: - green.append((index, row.name, row.variant, set(row.services))) + green.append((index, row, set(row.services))) out.append(row._replace(id=index, covered_by=coverer or 0)) return out @@ -398,6 +423,7 @@ def main(argv: list[str] | None = None) -> int: role: max(1, len(entries or [{}])) for role, entries in get_variants(roles_dir=roles_dir).items() }, + planner=rounds(roles_dir), ) _apply_sort(rows, sort_spec) diff --git a/cli/meta/roles/applications/complexity/reach.py b/cli/meta/roles/applications/complexity/reach.py new file mode 100644 index 0000000000..a1fc1ab88c --- /dev/null +++ b/cli/meta/roles/applications/complexity/reach.py @@ -0,0 +1,150 @@ +"""What a row's deploy brings up, as the deploy planner settles it.""" + +from __future__ import annotations + +import functools +from pathlib import Path +from typing import TYPE_CHECKING, NamedTuple + +from cli.administration.deploy.development.inventory.legacy_resolver import ( + prune_orphans_after_disable, +) +from cli.administration.inventory.provision.services.disabler import ( + find_provider_roles, + parse_services_disabled, +) +from utils.cache.applications import get_variants +from utils.github.variant import network +from utils.github.variant.pools import MODES +from utils.roles.applications.variants import resolve_round + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping + + from utils.roles.applications.variants import ResolvedRound + + from .model import ComplexityRow + + +class Rounds(NamedTuple): + """The deploy planner's answers the coverage cut asks of a row, cheapest + first, so the cut can stop at the first that rules a coverer out. + + Attributes: + modes: the deploy modes the row is tested in. + networks: the node network modes those deploy modes can take it to. + runs: ``{role: variant it runs in}`` for every role the row's round + deploys in each of its network modes. + """ + + modes: Callable[[ComplexityRow], frozenset[str]] + networks: Callable[[ComplexityRow], frozenset[str]] + runs: Callable[[ComplexityRow], Mapping[str, int]] + + +@functools.cache +def _round_of(roles_dir: str, app: str, variant: int) -> ResolvedRound: + """The round of ``app#variant``, settled as the deploy planner settles it + (``plan_dev_inventory_matrix`` resolves the same round, but every round of + the app, which a row asking for one of fourteen does not need). + + Args: + roles_dir: the roles tree the round is read from. + app: the round's only primary app. + variant: the primary's variant, which is also the round index. + """ + return resolve_round( + roles_dir=roles_dir, + round_index=variant, + primary_app_variants={app: variant}, + variants_per_app=get_variants(roles_dir=roles_dir, readonly=True), + ) + + +@functools.cache +def _networks( + roles_dir: str, app: str, variant: int, modes: frozenset[str] +) -> frozenset[str]: + """The node network modes ``app#variant`` can be deployed in. + + Args: + roles_dir: the roles tree the round is read from. + app: the round's only primary app. + variant: the primary's variant, which is also the round index. + modes: the deploy modes the row is tested in. + """ + states = network.row_states( + app, + variant, + get_variants(roles_dir=roles_dir, readonly=True), + pulls_tor=network.tor_provider() in _round_of(roles_dir, app, variant).include, + ) + return frozenset( + state + for mode in sorted(modes) + for state in network.network_states( + mode, states=states, network_input=network.AUTO + ) + ) + + +@functools.cache +def _runs( + roles_dir: str, app: str, variant: int, networks: frozenset[str] +) -> Mapping[str, int]: + """What ``app#variant`` deploys in every one of ``networks``. + + A network mode deploys with ``disable`` set as the matrix entry sets it + (:func:`utils.github.variant.network.disabled_services`), and the deploy + cuts those roles and every dependency only they pulled in + (``prune_orphans_after_disable``). + + Args: + roles_dir: the roles tree the round is read from. + app: the round's only primary app. + variant: the primary's variant, which is also the round index. + networks: the node network modes the row can be deployed in. + """ + resolved = _round_of(roles_dir, app, variant) + kept = set(resolved.include) + for state in sorted(networks): + tokens = network.disabled_services(state, resolved.include) + if not tokens: + continue + kept &= set( + prune_orphans_after_disable( + include=resolved.include, + primary_apps=[app], + disabled_app_ids=set( + find_provider_roles( + parse_services_disabled(tokens), Path(roles_dir) + ).values() + ), + services_overrides=resolved.services_overrides, + )[0] + ) + running = {**resolved.active_index, app: variant} + return {role: running.get(role, 0) for role in resolved.include if role in kept} + + +def rounds(roles_dir: Path) -> Rounds: + """The planner's answers for the coverage cut, read from ``roles_dir``. + + Args: + roles_dir: the roles tree the rounds are read from. + + Returns: + :class:`Rounds` over that tree; a whole-role row is round 0. + """ + root = str(roles_dir) + + def modes(row: ComplexityRow) -> frozenset[str]: + return frozenset(mode for mode in MODES if getattr(row, f"test_{mode}")) + + def networks(row: ComplexityRow) -> frozenset[str]: + return _networks(root, row.name, row.variant or 0, modes(row)) + + def runs(row: ComplexityRow) -> Mapping[str, int]: + return _runs(root, row.name, row.variant or 0, networks(row)) + + return Rounds(modes, networks, runs) diff --git a/roles/web-app-matrix/meta/services.yml b/roles/web-app-matrix/meta/services.yml index 2bf2048512..0d3df14533 100644 --- a/roles/web-app-matrix/meta/services.yml +++ b/roles/web-app-matrix/meta/services.yml @@ -48,9 +48,8 @@ coturn: enabled: "{{ 'web-svc-coturn' in group_names }}" shared: "{{ 'web-svc-coturn' in group_names }}" # nocheck: variants-coverage — the onion gate is a hard invariant; no variant may force Jitsi on a tor node. -# nocheck: bond-baseline — same reason: variant 0 must not pin Jitsi on. jitsi: - bond: 1 + bond: 0.5 enabled: "{{ lookup('config', 'web-app-matrix', 'services.matrix.flavor') == 'ansible' and 'svc-net-tor' not in group_names }}" # nocheck: dynamic-flag — Matrix offers Jitsi from the ansible flavor and off tor nodes only shared: "{{ 'web-app-jitsi' in group_names }}" domains: diff --git a/roles/web-app-matrix/meta/variants.yml b/roles/web-app-matrix/meta/variants.yml index e191874adb..9cf8002777 100644 --- a/roles/web-app-matrix/meta/variants.yml +++ b/roles/web-app-matrix/meta/variants.yml @@ -42,7 +42,8 @@ enabled: false shared: false jitsi: - shared: true + enabled: false + shared: false ldap: enabled: true shared: true diff --git a/roles/web-svc-translate/meta/variants.yml b/roles/web-svc-translate/meta/variants.yml index 63b098cc39..c5694e2beb 100644 --- a/roles/web-svc-translate/meta/variants.yml +++ b/roles/web-svc-translate/meta/variants.yml @@ -31,8 +31,8 @@ enabled: false shared: false weblate: - enabled: true - shared: true + enabled: false + shared: false prometheus: enabled: true shared: true @@ -123,9 +123,10 @@ s1: enabled: true shared: true + # variant-pin: web-app-weblate#reciprocal weblate: - enabled: false - shared: false + enabled: true + shared: true prometheus: enabled: true shared: true diff --git a/tests/integration/meta/workflows/test_covered_rows_are_deployed.py b/tests/integration/meta/workflows/test_covered_rows_are_deployed.py new file mode 100644 index 0000000000..548ee053cc --- /dev/null +++ b/tests/integration/meta/workflows/test_covered_rows_are_deployed.py @@ -0,0 +1,259 @@ +"""Integration: a row the sweep cuts as covered is deployed by its coverer. + +The cut drops a ``role#0`` row because an earlier row already brings that role +up in variant 0. When the claim is wrong, no job of the sweep deploys the row +and the plan still reads as complete. The complexity closure over-approximates +a round (it walks every provider's base ``meta/services.yml``), so the claim is +checked here against what the deploy jobs themselves run: the planner's include +pruned by ``disable`` as the compose and host deploy prunes it, and the include +a swarm job derives (``utils.tests.swarm.derive_includes``). The deploy and +network axes are assigned after the cut, so the claim must hold in every deploy +mode and network mode the coverer can rotate to. +""" + +from __future__ import annotations + +import functools +import os +import unittest +from unittest import mock + +from cli.administration.deploy.development.inventory import ( + _build_services_overrides_for_round as build_services_overrides_for_round, +) +from cli.administration.deploy.development.inventory import ( + plan_dev_inventory_matrix, + prune_orphans_after_disable, +) +from cli.administration.inventory.provision.services.disabler import ( + find_provider_roles, + parse_services_disabled, +) +from cli.meta.ci import query +from utils.cache.applications import get_variants +from utils.cache.files import PROJECT_ROOT +from utils.github.variant import network +from utils.github.variant.pools import MODES +from utils.tests.swarm.derive_includes import derive_includes + +ROLES = PROJECT_ROOT / "roles" + + +@functools.cache +def _rounds(app: str) -> tuple[tuple[dict[str, int], tuple[str, ...]], ...]: + return tuple( + (dict(variants), tuple(include)) + for _index, _dir, variants, include, _purge in plan_dev_inventory_matrix( + roles_dir=str(ROLES), + primary_apps=[app], + base_inventory_dir="plan", + ) + ) + + +@functools.cache +def _rows() -> tuple[dict, ...]: + return tuple(query.discover_rows(query.resolve_modes(query.ALL_MODES))) + + +@functools.cache +def _covered() -> tuple[tuple[dict, dict], ...]: + by_id = {row["id"]: row for row in _rows()} + return tuple( + (row, by_id[row["covered_by"]]) for row in _rows() if row["covered_by"] in by_id + ) + + +def _row(name: str, variant: int) -> dict: + return next( + row for row in _rows() if (row["name"], row["variant"] or 0) == (name, variant) + ) + + +def _modes(row: dict) -> set[str]: + return {mode for mode in MODES if row.get(f"test_{mode}")} + + +def _networks_by_mode(row: dict) -> dict[str, tuple[str, ...]]: + """The node network modes each deploy mode of ``row`` can take it to. + + Args: + row: a discovered row. + + Returns: + ``{deploy mode: network modes}`` for every mode ``row`` is tested in. + """ + include = _rounds(row["name"])[row["variant"] or 0][1] + states = network.row_states( + row["name"], + row["variant"], + get_variants(roles_dir=str(ROLES), readonly=True), + pulls_tor=network.tor_provider() in include, + ) + return { + mode: tuple( + network.network_states(mode, states=states, network_input=network.AUTO) + ) + for mode in sorted(_modes(row)) + } + + +def _network_losses(row: dict, coverer: dict) -> list[str]: + """Every ``mode/network`` the sweep can give ``row`` but never ``coverer``. + + Args: + row: the cut row. + coverer: the row it is cut for. + """ + offered = _networks_by_mode(coverer) + return [ + f"{mode}/{state}" + for mode, states in _networks_by_mode(row).items() + for state in states + if state not in offered.get(mode, ()) + ] + + +@functools.cache +def _deployed(app: str, index: int, mode: str, tokens: str) -> frozenset[str]: + """The roles a ``mode`` job of ``app#index`` deploys under ``disable``. + + Args: + app: the job's primary role. + index: the job's round index. + mode: the job's deploy mode. + tokens: the job's ``disable`` value. + """ + variants, include = _rounds(app)[index] + if mode == "swarm": + with mock.patch.dict(os.environ, {"disable": tokens}): + return frozenset(derive_includes(app, variants=variants)) + if not tokens: + return frozenset(include) + disabled = set(find_provider_roles(parse_services_disabled(tokens), ROLES).values()) + return frozenset( + prune_orphans_after_disable( + include=include, + primary_apps=[app] if app not in disabled else [], + disabled_app_ids=disabled, + services_overrides=build_services_overrides_for_round( + roles_dir=str(ROLES), + round_index=index, + primary_app_variants={app: variants.get(app, index)}, + ), + )[0] + ) + + +def _losses(row: dict, coverer: dict) -> list[str]: + """Every deploy mode and network mode of ``coverer`` whose job leaves + ``row`` out. + + Args: + row: the cut row. + coverer: the row it is cut for. + + Returns: + ``mode/network disable=...`` per such job. + """ + index = coverer["variant"] or 0 + include = _rounds(coverer["name"])[index][1] + return [ + f"{mode}/{state} disable={tokens!r}" + for mode, states in _networks_by_mode(coverer).items() + for state in states + for tokens in (network.disabled_services(state, include),) + if row["name"] not in _deployed(coverer["name"], index, mode, tokens) + ] + + +class TestCoveredRowsAreDeployed(unittest.TestCase): + def test_every_cut_row_runs_in_variant_zero_in_its_coverers_round(self) -> None: + findings = [ + f" - {query.token(row)} cut for {query.token(coverer)}, whose round " + f"runs it as {variants.get(row['name'], 0) if row['name'] in include else 'nothing'!r}" + for row, coverer in _covered() + for variants, include in ( + _rounds(coverer["name"])[coverer["variant"] or 0], + ) + if row["name"] not in include or variants.get(row["name"], 0) != 0 + ] + self.assertFalse( + findings, + f"{len(findings)} row(s) are cut as covered by a row whose deploy " + "never brings them up in variant 0, so no job deploys them:\n" + + "\n".join(findings), + ) + + def test_every_job_the_coverer_can_get_deploys_the_cut_row(self) -> None: + findings = [ + f" - {query.token(row)} cut for {query.token(coverer)}, whose " + f"{loss} job leaves it out" + for row, coverer in _covered() + for loss in _losses(row, coverer) + ] + self.assertFalse( + findings, + f"{len(findings)} cut row(s) are left out of a job their coverer can " + "rotate to, so that sweep deploys them nowhere:\n" + "\n".join(findings), + ) + + def test_every_cut_row_is_tested_only_in_modes_its_coverer_is_tested_in( + self, + ) -> None: + findings = [ + f" - {query.token(row)} cut for {query.token(coverer)}, which is " + f"never deployed in {sorted(_modes(row) - _modes(coverer))}" + for row, coverer in _covered() + if not _modes(row) <= _modes(coverer) + ] + self.assertFalse( + findings, + f"{len(findings)} cut row(s) offer a deploy mode their coverer does " + "not, so no job deploys them in it:\n" + "\n".join(findings), + ) + + def test_every_network_mode_of_a_cut_row_is_one_its_coverer_takes( + self, + ) -> None: + findings = [ + f" - {query.token(row)} cut for {query.token(coverer)}, which never " + f"deploys in {loss}" + for row, coverer in _covered() + for loss in _network_losses(row, coverer) + ] + self.assertFalse( + findings, + f"{len(findings)} cut row(s) can be given a network mode their coverer " + "never is, so no job deploys them in it:\n" + "\n".join(findings), + ) + + def test_the_network_guard_reports_a_network_the_coverer_never_takes( + self, + ) -> None: + self.assertIn( + "swarm/multi", + _network_losses( + _row("svc-ai-libretranslate-engine", 0), _row("web-svc-translate", 4) + ), + ) + + def test_the_guard_reports_a_disable_that_drops_the_cut_row(self) -> None: + row, coverer = next( + (row, coverer) + for row, coverer in _covered() + if _modes(coverer) & {"compose", "host"} + ) + with mock.patch.object( + network, "disabled_services", lambda state, include: row["name"] + ): + self.assertTrue(_losses(row, coverer)) + + def test_the_scan_finds_cut_rows_to_judge(self) -> None: + self.assertTrue( + _covered(), "no discovered row is cut as covered; the check is vacuous" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/roles/meta/variants/test_variant_tree.py b/tests/integration/roles/meta/variants/test_variant_tree.py index 63c93a2a2a..7e1a8d37ec 100644 --- a/tests/integration/roles/meta/variants/test_variant_tree.py +++ b/tests/integration/roles/meta/variants/test_variant_tree.py @@ -32,13 +32,11 @@ SHARED = { "svc-net-tor-smtp", "web-app-dashboard", "web-app-discourse", - "web-app-jitsi", "web-app-keycloak", "web-app-matomo", "web-app-matrix", "web-app-prometheus", "web-app-stalwart", - "web-app-weblate", "web-svc-asset", "web-svc-cdn", "web-svc-coturn", @@ -56,9 +54,9 @@ PINNED = { "web-svc-logout": (0, "pin by web-app-matomo#0"), } GOLDEN = { - "web-app-wordpress#0": (29, SHARED | {"web-app-wordpress"}, "round index", PINNED), + "web-app-wordpress#0": (27, SHARED | {"web-app-wordpress"}, "round index", PINNED), "web-app-nextcloud#7": ( - 29, + 27, SHARED | {"web-app-nextcloud"}, "default 0: round past its variants", PINNED, diff --git a/tests/unit/python/cli/meta/ci/test_query.py b/tests/unit/python/cli/meta/ci/test_query.py index baed7b6c21..624c9312ac 100644 --- a/tests/unit/python/cli/meta/ci/test_query.py +++ b/tests/unit/python/cli/meta/ci/test_query.py @@ -1,6 +1,9 @@ from __future__ import annotations +import subprocess +import sys import unittest +from unittest import mock from cli.meta.ci import query @@ -103,5 +106,25 @@ class TestQueryArgv(unittest.TestCase): self.assertIn("test_compose == true", argv[argv.index("--filter") + 1]) +class TestDiscoverRows(unittest.TestCase): + def _discover_with(self, script: str) -> list[dict]: + with mock.patch.object( + query, "_query_argv", return_value=[sys.executable, "-c", script] + ): + return query.discover_rows(("compose",)) + + def test_a_failing_query_leaves_its_error_on_stderr(self) -> None: + with self.assertRaises(subprocess.CalledProcessError) as raised: + self._discover_with( + "import sys; sys.stderr.write('VariantPinError: x\\n'); sys.exit(1)" + ) + self.assertIsNone(raised.exception.stderr) + + def test_the_rows_are_read_from_stdout(self) -> None: + self.assertEqual( + self._discover_with('print(\'[{"name": "r"}]\')'), [{"name": "r"}] + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py b/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py index 26e35c3170..51780d15c9 100644 --- a/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py +++ b/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py @@ -17,6 +17,7 @@ from cli.meta.roles.applications.complexity.model import ( compute_complexity_rows, compute_variant_complexity_rows, ) +from cli.meta.roles.applications.complexity.reach import Rounds from cli.meta.roles.applications.complexity.render import ( _bool_cell, _dwidth, @@ -725,6 +726,12 @@ class TestSortByCoveredBy(unittest.TestCase): "cli.meta.roles.applications.complexity.cli.PROJECT_ROOT", Path(td), ), + # Limitation: the deploy planner resolves includes against the + # project's own roles/, so it cannot plan this fixture tree. + mock.patch( + "cli.meta.roles.applications.complexity.cli.rounds", + lambda _roles_dir: _planner(), + ), redirect_stdout(buf), ): rc = main( @@ -895,11 +902,11 @@ def _row( class TestCoveredBy(unittest.TestCase): def test_id_is_numeric_sort_position(self) -> None: - marked = _mark_covered([_row("A", []), _row("B", [])]) + marked = _mark_covered([_row("A", []), _row("B", [])], planner=_planner()) self.assertEqual([m.id for m in marked], [1, 2]) def test_green_rows_get_covered_by_zero(self) -> None: - marked = _mark_covered([_row("A", ["B"]), _row("C", [])]) + marked = _mark_covered([_row("A", ["B"]), _row("C", [])], planner=_planner()) self.assertEqual([m.covered_by for m in marked], [0, 0]) def test_embedded_row_records_its_embedder_id(self) -> None: @@ -908,7 +915,8 @@ class TestCoveredBy(unittest.TestCase): _row("Z", []), _row("A", ["B"]), _row("B", []), - ] + ], + planner=_planner(), ) self.assertEqual([m.covered_by for m in marked], [0, 0, 2]) @@ -918,7 +926,8 @@ class TestCoveredBy(unittest.TestCase): _row("Z", []), _row("A", ["X", "Y"]), _row("B", ["X"]), - ] + ], + planner=_planner(), ) self.assertEqual([m.covered_by for m in marked], [0, 0, 0]) @@ -929,7 +938,8 @@ class TestCoveredBy(unittest.TestCase): _row("A", ["X"]), _row("B", ["X"]), _row("X", []), - ] + ], + planner=_planner(), ) self.assertEqual([m.covered_by for m in marked], [0, 0, 0, 2]) @@ -940,7 +950,8 @@ class TestCoveredBy(unittest.TestCase): _row("A", ["B", "C"]), _row("B", [], variant=0), _row("C", [], variant=1), - ] + ], + planner=_planner(), ) self.assertEqual([m.covered_by for m in marked], [0, 0, 2, 0]) @@ -952,6 +963,7 @@ class TestCoveredBy(unittest.TestCase): _row("B", [], variant=0), ], variant_counts={"B": 1}, + planner=_planner(), ) self.assertEqual([m.covered_by for m in marked], [0, 0, 2]) @@ -963,6 +975,7 @@ class TestCoveredBy(unittest.TestCase): _row("B", [], variant=0), ], variant_counts={"B": 5}, + planner=_planner(), ) self.assertEqual([m.covered_by for m in marked], [0, 0, 0]) @@ -974,24 +987,139 @@ class TestCoveredBy(unittest.TestCase): _row("B", [], variant=0), ], variant_counts={"B": 9}, + planner=_planner(), ) self.assertEqual([m.covered_by for m in marked], [0, 0, 2]) def test_a_variant_that_overrides_a_provider_does_not_cover_it(self) -> None: rows = [_row("A", ["B", "C"], variant=0), _row("B", []), _row("C", [])] - marked = _mark_covered(rows, {("A", 0): {"B"}}) + marked = _mark_covered(rows, {("A", 0): {"B"}}, planner=_planner()) self.assertEqual([m.covered_by for m in marked], [0, 0, 1]) def test_the_override_only_bars_the_provider_it_names(self) -> None: rows = [_row("A", ["B"], variant=0), _row("B", [])] - marked = _mark_covered(rows, {("A", 0): {"C"}}) + marked = _mark_covered(rows, {("A", 0): {"C"}}, planner=_planner()) self.assertEqual([m.covered_by for m in marked], [0, 1]) def test_an_override_in_another_variant_leaves_coverage_alone(self) -> None: rows = [_row("A", ["B"], variant=0), _row("B", [])] - marked = _mark_covered(rows, {("A", 2): {"B"}}) + marked = _mark_covered(rows, {("A", 2): {"B"}}, planner=_planner()) self.assertEqual([m.covered_by for m in marked], [0, 1]) + def test_a_row_whose_round_never_deploys_the_provider_does_not_cover_it( + self, + ) -> None: + rows = [_row("A", ["B"], variant=3), _row("B", [], variant=0)] + marked = _mark_covered(rows, planner=_planner({("A", 3): {"A": 3}})) + self.assertEqual([m.covered_by for m in marked], [0, 0]) + + def test_a_row_whose_round_deploys_the_provider_at_zero_covers_it(self) -> None: + rows = [_row("A", ["B"], variant=3), _row("B", [], variant=0)] + marked = _mark_covered(rows, planner=_planner({("A", 3): {"B": 0, "A": 3}})) + self.assertEqual([m.covered_by for m in marked], [0, 1]) + + def test_a_round_that_runs_the_provider_in_another_variant_does_not_cover( + self, + ) -> None: + rows = [_row("A", ["B"], variant=3), _row("B", [], variant=0)] + marked = _mark_covered(rows, planner=_planner({("A", 3): {"B": 1, "A": 3}})) + self.assertEqual([m.covered_by for m in marked], [0, 0]) + + def test_the_next_green_row_that_deploys_the_provider_covers_it(self) -> None: + rows = [ + _row("A", ["B"], variant=3), + _row("C", ["B"], variant=0), + _row("B", [], variant=0), + ] + marked = _mark_covered( + rows, + planner=_planner({("A", 3): {"A": 3}, ("C", 0): {"B": 0, "C": 0}}), + ) + self.assertEqual([m.covered_by for m in marked], [0, 0, 2]) + + def test_the_deploy_check_never_widens_what_services_covers(self) -> None: + rows = [_row("A", [], variant=0), _row("B", [], variant=0)] + marked = _mark_covered(rows, planner=_planner({("A", 0): {"B": 0, "A": 0}})) + self.assertEqual([m.covered_by for m in marked], [0, 0]) + + def test_a_row_taking_a_network_its_coverer_never_takes_is_not_covered( + self, + ) -> None: + rows = [_row("A", ["B"], variant=0), _row("B", [], variant=0)] + marked = _mark_covered( + rows, + planner=_planner( + {("A", 0): {"B": 0, "A": 0}}, + networks={("A", 0): CLEARNET_ONLY, ("B", 0): CLEARNET_AND_TOR}, + ), + ) + self.assertEqual([m.covered_by for m in marked], [0, 0]) + + def test_a_coverer_offering_every_network_the_row_takes_covers_it(self) -> None: + rows = [_row("A", ["B"], variant=0), _row("B", [], variant=0)] + marked = _mark_covered( + rows, + planner=_planner( + {("A", 0): {"B": 0, "A": 0}}, + networks={("A", 0): CLEARNET_AND_TOR, ("B", 0): CLEARNET_ONLY}, + ), + ) + self.assertEqual([m.covered_by for m in marked], [0, 1]) + + def test_a_row_tested_in_a_mode_its_coverer_is_not_is_not_covered(self) -> None: + rows = [_row("A", ["B"], variant=0), _row("B", [], variant=0)] + marked = _mark_covered( + rows, + planner=_planner(modes={("B", 0): COMPOSE_AND_HOST}), + ) + self.assertEqual([m.covered_by for m in marked], [0, 0]) + + def test_a_coverer_tested_in_every_mode_of_the_row_covers_it(self) -> None: + rows = [_row("A", ["B"], variant=0), _row("B", [], variant=0)] + marked = _mark_covered( + rows, + planner=_planner(modes={("A", 0): COMPOSE_AND_HOST}), + ) + self.assertEqual([m.covered_by for m in marked], [0, 1]) + + +CLEARNET_ONLY = frozenset({"clearnet"}) +CLEARNET_AND_TOR = frozenset({"clearnet", "tor"}) +COMPOSE_ONLY = frozenset({"compose"}) +COMPOSE_AND_HOST = frozenset({"compose", "host"}) + + +def _planner( + runs: dict[tuple[str, int], dict[str, int]] | None = None, + *, + networks: dict[tuple[str, int], frozenset[str]] | None = None, + modes: dict[tuple[str, int], frozenset[str]] | None = None, +) -> Rounds: + """A ``planner`` stub answering from fixed tables. + + Args: + runs: ``{(role, variant): {role: variant}}`` per coverer; a row absent + from it runs every role of its ``services`` in variant 0. + networks: ``{(role, variant): network modes}``; a row absent from it + takes clearnet only. + modes: ``{(role, variant): deploy modes}``; a row absent from it is + tested in compose only. + + Returns: + :class:`Rounds` answering from those tables. + """ + + def key(row: ComplexityRow) -> tuple[str, int]: + return (row.name, row.variant or 0) + + return Rounds( + lambda row: (modes or {}).get(key(row), COMPOSE_ONLY), + lambda row: (networks or {}).get(key(row), CLEARNET_ONLY), + lambda row: (runs or {}).get( + key(row), {**dict.fromkeys(row.services, 0), row.name: row.variant or 0} + ), + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py b/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py new file mode 100644 index 0000000000..b679818da7 --- /dev/null +++ b/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py @@ -0,0 +1,140 @@ +"""The coverage cut's view of a round: the networks a row takes and the roles +its round still runs once each network's ``disable`` is applied.""" + +from __future__ import annotations + +import unittest +from types import SimpleNamespace +from unittest import mock + +from cli.meta.roles.applications.complexity import reach + +APP = "web-app-a" +ROUND = SimpleNamespace( + include=("svc-db", "svc-net-tor", "web-svc-partner", APP), + active_index={"svc-db": 2}, + services_overrides={}, +) +DISABLE = {"clearnet": "tor", "tor": "web-svc-partner", "multi": ""} +PROVIDERS = {"tor": "svc-net-tor", "web-svc-partner": "web-svc-partner"} +ORPHANS = { + "svc-net-tor": {"svc-net-tor"}, + "web-svc-partner": {"web-svc-partner", "svc-db"}, +} +STATES = {"compose": ("clearnet",), "swarm": ("tor", "multi"), "host": ("clearnet",)} + + +def _prune( + *, + include: tuple[str, ...], + primary_apps: list[str], + disabled_app_ids: set[str], + services_overrides: dict, +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """A ``prune_orphans_after_disable`` stub cutting each disabled role with + the dependencies listed for it in ``ORPHANS``. + + Args: + include: the round's include. + primary_apps: the round's primaries, unused. + disabled_app_ids: the roles ``disable`` cuts. + services_overrides: the round's service maps, unused. + + Returns: + ``(kept, pruned)`` in include order. + """ + gone = set().union(*(ORPHANS[role] for role in disabled_app_ids)) + return tuple(r for r in include if r not in gone), tuple( + r for r in include if r in gone + ) + + +class _Fixture(unittest.TestCase): + def setUp(self) -> None: + caches = (reach._round_of, reach._networks, reach._runs) + for fn in caches: + fn.cache_clear() + self.addCleanup(fn.cache_clear) + self.row_states = mock.Mock(return_value=("clearnet", "tor", "multi")) + for patch in ( + mock.patch.object(reach, "_round_of", return_value=ROUND), + mock.patch.object(reach, "get_variants", return_value={}), + mock.patch.object(reach.network, "row_states", self.row_states), + mock.patch.object( + reach.network, "tor_provider", return_value="svc-net-tor" + ), + mock.patch.object( + reach.network, + "network_states", + side_effect=lambda mode, states, network_input: STATES[mode], + ), + mock.patch.object( + reach.network, + "disabled_services", + side_effect=lambda state, include: DISABLE[state], + ), + mock.patch.object( + reach, + "find_provider_roles", + side_effect=lambda services, roles_dir: { + s: PROVIDERS[s] for s in services + }, + ), + mock.patch.object(reach, "prune_orphans_after_disable", side_effect=_prune), + ): + patch.start() + self.addCleanup(patch.stop) + + +class TestRuns(_Fixture): + def test_a_network_without_disable_runs_the_whole_round(self) -> None: + self.assertEqual( + reach._runs("roles", APP, 3, frozenset({"multi"})), + {"svc-db": 2, "svc-net-tor": 0, "web-svc-partner": 0, APP: 3}, + ) + + def test_a_network_cuts_its_disabled_role_and_the_orphans_it_leaves( + self, + ) -> None: + self.assertEqual( + reach._runs("roles", APP, 3, frozenset({"tor"})), + {"svc-net-tor": 0, APP: 3}, + ) + + def test_a_role_any_network_cuts_is_not_run(self) -> None: + self.assertEqual( + reach._runs("roles", APP, 3, frozenset({"clearnet", "tor"})), {APP: 3} + ) + + +class TestNetworks(_Fixture): + def test_the_networks_are_those_of_every_tested_mode(self) -> None: + self.assertEqual( + reach._networks("roles", APP, 0, frozenset({"compose", "swarm"})), + {"clearnet", "tor", "multi"}, + ) + + def test_a_row_tested_in_no_mode_takes_no_network(self) -> None: + self.assertEqual(reach._networks("roles", APP, 0, frozenset()), frozenset()) + + def test_the_round_decides_whether_the_row_pulls_tor(self) -> None: + reach._networks("roles", APP, 0, frozenset({"compose"})) + self.assertTrue(self.row_states.call_args.kwargs["pulls_tor"]) + + +class TestRounds(_Fixture): + def test_the_modes_are_the_tested_ones(self) -> None: + row = SimpleNamespace( + name=APP, variant=None, test_compose=True, test_swarm=False, test_host=True + ) + self.assertEqual(reach.rounds("roles").modes(row), {"compose", "host"}) + + def test_a_whole_role_row_runs_round_zero(self) -> None: + row = SimpleNamespace( + name=APP, variant=None, test_compose=True, test_swarm=False, test_host=False + ) + self.assertEqual(reach.rounds("roles").runs(row)[APP], 0) + + +if __name__ == "__main__": + unittest.main() From 70ad97b05ce2f936f6b2b407d2e9ccf8520e44b6 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 19 Nov 2026 14:11:21 +0000 Subject: [PATCH 09/65] fix(web-app-gitlab): run the Confluence and Jira admin-page checks without their dead gates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The two tests in files/playwright/test-integrations.js only load GitLab's own /admin/application_settings/integrations//edit page as an anonymous visitor and assert the bounce to sign-in. The role never configures Confluence or Jira, and services.confluence/jira.enabled are pinned false because both partner roles are EOL, so skipUnlessServiceEnabled skipped them in every variant and no CI row ran them (issue #2241). Without the gate they run in the gitlab rows of the sweep head (gitlab#1/#2/#3, jenkins#2, matrix#1, nextcloud#6/#10, openproject#2). The env flags stay used by addons/confluence.spec.js and addons/jira.spec.js. Evidence: tests/integration/roles/playwright, tests/lint/ansible/roles/web-app/playwright and tests/lint/ansible/services: 172 passed, 60 subtests; eslint 0 errors; MEDUSA 100 %. Not run against a live stack. 🎯 Fix: 90 % 💥 Break: 5 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/web-app-gitlab/files/playwright/test-integrations.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/roles/web-app-gitlab/files/playwright/test-integrations.js b/roles/web-app-gitlab/files/playwright/test-integrations.js index 962d934bb2..ce5a6113ff 100644 --- a/roles/web-app-gitlab/files/playwright/test-integrations.js +++ b/roles/web-app-gitlab/files/playwright/test-integrations.js @@ -22,7 +22,6 @@ async function expectInstanceIntegrationIsAdminOnly(page, addon, label) { function register() { test("integration confluence: the Confluence instance-integration page is routed and admin-only", async ({ page }) => { - skipUnlessServiceEnabled("confluence"); await expectInstanceIntegrationIsAdminOnly(page, "confluence", "Confluence"); }); @@ -32,7 +31,6 @@ function register() { }); test("integration jira: the Jira instance-integration page is routed and admin-only", async ({ page }) => { - skipUnlessServiceEnabled("jira"); await expectInstanceIntegrationIsAdminOnly(page, "jira", "Jira"); }); From 8d4ee4e7ae1f7351af4925a5d8cb57cbfab29b08 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 19 Nov 2026 16:53:13 +0000 Subject: [PATCH 10/65] test(ci): assert the query diagnostic reaches stderr, single unittest import style MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The discover_rows test asserted only that the CalledProcessError carries no stderr, which also holds when stderr is discarded; it now captures fd 2 and requires the VariantPinError text there. The coverage-cut tests import unittest.mock as a plain import, so CodeQL no longer flags the mixed import/from-import of unittest. Review feedback on PR #2226. 🎯 Fix: 94 % 💥 Break: 2 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 92 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../test_covered_rows_are_deployed.py | 2 +- tests/unit/python/cli/meta/ci/test_query.py | 19 +++++++++++++++---- .../applications/complexity/test_reach.py | 2 +- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/tests/integration/meta/workflows/test_covered_rows_are_deployed.py b/tests/integration/meta/workflows/test_covered_rows_are_deployed.py index 548ee053cc..e8254e33ec 100644 --- a/tests/integration/meta/workflows/test_covered_rows_are_deployed.py +++ b/tests/integration/meta/workflows/test_covered_rows_are_deployed.py @@ -16,7 +16,7 @@ from __future__ import annotations import functools import os import unittest -from unittest import mock +import unittest.mock as mock from cli.administration.deploy.development.inventory import ( _build_services_overrides_for_round as build_services_overrides_for_round, diff --git a/tests/unit/python/cli/meta/ci/test_query.py b/tests/unit/python/cli/meta/ci/test_query.py index 624c9312ac..f8c385e76d 100644 --- a/tests/unit/python/cli/meta/ci/test_query.py +++ b/tests/unit/python/cli/meta/ci/test_query.py @@ -1,7 +1,9 @@ from __future__ import annotations +import os import subprocess import sys +import tempfile import unittest from unittest import mock @@ -114,10 +116,19 @@ class TestDiscoverRows(unittest.TestCase): return query.discover_rows(("compose",)) def test_a_failing_query_leaves_its_error_on_stderr(self) -> None: - with self.assertRaises(subprocess.CalledProcessError) as raised: - self._discover_with( - "import sys; sys.stderr.write('VariantPinError: x\\n'); sys.exit(1)" - ) + saved = os.dup(2) + with tempfile.TemporaryFile() as sink: + os.dup2(sink.fileno(), 2) + try: + with self.assertRaises(subprocess.CalledProcessError) as raised: + self._discover_with( + "import sys; sys.stderr.write('VariantPinError: x\\n'); sys.exit(1)" + ) + finally: + os.dup2(saved, 2) + os.close(saved) + sink.seek(0) + self.assertIn(b"VariantPinError: x", sink.read()) self.assertIsNone(raised.exception.stderr) def test_the_rows_are_read_from_stdout(self) -> None: diff --git a/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py b/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py index b679818da7..97795d7feb 100644 --- a/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py +++ b/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py @@ -4,8 +4,8 @@ its round still runs once each network's ``disable`` is applied.""" from __future__ import annotations import unittest +import unittest.mock as mock from types import SimpleNamespace -from unittest import mock from cli.meta.roles.applications.complexity import reach From 50b49ecbcfccf1857d13866f13a9759f7b1f3fec Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 19 Nov 2026 16:59:26 +0000 Subject: [PATCH 11/65] fix(tests): raise SkipTest when the MDAD pin source is unreachable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fetch_mdad_file skipped through case.skipTest(), which raises SkipTest internally; CodeQL cannot see that and reports response as possibly read before assignment (code scanning alert 1232). Raising unittest.SkipTest directly keeps the skip and makes the control flow explicit. 🎯 Fix: 95 % 💥 Break: 1 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 94 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- tests/external/roles/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/external/roles/__init__.py b/tests/external/roles/__init__.py index 48f3ccc656..7b07a8dc6c 100644 --- a/tests/external/roles/__init__.py +++ b/tests/external/roles/__init__.py @@ -40,7 +40,7 @@ def fetch_mdad_file(case: unittest.TestCase, path: str) -> str: title="MDAD pin unverified", file=str(MATRIX_SERVICES.relative_to(PROJECT_ROOT)), ) - case.skipTest(f"{url} unreachable") + raise unittest.SkipTest(f"{url} unreachable") from exc case.assertEqual( response.status_code, 200, From e32e848cca8446102545eecc648addb8ab8ea4fd Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Thu, 19 Nov 2026 18:44:39 +0000 Subject: [PATCH 12/65] test(ci): import unittest.mock as a plain import in the query test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit test_query.py imported unittest both as a module and through from-import, which tests/lint/repository/python/test_import_and_import_from.py rejects; main already failed test-lint on the same shape in test_render.py. 🎯 Fix: 97 % 💥 Break: 1 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 96 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- tests/unit/python/cli/meta/ci/test_query.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/python/cli/meta/ci/test_query.py b/tests/unit/python/cli/meta/ci/test_query.py index f8c385e76d..8abf5024bc 100644 --- a/tests/unit/python/cli/meta/ci/test_query.py +++ b/tests/unit/python/cli/meta/ci/test_query.py @@ -5,7 +5,7 @@ import subprocess import sys import tempfile import unittest -from unittest import mock +import unittest.mock as mock from cli.meta.ci import query From 5da3579d3e2a895b79824ce4d2db23cb327e8da5 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Fri, 20 Nov 2026 03:01:19 +0400 Subject: [PATCH 13/65] fix: address the review findings on the per-task overhead change - Require ansible-core 2.21: the deploy CLI refuses a venv whose packages differ from the exact pins of the deploy extra, the carrier action names the version it needs instead of failing on an import, and the image installs the pinned ansible from pyproject.toml. - Lint: catch compact == comparisons, scan compose/, inventories/ and both playbooks, flag bare services/packages/getent_* reads, and derive the allowlist from ansible-core's variable map and the plugins' documented options. - Tag the play environment freeze and check with always, and cover a task override, a handler, a delegated task and a tagged run. - Map a failed docker.service query to its fail_msg. - Pin the docker_cached options to the installed stock connection, read the carrier through hostvars in a two-host test, and correct the carrier guard message and the stale README line reference. Co-Authored-By: Claude Opus 5.5 --- Dockerfile | 2 +- cli/administration/deploy/dedicated/runner.py | 18 ++- playbook.yml | 12 +- plugins/action/applications_carrier.py | 18 ++- plugins/connection/docker_cached.py | 12 +- .../tasks/01_assert_requirements.yml | 3 +- .../test_applications_carrier.py | 50 ++++-- .../connection_plugins/test_docker_cached.py | 56 ++++++- .../playbooks/test_play_environment_frozen.py | 79 ++++++++-- .../test_no_deprecated_ansible_patterns.py | 149 ++++++++++++++---- .../deploy/dedicated/test_runner.py | 20 +++ .../action/test_applications_carrier.py | 12 ++ utils/cache/README.md | 2 +- utils/cache/carrier.py | 8 +- 14 files changed, 365 insertions(+), 76 deletions(-) diff --git a/Dockerfile b/Dockerfile index b3ac4fb1be..95c5c4335e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -57,7 +57,7 @@ RUN set -euo pipefail; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_PYTHON_INSTALL_SCRIPT:?}" ensure; \ VENV="${INFINITO_VENV_DIR}" bash "${INFINITO_SRC_DIR}/scripts/install/venv.sh"; \ ${PIP} install --upgrade pip setuptools wheel; \ - ${PIP} install ansible PyYAML; \ + ${PIP} install "$(grep -oE '"ansible==[^"]+"' "${INFINITO_SRC_DIR}/pyproject.toml" | tr -d '"')" PyYAML; \ ANSIBLE_COLLECTIONS_DIR="${HOME}/.ansible/collections" \ bash "${INFINITO_SRC_DIR}/scripts/install/ansible.sh" diff --git a/cli/administration/deploy/dedicated/runner.py b/cli/administration/deploy/dedicated/runner.py index 7dcd8e144d..d30eb87256 100644 --- a/cli/administration/deploy/dedicated/runner.py +++ b/cli/administration/deploy/dedicated/runner.py @@ -24,28 +24,37 @@ from utils.cache.files import read_text from .proc import run, run_make _REQUIREMENT_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*") +_EXACT_PIN = re.compile(r"([A-Za-z0-9][A-Za-z0-9._-]*)\s*==\s*([^\s;,]+)\s*$") def deploy_ansible_playbook(repo_root: str) -> str: """ Return the ansible-playbook of the running interpreter once that - interpreter carries every distribution of the `deploy` extra. + interpreter carries every distribution of the `deploy` extra, each + exact `==` pin at its pinned version. Args: repo_root: checkout whose pyproject.toml declares the `deploy` extra Returns: absolute path of the ansible-playbook next to sys.executable Exits: - 1 when a `deploy` distribution or that ansible-playbook is missing + 1 when a `deploy` distribution is missing or off its `==` pin, or that + ansible-playbook is missing """ pyproject = tomllib.loads(read_text(str(Path(repo_root) / "pyproject.toml"))) missing: list[str] = [] + stale: list[str] = [] for requirement in pyproject["project"]["optional-dependencies"]["deploy"]: name = _REQUIREMENT_NAME.match(requirement) try: - importlib.metadata.distribution(name.group(0)) + installed = importlib.metadata.distribution(name.group(0)).version except importlib.metadata.PackageNotFoundError: missing.append(requirement) + continue + pin = _EXACT_PIN.match(requirement) + if pin and installed != pin.group(2): + missing.append(requirement) + stale.append(f"{requirement} (installed: {installed})") ansible_playbook = Path(sys.executable).parent / "ansible-playbook" if missing: @@ -54,7 +63,8 @@ def deploy_ansible_playbook(repo_root: str) -> str: f"\n[ERROR] The deploy interpreter {sys.executable} lacks " f"{', '.join(missing)} from the `deploy` extra of " f"{repo_root}/pyproject.toml.\n" - f" Install them with: {sys.executable} -m pip install {quoted}\n" + + (f" Pinned but different: {', '.join(stale)}\n" if stale else "") + + f" Install them with: {sys.executable} -m pip install {quoted}\n" " or launch the CLI from the venv `make install` provisions.\n", file=sys.stderr, ) diff --git a/playbook.yml b/playbook.yml index b445f627fd..ad6b08a3b7 100644 --- a/playbook.yml +++ b/playbook.yml @@ -21,7 +21,11 @@ gather_facts: false pre_tasks: - name: "🧊 Render the play environment once for this host" - ansible.builtin.include_tasks: tasks/utils/play/environment/freeze.yml + ansible.builtin.include_tasks: + file: tasks/utils/play/environment/freeze.yml + apply: + tags: [always] + tags: [always] - name: "🐍 Link the managed Python interpreter before any module needs it" ansible.builtin.script: scripts/system/python/managed_interpreter.sh @@ -45,5 +49,9 @@ include_tasks: "tasks/stages/03_destructor.yml" post_tasks: - name: "✅ Check the play environment against its sources" - ansible.builtin.include_tasks: tasks/utils/play/environment/check.yml + ansible.builtin.include_tasks: + file: tasks/utils/play/environment/check.yml + apply: + tags: [always] + tags: [always] become: true diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index 51bbf87770..5c95648413 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -8,7 +8,9 @@ as non-persistent host variables, the layer ``set_fact`` writes; every later worker inherits them at fork time and ``get_merged_applications`` / ``get_merged_users`` serve them instead of rendering. They stay out of the fact cache on purpose: ``get_vars`` deep-copies every fact before every task, -and these are the whole rendered trees. The users carrier is keyed like the applications carrier plus +and these are the whole rendered trees. The action also registers an empty +cacheable layer, as ``set_fact`` does, so ansible-core never copies a result's +``ansible_facts`` into the fact cache. The users carrier is keyed like the applications carrier plus the token store digest and ``inventory_hostname``:: - name: 🧊 Render the applications SPOT once and carry it into every task's worker @@ -53,9 +55,10 @@ from __future__ import annotations from typing import Any +from ansible import release from ansible.errors import AnsibleActionFail from ansible.module_utils.parsing.convert_bool import boolean -from ansible.plugins.action import ActionBase, VariableLayer +from ansible.plugins.action import ActionBase from ansible.plugins.loader import lookup_loader from plugins.lookup.email import provider_view_carrier @@ -67,6 +70,11 @@ from utils.cache.carrier import ( revalidate_tokens_file, ) +try: + from ansible.plugins.action import VariableLayer +except ImportError: + VariableLayer = None + class ActionModule(ActionBase): TRANSFERS_FILES = False @@ -74,6 +82,12 @@ class ActionModule(ActionBase): def run( self, tmp: Any = None, task_vars: dict[str, Any] | None = None ) -> dict[str, Any]: + if VariableLayer is None: + raise AnsibleActionFail( + "applications_carrier needs ansible-core 2.21 or newer, found " + f"{release.__version__}; install the `deploy` extra of " + "pyproject.toml (make install-python)" + ) result = super().run(tmp, task_vars) task_vars = task_vars or {} args = self._task.args or {} diff --git a/plugins/connection/docker_cached.py b/plugins/connection/docker_cached.py index 63676db22a..0f8a04f4b6 100644 --- a/plugins/connection/docker_cached.py +++ b/plugins/connection/docker_cached.py @@ -1,12 +1,14 @@ -"""The community.docker docker connection, asking the Docker CLI for its version once per run. +"""The community.docker docker connection, asking the Docker CLI for its version at the start of a run. The stock plugin builds a fresh connection in every forked worker, and with a remote user set it runs ``docker version`` twice before every module run (the first probe never matches a current Docker). This subclass keeps the answer in a file under the run's ``DEFAULT_LOCAL_TMP``, which every worker inherits from the ``ansible-playbook`` process and which Ansible removes when the run ends, -so only the first task-host of a run pays for the version query. Everything -else (user, become, file transfer, timeouts, environment) is the stock plugin's. +so only the workers that start before the first answer is written pay for the +version query. The file is replaced atomically, so a concurrent writer never +leaves a partial answer. Everything else (user, become, file transfer, +timeouts, environment) is the stock plugin's. """ from __future__ import annotations @@ -24,8 +26,8 @@ DOCUMENTATION = r""" name: docker_cached short_description: Run tasks in docker containers, with the Docker version cached per run description: - - The community.docker docker connection, except that the Docker CLI version is queried once per - ansible-playbook run and shared by every forked worker. + - The community.docker docker connection, except that the Docker CLI version is queried at the start + of an ansible-playbook run and shared by every forked worker that starts after the first answer. options: remote_addr: description: diff --git a/roles/sys-svc-container/tasks/01_assert_requirements.yml b/roles/sys-svc-container/tasks/01_assert_requirements.yml index dc5c78b9e1..9cc6b4550a 100644 --- a/roles/sys-svc-container/tasks/01_assert_requirements.yml +++ b/roles/sys-svc-container/tasks/01_assert_requirements.yml @@ -13,8 +13,7 @@ - name: ✅ Assert docker service exists ansible.builtin.assert: that: - - sys_svc_container_docker_unit.status is defined - - sys_svc_container_docker_unit.status.LoadState != 'not-found' + - sys_svc_container_docker_unit.status.LoadState | default('not-found') != 'not-found' fail_msg: > docker.service is not registered in systemd. Docker engine does not appear to be installed. diff --git a/tests/integration/ansible/action_plugins/test_applications_carrier.py b/tests/integration/ansible/action_plugins/test_applications_carrier.py index cc1fe173aa..8cca57fc74 100644 --- a/tests/integration/ansible/action_plugins/test_applications_carrier.py +++ b/tests/integration/ansible/action_plugins/test_applications_carrier.py @@ -8,8 +8,9 @@ readers consult, and every lookup renders the payload again. These cases run real Ansible with fake ``applications`` and ``users`` lookups in front of the real ``applications_carrier`` action: the carrier must be -visible to a later task's worker with injection on and off and never sit in -``ansible_facts``. The hazard case parks a carrier the old way, as a fact, so +visible to a later task's worker with injection on and off, never sit in +``ansible_facts``, and reach another host through ``hostvars``, the path the +mail provider view reads. The hazard case parks a carrier the old way, as a fact, so the reader guard is shown to turn the invisible carrier into a failed task. """ @@ -136,13 +137,33 @@ HAZARD_PLAY = """--- """ -def _run(workdir: Path, play: str, inject: bool) -> tuple[int, str, dict | None]: +CROSS_HOST_PLAY = f"""--- +- name: Park the carrier on two hosts and read the other host's through hostvars + hosts: all + gather_facts: false + tasks: + - name: Park the carrier + applications_carrier: {{}} + + - name: Read node2's carrier on node1, the way the provider view does + ansible.builtin.copy: + dest: "{{{{ probe_out }}}}" + content: "{{{{ hostvars['node2'][{APPLICATIONS_RENDERED_FACT!r}].key | to_json }}}}" + mode: "0644" + when: inventory_hostname == 'node1' +""" + + +def _run( + workdir: Path, play: str, inject: bool, inventory: str +) -> tuple[int, str, dict | list | None]: """Run *play* once with fact injection set to *inject*. Args: workdir: an empty directory to build the plugins and the play in. play: the playbook text. inject: the value of ``ANSIBLE_INJECT_FACT_VARS``. + inventory: the comma-separated host list passed to ``-i``. Returns: ``(exit code, combined output, probe report or None)``. @@ -175,7 +196,7 @@ def _run(workdir: Path, play: str, inject: bool) -> tuple[int, str, dict | None] [ "ansible-playbook", "-i", - "localhost,", + inventory, "-c", "local", str(workdir / "play.yml"), @@ -194,14 +215,25 @@ def _run(workdir: Path, play: str, inject: bool) -> tuple[int, str, dict | None] @unittest.skipUnless(shutil.which("ansible-playbook"), "ansible-playbook not found") class TestApplicationsCarrierReachesLaterWorkers(unittest.TestCase): - def _play(self, play: str, inject: bool) -> tuple[int, str, dict | None]: + def _play( + self, play: str, inject: bool, inventory: str + ) -> tuple[int, str, dict | list | None]: with tempfile.TemporaryDirectory() as tmp: - return _run(Path(tmp), play, inject) + return _run(Path(tmp), play, inject, inventory) + + def test_another_host_reads_the_carrier_through_hostvars(self): + for inject in (True, False): + with self.subTest(inject=inject): + code, output, report = self._play( + CROSS_HOST_PLAY, inject, inventory="node1,node2," + ) + self.assertEqual(code, 0, output) + self.assertEqual(report, APPLICATIONS_KEY) def test_the_carrier_reaches_later_workers_outside_the_fact_cache(self): for inject in (True, False): with self.subTest(inject=inject): - code, output, report = self._play(CARRIER_PLAY, inject) + code, output, report = self._play(CARRIER_PLAY, inject, "localhost,") self.assertEqual(code, 0, output) self.assertNotIn("template error", output) self.assertEqual( @@ -214,7 +246,7 @@ class TestApplicationsCarrierReachesLaterWorkers(unittest.TestCase): ) def test_a_fact_parked_carrier_is_visible_only_while_facts_are_injected(self): - code, output, report = self._play(HAZARD_PLAY, True) + code, output, report = self._play(HAZARD_PLAY, True, "localhost,") self.assertEqual(code, 0, output) self.assertEqual( report, @@ -228,7 +260,7 @@ class TestApplicationsCarrierReachesLaterWorkers(unittest.TestCase): ) def test_the_reader_fails_on_a_fact_parked_carrier_without_injection(self): - code, output, report = self._play(HAZARD_PLAY, False) + code, output, report = self._play(HAZARD_PLAY, False, "localhost,") self.assertNotEqual(code, 0, output) self.assertIsNone(report) self.assertIn("not visible as a variable", output) diff --git a/tests/integration/ansible/connection_plugins/test_docker_cached.py b/tests/integration/ansible/connection_plugins/test_docker_cached.py index 4a59ee58f1..393a3e8e00 100644 --- a/tests/integration/ansible/connection_plugins/test_docker_cached.py +++ b/tests/integration/ansible/connection_plugins/test_docker_cached.py @@ -6,9 +6,12 @@ gets a fresh connection in a fresh worker. ``docker_cached`` keeps the answer for the run. These cases run the same play through both plugins against a stand-in ``docker`` executable that logs every call and runs the exec payload locally: the cached plugin must make the same exec calls with the same -results, and only the first task-host may query the version. +results, and only the first task-host may query the version. A static case +checks that the options the plugin copies still resolve like those of the +installed stock connection. """ +import ast import json import os import shutil @@ -19,10 +22,15 @@ import unittest from pathlib import Path from typing import ClassVar +from ansible_collections.community.docker.plugins.connection import docker + from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_str from . import PROJECT_ROOT +PLUGIN = PROJECT_ROOT / "plugins" / "connection" / "docker_cached.py" + SHIM = f"""#!{sys.executable} import json import os @@ -215,5 +223,51 @@ class TestDockerCachedConnection(unittest.TestCase): self.assertEqual(files["templated.txt"], "templated node1\n") +def _behaviour(options: dict) -> dict: + """Reduce plugin options to the fields that change how they resolve. + + Args: + options: the ``options`` mapping of a connection plugin's DOCUMENTATION. + + Returns: + Per option its type, default, choices, aliases and the env, ini and + vars sources it reads, without descriptions or ``version_added``. + """ + return { + name: { + "type": spec.get("type"), + "default": spec.get("default"), + "choices": spec.get("choices"), + "aliases": spec.get("aliases"), + "env": [entry["name"] for entry in spec.get("env") or []], + "ini": [ + (entry["section"], entry["key"]) for entry in spec.get("ini") or [] + ], + "vars": [entry["name"] for entry in spec.get("vars") or []], + } + for name, spec in options.items() + } + + +class TestDocumentationMatchesTheStockPlugin(unittest.TestCase): + def test_every_option_resolves_like_the_installed_stock_option(self): + module = ast.parse(read_text(str(PLUGIN))) + ours = next( + node.value.value + for node in module.body + if isinstance(node, ast.Assign) + and any( + isinstance(target, ast.Name) and target.id == "DOCUMENTATION" + for target in node.targets + ) + ) + self.assertEqual( + _behaviour(load_yaml_str(ours)["options"]), + _behaviour(load_yaml_str(docker.DOCUMENTATION)["options"]), + "docker_cached copies the stock connection's options; after a " + "community.docker bump, copy the changed options again", + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/integration/ansible/playbooks/test_play_environment_frozen.py b/tests/integration/ansible/playbooks/test_play_environment_frozen.py index 90de1f4279..604a2deb9c 100644 --- a/tests/integration/ansible/playbooks/test_play_environment_frozen.py +++ b/tests/integration/ansible/playbooks/test_play_environment_frozen.py @@ -7,7 +7,9 @@ end of the play and fails when a source changed after the freeze, because every task after the change ran with the stale value. These cases run real Ansible with the two shared task files: the frozen value -reaches a module's environment, and a source changed mid-play fails the check. +reaches a task, a handler and a delegated task while a task's own +``environment:`` still wins, a source changed mid-play fails the check, and a +``--tags`` run still freezes and checks. """ import shutil @@ -36,35 +38,65 @@ PLAY = f"""--- environment: "{{{{ PLAY_ENVIRONMENT }}}}" pre_tasks: - name: Freeze - ansible.builtin.include_tasks: {FREEZE} + ansible.builtin.include_tasks: + file: {FREEZE} + apply: + tags: [always] + tags: [always] tasks: - name: Report the value a module sees - ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_out }}}}" + ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_dir }}}}/task" + changed_when: true + notify: Report the value a handler sees + tags: [probe] + + - name: Report the value a task with its own environment sees + ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_dir }}}}/override" + environment: + PROBE_VALUE: own changed_when: false + tags: [probe] + + - name: Report the value a delegated task sees + ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_dir }}}}/delegated" + delegate_to: localhost + changed_when: false + tags: [probe] - name: Change the source mid-play ansible.builtin.set_fact: probe_source: changed when: change_source | bool + tags: [probe] + handlers: + - name: Report the value a handler sees + ansible.builtin.shell: printf '%s' "$PROBE_VALUE" > "{{{{ probe_dir }}}}/handler" + changed_when: false post_tasks: - name: Check - ansible.builtin.include_tasks: {CHECK} + ansible.builtin.include_tasks: + file: {CHECK} + apply: + tags: [always] + tags: [always] """ +PROBES = ("task", "override", "delegated", "handler") -def _run(change_source: bool) -> tuple[int, str, str]: + +def _run(change_source: bool, tags: list[str]) -> tuple[int, str, dict[str, str]]: """Run the play once. Args: change_source: whether the play changes the source after the freeze. + tags: the ``--tags`` to pass, none for a full run. Returns: - ``(exit code, combined output, value the module saw)``. + ``(exit code, combined output, value each probe saw)``. """ with tempfile.TemporaryDirectory() as tmp: workdir = Path(tmp) (workdir / "play.yml").write_text(PLAY, encoding="utf-8") - probe_out = workdir / "probe.txt" result = subprocess.run( [ "ansible-playbook", @@ -74,30 +106,49 @@ def _run(change_source: bool) -> tuple[int, str, str]: "local", str(workdir / "play.yml"), "-e", - f"probe_out={probe_out}", + f"probe_dir={workdir}", "-e", f"change_source={change_source}", + *[f"--tags={tag}" for tag in tags], ], cwd=str(workdir), capture_output=True, text=True, check=False, ) - seen = read_text(str(probe_out)) if probe_out.exists() else "" + seen = { + probe: read_text(str(workdir / probe)) + for probe in PROBES + if (workdir / probe).exists() + } return result.returncode, result.stdout + result.stderr, seen @unittest.skipUnless(shutil.which("ansible-playbook"), "ansible-playbook not found") class TestPlayEnvironmentFrozen(unittest.TestCase): - def test_a_module_sees_the_frozen_value_and_the_check_passes(self): - code, output, seen = _run(change_source=False) + def test_tasks_handlers_and_delegates_see_the_frozen_value(self): + code, output, seen = _run(change_source=False, tags=[]) self.assertEqual(code, 0, output) - self.assertEqual(seen, "frozen") + self.assertEqual( + seen, + { + "task": "frozen", + "override": "own", + "delegated": "frozen", + "handler": "frozen", + }, + ) def test_a_source_changed_mid_play_fails_the_check(self): - code, output, seen = _run(change_source=True) + code, output, seen = _run(change_source=True, tags=[]) self.assertNotEqual(code, 0, output) - self.assertEqual(seen, "frozen") + self.assertEqual(seen["task"], "frozen") + self.assertIn("A source of the play environment changed", output) + + def test_a_tagged_run_still_freezes_and_checks(self): + code, output, seen = _run(change_source=True, tags=["probe"]) + self.assertNotEqual(code, 0, output) + self.assertEqual(seen["task"], "frozen") self.assertIn("A source of the play environment changed", output) diff --git a/tests/lint/ansible/test_no_deprecated_ansible_patterns.py b/tests/lint/ansible/test_no_deprecated_ansible_patterns.py index efaf737124..68030a690e 100644 --- a/tests/lint/ansible/test_no_deprecated_ansible_patterns.py +++ b/tests/lint/ansible/test_no_deprecated_ansible_patterns.py @@ -18,36 +18,96 @@ Forbidden (with fix): * top-level injected facts (``ansible_os_family``, ``ansible_eth0`` and every other ``ansible_``) -- ``ansible.cfg`` turns fact injection off, so a top-level fact is undefined. Use ``ansible_facts['']``. Every - ``ansible_`` that is not a magic or connection variable - (``ALLOWED_NAMES``, ``ALLOWED_PREFIXES``) counts as a fact. The ``(?!=)`` + ``ansible_`` that is not a magic variable (``MAGIC_NAMES``) or a + variable a connection, become or shell plugin declares for its options (read + from the plugins' ``DOCUMENTATION``) counts as a fact. The facts that + ``service_facts``, ``package_facts`` and ``getent`` set without the prefix + (``services``, ``packages``, ``getent_``) are flagged when read bare + inside a Jinja expression or a condition line. The ``(?!=(?!=))`` guard skips a literal log label such as ``ansible_virtualization_type={{ ... - }}`` (name glued to ``=``) while still flagging a comparison like - ``ansible_os_family == 'X'`` (space before ``==``). In Python the rule reads + }}`` (name glued to a single ``=``) while still flagging a comparison like + ``ansible_os_family == 'X'`` or ``ansible_os_family=='X'``. In Python the rule reads only subscript and ``.get`` keys, the shape of a variable read. Scans ``.yml`` / ``.yaml`` / ``.j2`` under roles/, tasks/, group_vars/, -playbooks/ and the playbook, and ``.py`` outside tests/ and role ``files/``. Mark a genuine +playbooks/, compose/, inventories/ and both playbooks, and ``.py`` outside +tests/ and role ``files/``. Mark a genuine exception with ``# nocheck: deprecated-ansible`` same-or-above the line. """ from __future__ import annotations +import ast import re import unittest from pathlib import Path +from ansible import constants + from utils.annotations.suppress import is_suppressed_at from utils.cache.files import iter_project_files, read_text +from utils.cache.yaml import load_yaml_str from . import PROJECT_ROOT _RULE = "deprecated-ansible" SCAN_SUFFIXES = (".yml", ".yaml", ".j2", ".py") -_YAML_PREFIXES = ("roles/", "tasks/", "group_vars/", "playbooks/", "playbook.yml") +_YAML_PREFIXES = ( + "roles/", + "tasks/", + "group_vars/", + "playbooks/", + "compose/", + "inventories/", + "playbook.yml", + "playbook-sync.yml", +) _PY_EXCLUDED_PREFIXES = ("tests/",) _PY_EXCLUDED_PARTS = ("/files/",) +_ANSIBLE_PLUGINS = Path(constants.__file__).parent / "plugins" +_PLUGIN_DOC_DIRS = ( + _ANSIBLE_PLUGINS / "connection", + _ANSIBLE_PLUGINS / "become", + _ANSIBLE_PLUGINS / "shell", + _ANSIBLE_PLUGINS / "doc_fragments", + PROJECT_ROOT / "plugins" / "connection", +) -ALLOWED_NAMES = frozenset( + +def declared_plugin_vars(directories: tuple[Path, ...]) -> frozenset[str]: + """Return every ``ansible_*`` variable a plugin option declares under ``vars:``. + + Args: + directories: plugin directories whose ``.py`` files carry a + ``DOCUMENTATION`` string, at module or class level. + + Returns: + The declared variable names. + """ + names: set[str] = set() + for directory in directories: + for path in sorted(directory.glob("*.py")): + for node in ast.walk(ast.parse(read_text(str(path)))): + if not ( + isinstance(node, ast.Assign) + and any( + isinstance(target, ast.Name) and target.id == "DOCUMENTATION" + for target in node.targets + ) + and isinstance(node.value, ast.Constant) + and isinstance(node.value.value, str) + ): + continue + options = (load_yaml_str(node.value.value) or {}).get("options") or {} + for option in options.values(): + for var in (option or {}).get("vars") or []: + name = var.get("name", "") if isinstance(var, dict) else "" + if name.startswith("ansible_"): + names.add(name) + return frozenset(names) + + +MAGIC_NAMES = frozenset( { "ansible_facts", "ansible_local", @@ -80,29 +140,27 @@ ALLOWED_NAMES = frozenset( "ansible_failed_task", "ansible_failed_result", "ansible_job_id", - "ansible_host", - "ansible_port", - "ansible_user", - "ansible_password", - "ansible_connection", - "ansible_private_key_file", - "ansible_pipelining", - "ansible_timeout", - "ansible_remote_tmp", - "ansible_docker_extra_args", } ) -ALLOWED_PREFIXES = ( - "ansible_become", - "ansible_ssh_", - "ansible_shell_", - "ansible_winrm_", - "ansible_paramiko_", +ALLOWED_NAMES = ( + MAGIC_NAMES + | declared_plugin_vars(_PLUGIN_DOC_DIRS) + | frozenset( + name for names in constants.MAGIC_VARIABLE_MAPPING.values() for name in names + ) ) ALLOWED_SUFFIXES = ("_interpreter",) -_YAML_NAME = re.compile(r"\bansible_[A-Za-z0-9_]+\b(?!=)") +_YAML_NAME = re.compile(r"\bansible_[A-Za-z0-9_]+\b(?!=(?!=))") _PY_NAME = re.compile(r"(?:\[\s*|\.get\(\s*)[\"'](ansible_[A-Za-z0-9_]+)[\"']") +_BARE_FACT = re.compile( + r"(?.*)$" +) _PATTERNS: tuple[tuple[str, re.Pattern[str], str], ...] = ( ( @@ -117,6 +175,10 @@ _PATTERNS: tuple[tuple[str, re.Pattern[str], str], ...] = ( ), ) _FACT_FIX = "top-level injected fact, undefined with fact injection off -> use ansible_facts['']" +_BARE_FACT_FIX = ( + "fact without the ansible_ prefix (service_facts, package_facts, getent), " + "undefined with fact injection off -> use ansible_facts['']" +) def is_fact_name(name: str) -> bool: @@ -126,22 +188,20 @@ def is_fact_name(name: str) -> bool: name: an ``ansible_`` identifier. Returns: - ``True`` when the name is neither allowed explicitly nor by prefix or suffix. + ``True`` when the name is neither allowed explicitly nor by suffix. """ - return not ( - name in ALLOWED_NAMES - or name.startswith(ALLOWED_PREFIXES) - or name.endswith(ALLOWED_SUFFIXES) - ) + return not (name in ALLOWED_NAMES or name.endswith(ALLOWED_SUFFIXES)) -def scan_text(text: str, python: bool) -> list[str]: +def scan_text(text: str, python: bool, template: bool = False) -> list[str]: """Return one issue line per forbidden construct in *text*. Args: text: the file content. python: read *text* as Python (subscript and ``.get`` keys only) instead of YAML or Jinja. + template: read *text* as a Jinja template, whose list items are output, + not conditions. """ lines = text.splitlines() out: list[str] = [] @@ -159,6 +219,16 @@ def scan_text(text: str, python: bool) -> list[str]: out.append( f"line {idx}: [injected-fact] {line.strip()} -> {_FACT_FIX}" ) + if python or line.lstrip().startswith("#"): + continue + expressions = _JINJA_EXPR.findall(line) + condition = None if template else _CONDITION.match(line) + if condition: + expressions.append(condition.group("expr")) + if any(_BARE_FACT.search(expression) for expression in expressions): + out.append( + f"line {idx}: [injected-bare-fact] {line.strip()} -> {_BARE_FACT_FIX}" + ) return out @@ -181,7 +251,9 @@ class TestNoDeprecatedAnsiblePatterns(unittest.TestCase): text = read_text(str(abs_path)) except (OSError, UnicodeDecodeError): continue - issues = scan_text(text, python=rel.endswith(".py")) + issues = scan_text( + text, python=rel.endswith(".py"), template=rel.endswith(".j2") + ) if issues: offenders[Path(abs_path)] = issues @@ -197,15 +269,25 @@ class TestNoDeprecatedAnsiblePatterns(unittest.TestCase): def test_a_planted_top_level_fact_read_is_caught(self) -> None: planted = { "when: ansible_os_family == 'Debian'": False, + "when: ansible_os_family=='Debian'": False, "{{ ansible_eth0.ipv4.address }}": False, "{{ hostvars[h]['ansible_default_ipv4'] }}": False, 'distro = task_vars.get("ansible_distribution")': True, 'facts = task_vars["ansible_mounts"]': True, + "when: services['docker.service'] is defined": False, + "- packages['nfs-ganesha'] | first": False, + "- getent_group is defined": False, + "{{ getent_passwd.nixbld1[1] }}": False, } for line, python in planted.items(): with self.subTest(line=line): self.assertTrue(scan_text(line, python=python), line) + def test_every_option_var_of_the_lab_connection_is_allowed(self) -> None: + for name in ("ansible_docker_extra_env", "ansible_docker_working_dir"): + with self.subTest(name=name): + self.assertEqual(scan_text(f"{name}: x", python=False), [], name) + def test_magic_connection_and_namespaced_reads_pass(self) -> None: clean = { "when: ansible_facts['os_family'] == 'Debian'": False, @@ -215,6 +297,9 @@ class TestNoDeprecatedAnsiblePatterns(unittest.TestCase): 'facts = task_vars.get("ansible_facts") or {}': True, 'host = hostvars[h].get("ansible_host")': True, "ansible_playbook = shutil.which('ansible-playbook')": True, + "when: ansible_facts.services['docker.service'] is defined": False, + "{{ lookup('config', application_id, 'services.sso.enabled') }}": False, + "- name: install language packages": False, } for line, python in clean.items(): with self.subTest(line=line): diff --git a/tests/unit/python/cli/administration/deploy/dedicated/test_runner.py b/tests/unit/python/cli/administration/deploy/dedicated/test_runner.py index c328f9b9fa..f2366423ef 100644 --- a/tests/unit/python/cli/administration/deploy/dedicated/test_runner.py +++ b/tests/unit/python/cli/administration/deploy/dedicated/test_runner.py @@ -1,5 +1,6 @@ from __future__ import annotations +import importlib.metadata import io import json import subprocess @@ -365,6 +366,25 @@ class TestDeployAnsiblePlaybook(unittest.TestCase): self.assertIn(absent, stderr.getvalue()) self.assertNotIn("PyYAML", stderr.getvalue()) + def test_exits_naming_a_deploy_pin_the_interpreter_carries_at_another_version( + self, + ): + installed = importlib.metadata.version("PyYAML") + pinned = f"PyYAML=={installed}.post999" + repo_root, bindir = self._checkout( + [pinned, f"ruamel.yaml=={importlib.metadata.version('ruamel.yaml')}"], + with_playbook=True, + ) + stderr = io.StringIO() + with ( + unittest.mock.patch.object(runner.sys, "stderr", stderr), + self.assertRaises(SystemExit) as ctx, + ): + self._resolve(repo_root, bindir) + self.assertEqual(ctx.exception.code, 1) + self.assertIn(f"{pinned} (installed: {installed})", stderr.getvalue()) + self.assertNotIn("ruamel.yaml", stderr.getvalue()) + def test_exits_when_no_ansible_playbook_sits_beside_the_interpreter(self): repo_root, bindir = self._checkout(["PyYAML"], with_playbook=False) with ( diff --git a/tests/unit/python/plugins/action/test_applications_carrier.py b/tests/unit/python/plugins/action/test_applications_carrier.py index ea555f9af3..cfd2560f3f 100644 --- a/tests/unit/python/plugins/action/test_applications_carrier.py +++ b/tests/unit/python/plugins/action/test_applications_carrier.py @@ -235,6 +235,18 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): ): action.run(task_vars={}) + def test_an_ansible_core_without_variable_layers_fails_with_its_version(self): + action = _make_action(_FakeTask(args={"clear": True})) + with ( + patch("plugins.action.applications_carrier.VariableLayer", None), + patch("plugins.action.applications_carrier.release.__version__", "2.20.9"), + self.assertRaisesRegex( + AnsibleActionFail, r"2\.21 or newer, found 2\.20\.9" + ), + ): + action.run(task_vars={}) + self.assertEqual(action.registered, {}) + def test_clear_drops_every_carrier_without_rendering(self): applications, users, loader = _lookups() action = _make_action(_FakeTask(args={"clear": True})) diff --git a/utils/cache/README.md b/utils/cache/README.md index eda1e48f4d..2049c28142 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -86,7 +86,7 @@ flowchart TD proc -.->|"TRIP-WIRE: read BEFORE the
host's own carrier, so an inherited
entry outranks it"| fact render -.->|"TRIP-WIRE: main process renders
task names for one host; forked
workers inherit that entry"| proc - key -.->|"TRIP-WIRE: carrier.py:121 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact + key -.->|"TRIP-WIRE: carrier.py:136 stringifies
only one side, so a non-scalar key
part silently never matches again"| fact ``` The key covers `group_names`. `domains.py` derives from the applications view and shares that dependency; `users` reads `group_names` nowhere. diff --git a/utils/cache/carrier.py b/utils/cache/carrier.py index 7090bb85b4..41c168c7d5 100644 --- a/utils/cache/carrier.py +++ b/utils/cache/carrier.py @@ -116,9 +116,11 @@ def _carried( carrier = variables.get(fact) if fact not in variables and fact in (variables.get("ansible_facts") or {}): raise CarrierInvisibleError( - f"{fact} is parked in the fact cache but not visible as a variable; " - "park it with applications_carrier, which registers it outside the " - "fact cache, or every lookup renders the payload again" + f"{fact} is parked in the fact cache but not visible as a variable, " + "so every lookup would render the payload again; remove the task " + "that returns it as ansible_facts, or run " + "'applications_carrier: {clear: true}' before parking it again with " + "applications_carrier, which registers it outside the fact cache" ) if not isinstance(carrier, Mapping): return None From b80da444a12904fbcf488f95b96efc14d4a65472 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Fri, 20 Nov 2026 03:04:07 +0400 Subject: [PATCH 14/65] fix(sys-ctl-hlth-runtime): skip a container that stopped before its PHP probe A swarm task that recycles itself, such as the Shopware worker, can stop between the container listing and the php exec. The probe error then failed the whole scan. A failed probe now asks whether the container still runs: a stopped one is reported as info, a running one still fails. Co-Authored-By: Claude Opus 5.5 --- .../files/python/script.py | 40 +++++++++++++++++- .../sys-ctl-hlth-runtime/files/test_script.py | 41 ++++++++++++++++++- 2 files changed, 77 insertions(+), 4 deletions(-) diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index 27761cdd63..a0b2f11b51 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -459,17 +459,50 @@ def probe_php(container_id: str) -> PhpProbe | None: return parse_probe(result.stdout) +def container_running(container_id: str) -> bool: + """Tell whether a container still runs. + + Args: + container_id: the container to inspect. + + Returns: + ``True`` while ``container inspect`` reports it running, ``False`` + once it stopped or is gone. + """ + result = subprocess.run( + [ + "container", + "inspect", + "--type", + "container", + "--format", + "{{.State.Running}}", + container_id, + ], + capture_output=True, + text=True, + check=False, + timeout=EXEC_TIMEOUT_SECONDS, + ) + return result.returncode == 0 and result.stdout.strip() == "true" + + def check( containers: list[Container], hardened: dict, probe, + running, ) -> tuple[list[str], list[str]]: """Evaluate the PHP hardening of every container. + A container that stopped between the listing and its probe, as a swarm + task that recycles itself does, is reported as info, not as a failure. + Args: containers: the running containers. hardened: ``{stack: [service, ...]}`` that must run hardened PHP. probe: callable returning a :class:`PhpProbe` or ``None`` per id. + running: callable telling whether a container id still runs. Returns: ``(failures, infos)`` as printable lines. @@ -486,7 +519,10 @@ def check( try: result = probe(container.id) except ProbeError as exc: - failures.append(f"{container.name}: {exc}") + if running(container.id): + failures.append(f"{container.name}: {exc}") + else: + infos.append(f"{container.name}: stopped before its probe, skipped") continue if result is None: if must_harden: @@ -2248,7 +2284,7 @@ def main(argv=None) -> int: except (subprocess.TimeoutExpired, subprocess.CalledProcessError) as exc: print(f"❌ listing the running containers failed: {exc}") return 1 - failures, infos = check(containers, hardened, probe_php) + failures, infos = check(containers, hardened, probe_php, container_running) remote = host_network_mounts() if "host" in config.targets else [] infos += [ f"host scan skips the network or automounted filesystem at {printable(point)}" diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py index 3d9ffff556..8569b60c0c 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py @@ -2056,7 +2056,12 @@ def _probe(expose_php=False, upload_progress=False): def _check(containers, probes, hardened): - return SCRIPT.check(containers, hardened, lambda container_id: probes[container_id]) + return SCRIPT.check( + containers, + hardened, + lambda container_id: probes[container_id], + lambda _container_id: True, + ) class TestCheck(TestCase): @@ -2112,7 +2117,7 @@ class TestCheck(TestCase): failures, ["wp: declares php_hardening but has no php to verify it"] ) - def test_a_probe_error_in_a_hardened_stack_is_a_failure(self): + def test_a_probe_error_in_a_running_container_is_a_failure(self): def broken(_container_id): raise SCRIPT.ProbeError("php exited 255: boom") @@ -2120,9 +2125,41 @@ class TestCheck(TestCase): [_container("wp", "wordpress", "wordpress")], {"wordpress": ["wordpress"]}, broken, + lambda _container_id: True, ) self.assertEqual(failures, ["wp: php exited 255: boom"]) + def test_a_container_that_stopped_before_its_probe_is_info_only(self): + def gone(_container_id): + raise SCRIPT.ProbeError( + "php exited 1: Error response from daemon: container x is not running" + ) + + failures, infos = SCRIPT.check( + [_container("worker", "shopware", "worker")], + {"shopware": ["worker"]}, + gone, + lambda _container_id: False, + ) + self.assertEqual(failures, []) + self.assertEqual(infos, ["worker: stopped before its probe, skipped"]) + + +class TestContainerRunning(TestCase): + def _running(self, returncode, stdout): + completed = SimpleNamespace(returncode=returncode, stdout=stdout, stderr="") + with mock.patch.object(SCRIPT.subprocess, "run", return_value=completed): + return SCRIPT.container_running("abc") + + def test_a_running_container_runs(self): + self.assertTrue(self._running(0, "true\n")) + + def test_a_stopped_container_does_not_run(self): + self.assertFalse(self._running(0, "false\n")) + + def test_a_removed_container_does_not_run(self): + self.assertFalse(self._running(1, "")) + class TestProbePhp(TestCase): def _run(self, returncode, stdout="", stderr=""): From 0180935e1dff1762af0050b16760a2cea60dac60 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Fri, 20 Nov 2026 03:04:07 +0400 Subject: [PATCH 15/65] fix(svc-ai-s1): wait for the decider's healthcheck before the warm-up On a slow runner the model server was not listening yet when the warm-up ran, and its five tries ten seconds apart ran out. The role now waits until the container's healthcheck reports healthy, sized through the timeout lookup, before it sends the warm-up request. Co-Authored-By: Claude Opus 5.5 --- roles/svc-ai-s1/tasks/01_manager_ops.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/roles/svc-ai-s1/tasks/01_manager_ops.yml b/roles/svc-ai-s1/tasks/01_manager_ops.yml index fd0fa9aded..b42e0b616f 100644 --- a/roles/svc-ai-s1/tasks/01_manager_ops.yml +++ b/roles/svc-ai-s1/tasks/01_manager_ops.yml @@ -6,6 +6,18 @@ resolve_output_prefix: S1 resolve_compose_cid: "{{ S1_CONTAINER }}" +- name: "⏳ Wait until the decider answers its healthcheck" + ansible.builtin.command: >- + container inspect --type container + --format={% raw %}{{.State.Health.Status}}{% endraw %} + {{ S1_LOCAL_CID }} + register: s1_health_result + retries: "{{ lookup('timeout', 600) | int // 5 }}" + delay: 5 + until: (s1_health_result.stdout | trim) == 'healthy' + changed_when: false + delegate_to: "{{ S1_HOST_NODE }}" + - name: "🔥 Warm the decider so the first route is not a cold load" ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec -i {{ S1_LOCAL_CID | quote }} python3 -c {{ lookup('file', lookup('path_absolute', 'roles/svc-ai-s1/files/python/warm_model.py')) | quote }} From dbf500def39d90800117e559fd1ee83a37cbf555 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Fri, 20 Nov 2026 03:09:52 +0400 Subject: [PATCH 16/65] fix(sys-ctl-hlth-runtime): word the running check's docstring for the inspect lint Co-Authored-By: Claude Opus 5.5 --- roles/sys-ctl-hlth-runtime/files/python/script.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index a0b2f11b51..59af339ecb 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -466,7 +466,7 @@ def container_running(container_id: str) -> bool: container_id: the container to inspect. Returns: - ``True`` while ``container inspect`` reports it running, ``False`` + ``True`` while the container engine reports it running, ``False`` once it stopped or is gone. """ result = subprocess.run( From 95380106f32324d02c55ba5ce03a10f8cf6675ae Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Fri, 20 Nov 2026 03:30:56 +0400 Subject: [PATCH 17/65] fix(sys-ctl-hlth-runtime): count an engine that does not answer as a running container container_running runs inside the probe's error branch, so a timeout there crashed the scan. It now reports the container as running, which keeps the probe error a failure. Co-Authored-By: Claude Opus 5.5 --- .../files/python/script.py | 38 ++++++++++--------- .../sys-ctl-hlth-runtime/files/test_script.py | 5 +++ 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index 59af339ecb..bb6f05a8a9 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -466,24 +466,28 @@ def container_running(container_id: str) -> bool: container_id: the container to inspect. Returns: - ``True`` while the container engine reports it running, ``False`` - once it stopped or is gone. + ``True`` while the container engine reports it running or does not + answer in time, so a probe error then stays a failure; ``False`` once + it stopped or is gone. """ - result = subprocess.run( - [ - "container", - "inspect", - "--type", - "container", - "--format", - "{{.State.Running}}", - container_id, - ], - capture_output=True, - text=True, - check=False, - timeout=EXEC_TIMEOUT_SECONDS, - ) + try: + result = subprocess.run( + [ + "container", + "inspect", + "--type", + "container", + "--format", + "{{.State.Running}}", + container_id, + ], + capture_output=True, + text=True, + check=False, + timeout=EXEC_TIMEOUT_SECONDS, + ) + except subprocess.TimeoutExpired: + return True return result.returncode == 0 and result.stdout.strip() == "true" diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py index 8569b60c0c..d55f57a126 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py @@ -2160,6 +2160,11 @@ class TestContainerRunning(TestCase): def test_a_removed_container_does_not_run(self): self.assertFalse(self._running(1, "")) + def test_an_engine_that_does_not_answer_counts_as_running(self): + timeout = SCRIPT.subprocess.TimeoutExpired(cmd="container", timeout=1) + with mock.patch.object(SCRIPT.subprocess, "run", side_effect=timeout): + self.assertTrue(SCRIPT.container_running("abc")) + class TestProbePhp(TestCase): def _run(self, returncode, stdout="", stderr=""): From f722dd0ee86bccd331c5f537a21420dcd7f3cff7 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Fri, 20 Nov 2026 04:57:24 +0400 Subject: [PATCH 18/65] fix(sys-svc-container): set the run-once flag before the health roles load sys-svc-container shoots sys-ctl-hlth-runtime through list_or_shoot, and sys-ctl-hlth-runtime includes sys-svc-container while run_once_sys_svc_container is still unset. Outside a service-loader preload, such as the docs host-install replay of svc-opt-ssd-hdd, that recursed until Python's limit. The flag is now the first task of 00_core, as test_service_core_first_task_run_once already requires for service roles. Co-Authored-By: Claude Opus 5.5 --- roles/sys-svc-container/tasks/00_core.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/roles/sys-svc-container/tasks/00_core.yml b/roles/sys-svc-container/tasks/00_core.yml index 6c62a889a0..763e59c675 100644 --- a/roles/sys-svc-container/tasks/00_core.yml +++ b/roles/sys-svc-container/tasks/00_core.yml @@ -1,4 +1,6 @@ --- +- include_tasks: utils/once/flag.yml + - name: 📖 Read PID 1 process name ansible.builtin.slurp: src: /proc/1/comm @@ -144,5 +146,3 @@ - sys-ctl-hlth-container - sys-ctl-hlth-runtime - sys-ctl-hlth-volumes - -- include_tasks: utils/once/flag.yml From c66b3759abec0ad79229c3bbf4fa4477410d759f Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:53:19 +0000 Subject: [PATCH 19/65] update(images): update Docker image versions (svc-db-postgres) --- roles/svc-db-postgres/meta/services.yml | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/roles/svc-db-postgres/meta/services.yml b/roles/svc-db-postgres/meta/services.yml index bacf283b3c..b2b0f5fc4f 100644 --- a/roles/svc-db-postgres/meta/services.yml +++ b/roles/svc-db-postgres/meta/services.yml @@ -14,7 +14,7 @@ postgres: test: ["CMD-SHELL", "pg_isready -h 127.0.0.1"] image: postgres name: postgres - version: "18" + version: "19" custom: true min_storage: 419MB backup: @@ -33,11 +33,6 @@ postgres: internal: postgres: 5432 lifecycle: beta - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "18" - until: 2026-11-30 # nocheck: variants-coverage — sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in tor: bond: 0.5 From aecd3ec3dc12409c9d81cf6400091fca6c6f47ee Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:54:38 +0000 Subject: [PATCH 20/65] update(images): update Docker image versions (web-app-stalwart) --- roles/web-app-stalwart/meta/services.yml | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index 61b9b64764..de7d0371be 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -101,16 +101,11 @@ postgres: enabled: true # nocheck: dynamic-flag shared: "{{ ('svc-db-postgres' in group_names) and (IS_COMPOSE_MODE) }}" image: postgres - version: "18" + version: "19" cpus: "0.8" mem_reservation: 1g mem_limit: 2g pids_limit: 512 - security: - suppressions: - # nocheck: cve upstream tag ships fixable CRITICAL CVEs; lift it once a rebuilt tag lands - - image_tag: "18" - until: 2026-11-30 # nocheck: dynamic-flag — role-local sub-component, always deployed with the stack # nocheck: playwright-service-flag — internal sub-component webmail: From b8ae55f3b8e780e22563315f62d9da9d145a23f3 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Fri, 20 Nov 2026 13:17:53 +0400 Subject: [PATCH 21/65] fix(sys-ctl-hlth-runtime): retry the directory creates that race on shared lab storage In the swarm lab every node creates the report and cache directories at the same moment, and the path is shared between them. The node that loses the race gets EEXIST from the file module while its NFS attribute cache still says the directory is missing, and the deploy failed. A short retry sees the directory and succeeds; on a single host it never triggers. Co-Authored-By: Claude Opus 5.5 --- roles/sys-ctl-hlth-runtime/tasks/00_core.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/roles/sys-ctl-hlth-runtime/tasks/00_core.yml b/roles/sys-ctl-hlth-runtime/tasks/00_core.yml index 41a2d5d593..e7362e3747 100644 --- a/roles/sys-ctl-hlth-runtime/tasks/00_core.yml +++ b/roles/sys-ctl-hlth-runtime/tasks/00_core.yml @@ -15,6 +15,10 @@ path: "{{ HEALTH_RUNTIME_CACHE_DIR }}" state: directory mode: "0700" + register: sys_ctl_hlth_runtime_cache_dir + retries: 3 + delay: 2 + until: sys_ctl_hlth_runtime_cache_dir is succeeded - name: 📁 Create the report and findings log directories ansible.builtin.file: @@ -24,6 +28,10 @@ loop: - "{{ DIR_HEALTH_RUNTIME_REPORT }}" - "{{ DIR_HEALTH_RUNTIME_LOG }}" + register: sys_ctl_hlth_runtime_dirs + retries: 3 + delay: 2 + until: sys_ctl_hlth_runtime_dirs is succeeded - name: 📁 Create the node-exporter textfile directory ansible.builtin.file: From 8251b2f55ec686e826ff5b3d35aec8c05c43822d Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Fri, 20 Nov 2026 15:37:31 +0400 Subject: [PATCH 22/65] test(lint): forbid overriding a source of the frozen play environment The end-of-play check only reports a changed source after every later task ran with a stale value. The lint reads the root variables of PLAY_ENVIRONMENT_SOURCE from playbook.yml and fails on any set_fact, vars, register, include_vars name, loop_var or role vars/ file that assigns one. group_vars and inventory definitions and task-level environment keys stay allowed. Co-Authored-By: Claude Opus 5.5 --- ...play_environment_sources_not_overridden.py | 191 ++++++++++++++++++ 1 file changed, 191 insertions(+) create mode 100644 tests/lint/ansible/variables/test_play_environment_sources_not_overridden.py diff --git a/tests/lint/ansible/variables/test_play_environment_sources_not_overridden.py b/tests/lint/ansible/variables/test_play_environment_sources_not_overridden.py new file mode 100644 index 0000000000..2cd8fdd8f2 --- /dev/null +++ b/tests/lint/ansible/variables/test_play_environment_sources_not_overridden.py @@ -0,0 +1,191 @@ +"""Lint: no task, block, role or play may override a source of the play environment. + +``playbook.yml`` renders ``PLAY_ENVIRONMENT_SOURCE`` once per host +(``tasks/utils/play/environment/freeze.yml``) and every later task inherits +that frozen mapping. A ``set_fact``, ``vars:``, ``register``, ``include_vars``, +``loop_var`` or role ``vars/`` file that assigns one of the variables the +mapping templates from would leave the frozen environment stale for the rest +of the play; ``check.yml`` only catches that at the end of the run. + +The protected names are the root variables of every ``{{ ... }}`` expression +in ``PLAY_ENVIRONMENT_SOURCE``, read from ``playbook.yml`` itself. Their +definitions in ``group_vars/`` and ``inventories/`` are the intended sources +and are not scanned, nor are role ``defaults/`` (lower precedence than +``group_vars``). Task-level ``environment:`` keys that set a process variable +of the same spelling (``CA_CONTAINER_ENABLED: "0"``) are not Ansible variables +and stay allowed. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path +from typing import Any + +from utils.cache.files import iter_project_files, read_text +from utils.cache.yaml import load_yaml_str, load_yaml_tagged +from utils.roles.mapping import ROLE_FILE_TASKS_MAIN, ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +PLAYBOOK = PROJECT_ROOT / "playbook.yml" +SCAN_SUFFIXES = (".yml", ".yaml") +SCAN_PREFIXES = ("roles/", "tasks/", "playbooks/", "playbook.yml", "playbook-sync.yml") +SKIPPED_PARTS = frozenset({"defaults", "templates", "files"}) +SET_FACT_KEYS = frozenset( + {"set_fact", "ansible.builtin.set_fact", "ansible.legacy.set_fact"} +) +INCLUDE_VARS_KEYS = frozenset( + {"include_vars", "ansible.builtin.include_vars", "ansible.legacy.include_vars"} +) +PLANTED_TASKS = f"roles/x/{ROLE_FILE_TASKS_MAIN}" +PLANTED_VARS = f"roles/x/{ROLE_FILE_VARS_MAIN}" +_EXPRESSION = re.compile(r"\{\{\s*([A-Za-z_]\w*)") + + +def protected_names(playbook_text: str) -> frozenset[str]: + """Return the root variables ``PLAY_ENVIRONMENT_SOURCE`` templates from. + + Args: + playbook_text: content of ``playbook.yml``. + + Returns: + Every identifier that opens a ``{{ ... }}`` expression in a value of + the first play's ``PLAY_ENVIRONMENT_SOURCE``. + """ + plays = load_yaml_str(playbook_text) + source = plays[0]["vars"]["PLAY_ENVIRONMENT_SOURCE"] + return frozenset( + match.group(1) + for value in source.values() + for match in _EXPRESSION.finditer(str(value)) + ) + + +def _assigned_names(node: Any) -> list[tuple[str, str]]: + found: list[tuple[str, str]] = [] + if isinstance(node, list): + for item in node: + found.extend(_assigned_names(item)) + return found + if not isinstance(node, dict): + return found + for key, value in node.items(): + if key in SET_FACT_KEYS and isinstance(value, dict): + found.extend(("set_fact", name) for name in value) + elif key == "vars" and isinstance(value, dict): + found.extend(("vars", name) for name in value) + elif key == "register" and isinstance(value, str): + found.append(("register", value)) + elif key in INCLUDE_VARS_KEYS and isinstance(value, dict) and "name" in value: + found.append(("include_vars", str(value["name"]))) + elif key == "loop_control" and isinstance(value, dict) and "loop_var" in value: + found.append(("loop_var", str(value["loop_var"]))) + found.extend(_assigned_names(value)) + return found + + +def scan(relative_path: str, data: Any, protected: frozenset[str]) -> list[str]: + """Return one message per assignment of a protected name in a parsed file. + + Args: + relative_path: repository-relative path, used to detect role ``vars/`` files. + data: the parsed YAML document. + protected: names that must not be assigned. + + Returns: + ``": assigns "`` for every offending assignment. + """ + assignments = _assigned_names(data) + parts = Path(relative_path).parts + if ( + len(parts) > 2 + and parts[0] == "roles" + and parts[2] == "vars" + and isinstance(data, dict) + ): + assignments.extend(("role vars", name) for name in data) + return [ + f"{relative_path}: {kind} assigns {name}" + for kind, name in assignments + if name in protected + ] + + +def _target_files() -> list[str]: + root = f"{PROJECT_ROOT}/" + targets = [] + for absolute in iter_project_files(extensions=SCAN_SUFFIXES, exclude_tests=True): + relative = absolute.removeprefix(root) + if relative.startswith(SCAN_PREFIXES) and not SKIPPED_PARTS.intersection( + Path(relative).parts + ): + targets.append(relative) + return sorted(targets) + + +class TestPlayEnvironmentSourcesNotOverridden(unittest.TestCase): + def setUp(self) -> None: + self.protected = protected_names(read_text(str(PLAYBOOK))) + + def test_the_protected_names_come_from_the_playbook(self) -> None: + self.assertTrue( + {"CA_TRUST", "CA_CONTAINER_ENABLED", "BUILDKIT_ENABLED"} <= self.protected, + sorted(self.protected), + ) + + def test_no_file_overrides_a_play_environment_source(self) -> None: + offenders: list[str] = [] + for relative in _target_files(): + offenders.extend( + scan( + relative, load_yaml_tagged(PROJECT_ROOT / relative), self.protected + ) + ) + self.assertEqual( + offenders, + [], + "These assignments change a variable PLAY_ENVIRONMENT_SOURCE (playbook.yml) " + "renders from, so the frozen play environment goes stale. Set the value in " + "group_vars or the inventory instead, or pass a process variable through the " + "task's environment: block:\n" + "\n".join(offenders), + ) + + def test_planted_overrides_are_flagged(self) -> None: + planted = load_yaml_str( + "- set_fact:\n CA_TRUST: {}\n" + "- block:\n - debug: {msg: x}\n vars:\n BUILDKIT_ENABLED: true\n" + "- command: id\n register: CA_CONTAINER_ENABLED\n" + "- include_vars: {file: x.yml, name: CA_TRUST}\n" + "- debug: {msg: x}\n loop: [1]\n loop_control: {loop_var: BUILDKIT_ENABLED}\n" + "- include_role: {name: x}\n vars: {CA_CONTAINER_ENABLED: 0}\n" + ) + self.assertEqual( + scan(PLANTED_TASKS, planted, self.protected), + [ + f"{PLANTED_TASKS}: set_fact assigns CA_TRUST", + f"{PLANTED_TASKS}: vars assigns BUILDKIT_ENABLED", + f"{PLANTED_TASKS}: register assigns CA_CONTAINER_ENABLED", + f"{PLANTED_TASKS}: include_vars assigns CA_TRUST", + f"{PLANTED_TASKS}: loop_var assigns BUILDKIT_ENABLED", + f"{PLANTED_TASKS}: vars assigns CA_CONTAINER_ENABLED", + ], + ) + + def test_a_role_vars_file_is_flagged(self) -> None: + self.assertEqual( + scan(PLANTED_VARS, {"CA_TRUST": {}}, self.protected), + [f"{PLANTED_VARS}: role vars assigns CA_TRUST"], + ) + + def test_a_task_environment_key_is_allowed(self) -> None: + clean = load_yaml_str( + "- command: id\n environment:\n CA_CONTAINER_ENABLED: '0'\n" + "- set_fact:\n OTHER: '{{ CA_TRUST }}'\n" + ) + self.assertEqual(scan(PLANTED_TASKS, clean, self.protected), []) + + +if __name__ == "__main__": + unittest.main() From 28e0a3d37e8c0fae78fd3a41a11d2b67a79297ae Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 20 Nov 2026 22:01:27 +0000 Subject: [PATCH 23/65] fix(tests): import services_overrides_for_round from its public home MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit test_covered_rows_are_deployed imported the private alias _build_services_overrides_for_round from cli.administration.deploy.development.inventory, which no longer exists, so test-integration failed at collection with ImportError. It now imports services_overrides_for_round from utils.roles.applications.variants (same keyword-only signature). Proof: on the main-merged tree all 7 tests pass; the unchanged file fails with the ImportError (negative control); ruff, the import lint and MEDUSA are clean. 🎯 Fix: 93 % 💥 Break: 2 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 91 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../meta/workflows/test_covered_rows_are_deployed.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/integration/meta/workflows/test_covered_rows_are_deployed.py b/tests/integration/meta/workflows/test_covered_rows_are_deployed.py index e8254e33ec..027561df36 100644 --- a/tests/integration/meta/workflows/test_covered_rows_are_deployed.py +++ b/tests/integration/meta/workflows/test_covered_rows_are_deployed.py @@ -18,9 +18,6 @@ import os import unittest import unittest.mock as mock -from cli.administration.deploy.development.inventory import ( - _build_services_overrides_for_round as build_services_overrides_for_round, -) from cli.administration.deploy.development.inventory import ( plan_dev_inventory_matrix, prune_orphans_after_disable, @@ -34,6 +31,7 @@ from utils.cache.applications import get_variants from utils.cache.files import PROJECT_ROOT from utils.github.variant import network from utils.github.variant.pools import MODES +from utils.roles.applications.variants import services_overrides_for_round from utils.tests.swarm.derive_includes import derive_includes ROLES = PROJECT_ROOT / "roles" @@ -136,7 +134,7 @@ def _deployed(app: str, index: int, mode: str, tokens: str) -> frozenset[str]: include=include, primary_apps=[app] if app not in disabled else [], disabled_app_ids=disabled, - services_overrides=build_services_overrides_for_round( + services_overrides=services_overrides_for_round( roles_dir=str(ROLES), round_index=index, primary_app_variants={app: variants.get(app, index)}, From 20457d0f181b55c44cb67128908aabed8adaaed0 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:47:24 +0000 Subject: [PATCH 24/65] update(images): update Docker image versions (svc-ai-ollama) --- roles/svc-ai-ollama/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index 5959f27c9c..6d3220e56d 100644 --- a/roles/svc-ai-ollama/meta/services.yml +++ b/roles/svc-ai-ollama/meta/services.yml @@ -13,7 +13,7 @@ ollama: backup: stop_required: false image: ollama/ollama - version: 0.40.16 + version: 0.40.17 name: ollama gpu: true min_storage: 3473MB From da9df1ef59c694a7ac6586738f09341354508b5a Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:04:05 +0000 Subject: [PATCH 25/65] update(images): update Docker image versions (svc-ai-agent-broker) --- roles/svc-ai-agent-broker/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/svc-ai-agent-broker/meta/services.yml b/roles/svc-ai-agent-broker/meta/services.yml index b732689686..bde8646779 100644 --- a/roles/svc-ai-agent-broker/meta/services.yml +++ b/roles/svc-ai-agent-broker/meta/services.yml @@ -50,7 +50,7 @@ socket-proxy: bond: 1 enabled: true image: wollomatic/socket-proxy - version: 1.13.2 + version: 1.14.0 name: agent-socket-proxy cpus: "0.25" mem_reservation: 16m From 8d1c68c3f1b97fecf4f9e87dbb23f2d7b30e7d1d Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 21 Nov 2026 11:16:52 +0000 Subject: [PATCH 26/65] test(ci): run the reach tests as unittest TestCases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TestTestFilesContainUnittestTests counts only classes that inherit unittest.TestCase directly. TestRuns, TestNetworks and TestRounds inherited it through _Fixture, so test-lint failed on the pull request run 44825789102 with test_reach.py "do not define any unittest-runnable tests". _Fixture becomes a mixin and each test class inherits (_Fixture, unittest.TestCase). 🎯 Fix: 95 % 💥 Break: 2 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 93 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../cli/meta/roles/applications/complexity/test_reach.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py b/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py index 97795d7feb..92a6fbdefd 100644 --- a/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py +++ b/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py @@ -49,7 +49,7 @@ def _prune( ) -class _Fixture(unittest.TestCase): +class _Fixture: def setUp(self) -> None: caches = (reach._round_of, reach._networks, reach._runs) for fn in caches: @@ -86,7 +86,7 @@ class _Fixture(unittest.TestCase): self.addCleanup(patch.stop) -class TestRuns(_Fixture): +class TestRuns(_Fixture, unittest.TestCase): def test_a_network_without_disable_runs_the_whole_round(self) -> None: self.assertEqual( reach._runs("roles", APP, 3, frozenset({"multi"})), @@ -107,7 +107,7 @@ class TestRuns(_Fixture): ) -class TestNetworks(_Fixture): +class TestNetworks(_Fixture, unittest.TestCase): def test_the_networks_are_those_of_every_tested_mode(self) -> None: self.assertEqual( reach._networks("roles", APP, 0, frozenset({"compose", "swarm"})), @@ -122,7 +122,7 @@ class TestNetworks(_Fixture): self.assertTrue(self.row_states.call_args.kwargs["pulls_tor"]) -class TestRounds(_Fixture): +class TestRounds(_Fixture, unittest.TestCase): def test_the_modes_are_the_tested_ones(self) -> None: row = SimpleNamespace( name=APP, variant=None, test_compose=True, test_swarm=False, test_host=True From 7c3245ad8f64605cd4e49c2bf87f361591a27558 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:38:48 +0000 Subject: [PATCH 27/65] build(deps): Bump fastapi in /roles/web-svc-translate/files Bumps [fastapi](https://github.com/fastapi/fastapi) from 0.163.1 to 0.164.0. - [Release notes](https://github.com/fastapi/fastapi/releases) - [Commits](https://github.com/fastapi/fastapi/compare/0.163.1...0.164.0) --- updated-dependencies: - dependency-name: fastapi dependency-version: 0.163.2 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- roles/web-svc-translate/files/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-svc-translate/files/requirements.txt b/roles/web-svc-translate/files/requirements.txt index 8633c9f554..28e9d85315 100644 --- a/roles/web-svc-translate/files/requirements.txt +++ b/roles/web-svc-translate/files/requirements.txt @@ -1,4 +1,4 @@ -fastapi==0.163.1 +fastapi==0.164.0 python-multipart==0.0.34 uvicorn[standard]==0.54.0 asyncpg==0.32.0 From d1ce0063006162dad7dc4c18e77b919762cfd878 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 21 Nov 2026 18:40:27 +0000 Subject: [PATCH 28/65] fix(web-app-semaphore): pick the LDAP tab before an LDAP sign-in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Semaphore v2.20 (bumped in 6dcce7ab3a and 8a4c82af6a) shows a Sign In | LDAP toggle on its login page whenever LDAP is on, and the default Sign In tab posts method=password, which never queries LDAP. signInViaLdap filled the form on that default tab, so biber got a 401 and stayed on the login page: semaphore#0 and semaphore#2 on main push run 44909073843. It now selects the LDAP tab and asserts it is active before it signs in. The role never sets SEMAPHORE_PASSWORD_LOGIN_DISABLED, so the toggle renders whenever LDAP is on. 🎯 Fix: 92 % 💥 Break: 3 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 89 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../web-app-semaphore/files/playwright/_shared.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/roles/web-app-semaphore/files/playwright/_shared.js b/roles/web-app-semaphore/files/playwright/_shared.js index 36bb059eda..715e6e5fbb 100644 --- a/roles/web-app-semaphore/files/playwright/_shared.js +++ b/roles/web-app-semaphore/files/playwright/_shared.js @@ -63,8 +63,21 @@ async function signInViaLocal(page, username, password, label) { await assertAuthenticated(page, label); } +async function selectLdapLoginTab(page, label) { + const ldapTab = page.locator(".v-btn-toggle").getByRole("button", { name: "LDAP", exact: true }); + await expect( + ldapTab, + `${label}: the LDAP tab must render on the Semaphore login page; the default Sign In tab posts method=password and never queries LDAP`, + ).toBeVisible({ timeout: resolveTimeout(30_000) }); + await ldapTab.click({ timeout: resolveTimeout(30_000) }); + await expect(ldapTab, `${label}: the LDAP tab must be selected before signing in`).toHaveClass(/v-btn--active/); +} + async function signInViaLdap(page, username, password, label) { - await signInViaLocal(page, username, password, label); + await gotoLogin(page); + await selectLdapLoginTab(page, label); + await fillLocalLogin(page, username, password); + await assertAuthenticated(page, label); } async function signInViaOidc(page, username, password, label) { From 0f9a8a5922a535ea684fcf82a619c95c2278ba2c Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 21 Nov 2026 18:44:55 +0000 Subject: [PATCH 29/65] fix(networks): keep the default network of a role that joins no other MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit svc-ai roles without a local database suppress the compose default network. svc-ai-mcp-adapter attaches to nothing else, so its compose file rendered no network and compose fell back to the implicit mcp-adapter_default, whose labels match the mcp-adapter bridge the role network routine creates: compose adopted that bridge under the wrong name and the start failed with network mcp-adapter_default not found (PR 2006 run 44904469540, Agents swarm and compose). The default is now dropped only when the role has attachments. Root cause, docker probe and patch by Stage 2.0; ported onto main by hand where render.py differs. 🎯 Fix: 90 % 💥 Break: 4 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../unit/python/utils/networks/test_render.py | 25 ++++++++++--------- utils/networks/attachments.py | 19 ++++++++++++++ utils/networks/render.py | 5 ++-- 3 files changed, 35 insertions(+), 14 deletions(-) diff --git a/tests/unit/python/utils/networks/test_render.py b/tests/unit/python/utils/networks/test_render.py index cea41c8f86..2f451a53ba 100644 --- a/tests/unit/python/utils/networks/test_render.py +++ b/tests/unit/python/utils/networks/test_render.py @@ -112,22 +112,23 @@ class TestRenderComposeNetworks(unittest.TestCase): ) self.assertEqual(rendered, expected) - def test_a_role_with_nothing_to_attach_emits_no_networks_key(self): - """A bare `networks:` parses as null, and compose refuses it as not an array.""" + def test_a_role_with_nothing_to_attach_keeps_its_default(self): + """Without it compose falls back to `_default`, which the + `` bridge labelled as that project's default shadows: the start + fails with `network _default not found`.""" for render in (render_container_networks, render_compose_networks): for role in ("svc-ai-mcp-adapter", "svc-db-nothing"): with self.subTest(render=render.__name__, role=role): - self.assertEqual( - "", - render( - application_id=role, - deployment_mode="compose", - registry={}, - entity_name=_entity_name, - lookup_config=_const_lookup_config(), - lookup_database=_const_lookup_database(), - ), + rendered = render( + application_id=role, + deployment_mode="compose", + registry={}, + entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), ) + self.assertIn(" default:", rendered) + self.assertNotEqual(rendered.strip(), "networks:") def test_a_role_that_keeps_the_default_still_renders_it(self): """The guard must not swallow the default attachment it sits behind.""" diff --git a/utils/networks/attachments.py b/utils/networks/attachments.py index 7491251826..ef85438fc9 100644 --- a/utils/networks/attachments.py +++ b/utils/networks/attachments.py @@ -201,6 +201,25 @@ def _suppress_default( return not bool(lookup_database(application_id, "local")) +def _drops_default( + application_id: str, + attachments: list[dict[str, Any]], + lookup_database: Callable[[str, str], Any], +) -> bool: + """ + Args: + application_id: role the compose file belongs to. + attachments: what :func:`_compute_attachments` returns for it. + lookup_database: database value accessor. + + Returns: + Whether its compose file leaves ``default`` out; never for a role that + joins no other network, whose start would otherwise fail with ``network + _default not found`` on the ```` bridge. + """ + return bool(attachments) and _suppress_default(application_id, lookup_database) + + def _own_shared_net_provider( attachments: list[dict[str, Any]], own_entity: str, diff --git a/utils/networks/render.py b/utils/networks/render.py index c370a71313..a5f8905eac 100644 --- a/utils/networks/render.py +++ b/utils/networks/render.py @@ -47,6 +47,7 @@ if TYPE_CHECKING: from utils.networks.attachments import ( _coerce_bool, _compute_attachments, + _drops_default, _is_consumer, _own_shared_net_provider, _shared_network_key, @@ -157,7 +158,7 @@ def render_compose_networks( is_own_shared_net_provider = ( _shared_network_key(attachments, own_entity, entity_name) == own_entity ) - if not _suppress_default(application_id, lookup_database): + if not _drops_default(application_id, attachments, lookup_database): lines.append(" default:") if deployment_mode == "swarm": if not is_own_shared_net_provider and own_entity: @@ -230,7 +231,7 @@ def render_container_networks( return "" return "\n" + "\n".join(lines) - if not _suppress_default(application_id, lookup_database): + if not _drops_default(application_id, attachments, lookup_database): if default_aliases: lines.append(" default:") lines.append(" aliases:") From ab576e07841aef527152a80a05f12f0bb2fcd0fa Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 21 Nov 2026 18:47:22 +0000 Subject: [PATCH 30/65] fix(ci): wait for the privileged images on every fork PR MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since b138ca8c8a a fork PR gets its CI images only from the pull_request_target run, trusted or not, yet the validation wait skipped every PR labelled Trusted. On PR 2006 run 44929871897 the Wait for fork run job passed in 3 s and test-dns pulled ghcr.io/infinito-nexus/core/debian:ci-5ec326e5f2... at 17:35, ten minutes before the privileged run published it; the deploy batches only won the race because lint and test ran first. The wait now runs for every fork PR, and the trusted_pr input it was the only reader of goes from the validation, orchestrator and entry workflows. Found by Stage 2.0. 🎯 Fix: 90 % 💥 Break: 4 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .github/workflows/call-orchestrator.yml | 6 ------ .github/workflows/call-validation.yml | 11 +++-------- .github/workflows/entry-pr-change-orchestrate.yml | 1 - docs/contributing/artefact/git/pipeline.md | 5 ++--- 4 files changed, 5 insertions(+), 18 deletions(-) diff --git a/.github/workflows/call-orchestrator.yml b/.github/workflows/call-orchestrator.yml index cc1ac3fff9..684f009677 100644 --- a/.github/workflows/call-orchestrator.yml +++ b/.github/workflows/call-orchestrator.yml @@ -97,11 +97,6 @@ on: required: false type: string default: "" - trusted_pr: - description: "True when the PR carries the maintainer '🛡️ Trusted' label; skips the fork-prereq wait." - required: false - type: boolean - default: false permissions: actions: read @@ -125,7 +120,6 @@ jobs: sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} chunk_size: ${{ inputs.chunk_size }} fork_prereqs: true - trusted_pr: ${{ inputs.trusted_pr }} image_wait_attempts: ${{ inputs.image_wait_attempts }} image_wait_sleep_seconds: ${{ inputs.image_wait_sleep_seconds }} secrets: inherit diff --git a/.github/workflows/call-validation.yml b/.github/workflows/call-validation.yml index 0129e213d7..339eab8847 100644 --- a/.github/workflows/call-validation.yml +++ b/.github/workflows/call-validation.yml @@ -82,11 +82,6 @@ on: required: false type: boolean default: false - trusted_pr: - description: "🛡️ True when the PR carries the maintainer Trusted label; skips the fork-prereq wait." - required: false - type: boolean - default: false image_wait_attempts: description: "🔁 Polling attempts while waiting on prebuilt or mirrored images." required: false @@ -198,14 +193,14 @@ jobs: if: ${{ inputs.fork_prereqs }} runs-on: ubuntu-26.04 env: - WAIT_REQUIRED: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && !inputs.trusted_pr }} + WAIT_REQUIRED: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }} steps: - - name: 🏷️ Mark fork prerequisites as ready outside fork PRs or for trusted PRs + - name: 🏷️ Mark fork prerequisites as ready outside fork PRs if: ${{ env.WAIT_REQUIRED != 'true' }} shell: bash run: | set -euo pipefail - echo "Fork prerequisites are implicitly ready (non-fork PR or '🛡️ Trusted' label)." + echo "Fork prerequisites are implicitly ready (non-fork PR)." - name: ⬇️ Checkout trusted workflow repo (helpers) if: ${{ env.WAIT_REQUIRED == 'true' }} diff --git a/.github/workflows/entry-pr-change-orchestrate.yml b/.github/workflows/entry-pr-change-orchestrate.yml index 4f2921e911..5afe125666 100644 --- a/.github/workflows/entry-pr-change-orchestrate.yml +++ b/.github/workflows/entry-pr-change-orchestrate.yml @@ -117,7 +117,6 @@ jobs: with: distros: "arch debian ubuntu fedora centos" whitelist: ${{ needs.detect-affected-roles.outputs.whitelist }} - trusted_pr: ${{ contains(github.event.pull_request.labels.*.name, '🛡️ Trusted') }} prepare-fork-merge-ref: needs: diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index 865aebd255..c354599243 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -32,7 +32,7 @@ The orchestrator runs the following stages in order: ### 1. Fork Prerequisites ⏳ -For fork PRs, CI waits for privileged images built by the `pull_request_target` event before proceeding. That build and the mirror producer run only for a fork PR that carries the maintainer-applied `🛡️ Trusted` label; for an untrusted fork the `🛡️ Gate fork trust` job fails instead, and the waiting `pull_request` run fails fast with it. The label also switches the build source to the PR head and skips the wait — see [Trusted fork PRs](#trusted-fork-prs-). +For fork PRs, CI waits for privileged images built by the `pull_request_target` event before proceeding. That build and the mirror producer run only for a fork PR that carries the maintainer-applied `🛡️ Trusted` label; for an untrusted fork the `🛡️ Gate fork trust` job fails instead, and the waiting `pull_request` run fails fast with it. The label also switches the build source to the PR head — see [Trusted fork PRs](#trusted-fork-prs-). ### 2. Security 🛡️ @@ -147,7 +147,6 @@ For an **untrusted** fork PR the privileged `pull_request_target` jobs stop at t When a maintainer applies the `🛡️ Trusted` label, the fork PR is treated as deliberately released code: -- The orchestrator's `wait-fork-prereq-run` job **skips the wait** for the privileged fork images. - The privileged `pull_request_target` build switches its **build source** from the base merge ref to the **raw PR head** (`head.repo.full_name` @ `head.sha`). - The trusted mirror producer receives the Docker Hub mirror credentials; untrusted fork PRs get no privileged job at all. - A fork-sourced build imports the shared `buildcache-` registry cache but never exports to it, so only base-sourced builds write the cache every trusted build reads. @@ -159,4 +158,4 @@ Security gates: - Build-orchestration scripts (`scripts/image/push.sh` and the helper checkout) always come from the base repo at `github.sha`; only the Docker build **context** (`_src`) is the fork head. `persist-credentials: false` keeps the token out of the source checkout, and `USE_NIX_TOKEN` stays disabled for fork-sourced builds. - Fork `pull_request` runs always receive a read-only token (GitHub-enforced); the label never grants write tokens or secrets to the untrusted event. -Both events carry a `labeled` trigger, so applying the `🛡️ Trusted` label starts fresh runs that already observe it: the `pull_request_target` build switches to the PR head and the `pull_request` orchestrator skips the wait — no extra push is needed. (Re-running an existing run does not pick up a new label, because GitHub replays the original event payload.) The trade-off is that any label change starts a fresh PR CI run. +Both events carry a `labeled` trigger, so applying the `🛡️ Trusted` label starts fresh runs that already observe it: the `pull_request_target` build switches to the PR head, and the `pull_request` run waits in `wait-fork-prereq-run` until that build has published the images — no extra push is needed. (Re-running an existing run does not pick up a new label, because GitHub replays the original event payload.) The trade-off is that any label change starts a fresh PR CI run. From 1639edb44dde29f6237c955e17052b9d70e19521 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 21 Nov 2026 19:06:04 +0000 Subject: [PATCH 31/65] fix(web-app-kix): mark the sign-in page by its route and dock the sidebar for the hover spec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit KIX titles its sign-in page with a translated Welcome to KIX, so the stock check on the text missed it and the script appended the brand (main run 44909073843 KIX#0, test-design.js:449: Expected KIX, Received Welcome to KIX · KIX). The design script now marks the sign-in page by its /auth route. The hover spec runs at 1680x1050, where KIX docks the sidebar instead of floating it over the table cell the hover needs (test-design.js:347 hover timeout). Taken from IAM 2a298af605 plus the test package init of 652e590d54, byte-identical, so the IAM merge stays clean. Tests: tests/unit/python/roles/web-app-kix plus python and playwright lints, 46 passed, 571 subtests. 🎯 Fix: 90 % 💥 Break: 4 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../files/playwright/test-design.js | 3 + roles/web-app-kix/templates/design.js.j2 | 6 +- .../unit/python/roles/web-app-kix/__init__.py | 5 ++ .../roles/web-app-kix/test_design_title.py | 74 +++++++++++++++++++ 4 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 tests/unit/python/roles/web-app-kix/__init__.py create mode 100644 tests/unit/python/roles/web-app-kix/test_design_title.py diff --git a/roles/web-app-kix/files/playwright/test-design.js b/roles/web-app-kix/files/playwright/test-design.js index 8688ea08b7..9d7dad4c39 100644 --- a/roles/web-app-kix/files/playwright/test-design.js +++ b/roles/web-app-kix/files/playwright/test-design.js @@ -61,6 +61,7 @@ const MENU_ENTRY = `${MENU} ul.main-menu li`; const MENU_SELECTED = `${MENU} li.active`; const MOBILE_MENU = ".mobile-main-menu-container"; const LISTED = "/admin?moduleId=ticket-states"; +const DOCKED = { width: 1680, height: 1050 }; test.use({ ignoreHTTPSErrors: true }); @@ -346,6 +347,8 @@ exports.register = function (shared) { test("design: the signed-in interface takes frame, surfaces, dividers and text from the palette", async ({ page }) => { shared.skipUnlessServiceEnabled("design"); + // KIX floats a shown sidebar over the content between 1141 and 1600 px, where it covers the table cell the hover needs. + await page.setViewportSize(DOCKED); await signIn(page); for (const mode of MODES) { await page.emulateMedia({ colorScheme: mode }); diff --git a/roles/web-app-kix/templates/design.js.j2 b/roles/web-app-kix/templates/design.js.j2 index da07944259..3b66c396cb 100644 --- a/roles/web-app-kix/templates/design.js.j2 +++ b/roles/web-app-kix/templates/design.js.j2 @@ -4,12 +4,14 @@ var title = {{ design.title | to_json }}; var tail = " · " + title; var stock = /^KIX \d+$/; + // KIX titles its sign-in page with a translated "Welcome to KIX", so the route, not the text, marks it as stock. + var signIn = /(^|\/)auth\/?$/.test(location.pathname); function brand() { var current = document.title; - if (current === title || current.slice(-tail.length) === tail) { + if (current === title || (!signIn && current.slice(-tail.length) === tail)) { return; } - document.title = current === "" || stock.test(current) ? title : current + tail; + document.title = signIn || current === "" || stock.test(current) ? title : current + tail; } new MutationObserver(brand).observe(document.head, { childList: true, subtree: true, characterData: true }); brand(); diff --git a/tests/unit/python/roles/web-app-kix/__init__.py b/tests/unit/python/roles/web-app-kix/__init__.py new file mode 100644 index 0000000000..aa7a30d2e5 --- /dev/null +++ b/tests/unit/python/roles/web-app-kix/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-kix/test_design_title.py b/tests/unit/python/roles/web-app-kix/test_design_title.py new file mode 100644 index 0000000000..1fba8a9c82 --- /dev/null +++ b/tests/unit/python/roles/web-app-kix/test_design_title.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import json +import shutil +import subprocess +import unittest + +from jinja2 import Environment, select_autoescape + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +TEMPLATE = PROJECT_ROOT / "roles" / "web-app-kix" / "templates" / "design.js.j2" +TITLE = "Acme Desk" +HARNESS = """ +const vm = require("node:vm"); +const script = process.argv[1]; +const cases = JSON.parse(process.argv[2]); +const titles = cases.map(([pathname, title]) => { + const document = { title, head: {}, addEventListener() {} }; + const sandbox = { document, location: { pathname }, MutationObserver: class { observe() {} } }; + vm.runInNewContext(script, sandbox); + return document.title; +}); +process.stdout.write(JSON.stringify(titles)); +""" +CASES = ( + ("/auth", "Welcome to KIX", TITLE), + ("/auth", "Willkommen bei KIX", TITLE), + ("/kix/auth", "Welcome to KIX", TITLE), + ("/auth", TITLE, TITLE), + ("/home", "KIX 18", TITLE), + ("/home", "", TITLE), + ("/home", "Home", f"Home · {TITLE}"), + ("/home", f"Home · {TITLE}", f"Home · {TITLE}"), + ("/authors", "Authors", f"Authors · {TITLE}"), +) + + +def _render() -> str: + environment = Environment(autoescape=select_autoescape(default_for_string=False)) + environment.globals["lookup"] = lambda *_: {"title": TITLE} + environment.filters["to_json"] = json.dumps + return environment.from_string(read_text(str(TEMPLATE))).render( + application_id="web-app-kix" + ) + + +@unittest.skipUnless(shutil.which("node"), "node is not available in PATH") +class TestDesignTitle(unittest.TestCase): + def test_every_page_carries_the_configured_title(self) -> None: + proc = subprocess.run( + [ + "node", + "-e", + HARNESS, + _render(), + json.dumps([[path, title] for path, title, _ in CASES]), + ], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + for (path, title, expected), actual in zip( + CASES, json.loads(proc.stdout), strict=True + ): + with self.subTest(path=path, title=title): + self.assertEqual(actual, expected) + + +if __name__ == "__main__": + unittest.main() From be6e63b5b880c277c6fdd09fda55c2df0d8262ad Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:07:25 +0000 Subject: [PATCH 32/65] update(repos): bump git refs to latest tags and commits (web-app-bridgy-fed) --- roles/web-app-bridgy-fed/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-bridgy-fed/meta/services.yml b/roles/web-app-bridgy-fed/meta/services.yml index 52ce0a8acc..a18bbd3538 100644 --- a/roles/web-app-bridgy-fed/meta/services.yml +++ b/roles/web-app-bridgy-fed/meta/services.yml @@ -53,7 +53,7 @@ bridgy-fed: version: 3.14-slim name: web-app-bridgy-fed repository: https://github.com/snarfed/bridgy-fed.git - ref: 9dc7d38c5597e37162b1774816e0c4715a199adc + ref: 07a86d3ee33b36eaecf7c4cc0e4d670a60629b02 ports: local: http: 8053 From 0efadfbcb0120d31246faeb470de79cfaf9bdc01 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 05:11:24 +0000 Subject: [PATCH 33/65] fix(svc-ai-litellm): give LiteLLM its origin as PROXY_BASE_URL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LiteLLM v1.77.7-stable builds its fallback sign-in form action as PROXY_BASE_URL + /login without trimming. PROXY_BASE_URL came from the tls lookup url.base, which always ends in a slash, so the form posted to //login and the gateway answered 404 (main push run 44909073843 litellm#0: 30 POST //login 404 in the litellm container log, form action https://llm.ai.main.infinito.test//login in the Playwright trace; every signIn spec then waited in vain for the LiteLLM Brand logo). PROXY_BASE_URL now takes url.origin. test_proxy_base_url.py renders the variable, appends /login and expects a single slash; with url.base it fails (negative control). Tests: svc-ai-litellm unit tests plus URL and vars lints, 214 passed, 562 subtests. 🎯 Fix: 92 % 💥 Break: 2 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 90 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/svc-ai-litellm/templates/env.j2 | 2 +- roles/svc-ai-litellm/vars/main.yml | 2 +- .../vars/test_proxy_base_url.py | 55 +++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 tests/unit/python/roles/svc-ai-litellm/vars/test_proxy_base_url.py diff --git a/roles/svc-ai-litellm/templates/env.j2 b/roles/svc-ai-litellm/templates/env.j2 index f963f9eb75..a34a512a6b 100644 --- a/roles/svc-ai-litellm/templates/env.j2 +++ b/roles/svc-ai-litellm/templates/env.j2 @@ -10,7 +10,7 @@ UI_PASSWORD={{ lookup('config', application_id, 'secrets.credentials.ui_password {{ _provider | upper }}_API_KEY={{ LITELLM_PROVIDER_KEYS[_provider] | dotenv_quote }} {% endfor %} {% if LITELLM_UI_SSO | bool %} -PROXY_BASE_URL={{ LITELLM_UI_BASE_URL }} +PROXY_BASE_URL={{ LITELLM_UI_ORIGIN }} PROXY_ADMIN_ID={{ LITELLM_UI_ADMIN }} GENERIC_CLIENT_ID={{ OIDC.CLIENT.ID }} GENERIC_CLIENT_SECRET={{ OIDC.CLIENT.SECRET | dotenv_quote }} diff --git a/roles/svc-ai-litellm/vars/main.yml b/roles/svc-ai-litellm/vars/main.yml index 2ae3beafb5..38976b8dae 100644 --- a/roles/svc-ai-litellm/vars/main.yml +++ b/roles/svc-ai-litellm/vars/main.yml @@ -54,7 +54,7 @@ LITELLM_TEST_CONTRACT: LITELLM_UI_ROLE: "web-app-litellm" LITELLM_UI_SSO: "{{ (LITELLM_UI_ROLE in group_names) and (lookup('sso', LITELLM_UI_ROLE, 'is_oidc_native') | bool) }}" -LITELLM_UI_BASE_URL: "{{ lookup('tls', LITELLM_UI_ROLE, 'url.base') }}" +LITELLM_UI_ORIGIN: "{{ lookup('tls', LITELLM_UI_ROLE, 'url.origin') }}" LITELLM_UI_ADMIN: "{{ lookup('users', 'platform_administrator').username }}" LITELLM_UI_LOGO_URL: "{{ lookup('design', LITELLM_UI_ROLE).urls.logo.svg if ((LITELLM_UI_ROLE in group_names) and (lookup('config', LITELLM_UI_ROLE, 'services.design.enabled') | bool) and (lookup('design', LITELLM_UI_ROLE).logo is string)) else '' }}" diff --git a/tests/unit/python/roles/svc-ai-litellm/vars/test_proxy_base_url.py b/tests/unit/python/roles/svc-ai-litellm/vars/test_proxy_base_url.py new file mode 100644 index 0000000000..8e3496c01c --- /dev/null +++ b/tests/unit/python/roles/svc-ai-litellm/vars/test_proxy_base_url.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import re +import unittest + +from jinja2 import Environment, StrictUndefined, select_autoescape + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +_ROLE = PROJECT_ROOT / "roles/svc-ai-litellm" +_ENV_TEMPLATE = _ROLE / "templates/env.j2" +_PROXY_BASE_URL = re.compile( + r"^PROXY_BASE_URL=\{\{\s*(?P[A-Z_]+)\s*\}\}$", re.MULTILINE +) +_UI_ROLE = "web-app-litellm" +_ORIGIN = "https://llm.example" +_TLS_URLS = {"url.base": f"{_ORIGIN}/", "url.origin": _ORIGIN} + + +def _lookup(plugin: str, role: str, key: str) -> str: + """ + Args: + plugin: lookup plugin name, only "tls" is served. + role: application id, only the UI role is served. + key: "url.base" or "url.origin". + + Returns: + the URL the tls lookup returns for that key. + """ + if (plugin, role) != ("tls", _UI_ROLE): + raise AssertionError(f"unexpected lookup({plugin!r}, {role!r}, {key!r})") + return _TLS_URLS[key] + + +class TestProxyBaseUrl(unittest.TestCase): + def test_the_fallback_form_posts_to_the_login_route(self) -> None: + match = _PROXY_BASE_URL.search(read_text(str(_ENV_TEMPLATE))) + self.assertIsNotNone(match, "env.j2 must set PROXY_BASE_URL from one variable") + source = load_yaml(str(_ROLE / ROLE_FILE_VARS_MAIN))[match.group("name")] + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + proxy_base_url = env.from_string(source).render( + lookup=_lookup, LITELLM_UI_ROLE=_UI_ROLE + ) + self.assertEqual(f"{proxy_base_url}/login", f"{_ORIGIN}/login") + + +if __name__ == "__main__": + unittest.main() From daa4d51341ca380fcb72e56fd83ac571fe609d55 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 05:11:24 +0000 Subject: [PATCH 34/65] fix(sys-svc-container): set the run-once flag before the post-load roles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Outside the service-loader preload context, list_or_shoot includes the post-load roles at once. sys-ctl-hlth-runtime re-includes sys-svc-container while run_once_sys_svc_container is unset, and the flag was set only after list_or_shoot, so the two roles included each other until Ansible stopped with Exceeded maximum object depth. The web-app-docs replay of svc-opt-ssd-hdd reaches sys-svc-container only after the preload context closed (main push run 44909073843 ssd-hdd#0: the post-load shoot repeats about 44 times per replay copy against 7 in the deploy). The flag now comes before the shoot. test_once_flag_before_post_load.py fails any role core with the old order and keeps that order as a negative control. Ported from IAM 468199e1c2, container hunk and test byte-identical; the stack-entry part of that commit stays on IAM. Tests: once-flag, run-once and include lints, run_once integration, sys-svc-container unit tests, 113 passed, 587 subtests. 🎯 Fix: 92 % 💥 Break: 3 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 89 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/sys-svc-container/tasks/00_core.yml | 4 +- .../roles/test_once_flag_before_post_load.py | 70 +++++++++++++++++++ 2 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 tests/lint/ansible/roles/test_once_flag_before_post_load.py diff --git a/roles/sys-svc-container/tasks/00_core.yml b/roles/sys-svc-container/tasks/00_core.yml index 6c62a889a0..78e7e1d0a8 100644 --- a/roles/sys-svc-container/tasks/00_core.yml +++ b/roles/sys-svc-container/tasks/00_core.yml @@ -134,6 +134,8 @@ include_tasks: "03_reset.yml" when: MODE_RESET | bool +- include_tasks: utils/once/flag.yml + - name: "🧭 Route docker cleanup/health deps through service-loader" ansible.builtin.include_role: name: sys-service-loader @@ -144,5 +146,3 @@ - sys-ctl-hlth-container - sys-ctl-hlth-runtime - sys-ctl-hlth-volumes - -- include_tasks: utils/once/flag.yml diff --git a/tests/lint/ansible/roles/test_once_flag_before_post_load.py b/tests/lint/ansible/roles/test_once_flag_before_post_load.py new file mode 100644 index 0000000000..4dd255ed40 --- /dev/null +++ b/tests/lint/ansible/roles/test_once_flag_before_post_load.py @@ -0,0 +1,70 @@ +import unittest + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_str + +from . import PROJECT_ROOT + +FLAG = "utils/once/flag.yml" +LOADER = "list_or_shoot.yml" + + +def order_findings(tasks): + """Args: + tasks: the top-level tasks of a role's tasks/00_core.yml. + + Returns: + A message when the role shoots post-load roles through the service + loader before it sets its run-once flag. + """ + flag = loader = None + for index, task in enumerate(tasks or []): + if not isinstance(task, dict): + continue + if task.get("include_tasks") == FLAG and flag is None: + flag = index + include = task.get("ansible.builtin.include_role") or task.get("include_role") + if isinstance(include, dict) and include.get("tasks_from") == LOADER: + loader = index if loader is None else loader + if flag is not None and loader is not None and loader < flag: + return [ + f"post-load roles shot at task {loader}, run-once flag set at task {flag}" + ] + return [] + + +def offenders(roles): + """Args: + roles: the roles directory. + + Returns: + ``role: message`` for every role whose core tasks shoot post-load roles + before the run-once flag. + """ + found = [] + for core in sorted(roles.glob("*/tasks/00_core.yml")): + text = read_text(str(core)) + if FLAG not in text or LOADER not in text: + continue + found.extend( + f"{core.parent.parent.name}: {message}" + for message in order_findings(load_yaml_str(text)) + ) + return found + + +class TestOnceFlagBeforePostLoad(unittest.TestCase): + def test_every_role_sets_its_flag_before_it_shoots_post_load_roles(self): + self.assertEqual(offenders(PROJECT_ROOT / "roles"), []) + + def test_negative_control_the_old_container_order_recurses(self): + core = PROJECT_ROOT / "roles" / "sys-svc-container" / "tasks" / "00_core.yml" + tasks = load_yaml_str(read_text(str(core))) + flag = next(i for i, t in enumerate(tasks) if t.get("include_tasks") == FLAG) + planted = tasks[:flag] + tasks[flag + 1 :] + [tasks[flag]] + self.assertTrue(order_findings(tasks) == []) + self.assertNotEqual(order_findings(planted), []) + + +if __name__ == "__main__": + unittest.main() From f4e5d73cd065188c7cf27a5368f8e547642ecd16 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 10:37:19 +0000 Subject: [PATCH 35/65] fix(web-app-kix): draw the forced KIX focus ring from the design tokens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit KIX ships its own application.css that forces every focus ring with outline:var(--focus-outline)!important and resolves --focus-outline once on :root from --focus-color, its green --primary-6 (120,190,90). The outline style.css declares on :root :focus-visible therefore never won, and every keyboard ring stayed KIX green. With the sidebar docked, the design spec now reaches the skip link in its keyboard walk and fails (push run 44939230779 KIX#0, test-design.js:348: keyboard stop a.skip-to-main sits on --design-frame, Expected rgb(255, 255, 255), Received rgb(120, 190, 90)). style.css now maps --focus-color and --focus-color-alternative onto --design-link-rgb and --design-on-frame-rgb, sets --focus-outline on the focused element from --design-focus so the focus token of a frame reaches the ring, and puts the skip link on the frame colours. test_design_focus.py checks the three mappings; the old sheet declares none of them. Tests: KIX unit tests plus design and CSS lints, 17 passed, 11 subtests. 🎯 Fix: 90 % 💥 Break: 3 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 87 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/web-app-kix/files/style.css | 12 +++ .../roles/web-app-kix/test_design_focus.py | 75 +++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 tests/unit/python/roles/web-app-kix/test_design_focus.py diff --git a/roles/web-app-kix/files/style.css b/roles/web-app-kix/files/style.css index 55ff776db2..bee161e93a 100644 --- a/roles/web-app-kix/files/style.css +++ b/roles/web-app-kix/files/style.css @@ -4003,6 +4003,18 @@ th.selectedCell { #kix-header .new-object-dropdown-container ul { --design-focus: var(--design-link); } +:root { + --focus-color: var(--design-link-rgb); + --focus-color-alternative: var(--design-on-frame-rgb); +} +:root :focus, +:root :focus-within { + --focus-outline: 2px solid var(--design-focus, var(--design-link)); +} +#kix-header .skip-to-main { + background-color: var(--design-frame); + color: var(--design-on-frame); +} .login-wrapper { background-image: none; } diff --git a/tests/unit/python/roles/web-app-kix/test_design_focus.py b/tests/unit/python/roles/web-app-kix/test_design_focus.py new file mode 100644 index 0000000000..156571c3d0 --- /dev/null +++ b/tests/unit/python/roles/web-app-kix/test_design_focus.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +STYLESHEET = PROJECT_ROOT / "roles" / "web-app-kix" / "files" / "style.css" +RULE = re.compile(r"([^{}]+)\{([^{}]*)\}") + + +def _rules() -> list[tuple[frozenset[str], dict[str, str]]]: + """ + Returns: + One entry per rule: its selectors and its declarations by property. + """ + rules = [] + for selectors, body in RULE.findall(read_text(str(STYLESHEET))): + names = frozenset(" ".join(s.split()) for s in selectors.split(",")) + declarations = {} + for declaration in body.split(";"): + name, _, value = declaration.partition(":") + if value: + declarations[name.strip()] = value.strip() + rules.append((names, declarations)) + return rules + + +def _declared(selector: str, prop: str) -> list[str]: + """ + Args: + selector: a selector of the rule, whitespace collapsed. + prop: the property name. + + Returns: + Every value declared for it, in stylesheet order. + """ + return [ + declarations[prop] + for selectors, declarations in _rules() + if selector in selectors and prop in declarations + ] + + +class TestDesignFocus(unittest.TestCase): + def test_kix_focus_colors_take_the_tokens(self) -> None: + self.assertIn("var(--design-link-rgb)", _declared(":root", "--focus-color")) + self.assertIn( + "var(--design-on-frame-rgb)", + _declared(":root", "--focus-color-alternative"), + ) + + def test_the_ring_follows_the_focus_token_of_its_frame(self) -> None: + for selector in (":root :focus", ":root :focus-within"): + with self.subTest(selector=selector): + self.assertIn( + "2px solid var(--design-focus, var(--design-link))", + _declared(selector, "--focus-outline"), + ) + + def test_the_skip_link_sits_on_the_frame(self) -> None: + self.assertIn( + "var(--design-frame)", + _declared("#kix-header .skip-to-main", "background-color"), + ) + self.assertIn( + "var(--design-on-frame)", + _declared("#kix-header .skip-to-main", "color"), + ) + + +if __name__ == "__main__": + unittest.main() From a694479f349b8364c810ee28999549fef5911915 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 10:37:20 +0000 Subject: [PATCH 36/65] fix(locale): drop two hi translations with an invented t.co link MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The machine translation of two docs entries in locale/hi/LC_MESSAGES/docs.po turned (http + https) into https://t.co/ and left gained=https://t.co/ marker comments. The external URL test probes every link in the catalogs, and t.co answers 404 now and then: test-workspace failed on fedora:44 and centos:stream10 in push run 44939230779 (docs.po:48355: https://t.co/ -> HTTP 404) while debian and ubuntu passed at the same time. Both entries are emptied, so the English source shows until they are translated again; msgfmt --check passes. Tests: docs catalog, i18n and URL probe unit tests plus spot lints, 267 passed, 64 subtests. 🎯 Fix: 95 % 💥 Break: 1 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 94 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- locale/hi/LC_MESSAGES/docs.po | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/locale/hi/LC_MESSAGES/docs.po b/locale/hi/LC_MESSAGES/docs.po index 9146ed535f..3e29c8c7bc 100644 --- a/locale/hi/LC_MESSAGES/docs.po +++ b/locale/hi/LC_MESSAGES/docs.po @@ -48352,12 +48352,9 @@ msgstr "कंटेनर लीब स्टेट को हटा देत msgid "Removes the inventory directory in the running container." msgstr "चल कंटेनर में सूची निर्देशिका को हटा देता है।." -# (https://t.co/) इकाई के तहत प्रत्येक ऐप से संबंधित है। चारों ओर पतला रैपर -# [nginx_vhosts.py](../../../../utils/cleanup/nginx_vhosts.py)।. -# gained=['https://t.co/'] # translated-by: libretranslate msgid "Removes the per-domain nginx vhost files (http + https) belonging to every app under the entity. Thin wrapper around [nginx_vhosts.py](../../../../utils/cleanup/nginx_vhosts.py)." -msgstr "प्रति डोमेन nginx भूत फ़ाइलों को हटा देता है (https://t.co/) इकाई के तहत प्रत्येक ऐप से संबंधित है। चारों ओर पतला रैपर [nginx_vhosts.py](../../../../utils/cleanup/nginx_vhosts.py)।." +msgstr "" # translated-by: libretranslate msgid "Removes the stack directory and its volumes." @@ -74268,15 +74265,9 @@ msgstr "सभी ImageRef प्रविष्टियों को सभी msgid "Yield all canonical + alias domains from an app config." msgstr "एप्लिकेशन कॉन्फ़िगरेशन से सभी canonical + alias डोमेन को यील्ड करें।." -# प्रत्येक एप्लिकेशन के लिए *इकाई*, प्लस ``www..conf`` पुनर्निर्देशित -# वेरिएंट और - जब एक नोड प्याज का प्रावधान किया जाता है (``services.tor.node`` -# कुंजी फ़ाइल) - दोहरी स्टैक ``..conf`` वेरिएंट, इसलिए एक -# गिरा हुआ ऐप या तो कोई कहानी प्याज की लहर नहीं छोड़ता है। केवल उन फ़ाइलों को -# उत्पन्न करता है जो मौजूद हैं।. -# gained=['https://t.co/'] # translated-by: libretranslate msgid "Yield existing vhost files (http + https) for every app belonging to *entity*, plus the ``www..conf`` redirect variant and — when a node onion is provisioned (``services.tor.node`` / the key file) — the dual-stack ``..conf`` variant, so a dropped app leaves no stale onion vhost either. Only yields files that exist." -msgstr "मौजूदा भूत फ़ाइलों को पैदा करना (https://t.co/) प्रत्येक एप्लिकेशन के लिए *इकाई*, प्लस ``www..conf`` पुनर्निर्देशित वेरिएंट और - जब एक नोड प्याज का प्रावधान किया जाता है (``services.tor.node`` कुंजी फ़ाइल) - दोहरी स्टैक ``..conf`` वेरिएंट, इसलिए एक गिरा हुआ ऐप या तो कोई कहानी प्याज की लहर नहीं छोड़ता है। केवल उन फ़ाइलों को उत्पन्न करता है जो मौजूद हैं।." +msgstr "" # translated-by: libretranslate msgid "Yield mount dicts in ``volume['mounts']`` that target ``service``." From 3458112116baf2f3b36f3132fbde02757d7a33a4 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 10:37:20 +0000 Subject: [PATCH 37/65] fix(web-app-n8n): set Secure cookies on TLS vhosts only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a multi node the clearnet vhost has TLS, so env.j2 set N8N_SECURE_COOKIE=true. The onion vhost serves the same n8n over plain HTTP, and n8n then replaces its UI with its secure-cookie page (Your n8n server is configured to use a secure cookie, however you are either visiting this via an insecure URL). n8n#1 of push run 44939230779 (network multi) timed out in test-login-administrator.js:26 waiting for the email field. n8n now always runs with N8N_SECURE_COOKIE=false, and every vhost with TLS adds the Secure flag at the edge with proxy_cookie_flags ~ secure. An onion domain has no TLS (resolve_enabled in utils/tls_common.py), so its vhost adds none, and the onion sub_filter on /rest/settings is no longer needed. Ported byte-identically from IAM 27c9a076d1: IAM fork run 44939269920 passes the n8n sign-in specs on a tor node and deploys n8n green on clearnet with the edge flag rendered. test_onion_secure_cookie.py renders both vhosts; without the change 2 of its 6 tests fail. Tests: n8n unit tests plus python, comment, jinja and vhost lints, 232 passed, 1 skipped, 10 subtests. 🎯 Fix: 90 % 💥 Break: 4 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/web-app-n8n/templates/env.j2 | 2 +- roles/web-app-n8n/templates/proxy.conf.j2 | 13 +- .../web-app-n8n/test_onion_secure_cookie.py | 138 ++++++++++++++++++ 3 files changed, 141 insertions(+), 12 deletions(-) create mode 100644 tests/unit/python/roles/web-app-n8n/test_onion_secure_cookie.py diff --git a/roles/web-app-n8n/templates/env.j2 b/roles/web-app-n8n/templates/env.j2 index 38e8f505e1..5846228056 100644 --- a/roles/web-app-n8n/templates/env.j2 +++ b/roles/web-app-n8n/templates/env.j2 @@ -10,7 +10,7 @@ DB_POSTGRESDB_PASSWORD={{ lookup('database', application_id, 'password') | doten N8N_PORT={{ N8N_INTERNAL_PORT }} N8N_HOST={{ N8N_HOSTNAME }} N8N_PROTOCOL={{ N8N_WEB_PROTOCOL }} -N8N_SECURE_COOKIE={{ (N8N_WEB_PROTOCOL == 'https') | lower }} +N8N_SECURE_COOKIE=false WEBHOOK_URL={{ N8N_WEB_PROTOCOL }}://{{ N8N_HOSTNAME }}/ N8N_ENCRYPTION_KEY={{ N8N_ENCRYPTION_KEY | dotenv_quote }} N8N_PROXY_HOPS=1 diff --git a/roles/web-app-n8n/templates/proxy.conf.j2 b/roles/web-app-n8n/templates/proxy.conf.j2 index c50ac70d75..395618d234 100644 --- a/roles/web-app-n8n/templates/proxy.conf.j2 +++ b/roles/web-app-n8n/templates/proxy.conf.j2 @@ -13,17 +13,8 @@ server {% include 'roles/sys-front-inj-all/templates/server.conf.j2'%} {% include 'roles/sys-front-tls/templates/nginx_ssl_header.j2' %} - - {% if (domain | network_of) == 'tor' %} - {% set sso_proxy_enabled = lookup('sso', application_id, 'is_proxy_gated') %} - {% set webserver_location_extra_configuration %} - sub_filter '"authCookie":{"secure":true}' '"authCookie":{"secure":false}'; - sub_filter_types application/json; - sub_filter_once on; - {% endset %} - {% set location = '= /rest/settings' %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} - {% set webserver_location_extra_configuration = '' %} + {% if lookup('tls', domain, 'enabled') | bool %} + proxy_cookie_flags ~ secure; {% endif %} {% if lookup('sso', application_id, 'is_proxy_gated') %} diff --git a/tests/unit/python/roles/web-app-n8n/test_onion_secure_cookie.py b/tests/unit/python/roles/web-app-n8n/test_onion_secure_cookie.py new file mode 100644 index 0000000000..c11d4557e2 --- /dev/null +++ b/tests/unit/python/roles/web-app-n8n/test_onion_secure_cookie.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +import re +import unittest + +from jinja2 import ( + ChoiceLoader, + DictLoader, + Environment, + FunctionLoader, + StrictUndefined, + select_autoescape, +) + +from utils.cache.files import PROJECT_ROOT, read_text + +ENV = PROJECT_ROOT / "roles/web-app-n8n/templates/env.j2" +PROXY = "roles/web-app-n8n/templates/proxy.conf.j2" +SSL_HEADER = "roles/sys-front-tls/templates/nginx_ssl_header.j2" +EDGE_SECURE = "proxy_cookie_flags ~ secure;" +INCLUDE = re.compile(r"\{%-?\s*include\s+['\"]([^'\"]+)['\"]") + +CLEAR = "n8n.example.test" +ONION = "n8n." + "a" * 56 + ".onion" + + +def secure_cookie(web_protocol: str) -> bool: + """Return what ``env.j2`` sets ``N8N_SECURE_COOKIE`` to. + + Args: + web_protocol: the role's ``N8N_WEB_PROTOCOL``. + """ + line = next( + raw + for raw in read_text(str(ENV)).splitlines() + if raw.startswith("N8N_SECURE_COOKIE=") + ) + rendered = ( + Environment(undefined=StrictUndefined, autoescape=select_autoescape()) + .from_string(line) + .render(N8N_WEB_PROTOCOL=web_protocol) + ) + return rendered.partition("=")[2] == "true" + + +def editor_blocked(secure: bool, scheme: str, host: str) -> bool: + """Return whether n8n's editor replaces itself with the insecure page. + + Args: + secure: ``authCookie.secure`` of the public settings. + scheme: the scheme the browser opened the editor over. + host: the host the browser opened the editor on. + """ + return secure and scheme == "http" and host not in ("localhost", "127.0.0.1") + + +def vhost(domain: str) -> list[str]: + """Return the stripped lines n8n's own vhost template renders for a domain. + + Args: + domain: the vhost being rendered; only ``CLEAR`` is served over TLS. + """ + + def lookup(kind, *args): + if kind == "sso": + return False + if kind == "tls" and args == (domain, "enabled"): + return domain == CLEAR + raise AssertionError(f"unexpected lookup {kind!r} {args!r}") + + env = Environment( + loader=ChoiceLoader( + [ + DictLoader({PROXY: read_text(str(PROJECT_ROOT / PROXY))}), + FunctionLoader(lambda _name: ""), + ] + ), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters["bool"] = bool + env.filters["network_of"] = lambda d: "tor" if d.endswith(".onion") else "web" + rendered = env.get_template(PROXY).render( + application_id="web-app-n8n", domain=domain, lookup=lookup + ) + return [line.strip() for line in rendered.splitlines()] + + +def include_closure(name: str) -> set[str]: + """Return a template and every template it includes by a literal name. + + Args: + name: the repository-relative path of the template. + """ + seen: set[str] = set() + pending = [name] + while pending: + current = pending.pop() + if current in seen or not (PROJECT_ROOT / current).is_file(): + continue + seen.add(current) + pending.extend(INCLUDE.findall(read_text(str(PROJECT_ROOT / current)))) + return seen + + +class TestOnionSibling(unittest.TestCase): + def test_the_editor_opens_on_the_onion_sibling_of_a_tls_node(self) -> None: + self.assertFalse(editor_blocked(secure_cookie("https"), "http", ONION)) + + def test_the_editor_opens_on_a_plain_http_node(self) -> None: + self.assertFalse(editor_blocked(secure_cookie("http"), "http", ONION)) + + def test_the_onion_vhost_adds_no_secure_flag(self) -> None: + self.assertNotIn(EDGE_SECURE, vhost(ONION)) + + +class TestClearnetVhost(unittest.TestCase): + def test_a_tls_vhost_marks_every_cookie_secure(self) -> None: + self.assertEqual(vhost(CLEAR).count(EDGE_SECURE), 1) + + def test_the_clearnet_session_cookie_stays_secure(self) -> None: + self.assertTrue(secure_cookie("https") or EDGE_SECURE in vhost(CLEAR)) + + def test_no_included_location_replaces_the_server_rule(self) -> None: + included = include_closure(PROXY) - {PROXY, SSL_HEADER} + self.assertIn("roles/sys-svc-proxy/templates/location/html.conf.j2", included) + self.assertEqual( + [ + name + for name in sorted(included) + if "proxy_cookie_flags" in read_text(str(PROJECT_ROOT / name)) + ], + [], + ) + + +if __name__ == "__main__": + unittest.main() From d5338d8da2da392f9d6589ee0045944c55f525b7 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 10:49:16 +0000 Subject: [PATCH 38/65] fix(web-app-semaphore): link an LDAP login to the user its OIDC login created MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With OIDC and LDAP both enabled, the OIDC biber spec runs first and Semaphore v2.20.24 creates user biber with an OIDC identity. The LDAP login of the same person then authorizes (Semaphore log: User biber with email biber@main.infinito.test authorized via LDAP correctly) and fails on pq: duplicate key value violates unique constraint user_username_key, so the page answers 500 and test-login-ldap-biber.js:5 stays on the login page (semaphore#0 of push run 44939230779 behind the LDAP tab fix; same spec red in main run 44987966640). In the default auto mode, matchExternalUserByEmail in api/login_identity.go skips a user who already holds an external identity, so the second provider inserts the username again. env.j2 now renders SEMAPHORE_EXTERNAL_AUTH_EMAIL_MATCHING=always only when both providers are enabled. Semaphore never adopts a local account in any mode, OIDC matches by email only when email_verified is set, and Keycloak federates the same OpenLDAP, so both providers share one username space. test_external_auth_matching.py renders all four provider combinations; without the change the both-providers case fails. Tests: Semaphore unit tests plus the comment lint, 21 passed, 7 subtests. 🎯 Fix: 90 % 💥 Break: 4 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/web-app-semaphore/templates/env.j2 | 3 + .../test_external_auth_matching.py | 55 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 tests/unit/python/roles/web-app-semaphore/test_external_auth_matching.py diff --git a/roles/web-app-semaphore/templates/env.j2 b/roles/web-app-semaphore/templates/env.j2 index e49d7f0392..0c7b4a7ed8 100644 --- a/roles/web-app-semaphore/templates/env.j2 +++ b/roles/web-app-semaphore/templates/env.j2 @@ -35,3 +35,6 @@ SEMAPHORE_LDAP_MAPPING_UID={{ LDAP.USER.ATTRIBUTES.ID }} SEMAPHORE_LDAP_MAPPING_CN={{ LDAP.USER.ATTRIBUTES.FULLNAME }} SEMAPHORE_LDAP_MAPPING_MAIL={{ LDAP.USER.ATTRIBUTES.MAIL }} {% endif %} +{% if SEMAPHORE_OIDC_ENABLED | bool and SEMAPHORE_LDAP_ENABLED | bool %} +SEMAPHORE_EXTERNAL_AUTH_EMAIL_MATCHING=always +{% endif %} diff --git a/tests/unit/python/roles/web-app-semaphore/test_external_auth_matching.py b/tests/unit/python/roles/web-app-semaphore/test_external_auth_matching.py new file mode 100644 index 0000000000..becf749e0a --- /dev/null +++ b/tests/unit/python/roles/web-app-semaphore/test_external_auth_matching.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import unittest + +import jinja2 + +from utils.cache.files import PROJECT_ROOT, read_text + +ENV_TEMPLATE = "roles/web-app-semaphore/templates/env.j2" +INCLUDED = "roles/sys-svc-container/templates/env.j2" +MATCHING = "SEMAPHORE_EXTERNAL_AUTH_EMAIL_MATCHING=always" + + +def render(*, oidc: bool, ldap: bool) -> list[str]: + """ + Args: + oidc: what ``SEMAPHORE_OIDC_ENABLED`` resolves to. + ldap: what ``SEMAPHORE_LDAP_ENABLED`` resolves to. + + Returns: + The rendered lines. + """ + source = read_text(str(PROJECT_ROOT / ENV_TEMPLATE)) + environment = jinja2.Environment( + loader=jinja2.DictLoader({ENV_TEMPLATE: source, INCLUDED: ""}), + undefined=jinja2.ChainableUndefined, + ) + environment.filters["bool"] = bool + environment.filters["dotenv_quote"] = str + environment.globals["lookup"] = lambda *_args, **_kwargs: "" + rendered = environment.get_template(ENV_TEMPLATE).render( + SEMAPHORE_OIDC_ENABLED=oidc, + SEMAPHORE_LDAP_ENABLED=ldap, + ) + return rendered.splitlines() + + +class TestExternalAuthMatching(unittest.TestCase): + def test_both_providers_match_one_user(self) -> None: + self.assertIn(MATCHING, render(oidc=True, ldap=True)) + + def test_a_single_provider_keeps_the_default(self) -> None: + for oidc, ldap in ((True, False), (False, True), (False, False)): + with self.subTest(oidc=oidc, ldap=ldap): + lines = render(oidc=oidc, ldap=ldap) + self.assertFalse( + any( + line.startswith("SEMAPHORE_EXTERNAL_AUTH_EMAIL_MATCHING") + for line in lines + ) + ) + + +if __name__ == "__main__": + unittest.main() From 0c0f2d4c73bdc7e7e599ef0ce00081c8431fcc0e Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Sun, 22 Nov 2026 15:43:57 +0400 Subject: [PATCH 39/65] fix(sys-ctl-hlth-runtime): keep the probe failure when the container inspection itself fails container_running() returned False for every non-zero 'container inspect', so an engine error such as a refused daemon socket made a failed PHP probe look like a container that had stopped, and the run reported it as skipped. Only a container the engine reports stopped or no longer knows is skipped now; any other inspection error keeps the probe failure. The check docstring and the info line now say what the code does: the running state is read after the probe error, so a container that stops after its probe failed is skipped too. Co-Authored-By: Claude Opus 5.5 --- .../files/python/script.py | 22 +++++++--- .../sys-ctl-hlth-runtime/files/test_script.py | 43 ++++++++++++++++--- 2 files changed, 52 insertions(+), 13 deletions(-) diff --git a/roles/sys-ctl-hlth-runtime/files/python/script.py b/roles/sys-ctl-hlth-runtime/files/python/script.py index 87b1526518..5eafc30f15 100755 --- a/roles/sys-ctl-hlth-runtime/files/python/script.py +++ b/roles/sys-ctl-hlth-runtime/files/python/script.py @@ -466,9 +466,10 @@ def container_running(container_id: str) -> bool: container_id: the container to inspect. Returns: - ``True`` while the container engine reports it running or does not - answer in time, so a probe error then stays a failure; ``False`` once - it stopped or is gone. + ``False`` only when the container engine reports it stopped or no + longer knows it; ``True`` while it runs, and also when the engine does + not answer in time or the inspection fails for another reason, so a + probe error then stays a failure. """ try: result = subprocess.run( @@ -488,7 +489,9 @@ def container_running(container_id: str) -> bool: ) except subprocess.TimeoutExpired: return True - return result.returncode == 0 and result.stdout.strip() == "true" + if result.returncode == 0: + return result.stdout.strip() == "true" + return "no such container" not in result.stderr.lower() def check( @@ -499,8 +502,10 @@ def check( ) -> tuple[list[str], list[str]]: """Evaluate the PHP hardening of every container. - A container that stopped between the listing and its probe, as a swarm - task that recycles itself does, is reported as info, not as a failure. + A probe error counts as a failure only while the container still runs. + A container that is stopped or gone when it is inspected after the error, + as a swarm task that recycles itself is, is reported as info instead, + even when it stopped only after its probe had failed. Args: containers: the running containers. @@ -526,7 +531,10 @@ def check( if running(container.id): failures.append(f"{container.name}: {exc}") else: - infos.append(f"{container.name}: stopped before its probe, skipped") + infos.append( + f"{container.name}: not running when inspected after its " + "probe error, skipped" + ) continue if result is None: if must_harden: diff --git a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py index d67dd6450e..0de5769d26 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-runtime/files/test_script.py @@ -2156,23 +2156,54 @@ class TestCheck(TestCase): lambda _container_id: False, ) self.assertEqual(failures, []) - self.assertEqual(infos, ["worker: stopped before its probe, skipped"]) + self.assertEqual( + infos, ["worker: not running when inspected after its probe error, skipped"] + ) class TestContainerRunning(TestCase): - def _running(self, returncode, stdout): - completed = SimpleNamespace(returncode=returncode, stdout=stdout, stderr="") + def _running(self, returncode, stdout, stderr): + completed = SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr) with mock.patch.object(SCRIPT.subprocess, "run", return_value=completed): return SCRIPT.container_running("abc") def test_a_running_container_runs(self): - self.assertTrue(self._running(0, "true\n")) + self.assertTrue(self._running(0, "true\n", "")) def test_a_stopped_container_does_not_run(self): - self.assertFalse(self._running(0, "false\n")) + self.assertFalse(self._running(0, "false\n", "")) def test_a_removed_container_does_not_run(self): - self.assertFalse(self._running(1, "")) + self.assertFalse(self._running(1, "", "Error: No such container: abc")) + + def test_a_removed_podman_container_does_not_run(self): + self.assertFalse(self._running(125, "", 'Error: no such container "abc"')) + + def test_a_failed_inspection_keeps_the_probe_error(self): + self.assertTrue( + self._running( + 1, + "", + "Cannot connect to the Docker daemon. Is the docker daemon running?", + ) + ) + + def test_a_failed_inspection_does_not_hide_a_probe_failure(self): + def broken(_container_id): + raise SCRIPT.ProbeError("php exited 255: boom") + + completed = SimpleNamespace( + returncode=1, stdout="", stderr="permission denied while trying to connect" + ) + with mock.patch.object(SCRIPT.subprocess, "run", return_value=completed): + failures, infos = SCRIPT.check( + [_container("wp", "wordpress", "wordpress")], + {"wordpress": ["wordpress"]}, + broken, + SCRIPT.container_running, + ) + self.assertEqual(failures, ["wp: php exited 255: boom"]) + self.assertEqual(infos, []) def test_an_engine_that_does_not_answer_counts_as_running(self): timeout = SCRIPT.subprocess.TimeoutExpired(cmd="container", timeout=1) From cb6fa4b6bc77f8694bc0cddbc907ded9bc12fb84 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Sun, 22 Nov 2026 15:44:09 +0400 Subject: [PATCH 40/65] fix(applications_carrier): overwrite a carrier left in the fact cache on clear The fact cache merges the cacheable fact layer, so the empty mapping that clear registered there left an older fact-parked carrier in ansible_facts, where get_vars kept deep-copying it before every task. clear now writes None for every carrier key it finds in ansible_facts, which is the recovery the reader's CarrierInvisibleError message points to. The integration test parks the carrier as a fact, clears it and parks it again, with fact injection on and off. Co-Authored-By: Claude Opus 5.5 --- plugins/action/applications_carrier.py | 28 +++++++++------ .../test_applications_carrier.py | 34 ++++++++++++++++++- .../action/test_applications_carrier.py | 23 +++++++++++++ 3 files changed, 74 insertions(+), 11 deletions(-) diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index 5c95648413..6fd4e888f9 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -99,13 +99,13 @@ class ActionModule(ActionBase): ) if boolean(args.get("clear", False)): - self._park( - { - APPLICATIONS_RENDERED_FACT: None, - USERS_RENDERED_FACT: None, - PROVIDER_VIEW_RENDERED_FACT: None, - } - ) + cleared = { + APPLICATIONS_RENDERED_FACT: None, + USERS_RENDERED_FACT: None, + PROVIDER_VIEW_RENDERED_FACT: None, + } + facts = task_vars.get("ansible_facts") or {} + self._park(cleared, {fact: None for fact in cleared if fact in facts}) result.update(changed=False) return result @@ -136,10 +136,18 @@ class ActionModule(ActionBase): if view_carrier is not None: carriers[PROVIDER_VIEW_RENDERED_FACT] = view_carrier - self._park(carriers) + self._park(carriers, {}) result.update(changed=False, _ansible_no_log=True) return result - def _park(self, carriers: dict[str, Any]) -> None: - self.register_host_variables({}, VariableLayer.CACHEABLE_FACT) + def _park(self, carriers: dict[str, Any], cacheable: dict[str, Any]) -> None: + """Register the carriers outside the fact cache. + + Args: + carriers: carrier variables for the ephemeral fact layer. + cacheable: entries for the cacheable fact layer. The fact cache + merges this layer, so an empty mapping leaves a stale carrier + there; only ``None`` overwrites its payload. + """ + self.register_host_variables(cacheable, VariableLayer.CACHEABLE_FACT) self.register_host_variables(carriers, VariableLayer.EPHEMERAL_FACT) diff --git a/tests/integration/ansible/action_plugins/test_applications_carrier.py b/tests/integration/ansible/action_plugins/test_applications_carrier.py index 8cca57fc74..f1c1aa2abf 100644 --- a/tests/integration/ansible/action_plugins/test_applications_carrier.py +++ b/tests/integration/ansible/action_plugins/test_applications_carrier.py @@ -70,7 +70,7 @@ class LookupModule(LookupBase): ) is not None, "fact_cache": sorted( name for name in ({APPLICATIONS_RENDERED_FACT!r}, {USERS_RENDERED_FACT!r}) - if name in facts + if facts.get(name) is not None ), }}] """ @@ -137,6 +137,29 @@ HAZARD_PLAY = """--- """ +RECOVERY_PLAY = """--- +- name: Clear a fact-parked carrier and park it again + hosts: localhost + gather_facts: false + tasks: + - name: Park the carrier in the fact cache + fact_carrier: {} + + - name: Clear it, as the reader's recovery hint says + applications_carrier: + clear: true + + - name: Park the carrier again + applications_carrier: {} + + - name: Read the parked carrier + ansible.builtin.copy: + dest: "{{ probe_out }}" + content: "{{ lookup('carrier_probe') | to_json }}" + mode: "0644" +""" + + CROSS_HOST_PLAY = f"""--- - name: Park the carrier on two hosts and read the other host's through hostvars hosts: all @@ -265,6 +288,15 @@ class TestApplicationsCarrierReachesLaterWorkers(unittest.TestCase): self.assertIsNone(report) self.assertIn("not visible as a variable", output) + def test_clear_removes_a_fact_parked_carrier_from_the_fact_cache(self): + for inject in (True, False): + with self.subTest(inject=inject): + code, output, report = self._play(RECOVERY_PLAY, inject, "localhost,") + self.assertEqual(code, 0, output) + self.assertEqual( + report, {"applications": True, "users": True, "fact_cache": []} + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/action/test_applications_carrier.py b/tests/unit/python/plugins/action/test_applications_carrier.py index cfd2560f3f..690d9cb678 100644 --- a/tests/unit/python/plugins/action/test_applications_carrier.py +++ b/tests/unit/python/plugins/action/test_applications_carrier.py @@ -277,6 +277,29 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase): self.assertEqual(applications.calls, []) self.assertEqual(users.calls, []) + def test_clear_overwrites_a_carrier_left_in_the_fact_cache(self): + action = _make_action(_FakeTask(args={"clear": True})) + stale = {"key": ["roles", ["a"]], "applications": {"x": {}}} + with patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ): + action.run( + task_vars={ + "ansible_facts": { + APPLICATIONS_RENDERED_FACT: stale, + "os_family": "Debian", + } + } + ) + + self.assertEqual( + action.registered[VariableLayer.CACHEABLE_FACT], + {APPLICATIONS_RENDERED_FACT: None}, + ) + self.assertIsNone(_parked(action)[APPLICATIONS_RENDERED_FACT]) + def test_clear_false_still_renders(self): applications, users, loader = _lookups() action = _make_action(_FakeTask(args={"clear": "no"})) From ff46b707a5a9fc346245885612053520eca707a9 Mon Sep 17 00:00:00 2001 From: Alejandro Roman Date: Sun, 22 Nov 2026 15:44:20 +0400 Subject: [PATCH 41/65] test(lint): scan multi-line conditions and stop reading variable data as task keywords The bare-fact rule only looked at the first line of a condition and missed '- when:' items, so 'when: >' blocks and plain continuation lines were never checked. Lines indented under a condition key are now scanned as part of it. The play environment source lint walked into set_fact and vars values and read their keys as task keywords, so a value holding 'register: CA_TRUST' was reported as an override. Those values are no longer walked. Co-Authored-By: Claude Opus 5.5 --- .../test_no_deprecated_ansible_patterns.py | 28 +++++++++++++++---- ...play_environment_sources_not_overridden.py | 13 +++++++-- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/tests/lint/ansible/test_no_deprecated_ansible_patterns.py b/tests/lint/ansible/test_no_deprecated_ansible_patterns.py index 68030a690e..98aab7805d 100644 --- a/tests/lint/ansible/test_no_deprecated_ansible_patterns.py +++ b/tests/lint/ansible/test_no_deprecated_ansible_patterns.py @@ -158,9 +158,10 @@ _BARE_FACT = re.compile( r"(?=\s*(?:\[|\.\w|\||\s+is\s|==|!=|\s+in\b|\s*\)|\s*}}|\s*%}))" ) _JINJA_EXPR = re.compile(r"\{\{.*?\}\}|\{%.*?%\}") -_CONDITION = re.compile( - r"^\s*(?:(?:when|that|failed_when|changed_when|until):|-(?!\s+[\w\"']+:))\s+(?P.*)$" +_CONDITION_KEY = re.compile( + r"^\s*(?:-\s+)?(?Pwhen|that|failed_when|changed_when|until):(?:\s+(?P.*))?$" ) +_CONDITION_ITEM = re.compile(r"^\s*-(?!\s+[\w\"']+:)\s+(?P.*)$") _PATTERNS: tuple[tuple[str, re.Pattern[str], str], ...] = ( ( @@ -207,6 +208,7 @@ def scan_text(text: str, python: bool, template: bool = False) -> list[str]: out: list[str] = [] fact_pattern = _PY_NAME if python else _YAML_NAME patterns = () if python else _PATTERNS + condition_column: int | None = None for idx, line in enumerate(lines, start=1): if is_suppressed_at(lines, idx, _RULE, mode="same-or-above"): continue @@ -222,9 +224,19 @@ def scan_text(text: str, python: bool, template: bool = False) -> list[str]: if python or line.lstrip().startswith("#"): continue expressions = _JINJA_EXPR.findall(line) - condition = None if template else _CONDITION.match(line) - if condition: - expressions.append(condition.group("expr")) + if not template and line.strip(): + column = len(line) - len(line.lstrip()) + if condition_column is not None and column > condition_column: + expressions.append(line.strip()) + else: + condition_column = None + key = _CONDITION_KEY.match(line) + item = None if key else _CONDITION_ITEM.match(line) + if key: + condition_column = key.start("key") + expressions.append(key.group("expr") or "") + elif item: + expressions.append(item.group("expr")) if any(_BARE_FACT.search(expression) for expression in expressions): out.append( f"line {idx}: [injected-bare-fact] {line.strip()} -> {_BARE_FACT_FIX}" @@ -278,6 +290,10 @@ class TestNoDeprecatedAnsiblePatterns(unittest.TestCase): "- packages['nfs-ganesha'] | first": False, "- getent_group is defined": False, "{{ getent_passwd.nixbld1[1] }}": False, + "- when: services['docker.service'] is defined": False, + "when: >\n x is defined and\n services['docker.service'] is defined": False, + "failed_when: |-\n rc != 0 or packages['git'] | length == 0": False, + "when: x is defined and\n getent_group is defined": False, } for line, python in planted.items(): with self.subTest(line=line): @@ -300,6 +316,8 @@ class TestNoDeprecatedAnsiblePatterns(unittest.TestCase): "when: ansible_facts.services['docker.service'] is defined": False, "{{ lookup('config', application_id, 'services.sso.enabled') }}": False, "- name: install language packages": False, + "when: >\n x is defined\nvars:\n services: [a]": False, + "- when: x is defined\n name: list packages | services": False, } for line, python in clean.items(): with self.subTest(line=line): diff --git a/tests/lint/ansible/variables/test_play_environment_sources_not_overridden.py b/tests/lint/ansible/variables/test_play_environment_sources_not_overridden.py index 2cd8fdd8f2..6346fd3247 100644 --- a/tests/lint/ansible/variables/test_play_environment_sources_not_overridden.py +++ b/tests/lint/ansible/variables/test_play_environment_sources_not_overridden.py @@ -74,9 +74,11 @@ def _assigned_names(node: Any) -> list[tuple[str, str]]: for key, value in node.items(): if key in SET_FACT_KEYS and isinstance(value, dict): found.extend(("set_fact", name) for name in value) - elif key == "vars" and isinstance(value, dict): + continue + if key == "vars" and isinstance(value, dict): found.extend(("vars", name) for name in value) - elif key == "register" and isinstance(value, str): + continue + if key == "register" and isinstance(value, str): found.append(("register", value)) elif key in INCLUDE_VARS_KEYS and isinstance(value, dict) and "name" in value: found.append(("include_vars", str(value["name"]))) @@ -186,6 +188,13 @@ class TestPlayEnvironmentSourcesNotOverridden(unittest.TestCase): ) self.assertEqual(scan(PLANTED_TASKS, clean, self.protected), []) + def test_data_inside_a_variable_value_is_not_a_task_keyword(self) -> None: + clean = load_yaml_str( + "- set_fact:\n OTHER: {register: CA_TRUST, vars: {BUILDKIT_ENABLED: 1}}\n" + "- debug: {msg: x}\n vars:\n SPEC: {set_fact: {CA_TRUST: 1}}\n" + ) + self.assertEqual(scan(PLANTED_TASKS, clean, self.protected), []) + if __name__ == "__main__": unittest.main() From 95bf897c3462022770874eb885a88e3b37605006 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 12:14:30 +0000 Subject: [PATCH 42/65] fix(web-app-kix): read the sign-in route on every title update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit design.js.j2 evaluated the /auth route check once, when the script loaded. KIX changes routes on the client without a document load, so after a route change brand() kept the old answer: routed from /auth to /home it wrote the bare configured title over the page label, routed from /home to /auth it appended the suffix to the translated sign-in title (Welcome to KIX followed by the configured title). The check now runs inside brand(), so each MutationObserver callback reads the current location.pathname. Found by CodeRabbit on PR 2488 and reproduced: the old template returns the bare title and the suffixed sign-in title for the two navigations. test_design_title.py gained a navigation harness that loads the script on one route, moves location.pathname and fires the observer; both cases fail on the old template. Tests: KIX and Semaphore unit tests plus the once-flag, comment and import lints, 35 passed, 20 subtests. 🎯 Fix: 92 % 💥 Break: 2 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 90 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/web-app-kix/templates/design.js.j2 | 4 +- .../roles/web-app-kix/test_design_title.py | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/roles/web-app-kix/templates/design.js.j2 b/roles/web-app-kix/templates/design.js.j2 index 3b66c396cb..41a2beb9b5 100644 --- a/roles/web-app-kix/templates/design.js.j2 +++ b/roles/web-app-kix/templates/design.js.j2 @@ -4,9 +4,9 @@ var title = {{ design.title | to_json }}; var tail = " · " + title; var stock = /^KIX \d+$/; - // KIX titles its sign-in page with a translated "Welcome to KIX", so the route, not the text, marks it as stock. - var signIn = /(^|\/)auth\/?$/.test(location.pathname); function brand() { + // KIX titles its sign-in page with a translated "Welcome to KIX", so the route, not the text, marks it as stock. + var signIn = /(^|\/)auth\/?$/.test(location.pathname); var current = document.title; if (current === title || (!signIn && current.slice(-tail.length) === tail)) { return; diff --git a/tests/unit/python/roles/web-app-kix/test_design_title.py b/tests/unit/python/roles/web-app-kix/test_design_title.py index 1fba8a9c82..e036e77214 100644 --- a/tests/unit/python/roles/web-app-kix/test_design_title.py +++ b/tests/unit/python/roles/web-app-kix/test_design_title.py @@ -25,6 +25,27 @@ const titles = cases.map(([pathname, title]) => { }); process.stdout.write(JSON.stringify(titles)); """ +NAVIGATION_HARNESS = """ +const vm = require("node:vm"); +const script = process.argv[1]; +const cases = JSON.parse(process.argv[2]); +const titles = cases.map(([fromPath, fromTitle, toPath, toTitle]) => { + const document = { title: fromTitle, head: {}, addEventListener() {} }; + let onChange = null; + const location = { pathname: fromPath }; + const MutationObserver = class { constructor(callback) { onChange = callback; } observe() {} }; + vm.runInNewContext(script, { document, location, MutationObserver }); + location.pathname = toPath; + document.title = toTitle; + onChange(); + return document.title; +}); +process.stdout.write(JSON.stringify(titles)); +""" +NAVIGATIONS = ( + ("/auth", "Welcome to KIX", "/home", "Home", f"Home · {TITLE}"), + ("/home", "Home", "/auth", "Welcome to KIX", TITLE), +) CASES = ( ("/auth", "Welcome to KIX", TITLE), ("/auth", "Willkommen bei KIX", TITLE), @@ -69,6 +90,24 @@ class TestDesignTitle(unittest.TestCase): with self.subTest(path=path, title=title): self.assertEqual(actual, expected) + def test_a_client_side_route_change_reads_the_new_route(self) -> None: + proc = subprocess.run( + [ + "node", + "-e", + NAVIGATION_HARNESS, + _render(), + json.dumps([list(case[:4]) for case in NAVIGATIONS]), + ], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + for case, actual in zip(NAVIGATIONS, json.loads(proc.stdout), strict=True): + with self.subTest(navigation=f"{case[0]} -> {case[2]}"): + self.assertEqual(actual, case[4]) + if __name__ == "__main__": unittest.main() From c3a3eb307e2982c860f86d2e75f4b98bd2e81e9d Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 12:14:31 +0000 Subject: [PATCH 43/65] test: autoescape the Semaphore env render and assert the once-flag control by value MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR 2488 turned red in lint-python and CodeQL on two test changes. test_external_auth_matching.py built a jinja2.Environment without autoescape (ruff S701, CodeQL Jinja2 templating with autoescape=False); it now passes autoescape=jinja2.select_autoescape(), which leaves the env.j2 render unescaped because the template name has no html or xml extension. test_once_flag_before_post_load.py compared with assertTrue(a == b) (CodeQL imprecise assert); it now uses assertEqual, so a failure prints the findings. Negative control: ruff check of the committed Semaphore test reports S701 at line 24, the new file passes. Tests: KIX and Semaphore unit tests plus the once-flag, comment and import lints, 35 passed, 20 subtests. 🎯 Fix: 95 % 💥 Break: 1 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 94 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- tests/lint/ansible/roles/test_once_flag_before_post_load.py | 2 +- .../roles/web-app-semaphore/test_external_auth_matching.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/lint/ansible/roles/test_once_flag_before_post_load.py b/tests/lint/ansible/roles/test_once_flag_before_post_load.py index 4dd255ed40..3971767ccc 100644 --- a/tests/lint/ansible/roles/test_once_flag_before_post_load.py +++ b/tests/lint/ansible/roles/test_once_flag_before_post_load.py @@ -62,7 +62,7 @@ class TestOnceFlagBeforePostLoad(unittest.TestCase): tasks = load_yaml_str(read_text(str(core))) flag = next(i for i, t in enumerate(tasks) if t.get("include_tasks") == FLAG) planted = tasks[:flag] + tasks[flag + 1 :] + [tasks[flag]] - self.assertTrue(order_findings(tasks) == []) + self.assertEqual(order_findings(tasks), []) self.assertNotEqual(order_findings(planted), []) diff --git a/tests/unit/python/roles/web-app-semaphore/test_external_auth_matching.py b/tests/unit/python/roles/web-app-semaphore/test_external_auth_matching.py index becf749e0a..ab17520d19 100644 --- a/tests/unit/python/roles/web-app-semaphore/test_external_auth_matching.py +++ b/tests/unit/python/roles/web-app-semaphore/test_external_auth_matching.py @@ -23,6 +23,7 @@ def render(*, oidc: bool, ldap: bool) -> list[str]: source = read_text(str(PROJECT_ROOT / ENV_TEMPLATE)) environment = jinja2.Environment( loader=jinja2.DictLoader({ENV_TEMPLATE: source, INCLUDED: ""}), + autoescape=jinja2.select_autoescape(), undefined=jinja2.ChainableUndefined, ) environment.filters["bool"] = bool From 861a727ba0c5f7aae686e7dbb1f24819ceb4f909 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 12:18:30 +0000 Subject: [PATCH 44/65] test: import unittest.mock without an alias next to unittest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeQL flagged two test files of PR 2226 with Module is imported with import and import from (alerts on test_covered_rows_are_deployed.py:18 and test_reach.py:6): both import unittest and also import unittest.mock as mock, which CodeQL reads as a from-import. Both now import unittest.mock plainly and call unittest.mock.patch and unittest.mock.Mock, so the module is only ever imported with import. No behaviour change. Tests on the exported PR tree, isolated from other checkouts with python -P: both files plus the repository import lint, 22 passed; ruff check and format clean. 🎯 Fix: 92 % 💥 Break: 1 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 91 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../test_covered_rows_are_deployed.py | 6 ++--- .../applications/complexity/test_reach.py | 22 ++++++++++--------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/tests/integration/meta/workflows/test_covered_rows_are_deployed.py b/tests/integration/meta/workflows/test_covered_rows_are_deployed.py index 027561df36..f9b706aa9c 100644 --- a/tests/integration/meta/workflows/test_covered_rows_are_deployed.py +++ b/tests/integration/meta/workflows/test_covered_rows_are_deployed.py @@ -16,7 +16,7 @@ from __future__ import annotations import functools import os import unittest -import unittest.mock as mock +import unittest.mock from cli.administration.deploy.development.inventory import ( plan_dev_inventory_matrix, @@ -124,7 +124,7 @@ def _deployed(app: str, index: int, mode: str, tokens: str) -> frozenset[str]: """ variants, include = _rounds(app)[index] if mode == "swarm": - with mock.patch.dict(os.environ, {"disable": tokens}): + with unittest.mock.patch.dict(os.environ, {"disable": tokens}): return frozenset(derive_includes(app, variants=variants)) if not tokens: return frozenset(include) @@ -242,7 +242,7 @@ class TestCoveredRowsAreDeployed(unittest.TestCase): for row, coverer in _covered() if _modes(coverer) & {"compose", "host"} ) - with mock.patch.object( + with unittest.mock.patch.object( network, "disabled_services", lambda state, include: row["name"] ): self.assertTrue(_losses(row, coverer)) diff --git a/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py b/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py index 92a6fbdefd..9f646803c5 100644 --- a/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py +++ b/tests/unit/python/cli/meta/roles/applications/complexity/test_reach.py @@ -4,7 +4,7 @@ its round still runs once each network's ``disable`` is applied.""" from __future__ import annotations import unittest -import unittest.mock as mock +import unittest.mock from types import SimpleNamespace from cli.meta.roles.applications.complexity import reach @@ -55,32 +55,34 @@ class _Fixture: for fn in caches: fn.cache_clear() self.addCleanup(fn.cache_clear) - self.row_states = mock.Mock(return_value=("clearnet", "tor", "multi")) + self.row_states = unittest.mock.Mock(return_value=("clearnet", "tor", "multi")) for patch in ( - mock.patch.object(reach, "_round_of", return_value=ROUND), - mock.patch.object(reach, "get_variants", return_value={}), - mock.patch.object(reach.network, "row_states", self.row_states), - mock.patch.object( + unittest.mock.patch.object(reach, "_round_of", return_value=ROUND), + unittest.mock.patch.object(reach, "get_variants", return_value={}), + unittest.mock.patch.object(reach.network, "row_states", self.row_states), + unittest.mock.patch.object( reach.network, "tor_provider", return_value="svc-net-tor" ), - mock.patch.object( + unittest.mock.patch.object( reach.network, "network_states", side_effect=lambda mode, states, network_input: STATES[mode], ), - mock.patch.object( + unittest.mock.patch.object( reach.network, "disabled_services", side_effect=lambda state, include: DISABLE[state], ), - mock.patch.object( + unittest.mock.patch.object( reach, "find_provider_roles", side_effect=lambda services, roles_dir: { s: PROVIDERS[s] for s in services }, ), - mock.patch.object(reach, "prune_orphans_after_disable", side_effect=_prune), + unittest.mock.patch.object( + reach, "prune_orphans_after_disable", side_effect=_prune + ), ): patch.start() self.addCleanup(patch.stop) From 33084997018159b31467052ef85aea95f1fc161b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 15:07:27 +0000 Subject: [PATCH 45/65] feat(ci): add a Run all PR label and emoji CI labels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A PR run stops at its first failure: on pull request events the deploy matrix runs with fail-fast, so one failed row cancels the rest of its batch, and the batch 1 gate stops every later batch, so PR #2006 showed one failure per run. With the 🏃 Run all label the PR workflow calls the orchestrator with chunk_gate false, and call-test-deploy ties the matrix fail-fast to chunk_gate, so every row and batch deploys to its end; push and dispatch runs are unchanged. Every labeled event used to cancel the running PR pipeline and start a new one (42 of the last 200 PR runs): a run whose jobs all skip still joins the concurrency group, and the superseded-run canceller keeps it as the newest. Only 🧩 Subset, 🛡️ Trusted and 🏃 Run all now restart PR CI; any other label gets a group of its own and skips, in the PR workflow and in the canceller. The labels CI sets carry an emoji: ⬆️ update, 🔴 major, 🟡 minor, 🟢 patch, 💥 ci-failure, 🔓 vulnerability, 🔥 vulnerability-runtime, 💤 stale. pr.sh labels updater PRs through the label CLI with a new --level option, which also drops a stale level label when an existing PR changes level. test_pr_ci_labels.py keeps the three label lists equal and fails against the main workflows. Tests: update, security, meta/ci, workflow and repository lint suites green after the fixture updates (65 + 3 passed, 826 in the first full run); MEDUSA 100 %. 🎯 Fix: 88 % 💥 Break: 7 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 82 🚦 Gate: ⛔ fix 88 % < 90, break 7 % > 5 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 16 ++-- .github/workflows/call-orchestrator.yml | 6 +- .github/workflows/call-test-deploy.yml | 6 +- .github/workflows/cron-cleanup-stale.yml | 4 +- .github/workflows/entry-cancel-superseded.yml | 4 +- .../workflows/entry-pr-change-orchestrate.yml | 13 ++- cli/contributing/security/README.md | 4 +- cli/contributing/security/issues/__main__.py | 2 +- cli/contributing/update/README.md | 2 +- cli/contributing/update/label/__init__.py | 8 +- cli/contributing/update/label/__main__.py | 33 ++++--- cli/meta/ci/report_failures.py | 2 +- cli/meta/ci/runtime_vulnerabilities.py | 2 +- docs/contributing/artefact/git/pipeline.md | 6 +- .../tools/github/actions/configuration.md | 4 +- .../tools/github/actions/workflows.md | 8 +- scripts/github/update/open/pr.sh | 12 +-- .../test_cancel_superseded_workflow.py | 7 +- .../meta/workflows/test_pr_ci_labels.py | 90 +++++++++++++++++++ .../contributing/update/label/test_main.py | 75 +++++++++++----- .../contributing/update/merge/test_gate.py | 3 +- .../contributing/update/merge/test_main.py | 5 +- 22 files changed, 233 insertions(+), 79 deletions(-) create mode 100644 tests/integration/meta/workflows/test_pr_ci_labels.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml index b51f38680d..5ee2efb9ad 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -15,7 +15,7 @@ updates: rebase-strategy: "auto" labels: - "dependencies" - - "update" + - "⬆️ update" - "python" # ------------------------------------------------------------ @@ -30,7 +30,7 @@ updates: time: "00:00" labels: - "dependencies" - - "update" + - "⬆️ update" - "ci" # ------------------------------------------------------------ @@ -45,7 +45,7 @@ updates: time: "00:00" labels: - "dependencies" - - "update" + - "⬆️ update" - "docker" # ------------------------------------------------------------ @@ -60,7 +60,7 @@ updates: time: "00:00" labels: - "dependencies" - - "update" + - "⬆️ update" - "docker" # ------------------------------------------------------------ @@ -79,7 +79,7 @@ updates: time: "00:00" labels: - "dependencies" - - "update" + - "⬆️ update" - "ci" # ------------------------------------------------------------ @@ -95,7 +95,7 @@ updates: time: "00:00" labels: - "dependencies" - - "update" + - "⬆️ update" - "javascript" # ------------------------------------------------------------ @@ -110,7 +110,7 @@ updates: time: "00:00" labels: - "dependencies" - - "update" + - "⬆️ update" - "php" # ------------------------------------------------------------ @@ -195,7 +195,7 @@ updates: time: "00:00" labels: - "dependencies" - - "update" + - "⬆️ update" - "ruby" # cargo: no Cargo.toml found diff --git a/.github/workflows/call-orchestrator.yml b/.github/workflows/call-orchestrator.yml index cc1ac3fff9..ff70b48cab 100644 --- a/.github/workflows/call-orchestrator.yml +++ b/.github/workflows/call-orchestrator.yml @@ -48,7 +48,7 @@ on: type: string default: "0" chunk_gate: - description: "🛑 Stop the chunk chain at its first failed chunk; batch 1 also waits for a running workspace test and stops when it failed. Off: keep deploying the remaining chunks." + description: "🛑 Stop the chunk chain at its first failed chunk; batch 1 also waits for a running workspace test and stops when it failed. On a pull request a failed row also cancels the rest of its chunk. Off: keep deploying every row and chunk." required: false type: boolean default: true @@ -198,6 +198,7 @@ jobs: with: distros: ${{ inputs.distros }} index: "0" + chunk_gate: ${{ inputs.chunk_gate }} marker: ${{ needs.validate-selection.outputs.starred > 0 && ' ⭐' || '' }} sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} offset: ${{ inputs.offset }} @@ -254,6 +255,7 @@ jobs: with: distros: ${{ inputs.distros }} index: "1" + chunk_gate: ${{ inputs.chunk_gate }} marker: ${{ needs.validate-selection.outputs.starred > 1 && ' ⭐' || '' }} sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} offset: ${{ inputs.offset }} @@ -294,6 +296,7 @@ jobs: with: distros: ${{ inputs.distros }} index: "2" + chunk_gate: ${{ inputs.chunk_gate }} marker: ${{ needs.validate-selection.outputs.starred > 2 && ' ⭐' || '' }} sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} offset: ${{ inputs.offset }} @@ -336,6 +339,7 @@ jobs: with: distros: ${{ inputs.distros }} index: "3" + chunk_gate: ${{ inputs.chunk_gate }} marker: ${{ needs.validate-selection.outputs.starred > 3 && ' ⭐' || '' }} sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} offset: ${{ inputs.offset }} diff --git a/.github/workflows/call-test-deploy.yml b/.github/workflows/call-test-deploy.yml index d9cb405b8d..6bc49318e5 100644 --- a/.github/workflows/call-test-deploy.yml +++ b/.github/workflows/call-test-deploy.yml @@ -12,6 +12,10 @@ on: description: "Chunk index this call deploys; chunks run serially, one block per index." required: true type: string + chunk_gate: + description: "The orchestrator's chunk gate. On a pull request it also cancels the chunk's remaining rows at its first failed row; other events always run every row." + required: true + type: boolean sweep: description: "Sweep number driving the mode and network rotation and the regular-line offset." required: true @@ -368,7 +372,7 @@ jobs: queue: max strategy: - fail-fast: ${{ github.event_name == 'pull_request' || github.event_name == 'pull_request_target' }} + fail-fast: ${{ (github.event_name == 'pull_request' || github.event_name == 'pull_request_target') && inputs.chunk_gate }} matrix: include: ${{ fromJson(needs.discover.outputs.apps) }} diff --git a/.github/workflows/cron-cleanup-stale.yml b/.github/workflows/cron-cleanup-stale.yml index 471b59a26b..e68c05a4d6 100644 --- a/.github/workflows/cron-cleanup-stale.yml +++ b/.github/workflows/cron-cleanup-stale.yml @@ -23,7 +23,7 @@ jobs: with: days-before-issue-stale: 90 days-before-issue-close: 7 - stale-issue-label: "stale" + stale-issue-label: "💤 stale" stale-issue-message: > This issue has been marked as stale because it has had no activity for the last 90 days. It will be automatically closed in 7 days @@ -33,7 +33,7 @@ jobs: days-before-pr-stale: 180 days-before-pr-close: 30 - stale-pr-label: "stale" + stale-pr-label: "💤 stale" stale-pr-message: > This pull request has been marked as stale because it has had no activity for the last 180 days. It will be automatically closed in diff --git a/.github/workflows/entry-cancel-superseded.yml b/.github/workflows/entry-cancel-superseded.yml index 85ed6ee1db..33709ad76f 100644 --- a/.github/workflows/entry-cancel-superseded.yml +++ b/.github/workflows/entry-cancel-superseded.yml @@ -51,7 +51,9 @@ jobs: cancel-pull-request-runs: name: 🚫 Cancel superseded pull request runs - if: ${{ github.event_name == 'pull_request_target' }} + if: >- + ${{ github.event_name == 'pull_request_target' + && (github.event.action != 'labeled' || contains(fromJSON('["🧩 Subset", "🛡️ Trusted", "🏃 Run all"]'), github.event.label.name)) }} runs-on: ubuntu-26.04 permissions: actions: write diff --git a/.github/workflows/entry-pr-change-orchestrate.yml b/.github/workflows/entry-pr-change-orchestrate.yml index 4f2921e911..b5165c2e69 100644 --- a/.github/workflows/entry-pr-change-orchestrate.yml +++ b/.github/workflows/entry-pr-change-orchestrate.yml @@ -18,8 +18,13 @@ on: - ready_for_review - labeled +# Exception: a skipped run still joins its concurrency group and cancels the running pipeline, so a label CI ignores gets a group of its own. concurrency: - group: pr-ci-${{ github.repository }}-${{ github.event_name }}-pr-${{ github.event.pull_request.number }} + group: >- + ${{ github.event.action == 'labeled' + && !contains(fromJSON('["🧩 Subset", "🛡️ Trusted", "🏃 Run all"]'), github.event.label.name) + && format('pr-label-{0}', github.run_id) + || format('pr-ci-{0}-{1}-pr-{2}', github.repository, github.event_name, github.event.pull_request.number) }} cancel-in-progress: true permissions: @@ -28,7 +33,10 @@ permissions: jobs: detect-pr-scope: name: 🔎 Detect PR scope - if: ${{ github.event.pull_request.draft == false && (github.event_name == 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository) }} + if: >- + ${{ github.event.pull_request.draft == false + && (github.event_name == 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository) + && (github.event.action != 'labeled' || contains(fromJSON('["🧩 Subset", "🛡️ Trusted", "🏃 Run all"]'), github.event.label.name)) }} runs-on: ubuntu-26.04 outputs: scope: ${{ steps.resolve.outputs.scope }} @@ -117,6 +125,7 @@ jobs: with: distros: "arch debian ubuntu fedora centos" whitelist: ${{ needs.detect-affected-roles.outputs.whitelist }} + chunk_gate: ${{ !contains(github.event.pull_request.labels.*.name, '🏃 Run all') }} trusted_pr: ${{ contains(github.event.pull_request.labels.*.name, '🛡️ Trusted') }} prepare-fork-merge-ref: diff --git a/cli/contributing/security/README.md b/cli/contributing/security/README.md index 58a3aa7957..9f7d693458 100644 --- a/cli/contributing/security/README.md +++ b/cli/contributing/security/README.md @@ -7,5 +7,5 @@ Repository-side vulnerability tooling over the pinned role images, built on the | `make test-security` | Runs `scan`: Syft builds an SBOM of every pinned image straight from the GHCR mirror, cached by digest under `build/security/sbom`, and Trivy, Grype and OSV scan that SBOM tree with the role's threshold and suppressions. Every finding at the threshold goes to `build/test-reports/security.json`, a suppressed one with its `suppressed_until` day. The scan fails only on an engine or mirror error; the unsuppressed findings reach the vulnerability issues instead. | | `python -m cli.contributing.security.database --dir --engines ...` | Downloads the Trivy, Grype and OSV databases a CI deploy reads. | | `python -m cli.contributing.security.summary --report --counts --summary ` | Counts the failing findings of the report per image and per CVE, plus the suppressed total, into a JSON file and appends the tables to a Markdown summary. | -| `python -m cli.contributing.security.issues --report --repo ` | Opens one `vulnerability` issue per image of the report that lists its CVEs, suppressed ones with their `suppressed_until` day, updates it while it stays, and closes it once no engine reports a CVE for the image. The head line counts the CVEs per severity. | -| `python -m cli.meta.ci.runtime_vulnerabilities --run-id --repo --ref --dir ` | Run by the `report-main-failures` job of every `main` run, never for another ref: reads the hlth-runtime lines of the deploys' `rescue-diagnostics-*` journals into the same issue format under its own `vulnerability-runtime` label, one issue per image and one `host ` issue per distro. It closes an issue only when a deploy of the run scanned that target without an engine error and reported nothing, so neither sync ever touches the other's issues. | +| `python -m cli.contributing.security.issues --report --repo ` | Opens one `🔓 vulnerability` issue per image of the report that lists its CVEs, suppressed ones with their `suppressed_until` day, updates it while it stays, and closes it once no engine reports a CVE for the image. The head line counts the CVEs per severity. | +| `python -m cli.meta.ci.runtime_vulnerabilities --run-id --repo --ref --dir ` | Run by the `report-main-failures` job of every `main` run, never for another ref: reads the hlth-runtime lines of the deploys' `rescue-diagnostics-*` journals into the same issue format under its own `🔥 vulnerability-runtime` label, one issue per image and one `host ` issue per distro. It closes an issue only when a deploy of the run scanned that target without an engine error and reported nothing, so neither sync ever touches the other's issues. | diff --git a/cli/contributing/security/issues/__main__.py b/cli/contributing/security/issues/__main__.py index 12ad3fece6..3f9e3c07f6 100755 --- a/cli/contributing/security/issues/__main__.py +++ b/cli/contributing/security/issues/__main__.py @@ -37,7 +37,7 @@ class Tracker(NamedTuple): covers: Callable[[Mapping[str, Any], str], bool] -LABEL = "vulnerability" +LABEL = "🔓 vulnerability" LABEL_COLOR = "B60205" LABEL_DESCRIPTION = "A pinned image carries a CVE at the scan threshold" MIRROR = Tracker( diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index 8d2d2f9fa5..7b84af11d0 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -18,7 +18,7 @@ Every role-scoped updater (`docker`, `source`, `pip`, `repository`) and the addo A branch name and a short SHA stay as they are. `# nocheck: repository-version` on the line above `ref:` freezes a pin. Each repository is queried once per run and lookup, and a failed query leaves its pins untouched. The `update-repository-refs` job of `.github/workflows/cron-update.yml` opens one PR per changed role, and `tests/external/update/repository/` warns about pending bumps and fails on a commit SHA that a release tag already contains. A pin newer than the newest release keeps following the tip, so no pin moves back to an older release. -Every update PR carries the label `update` and one of `major`, `minor` or `patch`: the highest step among its changed versions, read by [level.py](../../../utils/update/level.py). A change that is no number step (a commit SHA, a SHA moving to a tag) counts as `major`. +Every update PR carries the label `⬆️ update` and one of `🔴 major`, `🟡 minor` or `🟢 patch`: the highest step among its changed versions, read by [level.py](../../../utils/update/level.py). A change that is no number step (a commit SHA, a SHA moving to a tag) counts as `🔴 major`. ## Declared version sources diff --git a/cli/contributing/update/label/__init__.py b/cli/contributing/update/label/__init__.py index ead172a6cf..6af67d0125 100644 --- a/cli/contributing/update/label/__init__.py +++ b/cli/contributing/update/label/__init__.py @@ -19,12 +19,12 @@ class Label(NamedTuple): description: str -UPDATE = Label("update", "0366D6", "Automated dependency or version update") +UPDATE = Label("⬆️ update", "0366D6", "Automated dependency or version update") MAJOR = Label( - "major", "B60205", "Update raises a major version, or one of unknown reach" + "🔴 major", "B60205", "Update raises a major version, or one of unknown reach" ) -MINOR = Label("minor", "FBCA04", "Update raises a minor version") -PATCH = Label("patch", "0E8A16", "Update raises a patch version") +MINOR = Label("🟡 minor", "FBCA04", "Update raises a minor version") +PATCH = Label("🟢 patch", "0E8A16", "Update raises a patch version") LEVELS = (MAJOR, MINOR, PATCH) __all__ = ["LEVELS", "MAJOR", "MINOR", "PATCH", "UPDATE", "Label"] diff --git a/cli/contributing/update/label/__main__.py b/cli/contributing/update/label/__main__.py index 460c355ccb..0f76f5c861 100755 --- a/cli/contributing/update/label/__main__.py +++ b/cli/contributing/update/label/__main__.py @@ -19,6 +19,7 @@ _LEVEL_OF_UPDATE_TYPE = { "version-update:semver-minor": MINOR, "version-update:semver-patch": PATCH, } +LEVEL_OF_NAME = {"major": MAJOR, "minor": MINOR, "patch": PATCH} def level(update_type: str) -> Label: @@ -100,21 +101,21 @@ def ensure_labels( def sync( - gh: Callable[[Sequence[str]], str], repo: str, pr: int, update_type: str + gh: Callable[[Sequence[str]], str], repo: str, pr: int, semver: Label ) -> list[str]: - """Leave *pr* carrying ``update`` and exactly one semver label. + """Leave *pr* carrying the update label and exactly one semver label. Args: gh: runs ``gh`` with the given arguments and returns its stdout. repo: ``owner/name``. pr: the pull request number. - update_type: the ``update-type`` output of ``dependabot/fetch-metadata``. + semver: the semver label the pull request must carry. Returns: what was done, one line per action. A label the pull request already - carries is not added again: a ``labeled`` event restarts its CI run. + carries is not added again. """ - wanted = (UPDATE, level(update_type)) + wanted = (UPDATE, semver) actions = [f"created label {name}" for name in ensure_labels(gh, repo, wanted)] current = names(gh, f"repos/{repo}/issues/{pr}/labels") for stale in LEVELS: @@ -141,8 +142,9 @@ def sync( def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser( description=( - "Label a Dependabot pull request `update` plus exactly one of " - "`major`, `minor` and `patch`, creating labels the repository lacks." + f"Label an update pull request `{UPDATE.name}` plus exactly one of " + f"{', '.join(f'`{label.name}`' for label in LEVELS)}, creating " + "labels the repository lacks." ) ) parser.add_argument("--repo", required=True, help="owner/name") @@ -156,14 +158,25 @@ def main(argv: Sequence[str] | None = None) -> int: "--update-type", help="update-type output of dependabot/fetch-metadata, possibly empty", ) + parser.add_argument( + "--level", + choices=sorted(LEVEL_OF_NAME), + help="semver level utils.update.level printed for an updater pull request", + ) args = parser.parse_args(argv) if args.ensure_only: for name in ensure_labels(run_gh, args.repo, (UPDATE, *LEVELS)): print(f"created label {name}") return 0 - if args.pr is None or args.update_type is None: - parser.error("--pr and --update-type are required without --ensure-only") - actions = sync(run_gh, args.repo, args.pr, args.update_type) + if args.pr is None or (args.update_type is None) == (args.level is None): + parser.error( + "--pr and exactly one of --update-type and --level are required " + "without --ensure-only" + ) + semver = ( + level(args.update_type) if args.level is None else LEVEL_OF_NAME[args.level] + ) + actions = sync(run_gh, args.repo, args.pr, semver) for line in actions or [f"#{args.pr} already carries its labels"]: print(line) return 0 diff --git a/cli/meta/ci/report_failures.py b/cli/meta/ci/report_failures.py index a1f59c8c15..6c608cdd2a 100644 --- a/cli/meta/ci/report_failures.py +++ b/cli/meta/ci/report_failures.py @@ -16,7 +16,7 @@ from utils.roles.display import display_names _DECISIVE_FILES = ("error-context.md", "meta.txt", "containers.txt") _TITLE = "CI failure: {role}" -_LABEL = "ci-failure" +_LABEL = "💥 ci-failure" class Failure(NamedTuple): diff --git a/cli/meta/ci/runtime_vulnerabilities.py b/cli/meta/ci/runtime_vulnerabilities.py index f505cff499..05250f45bc 100644 --- a/cli/meta/ci/runtime_vulnerabilities.py +++ b/cli/meta/ci/runtime_vulnerabilities.py @@ -39,7 +39,7 @@ FINDING = re.compile( EVENT_MARK = '{"event": "hlth_runtime.' EVENT = re.compile(r"\{\"event\": \"hlth_runtime\.(?:target|summary)\".*$") RUNTIME = Tracker( - label="vulnerability-runtime", + label="🔥 vulnerability-runtime", color="D93F0B", description="hlth-runtime reports a CVE at the threshold on a main deploy", source=lambda row: f"Runtime: `{row['runtime']}`", diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index 865aebd255..6133536d92 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -115,6 +115,10 @@ The subset path fails the run when: The `🧩 Subset` label must exist in the repository's label set and is applied through the PR labels UI. Both the `pull_request` and `pull_request_target` events carry a `labeled` trigger, so adding it starts a fresh run. +#### Run all label 🏃 + +By default a PR run stops at its first failure: a failed deploy row cancels the rest of its batch (matrix `fail-fast`), and the `1️⃣ Gate` stops every later batch. Apply the `🏃 Run all` label to see every failure of a PR in one run instead: [entry-pr-change-orchestrate.yml](../../../../.github/workflows/entry-pr-change-orchestrate.yml) then calls the orchestrator with `chunk_gate: false`, so every row of every batch deploys to its end. Lint, code tests and the CI image build still gate the deploys. Adding the label starts a fresh run; removing it changes nothing until the next push. + ### 10. Installation Tests 📦 The install-test workflows listed in the `Infrastructure tests` table of [workflows.md](../../tools/github/actions/workflows.md) run in parallel once `code-quality-gate` is green. All of them MUST pass `test-install-gate`. @@ -159,4 +163,4 @@ Security gates: - Build-orchestration scripts (`scripts/image/push.sh` and the helper checkout) always come from the base repo at `github.sha`; only the Docker build **context** (`_src`) is the fork head. `persist-credentials: false` keeps the token out of the source checkout, and `USE_NIX_TOKEN` stays disabled for fork-sourced builds. - Fork `pull_request` runs always receive a read-only token (GitHub-enforced); the label never grants write tokens or secrets to the untrusted event. -Both events carry a `labeled` trigger, so applying the `🛡️ Trusted` label starts fresh runs that already observe it: the `pull_request_target` build switches to the PR head and the `pull_request` orchestrator skips the wait — no extra push is needed. (Re-running an existing run does not pick up a new label, because GitHub replays the original event payload.) The trade-off is that any label change starts a fresh PR CI run. +Both events carry a `labeled` trigger, so applying the `🛡️ Trusted` label starts fresh runs that already observe it: the `pull_request_target` build switches to the PR head and the `pull_request` orchestrator skips the wait — no extra push is needed. (Re-running an existing run does not pick up a new label, because GitHub replays the original event payload.) Only the labels CI reads (`🧩 Subset`, `🛡️ Trusted`, `🏃 Run all`) start a fresh run; any other label gets a concurrency group of its own and skips every job, so it neither cancels nor restarts the running pipeline. diff --git a/docs/contributing/tools/github/actions/configuration.md b/docs/contributing/tools/github/actions/configuration.md index 9e0f1d2eb5..4b9e8eb3b7 100644 --- a/docs/contributing/tools/github/actions/configuration.md +++ b/docs/contributing/tools/github/actions/configuration.md @@ -161,14 +161,14 @@ Dependabot cannot read repository variables itself, so [entry-pr-open-dependabot | `true` | Run ✓ | Stay open ✓ | | any other value | Skipped ✓ | Auto-closed on open ✓ | -The same guard sits on [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml), which labels Dependabot PRs `update` plus `major`, `minor` or `patch`, and on [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml), which merges an update PR once CI proved it. With the variable unset, neither labels nor merges anything. +The same guard sits on [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml), which labels Dependabot PRs `⬆️ update` plus `🔴 major`, `🟡 minor` or `🟢 patch`, and on [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml), which merges an update PR once CI proved it. With the variable unset, neither labels nor merges anything. ### Automatic merge 🔀 An update PR merges itself only when all of these hold; otherwise the job prints the failing condition and the PR waits for a manual merge: 1. Its `🔀 Pull Request` run of the `pull_request` event concluded `success`. -2. `infinito-nexus-updater[bot]` opened it from `update/*`, or `dependabot[bot]` from `dependabot/*`, in this repository, against the default branch, not as a draft, and it carries the `update` label. +2. `infinito-nexus-updater[bot]` opened it from `update/*`, or `dependabot[bot]` from `dependabot/*`, in this repository, against the default branch, not as a draft, and it carries the `⬆️ update` label. 3. Every latest check run on its head commit completed as `success`, `skipped` or `neutral`, and every commit status is `success`. A check still running counts as not green; no later run retries the merge. 4. Every role under `roles//` the PR changes appears in the `role` column of a `role-runtimes-*` artifact of that run. A PR that changes no role needs no artifact; a missing artifact proves nothing. diff --git a/docs/contributing/tools/github/actions/workflows.md b/docs/contributing/tools/github/actions/workflows.md index d3063aa350..2f4fcf3352 100644 --- a/docs/contributing/tools/github/actions/workflows.md +++ b/docs/contributing/tools/github/actions/workflows.md @@ -25,10 +25,10 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | Workflow | Description | Trigger | Inputs | |---|---|---|---| -| [entry-pr-change-orchestrate.yml](../../../../../.github/workflows/entry-pr-change-orchestrate.yml): `🔀 Pull Request` | Detects PR scope from changed files + branch prefix, then conditionally calls the orchestrator. A maintainer `🛡️ Trusted` label builds the privileged images from the PR head — see [pipeline.md](../../../artefact/git/pipeline.md#trusted-fork-prs-). A `🧩 Subset` label pins the deploy matrix to the roles listed in the PR body — see [pipeline.md](../../../artefact/git/pipeline.md#subset-label-). | auto (`pull_request` & `pull_request_target`: opened, synchronize, reopened, ready_for_review, labeled) | none | +| [entry-pr-change-orchestrate.yml](../../../../../.github/workflows/entry-pr-change-orchestrate.yml): `🔀 Pull Request` | Detects PR scope from changed files + branch prefix, then conditionally calls the orchestrator. A maintainer `🛡️ Trusted` label builds the privileged images from the PR head — see [pipeline.md](../../../artefact/git/pipeline.md#trusted-fork-prs-). A `🧩 Subset` label pins the deploy matrix to the roles listed in the PR body — see [pipeline.md](../../../artefact/git/pipeline.md#subset-label-). A `🏃 Run all` label deploys every row and batch past the first failure — see [pipeline.md](../../../artefact/git/pipeline.md#run-all-label-). A `labeled` event for any other label skips every job. | auto (`pull_request` & `pull_request_target`: opened, synchronize, reopened, ready_for_review, labeled) | none | | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml): `📤 Push` | Syncs `main` from the configured source repository, then runs the orchestrator on pushes to `main`, `feature/**`, `hotfix/**`, `fix/**`, `update/**`, `chore/**`, `alert-autofix-*`; on tagged `main` it also calls `call-release-version.yml`. Respects the `CI_SYNC_MAIN_SOURCE_REPOSITORY` and `CI_RUN_ON_MAIN` repository variables, see [configuration.md](configuration.md). | auto (`push`) | none | | [entry-manual-steer.yml](../../../../../.github/workflows/entry-manual-steer.yml): `🕹️ Manual` | Manual dispatch of the full orchestrator for a chosen app whitelist. The `whitelist` input accepts the `__ALL__` sentinel for forced full deploy; see the "Diff-driven app selection" subsection in [pipeline.md](../../../artefact/git/pipeline.md). | manual | `distros` (optional; empty spreads the rows over every declared distro), `filesystem` (optional; empty spreads them over `zfs`, `btrfs`, `ext4`), `whitelist` (optional; `__ALL__` forces full deploy, empty triggers diff derivation, any other value is verbatim), `lifecycles`, `mode` (default `auto`), `priority` (optional; priority rows get chunks of their own, the regular chunks run after them), `offset` (default `0`; a row count or a selection token naming where the regular line resumes), `chunk_gate` (default `true`), `sweep` (optional; empty means the run number) | -| [entry-cancel-superseded.yml](../../../../../.github/workflows/entry-cancel-superseded.yml): `🚫 Cancel: Superseded Runs` | Cancels the runs superseded by a newer one on the same branch or PR via the API, for the case where the concurrency group fails to reap its occupant and the newer run parks on `pending` behind it — see [cancel/README.md](../../../../../scripts/github/cancel/README.md). Carries no concurrency group of its own, otherwise it would queue behind the run it has to free, and only touches the workflows that share the group it backs up. The push job skips `main` like the `global-ci-*` group it backs up, see [configuration.md](configuration.md). | auto (`push` except `main`, `pull_request_target`: opened, synchronize, reopened, ready_for_review, labeled) | none | +| [entry-cancel-superseded.yml](../../../../../.github/workflows/entry-cancel-superseded.yml): `🚫 Cancel: Superseded Runs` | Cancels the runs superseded by a newer one on the same branch or PR via the API, for the case where the concurrency group fails to reap its occupant and the newer run parks on `pending` behind it — see [cancel/README.md](../../../../../scripts/github/cancel/README.md). Carries no concurrency group of its own, otherwise it would queue behind the run it has to free, and only touches the workflows that share the group it backs up. The push job skips `main` like the `global-ci-*` group it backs up, see [configuration.md](configuration.md). The pull request job skips a `labeled` event for a label CI does not read, like the `🔀 Pull Request` run it would otherwise keep as the newest. | auto (`push` except `main`, `pull_request_target`: opened, synchronize, reopened, ready_for_review, labeled) | none | | [entry-pr-closed-cancel-workflows.yml](../../../../../.github/workflows/entry-pr-closed-cancel-workflows.yml): `🚫 Cancel: PR Runs on Close` | Cancels active workflow runs for a PR when it is closed or converted to draft. | auto (`pull_request_target`: closed, converted_to_draft) | none | | [entry-delete-branch.yml](../../../../../.github/workflows/entry-delete-branch.yml): `🚫 Cancel: Runs on Branch Delete` | Enters the push-entry concurrency group for the deleted branch so that any in-flight run on it is cancelled; a fallback step cancels remaining runs via the API. | auto (`delete`) | none | @@ -86,8 +86,8 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | [cron-update.yml](../../../../../.github/workflows/cron-update.yml): `🔄 Update versions` | Updates Docker image versions and other pinned dependencies; opens an update PR via a GitHub App installation token so PR-lifecycle events fire on the resulting PR. Both jobs are gated behind the `CI_ENABLE_AUTO_UPDATES` repository variable, see [configuration.md](configuration.md). Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`push` to `main`, `schedule`: daily 00:30 UTC), manual | none | | [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml): `🌐 Translate catalogs` | Merges the source strings of the `core` and `docs` domains into `locale/`, then machine-translates what a pull request leaves empty or fuzzy, one runner per language LibreTranslate supports. Each runner opens its own PR against the head branch of the triggering PR. Gated behind the `CI_ENABLE_AUTO_TRANSLATIONS` repository variable, see [configuration.md](configuration.md); pull requests from a fork are skipped. Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`pull_request` against `main`: opened, synchronize, reopened) | none | | [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml): `🚫 Dependabot: Close while auto-updates disabled` | Auto-closes Dependabot PRs while `CI_ENABLE_AUTO_UPDATES` is not set to `true`, so Dependabot honours the same gate as the workflow-driven update jobs. See [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened) | none | -| [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml): `🔄 Dependabot: Label update level` | Labels every Dependabot PR `update` plus exactly one of `major`, `minor` and `patch`, read from the `update-type` of `dependabot/fetch-metadata`; a type that names no semver level counts as `major`. Creates a missing label, adds only labels the PR lacks and checks out the base branch only. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened, synchronize) | none | -| [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml): `🔄 Update: Merge proven PRs` | Runs when a `🔀 Pull Request` run of the `pull_request` event succeeds on an `update/*` or `dependabot/*` branch. [cli.contributing.update.merge](../../../../../cli/contributing/update/merge/__main__.py) merges the PR only when the `infinito-nexus-updater[bot]` App or `dependabot[bot]` opened it, it carries `update`, every check run and commit status on its head is green, and the run's `role-runtimes-*` artifacts list every role the PR changes. Otherwise it prints why and the PR stays open for a manual merge. The merge pins the tested head and uses the App token, so the App MUST be a bypass actor of the `Main` ruleset. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md); requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`workflow_run` of `🔀 Pull Request`: completed) | none | +| [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml): `🔄 Dependabot: Label update level` | Labels every Dependabot PR `⬆️ update` plus exactly one of `🔴 major`, `🟡 minor` and `🟢 patch`, read from the `update-type` of `dependabot/fetch-metadata`; a type that names no semver level counts as `major`. Creates a missing label, adds only labels the PR lacks and checks out the base branch only. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened, synchronize) | none | +| [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml): `🔄 Update: Merge proven PRs` | Runs when a `🔀 Pull Request` run of the `pull_request` event succeeds on an `update/*` or `dependabot/*` branch. [cli.contributing.update.merge](../../../../../cli/contributing/update/merge/__main__.py) merges the PR only when the `infinito-nexus-updater[bot]` App or `dependabot[bot]` opened it, it carries `⬆️ update`, every check run and commit status on its head is green, and the run's `role-runtimes-*` artifacts list every role the PR changes. Otherwise it prints why and the PR stays open for a manual merge. The merge pins the tested head and uses the App token, so the App MUST be a bypass actor of the `Main` ruleset. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md); requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`workflow_run` of `🔀 Pull Request`: completed) | none | ## Changing workflows ✍️ diff --git a/scripts/github/update/open/pr.sh b/scripts/github/update/open/pr.sh index d59abbc00d..85bd915771 100755 --- a/scripts/github/update/open/pr.sh +++ b/scripts/github/update/open/pr.sh @@ -118,8 +118,6 @@ git push --force \ "https://x-access-token:${GH_TOKEN}@github.com/${REPO}.git" \ "HEAD:refs/heads/${BRANCH}" -python3 -m cli.contributing.update.label --repo "${REPO}" --ensure-only - PR_NUMBER="$( gh pr list \ --repo "${REPO}" \ @@ -134,9 +132,7 @@ if [[ -n "${PR_NUMBER}" ]]; then gh pr edit "${PR_NUMBER}" \ --repo "${REPO}" \ --title "${UPDATE_PR_TITLE}" \ - --body "${UPDATE_PR_BODY}" \ - --add-label update \ - --add-label "${UPDATE_LEVEL}" + --body "${UPDATE_PR_BODY}" else echo "Creating PR for ${BRANCH}" PR_URL="$( @@ -145,10 +141,10 @@ else --title "${UPDATE_PR_TITLE}" \ --body "${UPDATE_PR_BODY}" \ --base "${UPDATE_BASE_BRANCH}" \ - --head "${OWNER}:${BRANCH}" \ - --label update \ - --label "${UPDATE_LEVEL}" + --head "${OWNER}:${BRANCH}" )" PR_NUMBER="${PR_URL##*/}" echo "Created PR #${PR_NUMBER}: ${PR_URL}" fi + +python3 -m cli.contributing.update.label --repo "${REPO}" --pr "${PR_NUMBER}" --level "${UPDATE_LEVEL}" diff --git a/tests/integration/meta/workflows/test_cancel_superseded_workflow.py b/tests/integration/meta/workflows/test_cancel_superseded_workflow.py index 8689ac94ad..bad2b133ca 100644 --- a/tests/integration/meta/workflows/test_cancel_superseded_workflow.py +++ b/tests/integration/meta/workflows/test_cancel_superseded_workflow.py @@ -132,9 +132,10 @@ class TestCancelSupersededWorkflow(unittest.TestCase): ) def test_pull_request_job_runs_for_pull_request_target_only(self): - self.assertEqual( - self.workflow["jobs"]["cancel-pull-request-runs"]["if"], - "${{ github.event_name == 'pull_request_target' }}", + self.assertTrue( + self.workflow["jobs"]["cancel-pull-request-runs"]["if"].startswith( + "${{ github.event_name == 'pull_request_target'\n" + ) ) def _step(self, job_name): diff --git a/tests/integration/meta/workflows/test_pr_ci_labels.py b/tests/integration/meta/workflows/test_pr_ci_labels.py new file mode 100644 index 0000000000..aa1e92cd35 --- /dev/null +++ b/tests/integration/meta/workflows/test_pr_ci_labels.py @@ -0,0 +1,90 @@ +"""A ``labeled`` run whose jobs all skip still cancels the running pipeline +through its concurrency group and the superseded-run canceller, so every place +that tells CI labels from the rest must carry the same list.""" + +from __future__ import annotations + +import json +import re +import unittest + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any + +WORKFLOWS = PROJECT_ROOT / ".github" / "workflows" +PR = WORKFLOWS / "entry-pr-change-orchestrate.yml" +SUPERSEDED = WORKFLOWS / "entry-cancel-superseded.yml" +ORCHESTRATOR = WORKFLOWS / "call-orchestrator.yml" +DEPLOY = WORKFLOWS / "call-test-deploy.yml" +RUN_ALL = "🏃 Run all" +_LIST_RE = re.compile(r"fromJSON\('(\[[^']*\])'\)") +_READ_RE = re.compile(r"labels\.\*\.name, '([^']+)'") + + +def _labels(expression: str) -> list[str]: + """Return the label list a ``fromJSON('[...]')`` in *expression* holds.""" + found = _LIST_RE.findall(expression) + if len(found) != 1: + raise AssertionError(f"expected one label list in {expression!r}") + return json.loads(found[0]) + + +def _strings(node: object) -> list[str]: + """Return every string value of a loaded YAML document.""" + if isinstance(node, str): + return [node] + if isinstance(node, dict): + return [text for value in node.values() for text in _strings(value)] + if isinstance(node, list): + return [text for value in node for text in _strings(value)] + return [] + + +class TestPrCiLabels(unittest.TestCase): + def setUp(self) -> None: + self.pr = load_yaml_any(str(PR)) + self.restart = _labels(self.pr["concurrency"]["group"]) + + def test_the_skip_and_the_canceller_use_the_concurrency_list(self) -> None: + superseded = load_yaml_any(str(SUPERSEDED)) + for where, expression in ( + ("detect-pr-scope", self.pr["jobs"]["detect-pr-scope"]["if"]), + ( + "cancel-pull-request-runs", + superseded["jobs"]["cancel-pull-request-runs"]["if"], + ), + ): + with self.subTest(job=where): + self.assertEqual(_labels(expression), self.restart) + + def test_every_label_the_workflow_reads_restarts_it(self) -> None: + read = {name for text in _strings(self.pr) for name in _READ_RE.findall(text)} + self.assertIn(RUN_ALL, read) + self.assertLessEqual(read, set(self.restart)) + + def test_run_all_turns_the_chunk_gate_off(self) -> None: + chunk_gate = self.pr["jobs"]["ci-orchestrator"]["with"]["chunk_gate"] + self.assertEqual( + chunk_gate, + f"${{{{ !contains(github.event.pull_request.labels.*.name, '{RUN_ALL}') }}}}", + ) + + def test_every_chunk_hands_the_gate_to_its_matrix(self) -> None: + jobs = load_yaml_any(str(ORCHESTRATOR))["jobs"] + chunks = { + name: body + for name, body in jobs.items() + if re.fullmatch(r"test-deploy-chunk-\d+", name) + } + self.assertGreater(len(chunks), 1) + for name, body in sorted(chunks.items()): + with self.subTest(chunk=name): + self.assertEqual(body["with"]["chunk_gate"], "${{ inputs.chunk_gate }}") + fail_fast = load_yaml_any(str(DEPLOY))["jobs"]["deploy"]["strategy"][ + "fail-fast" + ] + self.assertIn("inputs.chunk_gate", fail_fast) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/contributing/update/label/test_main.py b/tests/unit/python/cli/contributing/update/label/test_main.py index 4d9327e77f..b43f05b317 100644 --- a/tests/unit/python/cli/contributing/update/label/test_main.py +++ b/tests/unit/python/cli/contributing/update/label/test_main.py @@ -7,8 +7,13 @@ from contextlib import redirect_stdout from unittest.mock import patch import cli.contributing.update.label.__main__ as label_main +from utils.update.level import LEVELS REPO = "infinito-nexus/core" +UPDATE = label_main.UPDATE.name +MAJOR = label_main.MAJOR.name +MINOR = label_main.MINOR.name +PATCH = label_main.PATCH.name class FakeGh: @@ -44,21 +49,31 @@ class TestLevel(unittest.TestCase): label_main.level(f"version-update:semver-{name}").name for name in ("major", "minor", "patch") ], - ["major", "minor", "patch"], + [MAJOR, MINOR, PATCH], ) def test_an_unknown_or_empty_type_counts_as_major(self): self.assertEqual( {label_main.level(kind).name for kind in ("", "security", "semver-minor")}, - {"major"}, + {MAJOR}, ) + def test_every_level_the_updater_prints_has_a_label(self): + self.assertEqual(set(label_main.LEVEL_OF_NAME), set(LEVELS)) + + def test_every_label_name_carries_an_emoji_before_its_word(self): + for label in (label_main.UPDATE, *label_main.LEVELS): + with self.subTest(label=label.name): + mark, _, word = label.name.partition(" ") + self.assertFalse(mark.isascii()) + self.assertTrue(word.isascii() and word) + class TestSync(unittest.TestCase): def test_a_bare_pull_request_gets_update_and_its_level(self): - gh = FakeGh({"update", "minor"}, set()) - actions = label_main.sync(gh, REPO, 4, "version-update:semver-minor") - self.assertEqual(actions, ["added update, minor"]) + gh = FakeGh({UPDATE, MINOR}, set()) + actions = label_main.sync(gh, REPO, 4, label_main.MINOR) + self.assertEqual(actions, [f"added {UPDATE}, {MINOR}"]) self.assertEqual( gh.writes, [ @@ -68,35 +83,33 @@ class TestSync(unittest.TestCase): "POST", f"repos/{REPO}/issues/4/labels", "-f", - "labels[]=update", + f"labels[]={UPDATE}", "-f", - "labels[]=minor", + f"labels[]={MINOR}", ] ], ) def test_labels_already_present_cause_no_write(self): - gh = FakeGh({"update", "patch"}, {"update", "patch", "dependencies"}) - self.assertEqual( - label_main.sync(gh, REPO, 4, "version-update:semver-patch"), [] - ) + gh = FakeGh({UPDATE, PATCH}, {UPDATE, PATCH, "dependencies"}) + self.assertEqual(label_main.sync(gh, REPO, 4, label_main.PATCH), []) self.assertEqual(gh.writes, []) def test_a_stale_level_is_removed(self): - gh = FakeGh({"update", "major", "minor"}, {"update", "minor"}) - actions = label_main.sync(gh, REPO, 4, "version-update:semver-major") - self.assertEqual(actions, ["removed minor", "added major"]) + gh = FakeGh({UPDATE, MAJOR, MINOR}, {UPDATE, MINOR}) + actions = label_main.sync(gh, REPO, 4, label_main.MAJOR) + self.assertEqual(actions, [f"removed {MINOR}", f"added {MAJOR}"]) def test_missing_repository_labels_are_created_first(self): gh = FakeGh(set(), set()) - label_main.sync(gh, REPO, 4, "version-update:semver-patch") + label_main.sync(gh, REPO, 4, label_main.PATCH) created = [write[2] for write in gh.writes if write[:2] == ["label", "create"]] - self.assertEqual(created, ["update", "patch"]) + self.assertEqual(created, [UPDATE, PATCH]) def test_a_label_a_parallel_run_created_counts_as_done(self): - gh = FakeGh({"patch"}, set(), racing={"update"}) - actions = label_main.sync(gh, REPO, 4, "version-update:semver-patch") - self.assertEqual(actions, ["added update, patch"]) + gh = FakeGh({PATCH}, set(), racing={UPDATE}) + actions = label_main.sync(gh, REPO, 4, label_main.PATCH) + self.assertEqual(actions, [f"added {UPDATE}, {PATCH}"]) def test_a_create_failure_that_leaves_the_label_missing_raises(self): gh = FakeGh(set(), set()) @@ -107,24 +120,24 @@ class TestSync(unittest.TestCase): return gh(args) with self.assertRaises(subprocess.CalledProcessError): - label_main.sync(failing, REPO, 4, "") + label_main.sync(failing, REPO, 4, label_main.MAJOR) class TestMain(unittest.TestCase): def test_main_reports_when_nothing_changes(self): - gh = FakeGh({"update", "major"}, {"update", "major"}) + gh = FakeGh({UPDATE, MAJOR}, {UPDATE, MAJOR}) out = io.StringIO() with patch.object(label_main, "run_gh", gh), redirect_stdout(out): code = label_main.main(["--repo", REPO, "--pr", "4", "--update-type", ""]) self.assertEqual((code, out.getvalue()), (0, "#4 already carries its labels\n")) def test_ensure_only_creates_the_missing_labels_and_touches_no_pr(self): - gh = FakeGh({"update", "minor"}, set()) + gh = FakeGh({UPDATE, MINOR}, set()) out = io.StringIO() with patch.object(label_main, "run_gh", gh), redirect_stdout(out): code = label_main.main(["--repo", REPO, "--ensure-only"]) created = [w[2] for w in gh.writes if w[:2] == ["label", "create"]] - self.assertEqual((code, created), (0, ["major", "patch"])) + self.assertEqual((code, created), (0, [MAJOR, PATCH])) self.assertEqual(len(gh.writes), 2) def test_without_ensure_only_the_pr_and_type_are_required(self): @@ -132,6 +145,22 @@ class TestMain(unittest.TestCase): label_main.main(["--repo", REPO, "--pr", "4"]) self.assertEqual(raised.exception.code, 2) + def test_the_level_labels_an_updater_pull_request(self): + gh = FakeGh({UPDATE, MINOR, PATCH}, {UPDATE, PATCH}) + out = io.StringIO() + with patch.object(label_main, "run_gh", gh), redirect_stdout(out): + code = label_main.main(["--repo", REPO, "--pr", "4", "--level", "minor"]) + self.assertEqual( + (code, out.getvalue()), (0, f"removed {PATCH}\nadded {MINOR}\n") + ) + + def test_a_level_and_an_update_type_together_are_refused(self): + with self.assertRaises(SystemExit) as raised, redirect_stdout(io.StringIO()): + label_main.main( + ["--repo", REPO, "--pr", "4", "--level", "minor", "--update-type", ""] + ) + self.assertEqual(raised.exception.code, 2) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/contributing/update/merge/test_gate.py b/tests/unit/python/cli/contributing/update/merge/test_gate.py index 826aa062d0..9ff4a4c9f3 100644 --- a/tests/unit/python/cli/contributing/update/merge/test_gate.py +++ b/tests/unit/python/cli/contributing/update/merge/test_gate.py @@ -2,6 +2,7 @@ from __future__ import annotations import unittest +from cli.contributing.update.label import UPDATE from cli.contributing.update.merge import gate from utils.roles.mapping import ROLE_FILE_META_SERVICES @@ -14,7 +15,7 @@ def pull_request(**overrides): "user": {"login": "dependabot[bot]"}, "head": {"ref": "dependabot/npm/left-pad-1.3.0", "repo": {"full_name": REPO}}, "base": {"ref": "main"}, - "labels": [{"name": "update"}], + "labels": [{"name": UPDATE.name}], } pr.update(overrides) return pr diff --git a/tests/unit/python/cli/contributing/update/merge/test_main.py b/tests/unit/python/cli/contributing/update/merge/test_main.py index 4a2522c5ac..3cd3d84da5 100644 --- a/tests/unit/python/cli/contributing/update/merge/test_main.py +++ b/tests/unit/python/cli/contributing/update/merge/test_main.py @@ -10,6 +10,7 @@ from pathlib import Path from unittest.mock import patch import cli.contributing.update.merge.__main__ as merge_main +from cli.contributing.update.label import MINOR, UPDATE from cli.contributing.update.merge import github from utils.roles.mapping import ROLE_FILE_META_SERVICES @@ -32,7 +33,7 @@ def pull_request(**overrides): "repo": {"full_name": REPO}, }, "base": {"ref": "main"}, - "labels": [{"name": "update"}, {"name": "minor"}], + "labels": [{"name": UPDATE.name}, {"name": MINOR.name}], } pr.update(overrides) return pr @@ -137,7 +138,7 @@ class TestEvaluate(unittest.TestCase): def test_a_missing_update_label_is_refused(self): unlabeled = pull_request(labels=[{"name": "minor"}]) refusals = evaluate(green_gh(prs=[unlabeled]))[1] - self.assertEqual(refusals, ["label update is missing"]) + self.assertEqual(refusals, [f"label {UPDATE.name} is missing"]) def test_a_pending_check_refuses(self): pending = check("🌐 Translate catalogs", status="in_progress", conclusion=None) From 2b035f767423dcb8413c10b27eea4b92fa3447f7 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:17:37 +0000 Subject: [PATCH 46/65] update(repos): bump git refs to latest tags and commits (web-app-bookwyrm) --- roles/web-app-bookwyrm/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-bookwyrm/meta/services.yml b/roles/web-app-bookwyrm/meta/services.yml index 843ed9945d..382a1f0e05 100644 --- a/roles/web-app-bookwyrm/meta/services.yml +++ b/roles/web-app-bookwyrm/meta/services.yml @@ -64,7 +64,7 @@ bookwyrm: version: 3.11-slim custom: true repository: https://github.com/bookwyrm-social/bookwyrm.git - ref: v0.9.4 + ref: v0.9.5 min_storage: 579MB registration_open: false allow_invite_request: false From d3d4d066e99e8e99007edeb03e392a8c34bc1670 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:17:42 +0000 Subject: [PATCH 47/65] update(images): update Docker image versions (web-app-funkwhale) --- roles/web-app-funkwhale/meta/services.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/roles/web-app-funkwhale/meta/services.yml b/roles/web-app-funkwhale/meta/services.yml index 7b1d2bae45..8ac897d1b5 100644 --- a/roles/web-app-funkwhale/meta/services.yml +++ b/roles/web-app-funkwhale/meta/services.yml @@ -13,7 +13,7 @@ funkwhale: # nocheck: default-placement-manager embedded typesense index; node-local in swarm placement: manager image: funkwhale/front - version: 2.0.16 + version: 2.0.17 min_storage: 224MB ports: internal: @@ -43,7 +43,7 @@ api: name: funkwhale-api image: funkwhale/api ca_client: true - version: 2.0.16 + version: 2.0.17 min_storage: 588MB ports: internal: From fdf1ff757c27384a834203590f08f155dbdb2f0d Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 16:52:06 +0000 Subject: [PATCH 48/65] fix(update): label an updater PR found as a duplicate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit on PR 2552 (pr.sh:150): since the label step runs after gh pr create, a failed label call left the PR unlabeled, and every later run matched it as a duplicate and exited before labeling. The duplicate path now runs the same label CLI on the matched PR, so the next run heals a missing label. test_pr.py logs every call of its gh stub and asserts the POST of both labels on the duplicate; against the old pr.sh it fails (negative control). Tests: test_pr.py, the update CLI suite and the Python repository lints, 116 passed; ruff and shellcheck clean. 🎯 Fix: 92 % 💥 Break: 4 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 88 🚦 Gate: ⏳ quality-high not run on this head, gates run on main Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- scripts/github/update/open/pr.sh | 1 + .../scripts/github/update/open/test_pr.py | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/scripts/github/update/open/pr.sh b/scripts/github/update/open/pr.sh index 85bd915771..d380385af2 100755 --- a/scripts/github/update/open/pr.sh +++ b/scripts/github/update/open/pr.sh @@ -104,6 +104,7 @@ done if [[ -n "${DUPLICATE_PR}" ]]; then echo "Open PR #${DUPLICATE_PR} already carries this exact change. Skipping push and PR creation." + python3 -m cli.contributing.update.label --repo "${REPO}" --pr "${DUPLICATE_PR}" --level "${UPDATE_LEVEL}" exit 0 fi diff --git a/tests/unit/python/scripts/github/update/open/test_pr.py b/tests/unit/python/scripts/github/update/open/test_pr.py index bf7f47b3c0..4c08d8336b 100644 --- a/tests/unit/python/scripts/github/update/open/test_pr.py +++ b/tests/unit/python/scripts/github/update/open/test_pr.py @@ -1,16 +1,20 @@ from __future__ import annotations import os +import re import subprocess import tempfile import unittest from pathlib import Path -from utils.cache.files import PROJECT_ROOT +from cli.contributing.update.label import UPDATE +from cli.contributing.update.label.__main__ import LEVEL_OF_NAME +from utils.cache.files import PROJECT_ROOT, read_text SCRIPT = PROJECT_ROOT / "scripts" / "github" / "update" / "open" / "pr.sh" PINNED_FILE = "pin.txt" GH_STUB = """#!/usr/bin/env bash +printf '%s\\n' "$*" >> "${GH_STUB_LOG}" if [[ "$1 $2" == "pr list" ]]; then printf '7\\t%s\\t%s\\n' "${GH_STUB_CROSS_REPO}" "${GH_STUB_BRANCH}" fi @@ -32,10 +36,12 @@ class UpdatePrFixture: stub = stub_dir / "gh" stub.write_text(GH_STUB) stub.chmod(0o755) + self.gh_log = Path(tmp) / "gh.log" inherited = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} self.env = { **inherited, "PATH": f"{stub_dir}{os.pathsep}{os.environ['PATH']}", + "GH_STUB_LOG": str(self.gh_log), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_ALLOW_PROTOCOL": "file", "GH_TOKEN": "unused", @@ -100,7 +106,7 @@ class UpdatePrFixture: class TestUpdatePrDedupe(unittest.TestCase): - def test_edited_branch_of_the_same_proposal_is_a_duplicate(self) -> None: + def test_edited_branch_of_the_same_proposal_is_a_labelled_duplicate(self) -> None: with tempfile.TemporaryDirectory() as tmp: fixture = UpdatePrFixture(tmp) branch = f"update/pins-20251231-{fixture.fingerprint()[:7]}" @@ -108,6 +114,14 @@ class TestUpdatePrDedupe(unittest.TestCase): self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertIn("Open PR #7 already carries this exact change", result.stdout) self.assertNotIn("Pushing change to branch", result.stdout) + level = re.search(r"^Update level: (\w+)$", result.stdout, re.MULTILINE) + self.assertIsNotNone(level, result.stdout) + self.assertIn( + "api --method POST repos/acme/widgets/issues/7/labels" + f" -f labels[]={UPDATE.name}" + f" -f labels[]={LEVEL_OF_NAME[level.group(1)].name}", + read_text(str(fixture.gh_log)).splitlines(), + ) def test_fork_branch_with_the_same_suffix_is_not_a_duplicate(self) -> None: with tempfile.TemporaryDirectory() as tmp: From 1a0ff5b9c78ec64ecf4d8318dfc1d1aa2ccc21a7 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 20:14:27 +0000 Subject: [PATCH 49/65] fix(web-app-seaweedfs): run the design specs and fix the two failures behind them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit skipUnlessUiServed skipped on env.frontendEnabled, which _shared.js never defines, so all seven design specs skipped on every row (main push run 44987966640: seaweedfs#0 and #1 junit tests=11 skipped=11). The gate now reads skipUnlessServiceEnabled("sso"), byte-identical to IAM 68c3e7aadf. Live specs then failed twice (IAM fork run 44939269920 seaweedfs#0): SeaweedFS 4.54 keys its upload list by item.path, so startUpload now gets { path }; on the +tor pass DESIGN_LOGO_URL names the onion CDN while the clearnet-only console renders the clearnet CDN, so logo and favicon are now checked by fetching the URL the page references and comparing its bytes with the generated asset, as the gitea logo spec does. 🎯 Fix: 92 % 💥 Break: 5 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 87 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../files/playwright/test-design.js | 40 ++++++++++++++----- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/roles/web-app-seaweedfs/files/playwright/test-design.js b/roles/web-app-seaweedfs/files/playwright/test-design.js index 1b4cadfb96..77451b9126 100644 --- a/roles/web-app-seaweedfs/files/playwright/test-design.js +++ b/roles/web-app-seaweedfs/files/playwright/test-design.js @@ -17,6 +17,8 @@ const READY_MS = 10_000; const SHOWCASE = "design-showcase"; const HEADING = ".page-header h1"; const LOGO = `${HEADING} > a > img`; +const ICON = "link[rel~='icon']"; +const CSS_URL = /^url\("(.+)"\)$/; const LISTING = "#drop-area table.table-hover"; const ROW = `${LISTING} tr`; const CELL = `${LISTING} tr > td`; @@ -45,6 +47,20 @@ function escapeRegExp(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } +/** + * Args: + * page: Playwright page whose request context reaches the CDN of every network. + * referenced: absolute URL of the asset the rendered page points at, on the CDN host of the network + * the console is served on, which on the +tor pass is not the host of DESIGN_*. + * generated: bytes of the generated asset as published under its DESIGN_* URL. + * label: the asset and the page, for the assertion messages. + */ +async function assertServesGenerated(page, referenced, generated, label) { + const served = await apiGetOnion(page.request, referenced); + expect(served.ok(), `${label} ${referenced} is served`).toBe(true); + expect((await served.body()).equals(generated), `${label} ${referenced} is the generated asset`).toBe(true); +} + exports.register = function (shared) { const { env, keycloakLogin, isAuthChain } = shared; const filer = (env.filerUrl || "").replace(/\/$/, ""); @@ -52,8 +68,7 @@ exports.register = function (shared) { function skipUnlessUiServed() { skipUnlessServiceEnabled("design"); - test.skip(!env.frontendEnabled, "frontend disabled (headless backend node)"); - test.skip(!env.ssoEnabled, "SSO disabled: the front proxy answers 403 on both UI domains"); + skipUnlessServiceEnabled("sso"); } /** @@ -112,8 +127,8 @@ exports.register = function (shared) { async function renderProgress(page) { await page.evaluate(() => { - window.startUpload({ name: "running.bin" }); - window.startUpload({ name: "done.bin" }); + window.startUpload({ path: "running.bin" }); + window.startUpload({ path: "done.bin" }); window.reportProgress("running.bin", 60); window.reportProgress("done.bin", 100); }); @@ -305,6 +320,12 @@ exports.register = function (shared) { const title = decodeDotenvQuotedValue(process.env.DESIGN_TITLE); test.skip(!logoUrl && !title, "logo and title replacement are disabled for this role"); + const published = new Map(); + for (const assetUrl of [logoUrl, faviconUrl].filter(Boolean)) { + const response = await apiGetOnion(page.request, assetUrl); + expect(response.ok(), `${assetUrl} is published on the CDN`).toBe(true); + published.set(assetUrl, await response.body()); + } for (const [url, suffix] of [ [`${filer}/`, " Filer"], [`${master}/`, ""], @@ -315,16 +336,17 @@ exports.register = function (shared) { await expect(page.locator(HEADING)).toContainText(`${title}${suffix}`); } if (logoUrl) { - await expect(page.locator(LOGO)).toHaveCSS("content", `url("${logoUrl}")`); + await expect(page.locator(LOGO)).toHaveCSS("content", CSS_URL); + const content = await page.locator(LOGO).evaluate((image) => getComputedStyle(image).content); + await assertServesGenerated(page, CSS_URL.exec(content)[1], published.get(logoUrl), `the logo of ${url}`); const box = await page.locator(LOGO).boundingBox(); expect(Math.round(box.width), "the logo keeps the 50 px box of upstream").toBe(50); expect(Math.round(box.height), "the logo keeps the 50 px box of upstream").toBe(50); - await expect(page.locator("link[rel~='icon']")).toHaveAttribute("href", faviconUrl); + await expect(page.locator(ICON)).toHaveAttribute("href", /\S/); + const icon = new URL(await page.locator(ICON).getAttribute("href"), page.url()).href; + await assertServesGenerated(page, icon, published.get(faviconUrl), `the favicon of ${url}`); } } - for (const assetUrl of [logoUrl, faviconUrl].filter(Boolean)) { - expect((await apiGetOnion(page.request, assetUrl)).ok(), `${assetUrl} is published on the CDN`).toBe(true); - } }); test("design: gallery of master status and filer listings", async ({ page }) => { From 50105ae7f100096897997230f84b300c0974f009 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:24:30 +0000 Subject: [PATCH 50/65] update(images): update Docker image versions (web-svc-logout) --- roles/web-svc-logout/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-svc-logout/meta/services.yml b/roles/web-svc-logout/meta/services.yml index 89a4cec74b..b840237f4a 100644 --- a/roles/web-svc-logout/meta/services.yml +++ b/roles/web-svc-logout/meta/services.yml @@ -12,7 +12,7 @@ logout: enabled: true shared: true image: ghcr.io/kevinveenbirkenbach/universal-logout - version: v1.5.2 + version: v1.6.0 name: logout min_storage: 250MB cpus: 0.2 From 36de1e6b0f220820a7c4737e2d44c2b85960e065 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 22:06:49 +0100 Subject: [PATCH 51/65] Update .github/workflows/entry-pr-change-orchestrate.yml --- .github/workflows/entry-pr-change-orchestrate.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/entry-pr-change-orchestrate.yml b/.github/workflows/entry-pr-change-orchestrate.yml index bf198757d5..3c57671769 100644 --- a/.github/workflows/entry-pr-change-orchestrate.yml +++ b/.github/workflows/entry-pr-change-orchestrate.yml @@ -18,7 +18,6 @@ on: - ready_for_review - labeled -# Exception: a skipped run still joins its concurrency group and cancels the running pipeline, so a label CI ignores gets a group of its own. concurrency: group: >- ${{ github.event.action == 'labeled' From 97a52d36d124f9a77020b2f37923eb60c3835b8f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:39:14 +0000 Subject: [PATCH 52/65] build(deps-dev): Bump ruff from 0.17.5 to 0.17.6 Bumps [ruff](https://github.com/astral-sh/ruff) from 0.17.5 to 0.17.6. - [Release notes](https://github.com/astral-sh/ruff/releases) - [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ruff/compare/0.17.5...0.17.6) --- updated-dependencies: - dependency-name: ruff dependency-version: 0.17.6 dependency-type: direct:development update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 55658d62ab..e5ac2c176a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,7 +36,7 @@ deploy = [ "requests", ] dev = [ - "ruff==0.17.5", + "ruff==0.17.6", "import-linter", "pre-commit", "git-maintainer-tools", From 19fa7fe2e0fbdadaf3b9e74d9e0dee104b2675d7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:39:28 +0000 Subject: [PATCH 53/65] build(deps): Bump fastapi in /roles/web-svc-translate/files Bumps [fastapi](https://github.com/fastapi/fastapi) from 0.164.0 to 0.165.0. - [Release notes](https://github.com/fastapi/fastapi/releases) - [Commits](https://github.com/fastapi/fastapi/compare/0.164.0...0.165.0) --- updated-dependencies: - dependency-name: fastapi dependency-version: 0.165.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- roles/web-svc-translate/files/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-svc-translate/files/requirements.txt b/roles/web-svc-translate/files/requirements.txt index 28e9d85315..6a465af28e 100644 --- a/roles/web-svc-translate/files/requirements.txt +++ b/roles/web-svc-translate/files/requirements.txt @@ -1,4 +1,4 @@ -fastapi==0.164.0 +fastapi==0.165.0 python-multipart==0.0.34 uvicorn[standard]==0.54.0 asyncpg==0.32.0 From c53578e82b76258a0548010f13533a52ae83b414 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:42:53 +0000 Subject: [PATCH 54/65] build(deps): Bump ossf/scorecard-action from 2.5.0 to 2.6.0 Bumps [ossf/scorecard-action](https://github.com/ossf/scorecard-action) from 2.5.0 to 2.6.0. - [Release notes](https://github.com/ossf/scorecard-action/releases) - [Changelog](https://github.com/ossf/scorecard-action/blob/main/RELEASE.md) - [Commits](https://github.com/ossf/scorecard-action/compare/fa7117db83c52d787ae5a89f350999701505d78e...23f22cd43608bae7a1f1fa2603d7314dee9538a5) --- updated-dependencies: - dependency-name: ossf/scorecard-action dependency-version: 2.6.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/cron-security-scorecard.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cron-security-scorecard.yml b/.github/workflows/cron-security-scorecard.yml index 41c6190233..19b4c7074a 100644 --- a/.github/workflows/cron-security-scorecard.yml +++ b/.github/workflows/cron-security-scorecard.yml @@ -45,7 +45,7 @@ jobs: persist-credentials: false - name: "🔬 Run analysis" - uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.4.1 + uses: ossf/scorecard-action@23f22cd43608bae7a1f1fa2603d7314dee9538a5 # v2.4.1 with: results_file: results.sarif results_format: sarif From 1a78695b9f54dabe3ead1f6f6c7844e239be288f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:43:01 +0000 Subject: [PATCH 55/65] build(deps): Bump ossf/scorecard-action in /.github/workflows Bumps [ossf/scorecard-action](https://github.com/ossf/scorecard-action) from 2.5.0 to 2.6.0. - [Release notes](https://github.com/ossf/scorecard-action/releases) - [Changelog](https://github.com/ossf/scorecard-action/blob/main/RELEASE.md) - [Commits](https://github.com/ossf/scorecard-action/compare/fa7117db83c52d787ae5a89f350999701505d78e...23f22cd43608bae7a1f1fa2603d7314dee9538a5) --- updated-dependencies: - dependency-name: ossf/scorecard-action dependency-version: 2.6.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/cron-security-scorecard.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cron-security-scorecard.yml b/.github/workflows/cron-security-scorecard.yml index 41c6190233..19b4c7074a 100644 --- a/.github/workflows/cron-security-scorecard.yml +++ b/.github/workflows/cron-security-scorecard.yml @@ -45,7 +45,7 @@ jobs: persist-credentials: false - name: "🔬 Run analysis" - uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.4.1 + uses: ossf/scorecard-action@23f22cd43608bae7a1f1fa2603d7314dee9538a5 # v2.4.1 with: results_file: results.sarif results_format: sarif From 76cb025488bce014016ced994d5c1d9bf63f5210 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 21:54:35 +0000 Subject: [PATCH 56/65] fix(svc-ai-lmstudio): cancel a model download that outlives its budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pre-pull budget ended only the docker exec client, since docker forwards no signal into the container, and the download is a job of the LM Studio daemon that outlives its client. The retry lms get then attached to the stalled transfer (Job ... already exists, resumed at 38.9 %, same ECONNRESET; PR 2253 Zammad#2, run 44931086506). The budget now runs inside the container: timeout sends one SIGINT to lms get, which answers its Continue to download in the background prompt with the piped N and sends cancelDownload. CONTAINER_EXEC_TIMEOUT outlasts budget plus kill grace. New test renders the task and runs it twice through the real container wrapper with a non-forwarding fake docker: 5 passed, 4 of them fail on the base. 🎯 Fix: 80 % 💥 Break: 5 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 76 🚦 Gate: ⛔ fix 80 % < 90 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/svc-ai-lmstudio/README.md | 2 +- .../tasks/utils/preload/pull.yml | 14 +- .../python/roles/svc-ai-lmstudio/__init__.py | 0 .../roles/svc-ai-lmstudio/tasks/__init__.py | 0 .../svc-ai-lmstudio/tasks/utils/__init__.py | 0 .../tasks/utils/preload/__init__.py | 0 .../tasks/utils/preload/test_pull.py | 228 ++++++++++++++++++ 7 files changed, 240 insertions(+), 4 deletions(-) create mode 100644 tests/unit/python/roles/svc-ai-lmstudio/__init__.py create mode 100644 tests/unit/python/roles/svc-ai-lmstudio/tasks/__init__.py create mode 100644 tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/__init__.py create mode 100644 tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/__init__.py create mode 100644 tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py diff --git a/roles/svc-ai-lmstudio/README.md b/roles/svc-ai-lmstudio/README.md index 4b594f6f8f..be8b027c94 100644 --- a/roles/svc-ai-lmstudio/README.md +++ b/roles/svc-ai-lmstudio/README.md @@ -13,7 +13,7 @@ This role deploys LM Studio as a headless model server in a single container, in - **OpenAI-compatible endpoint:** The headless server answers `/v1` requests on port 1234 inside the container network. - **CPU inference:** The role builds its own image from the pinned llmster release for the host's architecture, amd64 or arm64, keeps only the CPU llama.cpp engine and passes no GPU device into the container. - **Persistent model store:** A named volume mounted at `/root/.lmstudio` keeps downloaded models and server settings across redeploys. -- **Preloaded models:** Every entry of `services.lmstudio.preload_models` is downloaded on the hosting node with `lms get --gguf`, overlapped and reaped like the Ollama pre-pull. Each entry carries the `source` repository to download, the `quant` variant to take from it, the `name` LM Studio indexes that repository under and the gateway addresses it by, and the `alias` the gateway publishes it as. `source` is a full Hugging Face URL, never a search term: a search term resolves to whichever model the catalogue lists first. `quant` is appended as `@` and is required: without it LM Studio picks the variant itself, and the `file`, `sha256` and `bytes` the entry declares then describe a guess that the store check and the download budget are both measured against. +- **Preloaded models:** Every entry of `services.lmstudio.preload_models` is downloaded on the hosting node with `lms get --gguf`, overlapped and reaped like the Ollama pre-pull. A download that outlives its budget is cancelled inside the container through the interrupt prompt of `lms get`, so LM Studio drops the transfer and the retry downloads afresh instead of following the stalled one. Each entry carries the `source` repository to download, the `quant` variant to take from it, the `name` LM Studio indexes that repository under and the gateway addresses it by, and the `alias` the gateway publishes it as. `source` is a full Hugging Face URL, never a search term: a search term resolves to whichever model the catalogue lists first. `quant` is appended as `@` and is required: without it LM Studio picks the variant itself, and the `file`, `sha256` and `bytes` the entry declares then describe a guess that the store check and the download budget are both measured against. - **Loading:** The pre-pull downloads without loading. LM Studio serves with just-in-time loading, so the first `/v1/chat/completions` naming a `name` loads that model; the gateway's warm task issues that first request at deploy time. - **Gateway backend:** The LiteLLM Gateway publishes those aliases, which are the names Ollama serves too, so the same model name routes to whichever local backend a deployment runs. - **Bounded resources:** The container is capped at 4 CPUs, 8 GB of memory and 2048 processes, and the role declares a minimum of 4 GB free storage for building the image; downloaded models grow the volume beyond that. diff --git a/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml b/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml index 39ca8ad9d2..26577ea87d 100644 --- a/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml +++ b/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml @@ -1,12 +1,20 @@ --- - name: ⬇️ Pre-pull LM Studio models + # Exception: docker exec forwards no signal and the download is a daemon job, so a host-side budget leaves it running. + # lms cancels it only on SIGINT answered with N, which is why the budget runs inside the container and + # CONTAINER_EXEC_TIMEOUT must outlast budget plus kill grace. ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node - container exec -i {{ LMSTUDIO_LOCAL_CID | quote }} lms get --yes --gguf {{ (model.source ~ '@' ~ model.quant) | quote }} - environment: - CONTAINER_EXEC_TIMEOUT: >- + container exec {{ LMSTUDIO_LOCAL_CID | quote }} + sh -c 'echo N | timeout --foreground -s INT -k "$1" "$2" lms get --yes --gguf "$3"' + sh {{ _grace }} {{ _budget }} {{ (model.source ~ '@' ~ model.quant) | quote }} + vars: + _grace: 15 + _budget: >- {{ [ LMSTUDIO_PRELOAD_FLOOR_SECONDS | int, ((model.bytes | int) / (LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND | int)) | round(0, 'ceil') | int ] | max }} + environment: + CONTAINER_EXEC_TIMEOUT: "{{ (_budget | int) + 2 * (_grace | int) }}" register: lmstudio_pull_result loop: "{{ LMSTUDIO_PRELOAD_MODELS }}" loop_control: diff --git a/tests/unit/python/roles/svc-ai-lmstudio/__init__.py b/tests/unit/python/roles/svc-ai-lmstudio/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/svc-ai-lmstudio/tasks/__init__.py b/tests/unit/python/roles/svc-ai-lmstudio/tasks/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/__init__.py b/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/__init__.py b/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py b/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py new file mode 100644 index 0000000000..69ce073992 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py @@ -0,0 +1,228 @@ +from __future__ import annotations + +import os +import signal +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any +from utils.templating.ansible import _trust_as_template + +PULL = PROJECT_ROOT / "roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml" +WRAPPER = PROJECT_ROOT / "roles/sys-svc-container/files/python/container.py" +TASK = "⬇️ Pre-pull LM Studio models" +BUDGET_SECONDS = 2 + +# Exception: start_new_session and the relayed output reproduce what the defect hinges on, docker exec forwards no +# signal to the process it started and holds none of the client's descriptors open, so a client the host-side timeout +# kills returns at once and leaves that process running in the container. +FAKE_DOCKER = """ +import shutil +import subprocess +import sys + +args = sys.argv[2:] +flags = [] +while args[0].startswith("-"): + flags.append(args.pop(0)) +child = subprocess.Popen( + args[1:], + stdin=None if "-i" in flags else subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, +) +shutil.copyfileobj(child.stdout, sys.stdout.buffer) +sys.exit(child.wait()) +""" + +# Exception: models lms get against the LM Studio daemon, whose transfer outlives the client: an lms get started while +# a transfer is on record attaches to it, and only an N read after SIGINT cancels it. +FAKE_LMS = """ +import os +import signal +import sys +import time +from pathlib import Path + +state = Path(os.environ["FAKE_LMS_STATE"]) +job = state / "job" + + +def record(name, line): + with (state / name).open("a") as handle: + handle.write(line + "\\n") + + +def interrupted(signum, frame): + if sys.stdin.readline().strip().upper() == "N": + job.unlink() + record("events", "cancel") + else: + record("events", "background") + sys.exit(1) + + +signal.signal(signal.SIGINT, interrupted) +record("pids", str(os.getpid())) +if job.exists(): + record("events", "attach") +else: + job.touch() + record("events", "start") +time.sleep(30) +""" + + +def _install(path: Path, content: str) -> None: + """ + Args: + path: where the executable lands. + content: its full text, shebang included. + """ + path.write_text(content, encoding="utf-8") + path.chmod(0o755) + + +def _lines(path: Path) -> list[str]: + """ + Args: + path: a record the fake lms appends to. + + Returns: + Its lines, or [] while it does not exist. + """ + if not path.exists(): + return [] + return path.read_text().split() # nocheck: cache-read rewritten between reads + + +def _running(pid: int) -> bool: + """ + Args: + pid: a fake lms process. + + Returns: + Whether it still runs. + """ + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + return True + + +def _templar() -> tuple[dict, Templar]: + """ + Returns: + The pre-pull task and a templar holding one model whose budget is BUDGET_SECONDS. + """ + task = next( + task + for task in load_yaml_any(str(PULL), default_if_missing=[]) + if task.get("name") == TASK + ) + variables = { + "LMSTUDIO_LOCAL_CID": "lmstudio", + "LMSTUDIO_PRELOAD_FLOOR_SECONDS": BUDGET_SECONDS, + "LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND": 1_000_000, + "model": { + "alias": "llama3.2:1b", + "source": "https://huggingface.co/lmstudio-community/Llama-3.2-1B-Instruct-GGUF", + "quant": "Q4_K_M", + "bytes": 1, + }, + } + for key, value in (task.get("vars") or {}).items(): + variables[key] = _trust_as_template(value) + return task, Templar(loader=DataLoader(), variables=variables) + + +def _render(templar: Templar, value: str) -> str: + """ + Args: + templar: from _templar. + value: a task field. + + Returns: + The field rendered. + """ + return str(templar.template(_trust_as_template(value))) + + +class TestTimedOutPull(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.scratch = tempfile.TemporaryDirectory() + root = Path(cls.scratch.name) + bin_dir = root / "bin" + cls.state = root / "state" + bin_dir.mkdir() + cls.state.mkdir() + _install(bin_dir / "docker", f"#!{sys.executable} -I\n{FAKE_DOCKER}") + _install(bin_dir / "lms", f"#!{sys.executable} -I\n{FAKE_LMS}") + _install( + bin_dir / "container", + f'#!/bin/sh\nexec "{sys.executable}" -I "{WRAPPER}" "$@"\n', + ) + task, cls.templar = _templar() + command = _render(cls.templar, task["ansible.builtin.shell"]) + cls.environment = { + key: _render(cls.templar, value) + for key, value in task["environment"].items() + } + env = { + **os.environ, + **cls.environment, + "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", + "FAKE_LMS_STATE": str(cls.state), + } + cls.attempts = [] + for _attempt in range(2): + result = subprocess.run( + ["/bin/sh", "-c", command], + env=env, + stdin=subprocess.DEVNULL, + capture_output=True, + check=False, + timeout=120, + ) + pid = int(_lines(cls.state / "pids")[-1]) + cls.attempts.append((result.returncode, _running(pid))) + cls.events = _lines(cls.state / "events") + + @classmethod + def tearDownClass(cls) -> None: + for pid in map(int, _lines(cls.state / "pids")): + if _running(pid): + os.kill(pid, signal.SIGKILL) + cls.scratch.cleanup() + + def test_the_timeout_still_fails_the_attempt(self) -> None: + self.assertEqual([rc for rc, _alive in self.attempts], [124, 124]) + + def test_no_lms_outlives_its_attempt(self) -> None: + self.assertEqual([alive for _rc, alive in self.attempts], [False, False]) + + def test_the_timeout_cancels_the_transfer(self) -> None: + self.assertEqual(self.events[:2], ["start", "cancel"]) + + def test_the_retry_downloads_afresh(self) -> None: + self.assertEqual(self.events, ["start", "cancel", "start", "cancel"]) + + def test_the_host_guard_outlasts_the_in_container_cancel(self) -> None: + self.assertGreater( + int(self.environment["CONTAINER_EXEC_TIMEOUT"]), + int(_render(self.templar, "{{ (_budget | int) + (_grace | int) }}")), + ) + + +if __name__ == "__main__": + unittest.main() From a83580b663eab2ed4ce42e2fadb0a000286471ae Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 22:09:42 +0000 Subject: [PATCH 57/65] refactor(svc-ai-lmstudio): drop the explanatory comments of the pre-pull cancel Removes the Exception comment in pull.yml and the two comment blocks above the fake docker and fake lms in test_pull.py; the PR body carries that explanation. No behaviour change; both files parse, the task keeps its _budget and _grace vars. Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml | 3 --- .../roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py | 5 ----- 2 files changed, 8 deletions(-) diff --git a/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml b/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml index 26577ea87d..d196b6ce09 100644 --- a/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml +++ b/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml @@ -1,8 +1,5 @@ --- - name: ⬇️ Pre-pull LM Studio models - # Exception: docker exec forwards no signal and the download is a daemon job, so a host-side budget leaves it running. - # lms cancels it only on SIGINT answered with N, which is why the budget runs inside the container and - # CONTAINER_EXEC_TIMEOUT must outlast budget plus kill grace. ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec {{ LMSTUDIO_LOCAL_CID | quote }} sh -c 'echo N | timeout --foreground -s INT -k "$1" "$2" lms get --yes --gguf "$3"' diff --git a/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py b/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py index 69ce073992..d83063ebc7 100644 --- a/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py +++ b/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py @@ -20,9 +20,6 @@ WRAPPER = PROJECT_ROOT / "roles/sys-svc-container/files/python/container.py" TASK = "⬇️ Pre-pull LM Studio models" BUDGET_SECONDS = 2 -# Exception: start_new_session and the relayed output reproduce what the defect hinges on, docker exec forwards no -# signal to the process it started and holds none of the client's descriptors open, so a client the host-side timeout -# kills returns at once and leaves that process running in the container. FAKE_DOCKER = """ import shutil import subprocess @@ -43,8 +40,6 @@ shutil.copyfileobj(child.stdout, sys.stdout.buffer) sys.exit(child.wait()) """ -# Exception: models lms get against the LM Studio daemon, whose transfer outlives the client: an lms get started while -# a transfer is on record attaches to it, and only an N read after SIGINT cancels it. FAKE_LMS = """ import os import signal From 93f6b77bb6c5ec0ddec7882d6a447a3fa2bc54b2 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 22:24:21 +0000 Subject: [PATCH 58/65] fix(svc-ai-lmstudio): fail fast when a download budget outlasts the async lifetime CodeRabbit on PR 2561: LMSTUDIO_PRELOAD_ASYNC_TIME is fixed at 3600 s while the budget grows with the model, so a model above about 3.57 GB at the 1 MB/s floor would let async end the task before the in-container timeout cancels the download. A new assert before the pull checks budget plus twice the kill grace against services.lmstudio.preload_async_time for every model and fails naming that key; it shares the pull's _budget and _grace through one YAML anchor and runs only with async on. The shipped model needs 838 s. Tests: the guard and the pull share their vars, 3,569,000,000 bytes pass, 3,570,000,000 fail; 8 passed. Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../tasks/utils/preload/pull.yml | 27 +++++++++--- .../tasks/utils/preload/test_pull.py | 41 +++++++++++++++++++ 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml b/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml index d196b6ce09..6241b304cf 100644 --- a/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml +++ b/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml @@ -1,15 +1,30 @@ --- -- name: ⬇️ Pre-pull LM Studio models - ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node - container exec {{ LMSTUDIO_LOCAL_CID | quote }} - sh -c 'echo N | timeout --foreground -s INT -k "$1" "$2" lms get --yes --gguf "$3"' - sh {{ _grace }} {{ _budget }} {{ (model.source ~ '@' ~ model.quant) | quote }} - vars: +- name: 🛑 Fail if a model's download budget outlasts the pre-pull async lifetime + ansible.builtin.assert: + that: (_budget | int) + 2 * (_grace | int) < (LMSTUDIO_PRELOAD_ASYNC_TIME | int) + fail_msg: >- + {{ model.alias }} needs {{ (_budget | int) + 2 * (_grace | int) }} s for its download budget and cancel, + but services.lmstudio.preload_async_time of svc-ai-lmstudio allows {{ LMSTUDIO_PRELOAD_ASYNC_TIME }} s; + raise it in the inventory. + quiet: true + vars: &lmstudio_pull_budget _grace: 15 _budget: >- {{ [ LMSTUDIO_PRELOAD_FLOOR_SECONDS | int, ((model.bytes | int) / (LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND | int)) | round(0, 'ceil') | int ] | max }} + loop: "{{ LMSTUDIO_PRELOAD_MODELS }}" + loop_control: + loop_var: model + label: "{{ model.alias }}" + when: ASYNC_ENABLED | bool + +- name: ⬇️ Pre-pull LM Studio models + ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec {{ LMSTUDIO_LOCAL_CID | quote }} + sh -c 'echo N | timeout --foreground -s INT -k "$1" "$2" lms get --yes --gguf "$3"' + sh {{ _grace }} {{ _budget }} {{ (model.source ~ '@' ~ model.quant) | quote }} + vars: *lmstudio_pull_budget environment: CONTAINER_EXEC_TIMEOUT: "{{ (_budget | int) + 2 * (_grace | int) }}" register: lmstudio_pull_result diff --git a/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py b/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py index d83063ebc7..7609ad4267 100644 --- a/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py +++ b/tests/unit/python/roles/svc-ai-lmstudio/tasks/utils/preload/test_pull.py @@ -219,5 +219,46 @@ class TestTimedOutPull(unittest.TestCase): ) +class TestBudgetGuard(unittest.TestCase): + def _holds(self, model_bytes: int) -> bool: + """ + Args: + model_bytes: the declared size of the one model to pre-pull. + + Returns: + Whether the guard lets the pre-pull start under the shipped async lifetime. + """ + guard = next( + task + for task in load_yaml_any(str(PULL), default_if_missing=[]) + if "ansible.builtin.assert" in task + ) + variables = { + "LMSTUDIO_PRELOAD_ASYNC_TIME": 3600, + "LMSTUDIO_PRELOAD_FLOOR_SECONDS": 600, + "LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND": 1_000_000, + "model": {"alias": "probe", "bytes": model_bytes}, + } + for key, value in guard["vars"].items(): + variables[key] = _trust_as_template(value) + templar = Templar(loader=DataLoader(), variables=variables) + return ( + _render(templar, f"{{{{ {guard['ansible.builtin.assert']['that']} }}}}") + == "True" + ) + + def test_the_guard_shares_the_pull_budget(self) -> None: + tasks = load_yaml_any(str(PULL), default_if_missing=[]) + guard = next(task for task in tasks if "ansible.builtin.assert" in task) + pull = next(task for task in tasks if task.get("name") == TASK) + self.assertEqual(guard["vars"], pull["vars"]) + + def test_the_largest_budget_that_fits_passes(self) -> None: + self.assertTrue(self._holds(3_569_000_000)) + + def test_a_budget_reaching_the_async_lifetime_fails(self) -> None: + self.assertFalse(self._holds(3_570_000_000)) + + if __name__ == "__main__": unittest.main() From 27984bdf1835a085b9a61632d07ffa297b2e4902 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 22 Nov 2026 22:52:58 +0000 Subject: [PATCH 59/65] fix(web-app-matomo): treat an auth challenge as no own surface in the tracker spec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR 2226 Jenkins#0 (run 45037081070, job 137284073453) failed on main's code: the browser observed no successful response from the onion Matomo host during navigation to the Jenkins onion, observed loads []. Jenkins answers an anonymous GET / with a 403 page that carries the injected tracker and then redirects via commenceLogin to the clearnet IdP. skipWhenLandingOnIdp took any page holding the Matomo domain as the app's own surface, so it never followed that redirect and never skipped. A 401 or 403 response now counts as an auth challenge, not as the own surface, so the helper follows the redirect and skips on the IdP or fails off it. Tests: the real spec in node against stubs, 3 passed; on the base 2 fail. 🎯 Fix: 90 % 💥 Break: 3 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 87 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- .../files/playwright/tracking.spec.js | 8 +- .../files/test_tracking_spec.py | 204 ++++++++++++++++++ 2 files changed, 209 insertions(+), 3 deletions(-) create mode 100644 tests/unit/python/roles/web-app-matomo/files/test_tracking_spec.py diff --git a/roles/web-app-matomo/files/playwright/tracking.spec.js b/roles/web-app-matomo/files/playwright/tracking.spec.js index 4f58c14c22..27f911976f 100644 --- a/roles/web-app-matomo/files/playwright/tracking.spec.js +++ b/roles/web-app-matomo/files/playwright/tracking.spec.js @@ -16,6 +16,7 @@ const { assertInjectedAssetLoadsWithoutCspBlock, gotoOnion } = require("./person const { resolveTimeout } = require("./timeouts"); const SET_SITE_ID_CALL = /_paq\s*\.\s*push\s*\(\s*\[\s*['"]setSiteId['"]/g; +const AUTH_CHALLENGE_STATUSES = [401, 403]; function countTrackers(html) { return (String(html).match(SET_SITE_ID_CALL) || []).length; @@ -35,17 +36,18 @@ async function skipWhenLandingOnIdp(page, target, url) { `${target.id}: GET ${url} returned ${referenceResp.status()} — surface must respond for the tracker assertion to be meaningful` ).toBeLessThan(500); const referenceHtml = await referenceResp.text(); - const injected = referenceHtml.includes(matomoCanonicalDomain); + const challenged = AUTH_CHALLENGE_STATUSES.includes(referenceResp.status()); + const ownSurface = referenceHtml.includes(matomoCanonicalDomain) && !challenged; const ownHost = new URL(url).host; let landedHost = new URL(referenceResp.url()).host; - if (landedHost === ownHost && !injected) { + if (landedHost === ownHost && !ownSurface) { await gotoOnion(page, url, { waitUntil: "domcontentloaded" }); await page .waitForURL((landed) => new URL(landed).host !== ownHost, { timeout: resolveTimeout(15_000) }) .catch(() => {}); landedHost = new URL(page.url()).host; } - if (landedHost !== ownHost && !injected) { + if (landedHost !== ownHost && !ownSurface) { const idpHost = new URL(oidcIssuerUrl).host; expect( landedHost, diff --git a/tests/unit/python/roles/web-app-matomo/files/test_tracking_spec.py b/tests/unit/python/roles/web-app-matomo/files/test_tracking_spec.py new file mode 100644 index 0000000000..7f11b7b25e --- /dev/null +++ b/tests/unit/python/roles/web-app-matomo/files/test_tracking_spec.py @@ -0,0 +1,204 @@ +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import tempfile +import textwrap +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT + +SPEC = ( + PROJECT_ROOT + / "roles" + / "web-app-matomo" + / "files" + / "playwright" + / "tracking.spec.js" +) +MATOMO_HOST = "matomo." + "a" * 56 + ".onion" +TARGET_HOST = "jenkins." + "a" * 56 + ".onion" +IDP_URL = "https://auth.example.test/realms/example" +TRACKER_HTML = ( + "' +) + +PLAYWRIGHT_STUB = textwrap.dedent( + """ + const registered = []; + function test(title, fn) { + registered.push({ title, fn }); + } + test.use = () => {}; + test.beforeEach = () => {}; + test.skip = (condition, reason) => { + if (condition) { + const error = new Error(reason); + error.skipped = true; + throw error; + } + }; + function expect(actual, message) { + const check = (ok, what) => { + if (!ok) { + throw new Error(`${message || ""} (${what})`); + } + }; + return { + toBe: (value) => check(actual === value, `expected ${value}, got ${actual}`), + toBeLessThan: (value) => check(actual < value, `expected < ${value}, got ${actual}`), + toBeGreaterThan: (value) => check(actual > value, `expected > ${value}, got ${actual}`), + toBeTruthy: () => check(Boolean(actual), "expected truthy"), + toContain: (value) => check(String(actual).includes(value), `expected to contain ${value}`), + toEqual: (value) => check(JSON.stringify(actual) === JSON.stringify(value), "expected equal"), + }; + } + module.exports = { test, expect, registered }; + """ +) + +SHARED_STUB = textwrap.dedent( + """ + const scenario = JSON.parse(process.env.SCENARIO); + module.exports = { + appBaseUrl: `http://${scenario.matomo_host}`, + oidcIssuerUrl: scenario.idp_url, + matomoApiToken: "", + matomoTrackingScope: "", + matomoCanonicalDomain: scenario.matomo_host, + matomoTargetRoles: [scenario.target], + hostOf: (value) => value, + siteNeedleFor: (value) => value, + setupMatomoPage: async () => {}, + loginAsAdmin: async () => {}, + }; + """ +) + +PERSONAS_STUB = textwrap.dedent( + """ + module.exports = { + gotoOnion: async (page, url) => page.goto(url), + assertInjectedAssetLoadsWithoutCspBlock: async () => { + process.stdout.write("ASSERTED\\n"); + }, + }; + """ +) + +TIMEOUTS_STUB = "module.exports = { resolveTimeout: (ms) => ms };\n" + +DRIVER = textwrap.dedent( + """ + const { registered } = require("@playwright/test"); + require("./tracking.spec.js"); + const scenario = JSON.parse(process.env.SCENARIO); + const entry = registered.find((t) => t.title.startsWith(`matomo tracker injected in ${scenario.target.id} `)); + let current = "about:blank"; + const page = { + request: { + get: async (url) => ({ status: () => scenario.status, text: async () => scenario.html, url: () => url }), + }, + goto: async (url) => { + current = scenario.landing || url; + }, + url: () => current, + waitForURL: async (predicate) => { + if (!predicate(new URL(current))) { + throw new Error("waitForURL timed out"); + } + }, + content: async () => scenario.html, + }; + entry.fn({ page }).then( + () => process.stdout.write("RAN\\n"), + (error) => process.stdout.write(error.skipped ? `SKIP:${error.message}\\n` : `ERROR:${error.message}\\n`), + ); + """ +) + + +def _have_node() -> bool: + return shutil.which("node") is not None + + +@unittest.skipUnless(_have_node(), "node is not available in PATH") +class TestTrackingSpecIdpLanding(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + stub = self.root / "node_modules" / "@playwright" / "test" + stub.mkdir(parents=True) + (stub / "package.json").write_text( + json.dumps({"name": "@playwright/test", "main": "index.js"}) + ) + (stub / "index.js").write_text(PLAYWRIGHT_STUB) + (self.root / "_shared.js").write_text(SHARED_STUB) + (self.root / "personas.js").write_text(PERSONAS_STUB) + (self.root / "timeouts.js").write_text(TIMEOUTS_STUB) + (self.root / "run.js").write_text(DRIVER) + shutil.copy(SPEC, self.root / "tracking.spec.js") + + def _run(self, status: int, landing: str) -> str: + """Args: + status: HTTP status the target's anonymous GET answers with. + landing: URL the browser ends on after navigating to the target. + + Returns: + The driver's stdout: ASSERTED and RAN, SKIP: or ERROR:. + """ + scenario = { + "matomo_host": MATOMO_HOST, + "idp_url": IDP_URL, + "status": status, + "html": TRACKER_HTML, + "landing": landing, + "target": { + "id": "web-app-jenkins", + "canonical_domain": TARGET_HOST, + "canonical_url": f"http://{TARGET_HOST}", + "is_proxy_gated": False, + }, + } + proc = subprocess.run( + ["node", "run.js"], + capture_output=True, + text=True, + env={**os.environ, "SCENARIO": json.dumps(scenario)}, + cwd=self.root, + timeout=30, + check=False, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + return proc.stdout + + def test_an_auth_challenge_carrying_the_tracker_that_lands_on_the_idp_is_skipped( + self, + ) -> None: + out = self._run(403, f"{IDP_URL}/protocol/openid-connect/auth") + self.assertIn( + "SKIP:web-app-jenkins: its anonymous surface auto-redirects to the IdP", out + ) + self.assertNotIn("ASSERTED", out) + + def test_an_auth_challenge_landing_off_the_idp_is_a_routing_fault(self) -> None: + out = self._run(401, "https://elsewhere.example.test/") + self.assertIn("ERROR:", out) + self.assertIn("routing fault", out) + self.assertNotIn("ASSERTED", out) + + def test_a_rendered_surface_carrying_the_tracker_is_asserted(self) -> None: + out = self._run(200, f"http://{TARGET_HOST}/") + self.assertIn("ASSERTED", out) + self.assertIn("RAN", out) + + +if __name__ == "__main__": + unittest.main() From 7bdbb828dd1cf0c56e44eb13568a7e131f85842b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 23 Nov 2026 00:18:51 +0000 Subject: [PATCH 60/65] fix(sys-svc-container): keep one run-once flag so the once-flag negative control holds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit f722dd0ee8 (PR 2227) set the flag at the top of 00_core.yml and daa4d51341 set it before the list_or_shoot loader; both dropped the old end flag with the same hunk, so the merge 042fae09e6 kept both. The negative control of test_once_flag_before_post_load.py moves only the first flag behind the loader, the second still precedes it, and main fails with AssertionError [] == []. The top flag stays: it guards the whole role and the second include only re-set a fact. Tests: once-flag lint 2 passed (main: 1 failed); run-once integration, once-flag, foreign-core, first-task and include lints, sys-svc-cdn and sys-svc-container unit tests 95 passed, 25 subtests. 🎯 Fix: 96 % 💥 Break: 1 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 95 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/sys-svc-container/tasks/00_core.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/roles/sys-svc-container/tasks/00_core.yml b/roles/sys-svc-container/tasks/00_core.yml index 671da9acb7..763e59c675 100644 --- a/roles/sys-svc-container/tasks/00_core.yml +++ b/roles/sys-svc-container/tasks/00_core.yml @@ -136,8 +136,6 @@ include_tasks: "03_reset.yml" when: MODE_RESET | bool -- include_tasks: utils/once/flag.yml - - name: "🧭 Route docker cleanup/health deps through service-loader" ansible.builtin.include_role: name: sys-service-loader From 33ac4d75af5650ce5215211e8e2bd7b8ff078d6a Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 23 Nov 2026 01:20:56 +0000 Subject: [PATCH 61/65] fix(svc-ai-lmstudio): write the pull task vars out so the variable checker sees them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 93f6b77bb6 shared the pull vars through an anchor on the mapping (vars: &lmstudio_pull_budget). tests/integration/ansible/jinja/test_variable_definitions.py reads task files as text and only opens a vars block on a bare vars: line, so main's test-integration reports _grace and _budget at pull.yml:26 as used but not defined. Both tasks now list the keys and anchor only the values, as test-e2e-playwright's 03_run_pass.yml does; Ansible sees the same values. 🎯 Fix: 94 % 💥 Break: 2 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 92 🚦 Gate: ✅ 90/5 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml b/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml index 6241b304cf..a63974d8dd 100644 --- a/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml +++ b/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml @@ -7,9 +7,9 @@ but services.lmstudio.preload_async_time of svc-ai-lmstudio allows {{ LMSTUDIO_PRELOAD_ASYNC_TIME }} s; raise it in the inventory. quiet: true - vars: &lmstudio_pull_budget - _grace: 15 - _budget: >- + vars: + _grace: &lmstudio_pull_grace 15 + _budget: &lmstudio_pull_budget >- {{ [ LMSTUDIO_PRELOAD_FLOOR_SECONDS | int, ((model.bytes | int) / (LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND | int)) | round(0, 'ceil') | int ] | max }} @@ -24,7 +24,9 @@ container exec {{ LMSTUDIO_LOCAL_CID | quote }} sh -c 'echo N | timeout --foreground -s INT -k "$1" "$2" lms get --yes --gguf "$3"' sh {{ _grace }} {{ _budget }} {{ (model.source ~ '@' ~ model.quant) | quote }} - vars: *lmstudio_pull_budget + vars: + _grace: *lmstudio_pull_grace + _budget: *lmstudio_pull_budget environment: CONTAINER_EXEC_TIMEOUT: "{{ (_budget | int) + 2 * (_grace | int) }}" register: lmstudio_pull_result From ab8398b2d35973c6e7051a1fb26170d6fcf42781 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:32:38 +0000 Subject: [PATCH 62/65] update(repos): bump git refs to latest tags and commits (web-app-nextcloud) --- roles/web-app-nextcloud/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 8372d84ce9..641832456c 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -209,7 +209,7 @@ talk: version: 3.24.4 custom: nextcloud-talk-janus repository: https://github.com/meetecho/janus-gateway.git - ref: v1.4.3 + ref: v1.4.4 # nocheck: single-replica the signaling server addresses exactly one Janus by URL and keeps every media session on it replicas: 1 turn_server: From 373bc36e78860ec8a46a70e56ee7025faf05bb3c Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:33:00 +0000 Subject: [PATCH 63/65] update(images): update Docker image versions (web-app-penpot) --- roles/web-app-penpot/meta/services.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/roles/web-app-penpot/meta/services.yml b/roles/web-app-penpot/meta/services.yml index 405ecb355e..95358bbb90 100644 --- a/roles/web-app-penpot/meta/services.yml +++ b/roles/web-app-penpot/meta/services.yml @@ -82,7 +82,7 @@ frontend: backup: stop_required: false image: penpotapp/frontend - version: "2.19.3" + version: "2.19.4" name: penpot-frontend cpus: "0.5" mem_reservation: 256m @@ -92,7 +92,7 @@ backend: backup: stop_required: false image: penpotapp/backend - version: "2.19.3" + version: "2.19.4" name: penpot-backend cpus: "1.0" mem_reservation: 1g @@ -105,7 +105,7 @@ backend: http: 6060 exporter: image: penpotapp/exporter - version: "2.19.3" + version: "2.19.4" name: penpot-exporter cpus: "0.5" mem_reservation: 512m From c21537e1663a730b53fe393b3a97e1f20df7140b Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:33:08 +0000 Subject: [PATCH 64/65] update(versions): update pins with a declared source (web-app-stalwart) --- roles/web-app-stalwart/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index de7d0371be..091b36f8bf 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -43,7 +43,7 @@ stalwart: # nocheck: default-placement-manager mail edge at a known IP: MX A-record, PTR and SPF bind to the stack host IP (a floating task's egress IP breaks deliverability); the mail store is NFS-hostile and IS the app — same rationale as web-app-mailu placement: manager image: stalwartlabs/stalwart - webui_version: "v2.1.0" + webui_version: "v2.1.1" version: "v1.1.1" update: - key: webui_version From bdce276aa9781d45f26c84e52b11e3be51eba5e8 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:33:15 +0000 Subject: [PATCH 65/65] update(versions): update pins with a declared source (web-app-zammad) --- roles/web-app-zammad/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-zammad/meta/services.yml b/roles/web-app-zammad/meta/services.yml index 75d1374364..c6d5082bc9 100644 --- a/roles/web-app-zammad/meta/services.yml +++ b/roles/web-app-zammad/meta/services.yml @@ -135,7 +135,7 @@ websocket: # nocheck: playwright-service-flag - internal sub-component (bundled search) search: image: docker.elastic.co/elasticsearch/elasticsearch - version: "9.5.6" + version: "9.5.7" update: type: registry_tags image: docker.elastic.co/elasticsearch/elasticsearch