From d68e9f376f1d44349bc51cfa89bc19402dbb5da0 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 05:15:18 +0200 Subject: [PATCH 01/31] fix(healthcheck): render raw play vars in lookup container_healthcheck resolves application_id from the play vars instead of taking it as a positional term. Vars handed over by include_role arrive unrendered, so under sys-stk-full the lookup got the literal '{{ sys_stk_full_application_id }}', resolved no app and refused to render the dashboard compose file. Template such values before use. container_hostname had the same defect: it is a Jinja string in every role's vars and was baked verbatim into the curl Host header. Raise when a value survives templating unrendered, since ansible-core returns untrusted templates as-is. Co-Authored-By: Claude Opus 5 (1M context) --- plugins/lookup/container_healthcheck.py | 31 ++++- .../lookup/test_container_healthcheck.py | 126 ++++++++++++++++++ 2 files changed, 154 insertions(+), 3 deletions(-) create mode 100644 tests/unit/plugins/lookup/test_container_healthcheck.py diff --git a/plugins/lookup/container_healthcheck.py b/plugins/lookup/container_healthcheck.py index 38a947232c..745c6a0d8d 100644 --- a/plugins/lookup/container_healthcheck.py +++ b/plugins/lookup/container_healthcheck.py @@ -53,8 +53,8 @@ class LookupModule(LookupBase): self._vars = ( variables or getattr(self._templar, "available_variables", {}) or {} ) - self._application_id = kwargs.get("application_id") or self._vars.get( - "application_id" + self._application_id = self._render( + kwargs.get("application_id") or self._vars.get("application_id") ) if not self._application_id: raise AnsibleError( @@ -95,7 +95,9 @@ class LookupModule(LookupBase): config: that service's healthcheck entry. kwargs: the call site's keyword arguments. """ - hostname = config.get("hostname", self._vars.get("container_hostname")) + hostname = self._render( + config.get("hostname", self._vars.get("container_hostname")) + ) port_key = str(config.get("port_key", "http") or "http") context = { "test": config.get("test"), @@ -113,6 +115,29 @@ class LookupModule(LookupBase): ) return context + def _render(self, value: Any) -> Any: + """Template a value read straight out of the play vars. + + Args: + value: raw var value; ``include_role: vars:`` hands these over + unrendered, e.g. ``application_id: "{{ sys_stk_full_application_id }}"``. + + Raises: + AnsibleError: the value stayed a template. ansible-core only + renders strings tagged trusted and returns the rest verbatim, + which would bake ``{{ ... }}`` into the compose file. + """ + templar = getattr(self, "_templar", None) + if templar is None or not isinstance(value, str) or "{{" not in value: + return value + rendered = templar.template(value) + if isinstance(rendered, str) and "{{" in rendered: + raise AnsibleError( + f"container_healthcheck: '{value}' did not render; it reached the " + "lookup untrusted as a template." + ) + return rendered + def _config(self, path: str, default: Any) -> Any: """Read one services.yml value through the config SPOT, templated. diff --git a/tests/unit/plugins/lookup/test_container_healthcheck.py b/tests/unit/plugins/lookup/test_container_healthcheck.py new file mode 100644 index 0000000000..5a8b68731b --- /dev/null +++ b/tests/unit/plugins/lookup/test_container_healthcheck.py @@ -0,0 +1,126 @@ +"""Unit tests for the container_healthcheck lookup plugin. + +Pins that values taken straight out of the play vars are templated before +use. ``include_role: vars:`` hands them over unrendered, so under +``sys-stk-full`` ``application_id`` arrives as the literal string +``{{ sys_stk_full_application_id }}`` and ``container_hostname`` as +``{{ lookup('domain', application_id) }}``. +""" + +from __future__ import annotations + +import importlib.util +import unittest + +from ansible.errors import AnsibleError + +from . import PROJECT_ROOT + +SERVICES = { + "web-app-dashboard": { + "services.dashboard.healthcheck": {"flavor": "tcp", "start_period": "10m"}, + "services.dashboard.ports.internal.http": 5000, + }, + "web-app-x": { + "services.web.healthcheck": {"flavor": "curl", "samples": 2}, + "services.web.ports.internal.http": 8080, + }, + "web-app-bare": {}, +} + + +def _load_lookup(): + spec = importlib.util.spec_from_file_location( + "lookup_container_healthcheck", + str(PROJECT_ROOT / "plugins/lookup/container_healthcheck.py"), + ) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(mod) + return mod + + +class _DummyTemplar: + def __init__(self, available_variables=None, rendered=None): + self.available_variables = available_variables or {} + self.rendered = rendered or {} + + def template(self, value): + return self.rendered[value] + + +class _DummyConfigLookup: + def run(self, terms, variables=None): + application_id, path, default = terms[0], terms[1], terms[2] + return [SERVICES.get(application_id, {}).get(path, default)] + + +class TestContainerHealthcheckLookup(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.mod = _load_lookup() + + def setUp(self): + self.original_loader = self.mod.lookup_loader + self.mod.lookup_loader = type( + "_Loader", (), {"get": staticmethod(lambda *a, **kw: _DummyConfigLookup())} + )() + + def tearDown(self): + self.mod.lookup_loader = self.original_loader + + def _make(self, variables, rendered=None): + lm = self.mod.LookupModule() + lm._templar = _DummyTemplar(variables, rendered) + lm._loader = None + return lm + + def test_unrendered_application_id_is_templated(self): + vars_ = { + "application_id": "{{ sys_stk_full_application_id }}", + "sys_stk_full_application_id": "web-app-dashboard", + } + rendered = {"{{ sys_stk_full_application_id }}": "web-app-dashboard"} + block = self._make(vars_, rendered).run(["dashboard"], variables=vars_)[0] + self.assertIn("/dev/tcp/localhost/5000", block) + self.assertIn("start_period: 10m", block) + + def test_unrendered_container_hostname_is_templated(self): + vars_ = { + "application_id": "web-app-x", + "container_hostname": "{{ lookup('domain', application_id) }}", + } + rendered = {"{{ lookup('domain', application_id) }}": "x.example.com"} + block = self._make(vars_, rendered).run(["web"], variables=vars_)[0] + self.assertIn("Host: x.example.com", block) + self.assertNotIn("lookup(", block) + + def test_plain_application_id_passes_through(self): + vars_ = {"application_id": "web-app-dashboard"} + block = self._make(vars_).run(["dashboard"], variables=vars_)[0] + self.assertIn("/dev/tcp/localhost/5000", block) + + def test_missing_flavor_and_test_raises(self): + vars_ = {"application_id": "web-app-bare"} + with self.assertRaises(AnsibleError) as ctx: + self._make(vars_).run(["bare"], variables=vars_) + self.assertIn("web-app-bare", str(ctx.exception)) + + def test_missing_application_id_raises(self): + with self.assertRaises(AnsibleError): + self._make({}).run(["web"], variables={}) + + def test_missing_service_name_raises(self): + with self.assertRaises(AnsibleError): + self._make({}).run([], variables={}) + + def test_unrendered_leftover_template_raises(self): + vars_ = {"application_id": "{{ untrusted }}"} + rendered = {"{{ untrusted }}": "{{ untrusted }}"} + with self.assertRaises(AnsibleError) as ctx: + self._make(vars_, rendered).run(["web"], variables=vars_) + self.assertIn("did not render", str(ctx.exception)) + + +if __name__ == "__main__": + unittest.main() From aceebcda35b069ccd99283024e44e6e00e2173f7 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 05:16:18 +0200 Subject: [PATCH 02/31] test(lint): guard container_healthcheck call sites A service without a healthcheck.flavor or an explicit test only breaks while its compose file renders, one role at a time during a deploy. Replay the lookup's own validation against the static config so the failure surfaces in CI, and reject declarations the lookup would refuse anyway: an unknown flavor, or a flavor and a test fighting over the same entry. Both tests share _probe_defect and import PROBES from the same SPOT the lookup uses, so the known flavors cannot drift apart. 49 of the 56 call sites resolve statically; the rest set service_name in an included base template and are skipped. Co-Authored-By: Claude Opus 5 (1M context) --- ...st_container_healthcheck_requires_probe.py | 217 ++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 tests/lint/ansible/jinja/test_container_healthcheck_requires_probe.py diff --git a/tests/lint/ansible/jinja/test_container_healthcheck_requires_probe.py b/tests/lint/ansible/jinja/test_container_healthcheck_requires_probe.py new file mode 100644 index 0000000000..410610480a --- /dev/null +++ b/tests/lint/ansible/jinja/test_container_healthcheck_requires_probe.py @@ -0,0 +1,217 @@ +"""Strict guard: every ``lookup('container_healthcheck', key)`` call MUST +target a service whose ``meta/services.yml`` entry declares a probe - i.e. +``services..healthcheck`` exists and carries either a known ``flavor`` +or an explicit ``test`` argv. + +Why +=== + +``container_healthcheck`` (``plugins/lookup/container_healthcheck.py``) is +the SPOT for container probes: the call site passes only the service name, +everything else comes from the service's services config. A service that +declares no probe makes the lookup raise while the compose file is being +rendered: + + container_healthcheck: '' service '' declares no + healthcheck.flavor, so healthcheck.test is required. + +That only surfaces during a deploy, one role at a time. This lint replays +the lookup's own validation against the static config so the failure is +caught before CI ever deploys, and additionally rejects probe declarations +the lookup would refuse at render time (unknown flavor, or a ``flavor`` +and a ``test`` fighting over the same entry). + +Resolution scope: literal service keys, the ``service_name`` Jinja variable +resolved against the nearest preceding ``{% set service_name = ... %}``, +``entity_name``, ``application_id | get_entity_name``, and role var +constants (``CHESS_SERVICE``) whose ``vars/main.yml`` value resolves the +same way. Any other dynamic expression (loop variables) is skipped - it +cannot be resolved statically. + +Per-line opt-out: ``# nocheck: container-healthcheck-probe`` on the +offending line or the immediately preceding non-empty line. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path +from typing import Any + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.applications import get_application_defaults +from utils.cache.files import iter_project_files_with_content +from utils.cache.yaml import load_yaml +from utils.docker.healthcheck import PROBES, known_flavors +from utils.roles.entity.name import get_entity_name + +from . import PROJECT_ROOT + +_RULE = "container-healthcheck-probe" + +_SCAN_PREFIX = "roles/" +_SCAN_EXTENSIONS = (".j2",) + +_CALL = re.compile( + r"""lookup\(\s*['"]container_healthcheck['"]\s*,\s*([^,)]+?)\s*[,)]""" +) +_SET_SERVICE_NAME = re.compile(r"""\{%-?\s*set\s+service_name\s*=\s*(.+?)\s*-?%\}""") +_LITERAL = re.compile(r"""^['"]([^'"]+)['"]$""") +_INTERPOLATION = re.compile(r"""^\{\{\s*(.+?)\s*\}\}$""") +_ROLE_VAR = re.compile(r"^[A-Z][A-Z0-9_]*$") +_ENTITY_NAME_EXPRESSIONS = ("entity_name", "application_id | get_entity_name") + + +def _role_app_id(rel_path: str) -> str | None: + parts = Path(rel_path).parts + if len(parts) >= 2 and parts[0] == "roles": + return parts[1] + return None + + +def _resolve_expression(expression: str, app: str) -> str | None: + """Resolve a service-key expression to a literal key. + + Args: + expression: the Jinja expression the call site passed. + app: the application id owning the template. + """ + literal = _LITERAL.match(expression.strip()) + if literal: + return _resolve_expression(literal.group(1), app) or literal.group(1) + normalized = " ".join(expression.split()) + interpolation = _INTERPOLATION.match(normalized) + if interpolation: + return _resolve_expression(interpolation.group(1), app) + if normalized in _ENTITY_NAME_EXPRESSIONS: + return get_entity_name(app) + if _ROLE_VAR.match(normalized): + return _resolve_role_var(normalized, app) + return None + + +def _resolve_role_var(name: str, app: str) -> str | None: + """Resolve a role var constant against the role's ``vars/main.yml``. + + Args: + name: the upper-case var name the template referenced. + app: the application id owning the template. + """ + role_vars = load_yaml( + PROJECT_ROOT / "roles" / app / "vars" / "main.yml", default_if_missing={} + ) + value = role_vars.get(name) + return _resolve_expression(value, app) if isinstance(value, str) else None + + +def _resolve_service_key( + argument: str, lines: list[str], index: int, app: str +) -> str | None: + """Resolve the service key a ``container_healthcheck`` call targets. + + Args: + argument: the call's first argument as written. + lines: the template's lines. + index: zero-based line index of the call. + app: the application id owning the template. + """ + if argument.strip() != "service_name": + return _resolve_expression(argument, app) + for line in reversed(lines[: index + 1]): + assignment = _SET_SERVICE_NAME.search(line) + if assignment: + return _resolve_expression(assignment.group(1), app) + return None + + +def _probe_defect(services: dict[str, Any], key: str) -> str | None: + """Report why a service's probe declaration would fail at render time. + + Args: + services: the application's ``services`` mapping. + key: the service key the call site targets. + """ + if key not in services: + return f"service '{key}' missing in services config" + config = services[key].get("healthcheck") + if not isinstance(config, dict): + return ( + f"service '{key}' declares no healthcheck.flavor, so healthcheck.test " + f"is required. Known flavors: {known_flavors()}" + ) + flavor = str(config.get("flavor", "") or "").strip() + if not flavor and not config.get("test"): + return ( + f"service '{key}' healthcheck has neither flavor nor test. " + f"Known flavors: {known_flavors()}" + ) + if flavor and flavor not in PROBES: + return f"service '{key}' has unknown flavor '{flavor}'" + if flavor and config.get("test"): + return ( + f"service '{key}' declares both flavor '{flavor}' and test; " + "the test would be ignored" + ) + return None + + +class TestContainerHealthcheckRequiresProbe(unittest.TestCase): + def test_healthcheck_call_sites_target_declared_probes(self) -> None: + apps = get_application_defaults() + findings: list[tuple[str, int, str]] = [] + for path_str, content in iter_project_files_with_content( + extensions=_SCAN_EXTENSIONS, + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not rel.startswith(_SCAN_PREFIX): + continue + app = _role_app_id(rel) + if app not in apps: + continue + lines = content.splitlines() + for index, line in enumerate(lines): + for match in _CALL.finditer(line): + key = _resolve_service_key(match.group(1), lines, index, app) + if key is None: + continue + defect = _probe_defect(apps[app].get("services", {}) or {}, key) + if defect and not is_suppressed_at( + lines, index + 1, _RULE, mode="same-or-above" + ): + findings.append((rel, index + 1, f"'{app}' {defect}")) + + if findings: + formatted = "\n".join( + f"- {p}:{n}: {msg}" + for p, n, msg in sorted(set(findings), key=lambda i: (i[0], i[1])) + ) + self.fail( + "container_healthcheck() calls target services without a usable " + "probe. Declare `healthcheck.flavor` (or an explicit " + "`healthcheck.test`) on the service in the role's " + "`meta/services.yml`, or mark a deliberate exception with " + f"`# nocheck: {_RULE}`.\n\nOffenders:\n{formatted}" + ) + + def test_declared_probes_are_renderable(self) -> None: + findings: list[str] = [] + for app, config in sorted(get_application_defaults().items()): + services = config.get("services", {}) or {} + for key in sorted(services): + if not isinstance(services[key].get("healthcheck"), dict): + continue + defect = _probe_defect(services, key) + if defect: + findings.append(f"- {app}: {defect}") + + if findings: + self.fail( + "services declare healthcheck blocks the container_healthcheck " + "lookup would refuse at render time:\n\n" + "\n".join(findings) + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() From f0c2c946f0338bdc46b7069162e33494f0ddc025 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 05:23:46 +0200 Subject: [PATCH 03/31] test(lint): use ROLE_FILE_VARS_MAIN in probe guard The role-file SPOT lint rejects a pathlib chain ending in a literal role filename. Co-Authored-By: Claude Opus 5 (1M context) --- .../ansible/jinja/test_container_healthcheck_requires_probe.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/lint/ansible/jinja/test_container_healthcheck_requires_probe.py b/tests/lint/ansible/jinja/test_container_healthcheck_requires_probe.py index 410610480a..ed183307f5 100644 --- a/tests/lint/ansible/jinja/test_container_healthcheck_requires_probe.py +++ b/tests/lint/ansible/jinja/test_container_healthcheck_requires_probe.py @@ -45,6 +45,7 @@ from utils.cache.files import iter_project_files_with_content from utils.cache.yaml import load_yaml from utils.docker.healthcheck import PROBES, known_flavors from utils.roles.entity.name import get_entity_name +from utils.roles.mapping import ROLE_FILE_VARS_MAIN from . import PROJECT_ROOT @@ -99,7 +100,7 @@ def _resolve_role_var(name: str, app: str) -> str | None: app: the application id owning the template. """ role_vars = load_yaml( - PROJECT_ROOT / "roles" / app / "vars" / "main.yml", default_if_missing={} + PROJECT_ROOT / "roles" / app / ROLE_FILE_VARS_MAIN, default_if_missing={} ) value = role_vars.get(name) return _resolve_expression(value, app) if isinstance(value, str) else None From 115cc885b0c33f609f697abb8a219855a7da2d38 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 12:31:54 +0200 Subject: [PATCH 04/31] fix(ollama): gate async on ASYNC_ENABLED like poll The pre-pull task set `async` unconditionally while gating only `poll`. With async disabled, `poll` became `omit` and ansible fell back to its built-in 15s poll while `async` still routed the task through async_wrapper: ansible collected the job itself and then ran `async_status mode=cleanup`, deleting the job file that tasks/utils/async/reap.yml expects to read. The reap reported a successful `ollama pull` as a failed async job, failing web-app-nextcloud 2 in run 30781723102. Both keys are now switched off together, matching all six peer call sites. On the resulting synchronous path the reap's `async_reap_tolerate` list no longer applies, so the tolerated "up to date" answer is carved out in `failed_when` instead. It keys on `failed` rather than `rc`, so a module-level failure that carries no rc is not swallowed. async_failures._which() now honours loop_control.loop_var: the fired result records the chosen name under `ansible_loop_var`, so a batch failure names `smollm2:135m` instead of the bare job id. A second lint case asserts that async and poll carry `omit` together - the rule this call site was the only one of seven to break. Co-Authored-By: Claude Opus 5 (1M context) --- plugins/filter/async_failures.py | 9 +++-- roles/svc-ai-ollama/tasks/01_manager_ops.yml | 5 ++- .../roles/test_async_reason_documented.py | 36 +++++++++++++++++++ .../plugins/filter/test_async_failures.py | 14 ++++++++ 4 files changed, 60 insertions(+), 4 deletions(-) diff --git a/plugins/filter/async_failures.py b/plugins/filter/async_failures.py index 0b58619844..1f1828ad42 100644 --- a/plugins/filter/async_failures.py +++ b/plugins/filter/async_failures.py @@ -39,15 +39,18 @@ def _which(result: dict) -> str: """Name the job, so a batch failure says which item broke. A collected result nests the fired result under ``item``, which in turn - nests the original loop value - a model name, a user entry - under its own - ``item``. Without it a twenty-user batch reports only how many failed. + nests the original loop value - a model name, a user entry - under the key + ansible used for it. That key is ``item`` unless ``loop_control.loop_var`` + renamed it, in which case the fired result records the name it chose under + ``ansible_loop_var``. Without it a twenty-user batch reports only how many + failed. Args: result: one collected ``async_status`` result. """ fired = result.get("item") if isinstance(fired, dict): - original = fired.get("item") + original = fired.get(fired.get("ansible_loop_var") or "item") if original not in (None, ""): if isinstance(original, dict): for key in ("key", "name", "model"): diff --git a/roles/svc-ai-ollama/tasks/01_manager_ops.yml b/roles/svc-ai-ollama/tasks/01_manager_ops.yml index 49d955db2c..4ca4c4bbed 100644 --- a/roles/svc-ai-ollama/tasks/01_manager_ops.yml +++ b/roles/svc-ai-ollama/tasks/01_manager_ops.yml @@ -14,9 +14,12 @@ loop_control: loop_var: model # rationale: async; model pulls run overlapped, results reaped below before playwright - async: "{{ OLLAMA_PRELOAD_ASYNC_TIME }}" + async: "{{ OLLAMA_PRELOAD_ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" changed_when: false + failed_when: >- + (pull_result.failed | default(false)) + and 'up to date' not in ((pull_result.stdout | default('')) ~ (pull_result.stderr | default(''))) delegate_to: "{{ OLLAMA_HOST_NODE }}" - name: "⏳ Reap the Ollama model pulls" diff --git a/tests/lint/ansible/roles/test_async_reason_documented.py b/tests/lint/ansible/roles/test_async_reason_documented.py index 32d2981f32..e0d45acb34 100644 --- a/tests/lint/ansible/roles/test_async_reason_documented.py +++ b/tests/lint/ansible/roles/test_async_reason_documented.py @@ -29,6 +29,9 @@ Write it as ONE line directly above the ``async`` key: ``rationale:`` is a marker the comment lint accepts, so this does not count as narration. There is no ``nocheck`` escape: the requirement is one sentence, and a task that cannot be given one has not earned its ``async``. + +``async`` and ``poll`` must also be switched off by the SAME condition: both +keys carry ``omit`` on the off branch, or neither does. """ from __future__ import annotations @@ -44,8 +47,10 @@ from . import PROJECT_ROOT ROLES_DIR = PROJECT_ROOT / "roles" _ASYNC_RE = re.compile(r"^(\s*)async:") +_POLL_RE = re.compile(r"^(\s*)poll:") _TASK_START_RE = re.compile(r"^\s*-\s") _REASON_RE = re.compile(r"#\s*rationale:\s*async;\s*\S") +_OMIT_RE = re.compile(r"\bomit\b") def _task_files(): @@ -108,6 +113,37 @@ class TestAsyncReasonDocumented(unittest.TestCase): + "\n".join(f" {o}" for o in offenders), ) + def test_async_and_poll_are_gated_by_the_same_condition(self): + offenders: list[str] = [] + + for path in _task_files(): + lines = read_text(str(path)).splitlines() + for i, line in enumerate(lines): + if not _ASYNC_RE.match(line): + continue + block = _enclosing_task(lines, i) + poll = next((e for e in block if _POLL_RE.match(e)), None) + if poll is None: + continue + if bool(_OMIT_RE.search(line)) == bool(_OMIT_RE.search(poll)): + continue + offenders.append( + f"{path.relative_to(PROJECT_ROOT)}:{i + 1}: " + f"{line.strip()} / {poll.strip()}" + ) + + self.assertEqual( + [], + offenders, + "async and poll must be switched off together.\n" + "Gating only poll leaves the task on the async_wrapper path with " + "ansible's built-in 15s poll, which collects the job and then runs " + "async_status mode=cleanup - deleting the job file a later reap " + "still expects to read, so a successful command reports as a " + "failed async job.\n" + + "\n".join(f" {o}" for o in offenders), + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/plugins/filter/test_async_failures.py b/tests/unit/plugins/filter/test_async_failures.py index c17b3981cf..03699c693b 100644 --- a/tests/unit/plugins/filter/test_async_failures.py +++ b/tests/unit/plugins/filter/test_async_failures.py @@ -76,6 +76,20 @@ class TestAsyncFailures(unittest.TestCase): async_failures(results, []), ) + def test_a_renamed_loop_var_is_still_named_in_the_report(self): + """loop_control.loop_var moves the loop value off the `item` key.""" + renamed = { + "finished": 1, + "rc": 1, + "stderr": "pull failed", + "ansible_job_id": "j5", + "item": { + "ansible_loop_var": "model", + "model": "smollm2:135m", + }, + } + self.assertEqual(["smollm2:135m: pull failed"], async_failures([renamed], [])) + def test_unreadable_job_is_a_failure_not_a_silent_pass(self): """async_status on a job started elsewhere returns finished:true with no outcome. From e8a3b6bf3db5885221295015f0f82d42c84dd13a Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 12:46:43 +0200 Subject: [PATCH 05/31] fix(sys-ctl-rpr-container-hard): do not run the repair during the deploy Under MODE_DEBUG, sys-service maps SYS_SERVICE_DEFAULT_STATE to 'restarted', so the role did not merely install and enable the weekly unit - the handler started it mid-play. Its ExecStart runs files/script.py over DIR_COMPOSITIONS without --only and with no health filter, i.e. `compose down` + `compose up -d` on every project on the host, unlike sys-ctl-rpr-container-soft which restarts only unhealthy or exited ones. In run 30781723102 that destroyed a matrix stack the role had just proven healthy: the loopback probe answered 200 from Synapse/1.157.2 at 08:34:20, the handler ran 08:36:27-08:37:33, and the kill markers list all 17 projects with matrix at 08:37:12. Because the mdad bootstrap gate gets its marker from a volume but the synapse unit from the container rootfs, the recreated container re-ran the full cold bootstrap and was still installing galaxy roles 13 minutes later, so the readiness probe measured 502 for its entire budget. system_service_suppress_flush skips only the state task in the handler; the unit file, the enable and the timer are unaffected, and the repair still runs on its schedule and via OnFailure. The unit does not reach the sys-service-terminator either, since the final run list is written only when system_service_force_flush_final is set. Co-Authored-By: Claude Opus 5 (1M context) --- roles/sys-ctl-rpr-container-hard/tasks/00_core.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/roles/sys-ctl-rpr-container-hard/tasks/00_core.yml b/roles/sys-ctl-rpr-container-hard/tasks/00_core.yml index 959b8f9a09..76f8ccc145 100644 --- a/roles/sys-ctl-rpr-container-hard/tasks/00_core.yml +++ b/roles/sys-ctl-rpr-container-hard/tasks/00_core.yml @@ -7,6 +7,7 @@ - include_role: name: sys-service vars: + system_service_suppress_flush: true system_service_on_calendar: "{{ SYS_SCHEDULE_REPAIR_DOCKER_HARD }}" system_service_timer_enabled: true system_service_tpl_exec_start_pre: '{{ BIN_LOCK }} {{ SYS_SERVICE_GROUP_MANIPULATION | join(" ") }} --ignore {{ SYS_SERVICE_REPAIR_CONTAINER_HARD }} {{ SYS_SERVICE_GROUP_CLEANUP From 4db015f6a9dff665e110deac9c31193ebc6fa948 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 12:51:41 +0200 Subject: [PATCH 06/31] fix(ci): honour the decline contract when zpool create fails The script promises at :12-13 that a host which cannot deliver the stated filesystem declines and reports when REQUIRED is false. The zfs branch did not: `zpool create` stood unguarded, so a random pick that the host could not satisfy exited 1. In run 30781723102 that killed the swarm lab bring-up on all five nodes of the nested svc-db-postgres drill (compose/swarm/playbook.yml:84) and cascaded through swarm-zombie to a red Workspace (debian:bookworm) job. The pre-flight could not have caught it: it only tested that /dev/zfs exists as a character device, and on those nodes it did while the module was unusable. Guarding the real operation instead removes the predictor entirely - whatever makes zfs undeliverable now routes through decline, and REQUIRED=true still fails hard there. The teardown is required because a loop device is already attached to the image at that point and decline exits 0. This does NOT fix why the module is unusable on debian nodes. That is pre-existing and was already silent: the mariadb drill in the same job declined zfs on all five nodes and stayed green, while ubuntu applied zfs on ten. The change makes the two paths consistent; it does not restore the lost coverage. To make the loss diagnosable rather than invisible, modprobe's output is no longer discarded into `|| true` but reported and attached to the decline reason, and verdict() now records the reason in the step summary, folded to one line so the markdown list item survives a multi-line stderr. Co-Authored-By: Claude Opus 5 (1M context) --- .../utils/filesystem/docker_dataroot.sh | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh b/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh index a65a9f26cc..e91ba3657f 100755 --- a/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh +++ b/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh @@ -33,13 +33,16 @@ current_fstype() { echo unknown } +# Param: $1 status word recorded for this host +# Param: $2 reason behind the status, empty when it needs none verdict() { - local status="$1" effective host + local status="$1" reason effective host + reason="$(printf '%s' "${2:-}" | tr '\n' ' ')" effective="$(current_fstype)" host="$(hostname 2>/dev/null || echo unknown)" report "status=${status} requested=${FSTYPE:-none} effective=${effective}" [ -n "${GITHUB_STEP_SUMMARY:-}" ] || return 0 - echo "- \`${host}\` docker data root: **${effective}** (requested \`${FSTYPE:-none}\`, ${status})" \ + echo "- \`${host}\` docker data root: **${effective}** (requested \`${FSTYPE:-none}\`, ${status})${reason:+ - ${reason}}" \ >>"${GITHUB_STEP_SUMMARY}" } @@ -63,11 +66,11 @@ arm_autoclear() { decline() { if [ "${REQUIRED}" = true ]; then report "FAIL: ${FSTYPE} was stated but cannot be delivered: $*" - verdict required-but-unavailable + verdict required-but-unavailable "$*" exit 1 fi report "skipping ${FSTYPE}: $*" - verdict declined + verdict declined "$*" exit 0 } @@ -129,12 +132,14 @@ btrfs) zfs) require_tool zpool zfsutils-linux zfs zfs-utils || decline "the zfs userland is unavailable on this distribution" - modprobe zfs 2>/dev/null || true + if ! modprobe_out="$(modprobe zfs 2>&1)"; then + report "modprobe zfs failed: ${modprobe_out}" + fi if [ ! -c /dev/zfs ]; then zfs_major="$(awk '$2 == "zfs" {print $1}' /proc/devices | head -n1)" [ -n "${zfs_major}" ] && mknod /dev/zfs c "${zfs_major}" 0 fi - [ -c /dev/zfs ] || decline "the zfs kernel module is not loaded on the host" + [ -c /dev/zfs ] || decline "the zfs kernel module is not loaded on the host: ${modprobe_out}" ;; esac @@ -172,7 +177,12 @@ done [ -n "${LOOP}" ] || decline "no loop device could be claimed after ${attempt} attempts" if [ "${FSTYPE}" = zfs ]; then - zpool create -f -m "${MOUNT}" -O acltype=posixacl -O xattr=sa "${POOL}" "${LOOP}" + if ! zpool_out="$(zpool create -f -m "${MOUNT}" -O acltype=posixacl -O xattr=sa "${POOL}" "${LOOP}" 2>&1)"; then + losetup -d "${LOOP}" || + report "WARNING: ${LOOP} refused the detach and will leak into the next round" + rm -f "${IMAGE}" + decline "zpool create failed: ${zpool_out}" + fi zfs create -o mountpoint="${MOUNT}/docker" "${POOL}/docker" else "mkfs.${FSTYPE}" -q "${LOOP}" From 0f27e60d236946b1052140053d3bb50a71bb5837 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 12:52:44 +0200 Subject: [PATCH 07/31] fix(matrix): name both bootstrap phases in the failure message `ActiveState=failed` only says the oneshot exited non-zero, and the unit runs two phases: `ansible-galaxy install -r requirements.yml --force` and then `ansible-playbook setup.yml` (bootstrap.sh:39-44, under set -euo pipefail). Claiming the playbook failed sends the reader looking for an inner PLAY RECAP. In run 30781723102 the web-app-nextcloud 3 job died in the first phase, at role 21 of 31, on a git clone that got HTTP 503. The container journal logs "starting ansible-galaxy install" and never reaches "galaxy install done" or "starting ansible-playbook setup.yml", so there was no recap to find. Wording only; the branch, its condition and the diagnostics are unchanged. The cause of that 503 is still open. Co-Authored-By: Claude Opus 5 (1M context) --- roles/web-app-matrix/tasks/flavor/ansible/05_proxy_wiring.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-matrix/tasks/flavor/ansible/05_proxy_wiring.yml b/roles/web-app-matrix/tasks/flavor/ansible/05_proxy_wiring.yml index b5f907d3e2..1b49fb68ff 100644 --- a/roles/web-app-matrix/tasks/flavor/ansible/05_proxy_wiring.yml +++ b/roles/web-app-matrix/tasks/flavor/ansible/05_proxy_wiring.yml @@ -65,7 +65,7 @@ {% if 'docker=failed' in matrix_mdad_bootstrap_state.stdout_lines | default([]) -%} the docker daemon inside matrix-mdad failed to start - see matrix_mdad_diagnostics above. {%- elif 'ActiveState=failed' in matrix_mdad_bootstrap_state.stdout_lines | default([]) -%} - matrix-mdad bootstrap playbook failed inside the container - see matrix_mdad_diagnostics above. + matrix-mdad bootstrap failed inside the container, in its galaxy install or its playbook - see matrix_mdad_diagnostics above. {%- elif matrix_mdad_bootstrap_state is failed -%} matrix-mdad bootstrap never reached a terminal state within the wait budget - see matrix_mdad_diagnostics above. {%- else -%} From 15e71f465b0b01b567aa380a7b518a17476be07f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 13:03:03 +0200 Subject: [PATCH 08/31] fix(nextcloud): resolve the Zammad partner node instead of probing for it 02_manager_ops.yml includes the plugin chain with `apply: delegate_to: NEXTCLOUD_HOST_NODE`, so the addon hook runs wherever that node happens to be. On a swarm worker the partner probe could not answer: it used NEXTCLOUD_ZAMMAD_CONTAINER_ADDRESS, which expands to a `resolve-container-id zammad railsserver` subshell, and that helper exits 64 off a manager. The substitution came back empty, `container inspect ""` failed, `failed_when: false` swallowed it, and the gate `(nextcloud_zammad_partner_running.stdout | trim) == 'true'` was false. The OAuth provisioning was therefore skipped, client_id and client_secret stayed empty, and integration_zammad's personal view fell back to its access-token UI - so the 'Connect to Zammad' control the spec waits for never existed. That is what failed web-app-nextcloud 5 in run 30781723102. The probe and its clause are gone; provisioning now resolves the railsserver's hosting node and local container id through the standard sys-svc-compose/utils/swarm/resolve_host_cid.yml and delegates the rails call there. resolve_host_cid pins its own delegate_to on STACK_HOST and _HOST_NODE, so it is unaffected by the inherited one, and the trailing occ tasks keep no delegate_to and still run on the Nextcloud node. Losing the probe also loses its quiet skip. The addon is still gated on services.zammad.enabled, i.e. 'web-app-zammad' in group_names (meta/addons/integration_zammad.yml:2), so the exposure is a targeted deploy where the partner is in the inventory but excluded from the run: wait_converged then spends 120x5s before failing instead of skipping. Co-Authored-By: Claude Opus 5 (1M context) --- .../tasks/addons/integration_zammad.yml | 8 -------- .../tasks/addons/integration_zammad_provision.yml | 14 +++++++++++++- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/roles/web-app-nextcloud/tasks/addons/integration_zammad.yml b/roles/web-app-nextcloud/tasks/addons/integration_zammad.yml index d6a25d478c..da66d43ec1 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_zammad.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_zammad.yml @@ -10,13 +10,6 @@ nextcloud_zammad_nc_base_url: "{{ lookup('tls', 'web-app-nextcloud', 'url.base') | regex_replace('/$', '') }}" changed_when: false -- name: 🔍 Probe whether the Zammad partner container is running - shell: > - container inspect --type container -f '{% raw %}{{.State.Running}}{% endraw %}' {{ NEXTCLOUD_ZAMMAD_CONTAINER_ADDRESS }} - register: nextcloud_zammad_partner_running - changed_when: false - failed_when: false - - name: 📖 Read persisted integration_zammad OAuth client id shell: > {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:get integration_zammad client_id @@ -36,7 +29,6 @@ include_tasks: integration_zammad_provision.yml when: >- IS_STACK_HOST | bool - and (nextcloud_zammad_partner_running.stdout | trim) == 'true' and ( (nextcloud_zammad_client_id_current.stdout | trim) | length == 0 or (nextcloud_zammad_client_secret_current.stdout | trim) | length == 0 diff --git a/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml b/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml index 18d685784a..fedd70ae85 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml @@ -1,4 +1,15 @@ --- +- name: "🔍 Resolve Zammad railsserver hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: railsserver + resolve_service_name: "{{ lookup('container_service', 'web-app-zammad', 'railsserver') }}" + resolve_output_prefix: NEXTCLOUD_ZAMMAD + resolve_compose_cid: "{{ NEXTCLOUD_ZAMMAD_CONTAINER_ADDRESS }}" + resolve_converge_retries: 120 + resolve_converge_delay: 5 + +# nocheck: container-exec-resolver NEXTCLOUD_ZAMMAD_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell - name: 🔧 Provision the Zammad OAuth application for Nextcloud and capture credentials ansible.builtin.shell: cmd: >- @@ -6,9 +17,10 @@ -e 'NC_BASE_URL={{ nextcloud_zammad_nc_base_url }}' -e 'NC_REDIRECT_PATH=/apps/integration_zammad/oauth-redirect' -e 'NC_HAS_SECRET={{ nextcloud_zammad_client_secret_current.stdout | trim }}' - {{ NEXTCLOUD_ZAMMAD_CONTAINER_ADDRESS }} + {{ NEXTCLOUD_ZAMMAD_LOCAL_CID | quote }} bundle exec rails r - stdin: "{{ lookup('file', 'zammad/provision_oauth_app.rb') }}" + delegate_to: "{{ NEXTCLOUD_ZAMMAD_HOST_NODE }}" register: nextcloud_zammad_provision retries: 12 delay: 10 From d0937b0bb708da358a15a0f6efb08dc6cae99ce5 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 15:14:13 +0200 Subject: [PATCH 09/31] fix(ci): stop dropping ext4 verdicts and losing their reasons Three places where a data-root verdict was produced and then lost. report.sh matched `requested=[a-z]+`, which never matches `ext4`. Against the real deploy log of a run that recorded five ext4 verdicts, the old pattern yields 0 matches and the summary table was silently empty of them; the fixed pattern aggregates the same five into one row. docker_dataroot.sh wrote the reason only to GITHUB_STEP_SUMMARY, which is unset inside the lab node containers - so on exactly the machines that decline, the reason went nowhere. It now rides on the machine-readable report line too. This is what leaves the mariadb drill's decline reason unrecoverable from run 30781723102. resolve.sh's exclusions went to stderr only, i.e. into the deploy log rather than the job summary. The reason is emitted as a list below the table, not as a column: reasons embed per-node data (the pool name carries the hostname, plus the loop device), so folding them into the `sort | uniq -c` key would split one five-node row into five one-node rows exactly in the failure case the reason exists to explain. `reason=[^']*` keeps ansible's closing quote out of the value, and `|` is replaced so a reason cannot break the markdown table. Co-Authored-By: Claude Opus 5 (1M context) --- scripts/tests/deploy/utils/filesystem/docker_dataroot.sh | 2 +- scripts/tests/deploy/utils/filesystem/report.sh | 9 +++++++-- scripts/tests/deploy/utils/filesystem/resolve.sh | 6 +++++- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh b/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh index e91ba3657f..0eb0da8382 100755 --- a/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh +++ b/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh @@ -40,7 +40,7 @@ verdict() { reason="$(printf '%s' "${2:-}" | tr '\n' ' ')" effective="$(current_fstype)" host="$(hostname 2>/dev/null || echo unknown)" - report "status=${status} requested=${FSTYPE:-none} effective=${effective}" + report "status=${status} requested=${FSTYPE:-none} effective=${effective}${reason:+ reason=${reason}}" [ -n "${GITHUB_STEP_SUMMARY:-}" ] || return 0 echo "- \`${host}\` docker data root: **${effective}** (requested \`${FSTYPE:-none}\`, ${status})${reason:+ - ${reason}}" \ >>"${GITHUB_STEP_SUMMARY}" diff --git a/scripts/tests/deploy/utils/filesystem/report.sh b/scripts/tests/deploy/utils/filesystem/report.sh index 195f28fe33..e573d94a39 100755 --- a/scripts/tests/deploy/utils/filesystem/report.sh +++ b/scripts/tests/deploy/utils/filesystem/report.sh @@ -6,7 +6,8 @@ set -euo pipefail LOG="${1:?usage: report.sh LOG}" -PATTERN='status=[a-z-]+ requested=[a-z]+ effective=[A-Za-z0-9_./-]+' +PATTERN='status=[a-z-]+ requested=[a-z0-9]+ effective=[A-Za-z0-9_./-]+' +REASON_PATTERN="${PATTERN} reason=[^']*" [ -f "${LOG}" ] || exit 0 [ -n "${GITHUB_STEP_SUMMARY:-}" ] || exit 0 @@ -16,6 +17,9 @@ if ! VERDICTS="$(grep -ohE "${PATTERN}" "${LOG}" | sort | uniq -c | sort -rn)"; fi [ -n "${VERDICTS}" ] || exit 0 +REASONS="$(grep -ohE "${REASON_PATTERN}" "${LOG}" | sed -E 's/.* reason=//' | tr '|' '/' | sort -u)" || + REASONS="" + { echo "#### Docker data root, as actually used" echo @@ -23,6 +27,7 @@ fi echo "|---:|---|---|---|" # shellcheck disable=SC2016 echo "${VERDICTS}" | sed -E \ - 's/^ *([0-9]+) status=([a-z-]+) requested=([a-z]+) effective=(.+)$/| \1 | `\4` | `\3` | \2 |/' + 's/^ *([0-9]+) status=([a-z-]+) requested=([a-z0-9]+) effective=(.+)$/| \1 | `\4` | `\3` | \2 |/' echo + [ -z "${REASONS}" ] || printf '%s\n\n' "$(echo "${REASONS}" | sed -E 's/^/- /')" } >>"${GITHUB_STEP_SUMMARY}" diff --git a/scripts/tests/deploy/utils/filesystem/resolve.sh b/scripts/tests/deploy/utils/filesystem/resolve.sh index f666494d8d..4a50c47aa4 100755 --- a/scripts/tests/deploy/utils/filesystem/resolve.sh +++ b/scripts/tests/deploy/utils/filesystem/resolve.sh @@ -23,7 +23,11 @@ SCOPE="${4:?usage: resolve.sh STATED LABEL DISTROS SCOPE}" POOL="ext4 btrfs zfs" -note() { echo "filesystem: $*" >&2; } +note() { + echo "filesystem: $*" >&2 + [ -n "${GITHUB_STEP_SUMMARY:-}" ] || return 0 + echo "- \`${LABEL}\` filesystem: $*" >>"${GITHUB_STEP_SUMMARY}" +} kernel_serves() { local fs="$1" From 539c71a5b77dd3844cc943341a71804c2941b493 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 15:17:56 +0200 Subject: [PATCH 10/31] perf(matrix): skip the galaxy install when requirements.yml is unchanged bootstrap.sh re-cloned all 31 unauthenticated GitHub repos on every bootstrap, including warm re-runs where roles/galaxy was already fully populated. The install is now keyed on the sha256 of requirements.yml: the stamp is removed before the install and written only after it, `--force` stays inside the branch so a changed requirements.yml still refreshes every role, and set -euo pipefail still aborts on a galaxy failure. Nothing is masked and no retry is added. The stamp lives in roles/galaxy/, not in the matrix_mdad_state volume, so it shares one lifecycle with the roles it describes. The volume-vs-bind-mount split is the same cross-domain state coupling that 5d6d1c7ca blames for this run's matrix failure, where the bootstrap gate read its marker from a volume and the synapse unit from the container rootfs. This is not a fix for the HTTP 503 that failed web-app-nextcloud 3 in run 30781723102: that job ran a cold container, which always clones. It removes re-clones on redeploys of a persistent host. The 503's mechanism is still open - the observed ~31.8s per clone is flat and payload-independent, and neither runner bandwidth nor host load explains it. PYTHONUNBUFFERED=1 line-buffers ansible's stdout in the unit. Without it every progress line carries one flush timestamp at process exit, which is why the 667s of the failing install cannot be split into per-clone times. Co-Authored-By: Claude Opus 5 (1M context) --- .../flavor/ansible/runner/bootstrap.service | 1 + .../files/flavor/ansible/runner/bootstrap.sh | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/roles/web-app-matrix/files/flavor/ansible/runner/bootstrap.service b/roles/web-app-matrix/files/flavor/ansible/runner/bootstrap.service index e92eba3393..eba22b3e02 100644 --- a/roles/web-app-matrix/files/flavor/ansible/runner/bootstrap.service +++ b/roles/web-app-matrix/files/flavor/ansible/runner/bootstrap.service @@ -6,6 +6,7 @@ Requires=docker.service [Service] Type=oneshot Environment=PATH=/opt/ansible/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin +Environment=PYTHONUNBUFFERED=1 ExecStartPre=/usr/bin/docker info ExecStart=/usr/local/bin/matrix-mdad-bootstrap RemainAfterExit=yes diff --git a/roles/web-app-matrix/files/flavor/ansible/runner/bootstrap.sh b/roles/web-app-matrix/files/flavor/ansible/runner/bootstrap.sh index 300a41fc83..766b476292 100644 --- a/roles/web-app-matrix/files/flavor/ansible/runner/bootstrap.sh +++ b/roles/web-app-matrix/files/flavor/ansible/runner/bootstrap.sh @@ -35,10 +35,18 @@ fi cd /mdad -START_GALAXY=$SECONDS -echo ">>> matrix-mdad-bootstrap: starting ansible-galaxy install" -/opt/ansible/bin/ansible-galaxy install -r requirements.yml -p roles/galaxy/ --force -echo "<<< matrix-mdad-bootstrap: galaxy install done in $((SECONDS - START_GALAXY))s" +GALAXY_STAMP=roles/galaxy/.requirements.sha256 +GALAXY_WANT=$(sha256sum requirements.yml | cut -d' ' -f1) +if [ -f "$GALAXY_STAMP" ] && [ "$(cat "$GALAXY_STAMP")" = "$GALAXY_WANT" ] && [ -d roles/galaxy ]; then + echo ">>> matrix-mdad-bootstrap: galaxy roles match requirements.yml ($GALAXY_WANT), skipping install" +else + START_GALAXY=$SECONDS + echo ">>> matrix-mdad-bootstrap: starting ansible-galaxy install" + rm -f "$GALAXY_STAMP" + /opt/ansible/bin/ansible-galaxy install -r requirements.yml -p roles/galaxy/ --force + printf '%s\n' "$GALAXY_WANT" > "$GALAXY_STAMP" + echo "<<< matrix-mdad-bootstrap: galaxy install done in $((SECONDS - START_GALAXY))s" +fi START_PLAY=$SECONDS echo ">>> matrix-mdad-bootstrap: starting ansible-playbook setup.yml --tags=${MATRIX_MDAD_PLAYBOOK_TAGS:-setup-all,start}" From 98396dcfbb7427de22ffa7e3cd9f58d8080c7182 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 15:21:25 +0200 Subject: [PATCH 11/31] fix(ci): bring docker back up on every exit after the data-root stop The script stops the daemon at :157-158 and starts it again only on the success path at :220. decline() exits 0 and set -e exits non-zero, and both walk past that start, so any other outcome leaves the host without docker. One of the three callers is test-deploy-host.yml:171, where the script runs on the GitHub runner itself rather than in a lab node container. An EXIT trap rather than a restart inside decline(), because decline is not the only affected exit: arm_autoclear's exit 1 and every set -e abort at mkdir, truncate, zfs create, mkfs, mount, btrfs subvolume create and the daemon.json writer sit in the same window. The trap is armed only after the stop, and DOCKER_STOPPED=false after a successful start makes it a no-op on the green path. A failed restart is reported rather than swallowed, so it cannot hide the failure that led there. This hazard predates 02dc003bb: the loop-device decline added in the commit before it has the same property. 02dc003bb widened it by putting a second decline behind the stop. Verified with a stubbed-PATH harness driving the real script: after a failed zpool create the call log contains `systemctl start docker`, and it comes after `losetup -d`, so the teardown still precedes the restart. REQUIRED=true still exits 1, the success path is unchanged. Co-Authored-By: Claude Opus 5 (1M context) --- .../tests/deploy/utils/filesystem/docker_dataroot.sh | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh b/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh index 0eb0da8382..6c11130733 100755 --- a/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh +++ b/scripts/tests/deploy/utils/filesystem/docker_dataroot.sh @@ -152,9 +152,18 @@ if mountpoint -q "${MOUNT}"; then exit 0 fi +restore_docker() { + [ "${DOCKER_STOPPED:-false}" = true ] || return 0 + systemctl cat docker.service >/dev/null 2>&1 || return 0 + systemctl start docker || + report "WARNING: docker did not come back up after the ${FSTYPE} setup" +} + report "putting the docker data root on ${FSTYPE}" systemctl stop docker.socket 2>/dev/null || true systemctl stop docker 2>/dev/null || true +DOCKER_STOPPED=true +trap restore_docker EXIT mkdir -p "${MOUNT}" "$(dirname "${IMAGE}")" rm -f "${IMAGE}" @@ -209,6 +218,7 @@ PYTHON if systemctl cat docker.service >/dev/null 2>&1; then systemctl start docker + DOCKER_STOPPED=false verdict applied else report "docker.service is not installed yet; the data root takes effect when it is" From b19d1d18a0e5074e7f9706c904d23ddd9698758d Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 15:23:53 +0200 Subject: [PATCH 12/31] style(nextcloud): drop a nocheck marker the resolver rule never reads The marker claimed to suppress container-exec-resolver, but that rule does not fire on this task. Its extractor reads the first argument after `container exec` and finds `-i`, so it returns no target; the container id is four lines further down. The position was wrong too: the rule accepts a marker on the same or the immediately preceding non-empty line, and three lines separated the two. That leaves a suppression marker carrying a rationale, which is the shape the comment policy exists to prevent. The reason it stated - that container_address would expand to a manager-only subshell - is already in 04b8cfead's message. tests/lint/ansible/shell/container/ stays green without it. Co-Authored-By: Claude Opus 5 (1M context) --- .../tasks/addons/integration_zammad_provision.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml b/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml index fedd70ae85..4650e11caa 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml @@ -9,7 +9,6 @@ resolve_converge_retries: 120 resolve_converge_delay: 5 -# nocheck: container-exec-resolver NEXTCLOUD_ZAMMAD_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell - name: 🔧 Provision the Zammad OAuth application for Nextcloud and capture credentials ansible.builtin.shell: cmd: >- From ee6fb584bc187d4242338e9c9353aa23400d02ff Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 16:18:51 +0200 Subject: [PATCH 13/31] fix(swarm): install kmod in the lab node image The node image ships no module loader, so `modprobe zfs` in scripts/tests/deploy/utils/filesystem/docker_dataroot.sh was a no-op whose error was additionally discarded by `2>/dev/null || true`. Every node's own systemd says so at boot, in rescue-diagnostics-workspace-debian-bookworm of run 30781723102: (modprobe)[27]: modprobe@configfs.service: Unable to locate executable '/sbin/modprobe': No such file or directory The module itself is reachable: the nodes run privileged with /lib/modules bind-mounted read-only, and their df confirms it. What was missing is the loader, not the module. zfs-load-module.service is installed and enabled in the image and sits inactive for the same reason. This does not by itself make the debian lane apply zfs. `The ZFS modules are not loaded.` in job 91588086713 came from libzfs at `zpool create`, not from the suppressed modprobe - the kernel ring buffer shows five 30 GiB loop attachments at 07:37:32, i.e. the script was past the /dev/zfs gate. And a Debian bookworm node only has a zfsutils-linux candidate while the package cache stack is up: the cache was removed at 06:39:49 and rebuilt at 07:18:25, which is why the mariadb drill declined at the userland check while the postgres drill reached zpool create. That cache dependency is untouched here. Co-Authored-By: Claude Opus 5 (1M context) --- compose/swarm/Dockerfile | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/compose/swarm/Dockerfile b/compose/swarm/Dockerfile index 5e70fa0d79..6f812224cb 100644 --- a/compose/swarm/Dockerfile +++ b/compose/swarm/Dockerfile @@ -1,7 +1,8 @@ # Node image for the swarm DR test cluster, layered on the distro's infinito # image so python + ansible + the CLI (venv) are already baked -- the per-node # .deb bootstrap is gone. Adds only the node extras: dnsmasq (lab DNS), openssh -# server (backup pull chain), cryptsetup + e2fsprogs (LUKS drill device). +# server (backup pull chain), cryptsetup + e2fsprogs (LUKS drill device), kmod +# (modprobe, for the data-root filesystem). # Distro-agnostic install (apt/dnf/pacman) since INFINITO_IMAGE is per-distro. # systemd-resolved is masked so it never races dnsmasq for port 53. The pacman # branch refreshes the keyring and does a full -Syu: the pinned parent image can @@ -22,14 +23,14 @@ FROM ${INFINITO_IMAGE} RUN set -eux; \ if command -v apt-get >/dev/null 2>&1; then \ apt-get update -qq; \ - apt-get install -y -qq --no-install-recommends dnsmasq openssh-server cryptsetup e2fsprogs elfutils; \ + apt-get install -y -qq --no-install-recommends dnsmasq openssh-server cryptsetup e2fsprogs elfutils kmod; \ rm -rf /var/lib/apt/lists/*; \ elif command -v dnf >/dev/null 2>&1; then \ - dnf install -y dnsmasq openssh-server cryptsetup e2fsprogs elfutils; \ + dnf install -y dnsmasq openssh-server cryptsetup e2fsprogs elfutils kmod; \ dnf clean all; \ elif command -v pacman >/dev/null 2>&1; then \ pacman -Sy --noconfirm --needed archlinux-keyring; \ - pacman -Syu --noconfirm --needed dnsmasq openssh cryptsetup e2fsprogs elfutils; \ + pacman -Syu --noconfirm --needed dnsmasq openssh cryptsetup e2fsprogs elfutils kmod; \ rm -rf /var/cache/pacman/pkg/*; \ else \ echo "no supported package manager (apt/dnf/pacman)" >&2; exit 1; \ From 41732fbf9a13c88197a21bebd3f57ab5f0f97cd8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 16:22:42 +0200 Subject: [PATCH 14/31] fix(drill): measure the device instead of budgeting a sparse nominal size The guard compared free space against USB_SIZE_MB = PULLED_MB*2+256, which is the nominal size of an image 02_luks_device.sh creates with truncate - sparse, so nothing ever allocates it. It also ran after that script, i.e. once the image was already created, formatted and mounted, so the image's own footprint was already subtracted from the df it read. It charged the pulled tree a second time while that tree was counted as used, not free. In run 30781723102 it demanded 28108M against 16582M and refused a drill that fits: the peak is 14555M additional, derived from rescue-diagnostics-swarm-web-app-nextcloud-0, and the same run's debian job contains a full 9/9 completion of the same drill. Rather than predicting the image's ext4 overhead - two earlier attempts at that constant were wrong in both directions - both thresholds are now read: df on DEV_MOUNT reports what the encrypted filesystem actually offers after mkfs, and df on DIR_BACKUPS reports what the host still has for the copy the sync writes into the sparse file and, later, the restore root. Both are compared against PULLED_MB, a measured quantity. USB_SIZE_MB keeps sizing the image. Every abort now tears the device down (umount, luksClose, rm -f); a refused drill previously left the mapping and the image behind. Exercised against the recorded numbers and six edge cases: 26624/16582/13926 passes where the old guard refused, an undersized device or host is refused, and an empty or non-numeric df reading is reported as unreadable. Both thresholds sit exactly at PULLED_MB, so second-order allocation inside the image (extent trees, directory blocks) is uncovered - tens of MiB against a 13.9 GiB tree. The drill has not been run with this guard. Co-Authored-By: Claude Opus 5 (1M context) --- .../tests/deploy/swarm/routine/backup/base.sh | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/scripts/tests/deploy/swarm/routine/backup/base.sh b/scripts/tests/deploy/swarm/routine/backup/base.sh index 898b0a4eab..f4735ce649 100755 --- a/scripts/tests/deploy/swarm/routine/backup/base.sh +++ b/scripts/tests/deploy/swarm/routine/backup/base.sh @@ -141,20 +141,37 @@ USB_SIZE_MB=$((PULLED_MB * 2 + 256)) echo " ${PULLED_MB}M pulled; sizing the loop image to ${USB_SIZE_MB}M (2x pulled tree + headroom, floor 2G)" docker exec "${BACKUP_NODE}" bash "${BKP_IN_NODE}/02_luks_device.sh" \ "${USB_IMG}" "${DEV_MOUNT}" "${DEV_DEST}" "${USB_MAPPER}" "${USB_PASS}" "${USB_SIZE_MB}" +drill_device_teardown() { + docker exec "${BACKUP_NODE}" umount "${DEV_MOUNT}" 2>/dev/null || true + docker exec "${BACKUP_NODE}" cryptsetup luksClose "${USB_MAPPER}" 2>/dev/null || true + docker exec "${BACKUP_NODE}" rm -f "${USB_IMG}" 2>/dev/null || true +} +if ! DEVICE_FREE_RAW="$(docker exec "${BACKUP_NODE}" df --output=avail -B1M "${DEV_MOUNT}" 2>/dev/null)"; then + DEVICE_FREE_RAW="" +fi +DEVICE_FREE_MB="$(printf '%s\n' "${DEVICE_FREE_RAW}" | tail -n1 | tr -d ' ')" if ! FREE_RAW="$(docker exec "${BACKUP_NODE}" df --output=avail -B1M "${DIR_BACKUPS}" 2>/dev/null)"; then FREE_RAW="" fi FREE_MB="$(printf '%s\n' "${FREE_RAW}" | tail -n1 | tr -d ' ')" -case "${FREE_MB}" in -'' | *[!0-9]*) - echo "FAILURE: cannot read free space on ${BACKUP_NODE}:${DIR_BACKUPS} — df --output returned '${FREE_MB}'" +case "${DEVICE_FREE_MB}:${FREE_MB}" in +*[!0-9:]* | *::* | :* | *:) + echo "FAILURE: cannot read free space on ${BACKUP_NODE} — df --output returned device '${DEVICE_FREE_MB}', backup root '${FREE_MB}'" + drill_device_teardown exit 1 ;; esac -if [ "${FREE_MB}" -lt "${USB_SIZE_MB}" ]; then - echo "FAILURE: the drill holds the ${PULLED_MB}M pulled tree twice over (device sync, then the restore root plus one stage copy); ${FREE_MB}M free on ${BACKUP_NODE}:${DIR_BACKUPS}, ${USB_SIZE_MB}M needed" +if [ "${DEVICE_FREE_MB}" -lt "${PULLED_MB}" ]; then + echo "FAILURE: the encrypted device offers ${DEVICE_FREE_MB}M usable after mkfs on a ${USB_SIZE_MB}M image; the ${PULLED_MB}M pulled tree does not fit" + drill_device_teardown exit 1 fi +if [ "${FREE_MB}" -lt "${PULLED_MB}" ]; then + echo "FAILURE: the drill still has to allocate one more copy of the ${PULLED_MB}M pulled tree (the sync into the sparse image, later the restore root); ${FREE_MB}M free on ${BACKUP_NODE}:${DIR_BACKUPS}" + drill_device_teardown + exit 1 +fi +echo " device offers ${DEVICE_FREE_MB}M, backup root has ${FREE_MB}M free, ${PULLED_MB}M to place" if ! docker exec "${BACKUP_NODE}" bash "${TRIGGER_UNITS}" 'svc-bkp-local-2-device*.service' "${UNIT_DUMPS}"; then echo "FAILURE: local-2-device unit missing or failed on ${BACKUP_NODE} (role not deployed?)" exit 1 From 3f5d22b1ae16f8a82268877f34a63bd93490fa77 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 16:33:17 +0200 Subject: [PATCH 15/31] fix(swarm): mask modprobe@.service in the lab node image 18abce480 added kmod so the data-root setup can run its one explicit `modprobe zfs`. It also handed a working loader to the four modprobe@ instances systemd pulls at every node boot - configfs, drm, efi_pstore and fuse - which until now failed on the missing binary, as every node's journal in rescue-diagnostics-workspace-debian-bookworm shows. They would have started loading host modules from a privileged container, on every node of every swarm job in all five distros. Masking the template keeps them exactly as dead as they are today and leaves the loader available to the caller that needs it, so the behaviour change of 18abce480 is confined to the one site it was meant for. It sits with the existing masks for systemd-resolved and systemd-udevd. The image was not built; that the mask covers every instance of the template is read from systemd's behaviour, not measured. The next run shows it: the units report masked instead of failed. Co-Authored-By: Claude Opus 5 (1M context) --- compose/swarm/Dockerfile | 1 + 1 file changed, 1 insertion(+) diff --git a/compose/swarm/Dockerfile b/compose/swarm/Dockerfile index 6f812224cb..af77cf690f 100644 --- a/compose/swarm/Dockerfile +++ b/compose/swarm/Dockerfile @@ -37,6 +37,7 @@ RUN set -eux; \ fi; \ systemctl mask systemd-resolved; \ systemctl mask systemd-udevd systemd-udevd-kernel.socket systemd-udevd-control.socket systemd-udevd-varlink.socket systemd-udev-trigger; \ + systemctl mask modprobe@.service; \ systemctl enable ssh 2>/dev/null || systemctl enable sshd; \ chmod u+rw /etc/shadow; \ if [ -e /etc/gshadow ]; then chmod u+rw /etc/gshadow; fi; \ From 40173e826629263b31c45642f8d16f868e2ade39 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 16:34:38 +0200 Subject: [PATCH 16/31] test(lint): compare the async/poll gate, not the word omit The rule checked whether both keys contain the token `omit`. That catches the Ollama shape, where async carried no omit at all, but it does not enforce what the failure message claims: two keys can both carry omit and still hang on different switches, and the old check passed that. _gate() now reads the switch each key states inline - the test of an `if ... else omit`, or the left side of a `| ternary(..., omit)` - and the two must match. A key that names no gate matches another that names none, which is the shape sys-service and the canonical ASYNC_TIME/ASYNC_POLL pair use; both then inherit whatever their variables do. An unrecognised omit-bearing form falls into a single bucket, so it only matches another unrecognised form. Checked against all five shapes in the tree: the pre-fix Ollama pair is an offender, the fixed pair and the ternary and bare-variable pairs are not, and two different conditions are now an offender where the token check passed them. The rule still does not catch two ungated keys whose variables diverge. That is deliberate: group_vars makes ASYNC_TIME evaluate to omit while ASYNC_POLL stays numeric, and a poll without async is ignored. Co-Authored-By: Claude Opus 5 (1M context) --- .../roles/test_async_reason_documented.py | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/tests/lint/ansible/roles/test_async_reason_documented.py b/tests/lint/ansible/roles/test_async_reason_documented.py index e0d45acb34..ce96fc6759 100644 --- a/tests/lint/ansible/roles/test_async_reason_documented.py +++ b/tests/lint/ansible/roles/test_async_reason_documented.py @@ -30,8 +30,11 @@ Write it as ONE line directly above the ``async`` key: narration. There is no ``nocheck`` escape: the requirement is one sentence, and a task that cannot be given one has not earned its ``async``. -``async`` and ``poll`` must also be switched off by the SAME condition: both -keys carry ``omit`` on the off branch, or neither does. +``async`` and ``poll`` must also be switched off by the SAME condition. The rule +reads the gate each key states inline - the test of an ``if ... else omit`` or +the left side of a ``| ternary(..., omit)`` - and requires the two to match. A +key that names no gate matches another that names none, since both then inherit +whatever the referenced variables do. """ from __future__ import annotations @@ -51,6 +54,8 @@ _POLL_RE = re.compile(r"^(\s*)poll:") _TASK_START_RE = re.compile(r"^\s*-\s") _REASON_RE = re.compile(r"#\s*rationale:\s*async;\s*\S") _OMIT_RE = re.compile(r"\bomit\b") +_IF_ELSE_OMIT_RE = re.compile(r"if\s+(.+?)\s+else\s+omit") +_TERNARY_OMIT_RE = re.compile(r"\{\{\s*(.+?)\s*\|\s*ternary\(") def _task_files(): @@ -63,6 +68,18 @@ def _task_files(): yield path +def _gate(line: str) -> str | None: + """The off-switch a key states inline, normalised, or None when it states none. + + Args: + line: the ``async:`` or ``poll:`` line. + """ + if not _OMIT_RE.search(line): + return None + match = _IF_ELSE_OMIT_RE.search(line) or _TERNARY_OMIT_RE.search(line) + return " ".join(match.group(1).split()) if match else "omit" + + def _enclosing_task(lines: list[str], index: int) -> list[str]: """Return the lines of the task containing ``lines[index]``. @@ -125,7 +142,7 @@ class TestAsyncReasonDocumented(unittest.TestCase): poll = next((e for e in block if _POLL_RE.match(e)), None) if poll is None: continue - if bool(_OMIT_RE.search(line)) == bool(_OMIT_RE.search(poll)): + if _gate(line) == _gate(poll): continue offenders.append( f"{path.relative_to(PROJECT_ROOT)}:{i + 1}: " From cdf5db4c1f335a01fae01ec59c08b0d31e180811 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 16:35:58 +0200 Subject: [PATCH 17/31] feat(diagnostics): collect module, device and network counters Two investigations of run 30781723102 stalled on files the rescue capture does not take. The zfs question - why the debian lab nodes cannot use a module their ubuntu counterparts apply on ten nodes - needed /proc/modules to see whether the module is loaded, /proc/misc to see whether it registered (a misc device never appears in /proc/devices, which is what docker_dataroot.sh was searching), `ls -l /dev/zfs` to tell a real node from the static one every privileged container inherits, and `zfs version` for the libzfs version a whole refuted hypothesis turned on. The matrix-mdad question - whether ~31.8s per git clone is a connect stall or a server-side queue - needs the TCP retransmission counters in /proc/net/snmp and /proc/net/netstat and the conntrack drop counters. Neither can be distinguished from per-clone timings alone. Executed on a host with no zfs: a missing binary and a missing proc file each land as text in the artifact rather than aborting the capture, which is the best-effort contract run() already implements. Co-Authored-By: Claude Opus 5 (1M context) --- utils/diagnostics/container.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/utils/diagnostics/container.py b/utils/diagnostics/container.py index 929bb092df..b40dce96b6 100755 --- a/utils/diagnostics/container.py +++ b/utils/diagnostics/container.py @@ -111,6 +111,12 @@ def collect_host(out: Path, app_id: str, context: str, stamp: str) -> None: "resolve-probe.txt", ["getent", "hosts", "deb.debian.org", "ghcr.io", "repo.packagist.org"], ), + ("modules.txt", ["cat", "/proc/modules"]), + ("devices.txt", ["cat", "/proc/devices", "/proc/misc"]), + ("zfs-dev.txt", ["ls", "-l", "/dev/zfs"]), + ("zfs-version.txt", ["zfs", "version"]), + ("net-snmp.txt", ["cat", "/proc/net/snmp", "/proc/net/netstat"]), + ("conntrack-stat.txt", ["cat", "/proc/net/stat/nf_conntrack"]), ): capture(out, name, cmd) dmesg = run(["dmesg", "-T"]).stdout.decode(errors="replace") From ee62f76a5d4c3b49e450773aa46bb3b922fc6162 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 16:48:52 +0200 Subject: [PATCH 18/31] fix(nextcloud): wait for the Zammad endpoint before provisioning resolve_host_cid's convergence wait is swarm-only (wait_converged.yml:9), so in compose mode nothing made sure Zammad answers before the rails provisioning ran - the only budget there was the provisioning task's own 12x10s against a rails server whose cold start can exceed it. integration_openproject_provision.yml already guards its partner this way; this restores the symmetry. The wait sits after the resolver rather than before it. Both waits are needed and check different things - wait_converged asks swarm whether the task reached running, the wait_for asks whether the service answers - but ordering the cheap service-level check first means a partner that is not deployed at all fails after one budget instead of two. The resolver itself needs no HTTP: it only runs container service ps / container ps and set_fact. Not executed: that lookup('domain', 'web-app-zammad') resolves to a name answering on port 80 is taken from the openproject twin, not measured. Co-Authored-By: Claude Opus 5 (1M context) --- .../tasks/addons/integration_zammad_provision.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml b/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml index 4650e11caa..9fdd4e4d63 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_zammad_provision.yml @@ -9,6 +9,13 @@ resolve_converge_retries: 120 resolve_converge_delay: 5 +- name: ⏳ Wait for the Zammad web endpoint + wait_for: + host: "{{ lookup('domain', 'web-app-zammad') }}" + port: 80 + delay: 5 + timeout: "{{ lookup('timeout', 600) | int }}" + - name: 🔧 Provision the Zammad OAuth application for Nextcloud and capture credentials ansible.builtin.shell: cmd: >- From ee12b412e05debbea4c8559ecd2cd593c92a34b0 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 16:50:16 +0200 Subject: [PATCH 19/31] refactor(nextcloud): resolve OpenProject before waiting on its endpoint Both waits are needed and check different things: wait_converged inside resolve_host_cid asks swarm whether the task reached running, the wait_for asks whether the service answers. Running the endpoint wait first meant a partner that is not deployed at all paid both budgets in sequence - up to 600s of HTTP timeout followed by 120x5s of convergence - before the play gave up. Ordering the cheap service-level check first halves that without giving up either guarantee. The resolver needs no HTTP: it runs container service ps, container ps and set_fact, and its two outputs are first consumed by the rails call further down, i.e. after both waits. Task order only; nothing added, removed or reparameterised. 8b2cbcb04 applies the same ordering to the Zammad twin, where the wait was newly introduced. Co-Authored-By: Claude Opus 5 (1M context) --- .../addons/integration_openproject_provision.yml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/roles/web-app-nextcloud/tasks/addons/integration_openproject_provision.yml b/roles/web-app-nextcloud/tasks/addons/integration_openproject_provision.yml index fbd11d6650..87a97e39df 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_openproject_provision.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_openproject_provision.yml @@ -1,11 +1,4 @@ --- -- name: ⏳ Wait for the OpenProject web endpoint - wait_for: - host: "{{ lookup('domain', 'web-app-openproject') }}" - port: 80 - delay: 5 - timeout: "{{ lookup('timeout', 600) | int }}" - - name: "🔍 Resolve the OpenProject web hosting node and container id" ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" vars: @@ -16,6 +9,13 @@ resolve_converge_retries: 120 resolve_converge_delay: 5 +- name: ⏳ Wait for the OpenProject web endpoint + wait_for: + host: "{{ lookup('domain', 'web-app-openproject') }}" + port: 80 + delay: 5 + timeout: "{{ lookup('timeout', 600) | int }}" + - name: 📁 Create the Nextcloud storage + OpenProject OAuth application ansible.builtin.shell: cmd: >- # nocheck: container-exec-resolver NEXTCLOUD_OPENPROJECT_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell From bbb35c7bcef1c2dfbb02970bf6350cbc613dc45f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 17:02:26 +0200 Subject: [PATCH 20/31] fix(openresty): dump the debug logs from a manager The MODE_DEBUG block of the restart handler carries no host gate, unlike its two siblings in the same file which are pinned to a deployment mode and, in swarm, to IS_STACK_HOST. A handler runs on the host that notified it, and a worker reaches this notify: sys-stk-front-proxy/tasks/main.yml:112-118 is an always-changed `command: true` whose only guard is `not nginx_conf.changed`, and the stack-host template action forces changed:False on workers, so the guard is always satisfied there. On a worker the container_address subshell then exits 64 - resolve-container-id refuses to run off a manager - the substitution collapses to empty, `container logs --tail=200` fails, and failed_when:false plus ignore_errors:true swallow it. The debug task below prints an empty string, so the diagnostic reports "no logs" on exactly the node someone enabled MODE_DEBUG to inspect. container_address returns a string to embed, not a delegation; it decides what is addressed, not from where. delegate_to supplies the second half. STACK_HOST rather than the resolve_host_cid include, because svc-prx-openresty declares placement: manager (meta/services.yml:9), so the task can only run on a manager and the full host resolution buys nothing. In compose STACK_HOST is inventory_hostname, so this is a no-op there. The sibling `container ps -a` stays undelegated: a per-node container listing is legitimately node-local. Diagnostics only - nothing gates on openresty_logs, and MODE_DEBUG defaults to false. Not executed: no swarm worker run reproduces the empty dump. Co-Authored-By: Claude Opus 5 (1M context) --- roles/svc-prx-openresty/handlers/restart_and_validate.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/roles/svc-prx-openresty/handlers/restart_and_validate.yml b/roles/svc-prx-openresty/handlers/restart_and_validate.yml index cc93fa7565..a101164285 100644 --- a/roles/svc-prx-openresty/handlers/restart_and_validate.yml +++ b/roles/svc-prx-openresty/handlers/restart_and_validate.yml @@ -62,6 +62,7 @@ changed_when: false failed_when: false ignore_errors: true + delegate_to: "{{ STACK_HOST }}" - ansible.builtin.debug: msg: | From b7c28e5b5c72a48ea9b235d6102aa020833cca4e Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 17:14:14 +0200 Subject: [PATCH 21/31] feat(ci): warn when a job applied the requested filesystem nowhere A job whose nodes all declined the filesystem tested none of it, and the table row saying so reads like an ordinary result. That is how the debian arm lost its zfs coverage without anyone noticing: docker_dataroot.sh exists to exercise the snapshot mode of svc-bkp-volume-2-local, which engages only on btrfs and zfs, and on that arm it has been engaging on neither. The summary now carries an explicit warning when no node applied the requested filesystem and at least one declined it. Partial coverage is coverage and stays unflagged; a job with no verdicts at all still exits early. Deliberately a finding, not a failure. Stating a filesystem instead of `auto` would set REQUIRED=true in resolve.sh and turn a decline into a hard error, but that would paint the debian arm red for a cause that is understood and not yet fixed - the node image has no zfsutils candidate without the package cache. The goal was never to enforce the pick, only to stop losing it silently. Exercised against three real job logs from run 30781723102: the debian arm (5 nodes, all declined) produces the warning; the ubuntu arm (10 nodes, zfs applied) and an ext4 job do not. Co-Authored-By: Claude Opus 5 (1M context) --- scripts/tests/deploy/utils/filesystem/report.sh | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/scripts/tests/deploy/utils/filesystem/report.sh b/scripts/tests/deploy/utils/filesystem/report.sh index e573d94a39..292bee42bd 100755 --- a/scripts/tests/deploy/utils/filesystem/report.sh +++ b/scripts/tests/deploy/utils/filesystem/report.sh @@ -20,6 +20,13 @@ fi REASONS="$(grep -ohE "${REASON_PATTERN}" "${LOG}" | sed -E 's/.* reason=//' | tr '|' '/' | sort -u)" || REASONS="" +APPLIED="$(printf '%s\n' "${VERDICTS}" | grep -c 'status=applied')" || APPLIED=0 +DECLINED="$(printf '%s\n' "${VERDICTS}" | grep -c 'status=declined')" || DECLINED=0 +LOST="" +if [ "${APPLIED}" -eq 0 ] && [ "${DECLINED}" -gt 0 ]; then + LOST="$(printf '%s\n' "${VERDICTS}" | sed -E 's/.*requested=([a-z0-9]+).*/\1/' | sort -u | paste -sd' ')" +fi + { echo "#### Docker data root, as actually used" echo @@ -29,5 +36,7 @@ REASONS="$(grep -ohE "${REASON_PATTERN}" "${LOG}" | sed -E 's/.* reason=//' | tr echo "${VERDICTS}" | sed -E \ 's/^ *([0-9]+) status=([a-z-]+) requested=([a-z0-9]+) effective=(.+)$/| \1 | `\4` | `\3` | \2 |/' echo + # shellcheck disable=SC2016 + [ -z "${LOST}" ] || printf '> [!WARNING]\n> No node applied `%s`; this job exercised none of it.\n\n' "${LOST}" [ -z "${REASONS}" ] || printf '%s\n\n' "$(echo "${REASONS}" | sed -E 's/^/- /')" } >>"${GITHUB_STEP_SUMMARY}" From afff6b3787c18ce252e4f1a30b4bdeeec3c52381 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 17:28:51 +0200 Subject: [PATCH 22/31] fix(swarm): bake the zfs userland into the apt node image docker_dataroot.sh installs zfsutils-linux at runtime, so the zfs pick depends on the package cache being up. In run 30781723102 that decided the two swarm drills differently: the cache stack was removed at 06:39:49 and rebuilt at 07:18:25, so the mariadb drill had no zfsutils candidate at all and declined, while the postgres drill got one and reached zpool create. Installing it at build time removes that dependency. Debian keeps zfsutils-linux in contrib, which the base image does not enable, so the branch adds a contrib source first - only for ID=debian, since Ubuntu ships it in its default components. A failed update after adding the source removes the source again rather than leaving a broken repo line behind. The install is deliberately separate from the mandatory packages and non-fatal. Node images for centos, fedora and arch have no zfs userland either and resolve.sh's userland_for() already accounts for that, so a missing zfs userland is a supported state - whereas folding it into the mandatory install would let a packaging error break the node image for all five distros. A failure now prints to stderr and the run declines the pick visibly. Verified against the real bookworm contrib index (deb.debian.org, HTTP 200): zfsutils-linux 2.1.11-1+deb12u1 exists there, all four libzfs libraries are Depends rather than Recommends so --no-install-recommends keeps them, and the only Recommends are zfs-modules|zfs-dkms and zfs-zed, which we do not want - the module comes from the host via /lib/modules. Control flow exercised with a stubbed apt-get across six combinations of distro, package availability and update failure; every one leaves the build at rc 0. Not covered here: whether a 2.1 userland can drive the runner's newer host module. zfs-version.txt and modules.txt from 264556a31 answer that next run. Co-Authored-By: Claude Opus 5 (1M context) --- compose/swarm/Dockerfile | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/compose/swarm/Dockerfile b/compose/swarm/Dockerfile index af77cf690f..492e19289b 100644 --- a/compose/swarm/Dockerfile +++ b/compose/swarm/Dockerfile @@ -24,6 +24,13 @@ RUN set -eux; \ if command -v apt-get >/dev/null 2>&1; then \ apt-get update -qq; \ apt-get install -y -qq --no-install-recommends dnsmasq openssh-server cryptsetup e2fsprogs elfutils kmod; \ + . /etc/os-release; \ + if [ "${ID:-}" = debian ] && [ -n "${VERSION_CODENAME:-}" ]; then \ + echo "deb http://deb.debian.org/debian ${VERSION_CODENAME} contrib" >/etc/apt/sources.list.d/contrib.list; \ + apt-get update -qq || rm -f /etc/apt/sources.list.d/contrib.list; \ + fi; \ + apt-get install -y -qq --no-install-recommends zfsutils-linux || \ + echo "zfsutils-linux unavailable; a zfs data-root pick will decline on this image" >&2; \ rm -rf /var/lib/apt/lists/*; \ elif command -v dnf >/dev/null 2>&1; then \ dnf install -y dnsmasq openssh-server cryptsetup e2fsprogs elfutils kmod; \ From 25372b24fafaa0054193885d478b56acc2c465e8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 17:40:39 +0200 Subject: [PATCH 23/31] fix(mariadb): do not read a missing container as a wrong root password The login probe concludes "login failed, so the password is wrong" and hands over to 02_reset_root_password.yml, which stops the container, scales the swarm service to 0, boots a recovery server with --skip-grant-tables, rewrites the root password and scales back. That is a full teardown of the central database, so what triggers it has to be right. container exec also fails when the container is not on this node. The probe delegates to STACK_HOST, and resolve_container_id.sh tries a local lookup first but otherwise falls back to `container service ps` + `container inspect --type=task`, which returns the container id of a task on ANY node and exits 0. On a manager that does not host the task, container exec then answers "No such container". Two amplifiers turn that into a silent misdiagnosis: failed_when: false, and - verified by execution, since the opposite was claimed - retry exhaustion under until: does NOT abort a task carrying failed_when: false. The task stays ok, `failed: True` only appears in the result, and the gate fires. The clause excludes exactly that case. mariadb never prints "No such container" for a bad password, so no legitimate trigger is lost, and the exec failure stays as visible as it was. Not reachable today: the swarm topology has one manager and svc-db-mariadb declares placement: manager, so the local branch of the resolver always matches. It becomes reachable with two or more managers, which the comment on that placement line names as planned. Co-Authored-By: Claude Opus 5 (1M context) --- roles/svc-db-mariadb/tasks/00_core.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/roles/svc-db-mariadb/tasks/00_core.yml b/roles/svc-db-mariadb/tasks/00_core.yml index fda61d50ba..a986f0e93b 100644 --- a/roles/svc-db-mariadb/tasks/00_core.yml +++ b/roles/svc-db-mariadb/tasks/00_core.yml @@ -49,6 +49,7 @@ include_tasks: 02_reset_root_password.yml when: - mariadb_login_desired.rc != 0 + - "'No such container' not in (mariadb_login_desired.stderr | default(''))" when: MARIADB_ALLOW_RESET_WITHOUT_PREVIOUS | bool From 3ea77004c2e412aaa16a0213dc654c4a58295fd8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 18:00:24 +0200 Subject: [PATCH 24/31] style(lint): reflow the async gate assertion message autoformat joined the two operands of the message concatenation during make quality; 1408c6770 had them on separate lines. Formatting only, same expression and same output. Co-Authored-By: Claude Opus 5 (1M context) --- tests/lint/ansible/roles/test_async_reason_documented.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/lint/ansible/roles/test_async_reason_documented.py b/tests/lint/ansible/roles/test_async_reason_documented.py index ce96fc6759..6489d193b3 100644 --- a/tests/lint/ansible/roles/test_async_reason_documented.py +++ b/tests/lint/ansible/roles/test_async_reason_documented.py @@ -157,8 +157,7 @@ class TestAsyncReasonDocumented(unittest.TestCase): "ansible's built-in 15s poll, which collects the job and then runs " "async_status mode=cleanup - deleting the job file a later reap " "still expects to read, so a successful command reports as a " - "failed async job.\n" - + "\n".join(f" {o}" for o in offenders), + "failed async job.\n" + "\n".join(f" {o}" for o in offenders), ) From f3b478b79c29d7cf47af4ec527002ac894733860 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 20:24:19 +0200 Subject: [PATCH 25/31] refactor(networks): assemble the lookup context in one place compose_networks, container_networks and compose_external_networks each rebuilt the same Ansible-side context before calling their renderer: resolve the variables, settle the deployment mode, load applications, build the service registry, and close over the config and database lookups. Around forty lines, three times, each with its own copy of _resolve_var. A change to how the registry or the closures are obtained could reach one lookup and miss another. build_context() returns that context once. honour_mode_force carries the only real difference between the callers: compose_external_networks never consulted compose_mode_force, and still does not. The lookups keep only what is theirs - term validation, their own arguments, their renderer call - and drop from 94/90/87 lines to 59/54/53. No assertion changed in the tests; only the mock targets moved with the seam, from the plugin modules to utils.networks.lookup_context. Twelve legacy comments in those test files lost their grandfathering when the files entered the lint's diff scope: two became docstrings naming the call contract, the rest were narration and are gone. Behaviour-preserving: the same 13 lookup tests pass before and after. Co-Authored-By: Claude Opus 5 (1M context) --- plugins/lookup/compose_external_networks.py | 58 +++-------- plugins/lookup/compose_networks.py | 69 ++++--------- plugins/lookup/container_networks.py | 78 ++++----------- .../lookup/test_compose_external_networks.py | 4 +- .../plugins/lookup/test_compose_networks.py | 21 ++-- .../plugins/lookup/test_container_networks.py | 19 ++-- utils/networks/lookup_context.py | 98 +++++++++++++++++++ 7 files changed, 166 insertions(+), 181 deletions(-) create mode 100644 utils/networks/lookup_context.py diff --git a/plugins/lookup/compose_external_networks.py b/plugins/lookup/compose_external_networks.py index fc4302113c..cbf57f14d0 100644 --- a/plugins/lookup/compose_external_networks.py +++ b/plugins/lookup/compose_external_networks.py @@ -13,25 +13,13 @@ even when the provider role did not run in the same play. from __future__ import annotations -import contextlib from typing import Any from ansible.errors import AnsibleError -from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from utils.networks.lookup_context import build_context, resolve_var from utils.networks.render import compute_external_network_roles -from utils.roles.applications.services.registry import ( - build_service_registry_from_applications, -) - - -def _resolve_var(templar, value: Any) -> Any: - if templar is None: - return value - with contextlib.suppress(Exception): - return templar.template(value) - return value class LookupModule(LookupBase): @@ -46,42 +34,20 @@ class LookupModule(LookupBase): "compose_external_networks lookup takes no positional terms" ) - vars_ = variables or getattr(self._templar, "available_variables", {}) or {} - templar = getattr(self, "_templar", None) + ctx = build_context(self, variables, honour_mode_force=False) - application_id = _resolve_var(templar, vars_.get("application_id")) + application_id = resolve_var(ctx.templar, ctx.vars.get("application_id")) if not application_id: raise AnsibleError( "compose_external_networks lookup: application_id is required in variables" ) - deployment_mode = str( - _resolve_var(templar, vars_.get("DEPLOYMENT_MODE", "compose")) - ) - - applications = lookup_loader.get( - "applications", loader=self._loader, templar=getattr(self, "_templar", None) - ).run([], variables=vars_)[0] - registry = build_service_registry_from_applications(applications) - - config_lookup = lookup_loader.get( - "config", loader=self._loader, templar=templar - ) - database_lookup = lookup_loader.get( - "database", loader=self._loader, templar=templar - ) - - def _lookup_config(app: str, path: str, default: Any) -> Any: - return config_lookup.run([app, path, default], variables=vars_)[0] - - def _lookup_database(app: str, key: str) -> Any: - return database_lookup.run([app, key], variables=vars_)[0] - - roles = compute_external_network_roles( - application_id=str(application_id), - deployment_mode=deployment_mode, - registry=registry, - lookup_config=_lookup_config, - lookup_database=_lookup_database, - ) - return [roles] + return [ + compute_external_network_roles( + application_id=str(application_id), + deployment_mode=ctx.deployment_mode, + registry=ctx.registry, + lookup_config=ctx.lookup_config, + lookup_database=ctx.lookup_database, + ) + ] diff --git a/plugins/lookup/compose_networks.py b/plugins/lookup/compose_networks.py index 31f285da14..8a67620e33 100644 --- a/plugins/lookup/compose_networks.py +++ b/plugins/lookup/compose_networks.py @@ -11,28 +11,16 @@ The output starts at column 0 (no caller-side indent). from __future__ import annotations -import contextlib from typing import Any from ansible.errors import AnsibleError -from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from utils.networks.lookup_context import build_context, resolve_var from utils.networks.render import render_compose_networks -from utils.roles.applications.services.registry import ( - build_service_registry_from_applications, -) from utils.roles.entity.name import get_entity_name -def _resolve_var(templar, value: Any) -> Any: - if templar is None: - return value - with contextlib.suppress(Exception): - return templar.template(value) - return value - - class LookupModule(LookupBase): def run( self, @@ -43,52 +31,29 @@ class LookupModule(LookupBase): if terms: raise AnsibleError("compose_networks lookup takes no positional terms") - vars_ = variables or getattr(self._templar, "available_variables", {}) or {} - templar = getattr(self, "_templar", None) + ctx = build_context(self, variables) - application_id = _resolve_var(templar, vars_.get("application_id")) + application_id = resolve_var(ctx.templar, ctx.vars.get("application_id")) if not application_id: raise AnsibleError( "compose_networks lookup: application_id is required in variables" ) - mode_force = _resolve_var(templar, vars_.get("compose_mode_force", "")) - deployment_mode = str( - mode_force or _resolve_var(templar, vars_.get("DEPLOYMENT_MODE", "compose")) - ).strip() - - swarm_cfg = _resolve_var(templar, vars_.get("swarm", {})) or {} - swarm_encrypted = True + swarm_cfg = resolve_var(ctx.templar, ctx.vars.get("swarm", {})) or {} net_cfg = swarm_cfg.get("network", {}) if isinstance(swarm_cfg, dict) else {} + swarm_encrypted = True if isinstance(net_cfg, dict) and "encryption" in net_cfg: swarm_encrypted = bool(net_cfg.get("encryption")) - applications = lookup_loader.get( - "applications", loader=self._loader, templar=getattr(self, "_templar", None) - ).run([], variables=vars_)[0] - registry = build_service_registry_from_applications(applications) - - config_lookup = lookup_loader.get( - "config", loader=self._loader, templar=templar - ) - database_lookup = lookup_loader.get( - "database", loader=self._loader, templar=templar - ) - - def _lookup_config(app: str, path: str, default: Any) -> Any: - return config_lookup.run([app, path, default], variables=vars_)[0] - - def _lookup_database(app: str, key: str) -> Any: - return database_lookup.run([app, key], variables=vars_)[0] - - rendered = render_compose_networks( - application_id=str(application_id), - deployment_mode=deployment_mode, - registry=registry, - get_entity_name=get_entity_name, - lookup_config=_lookup_config, - lookup_database=_lookup_database, - swarm_encrypted=swarm_encrypted, - node_local=bool(kwargs.get("node_local", False)), - ) - return [rendered] + return [ + render_compose_networks( + application_id=str(application_id), + deployment_mode=ctx.deployment_mode, + registry=ctx.registry, + get_entity_name=get_entity_name, + lookup_config=ctx.lookup_config, + lookup_database=ctx.lookup_database, + swarm_encrypted=swarm_encrypted, + node_local=bool(kwargs.get("node_local", False)), + ) + ] diff --git a/plugins/lookup/container_networks.py b/plugins/lookup/container_networks.py index 95e064fe06..b6cf120a6f 100644 --- a/plugins/lookup/container_networks.py +++ b/plugins/lookup/container_networks.py @@ -1,39 +1,27 @@ -"""Lookup ``container_networks``: emit the per-service ``networks:`` -attachment block. Reads the service_registry plus ``application_id`` and +"""Lookup ``container_networks``: emit the per-service ``networks:`` attachment +block. Reads the service_registry, the rendering role's ``application_id`` and ``DEPLOYMENT_MODE`` from variables. -Usage inside a service block in ``compose.yml.j2``: +Usage in any service template: - {{ lookup('container_networks') }} + {{ lookup('container_networks') | indent(4) }} -The output is pre-indented by 4 spaces so it sits cleanly under a -``services.`` block. +Pass ``provider_self_alias=False`` for a sidecar service that must not carry the +provider's own alias. """ from __future__ import annotations -import contextlib from typing import Any from ansible.errors import AnsibleError -from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from utils.networks.lookup_context import build_context, resolve_var from utils.networks.render import render_container_networks -from utils.roles.applications.services.registry import ( - build_service_registry_from_applications, -) from utils.roles.entity.name import get_entity_name -def _resolve_var(templar, value: Any) -> Any: - if templar is None: - return value - with contextlib.suppress(Exception): - return templar.template(value) - return value - - class LookupModule(LookupBase): def run( self, @@ -44,47 +32,23 @@ class LookupModule(LookupBase): if terms: raise AnsibleError("container_networks lookup takes no positional terms") - vars_ = variables or getattr(self._templar, "available_variables", {}) or {} - templar = getattr(self, "_templar", None) + ctx = build_context(self, variables) - application_id = _resolve_var(templar, vars_.get("application_id")) + application_id = resolve_var(ctx.templar, ctx.vars.get("application_id")) if not application_id: raise AnsibleError( "container_networks lookup: application_id is required in variables" ) - mode_force = _resolve_var(templar, vars_.get("compose_mode_force", "")) - deployment_mode = str( - mode_force or _resolve_var(templar, vars_.get("DEPLOYMENT_MODE", "compose")) - ).strip() - provider_self_alias = bool(kwargs.get("provider_self_alias", True)) - - applications = lookup_loader.get( - "applications", loader=self._loader, templar=getattr(self, "_templar", None) - ).run([], variables=vars_)[0] - registry = build_service_registry_from_applications(applications) - - config_lookup = lookup_loader.get( - "config", loader=self._loader, templar=templar - ) - database_lookup = lookup_loader.get( - "database", loader=self._loader, templar=templar - ) - - def _lookup_config(app: str, path: str, default: Any) -> Any: - return config_lookup.run([app, path, default], variables=vars_)[0] - - def _lookup_database(app: str, key: str) -> Any: - return database_lookup.run([app, key], variables=vars_)[0] - - rendered = render_container_networks( - application_id=str(application_id), - deployment_mode=deployment_mode, - registry=registry, - get_entity_name=get_entity_name, - lookup_config=_lookup_config, - lookup_database=_lookup_database, - provider_self_alias=provider_self_alias, - node_local=bool(kwargs.get("node_local", False)), - ) - return [rendered] + return [ + render_container_networks( + application_id=str(application_id), + deployment_mode=ctx.deployment_mode, + registry=ctx.registry, + get_entity_name=get_entity_name, + lookup_config=ctx.lookup_config, + lookup_database=ctx.lookup_database, + provider_self_alias=bool(kwargs.get("provider_self_alias", True)), + node_local=bool(kwargs.get("node_local", False)), + ) + ] diff --git a/tests/unit/plugins/lookup/test_compose_external_networks.py b/tests/unit/plugins/lookup/test_compose_external_networks.py index e554d5412e..0894a8cc9e 100644 --- a/tests/unit/plugins/lookup/test_compose_external_networks.py +++ b/tests/unit/plugins/lookup/test_compose_external_networks.py @@ -47,11 +47,11 @@ class TestComposeExternalNetworksLookup(unittest.TestCase): with ( mock.patch( - "plugins.lookup.compose_external_networks.build_service_registry_from_applications", + "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), mock.patch( - "plugins.lookup.compose_external_networks.lookup_loader" + "utils.networks.lookup_context.lookup_loader" ) as loader_mock, mock.patch( "plugins.lookup.compose_external_networks.compute_external_network_roles", diff --git a/tests/unit/plugins/lookup/test_compose_networks.py b/tests/unit/plugins/lookup/test_compose_networks.py index 421f3b336c..438fb62ca5 100644 --- a/tests/unit/plugins/lookup/test_compose_networks.py +++ b/tests/unit/plugins/lookup/test_compose_networks.py @@ -55,10 +55,10 @@ class TestComposeNetworksLookup(unittest.TestCase): with ( mock.patch( - "plugins.lookup.compose_networks.build_service_registry_from_applications", + "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), - mock.patch("plugins.lookup.compose_networks.lookup_loader") as loader_mock, + mock.patch("utils.networks.lookup_context.lookup_loader") as loader_mock, mock.patch( "plugins.lookup.compose_networks.render_compose_networks", return_value="RENDERED", @@ -72,7 +72,6 @@ class TestComposeNetworksLookup(unittest.TestCase): kwargs = render_mock.call_args.kwargs self.assertEqual(kwargs["application_id"], "web-app-baserow") self.assertEqual(kwargs["deployment_mode"], "swarm") - # swarm.network.encryption: False is honoured self.assertFalse(kwargs["swarm_encrypted"]) def test_swarm_encrypted_defaults_to_true_when_unset(self): @@ -84,10 +83,10 @@ class TestComposeNetworksLookup(unittest.TestCase): with ( mock.patch( - "plugins.lookup.compose_networks.build_service_registry_from_applications", + "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), - mock.patch("plugins.lookup.compose_networks.lookup_loader") as loader_mock, + mock.patch("utils.networks.lookup_context.lookup_loader") as loader_mock, mock.patch( "plugins.lookup.compose_networks.render_compose_networks", return_value="RENDERED", @@ -99,11 +98,8 @@ class TestComposeNetworksLookup(unittest.TestCase): self.assertTrue(render_mock.call_args.kwargs["swarm_encrypted"]) def test_lookup_closures_pass_arguments_in_expected_order(self): - # Pin the call shape of the closures that the plugin synthesises: - # config_lookup.run([app, path, default], variables=vars_) - # database_lookup.run([app, key], variables=vars_) - # A regression that swaps app/path or drops the variables kwarg would - # break at runtime but stay green with naive MagicMock stubs. + """config_lookup.run([app, path, default]) and + database_lookup.run([app, key]), both with variables=vars_.""" vars_ = { "application_id": "web-app-x", "DEPLOYMENT_MODE": "swarm", @@ -122,17 +118,16 @@ class TestComposeNetworksLookup(unittest.TestCase): return [""] def _exercise(*_, lookup_config, lookup_database, **__): - # Render-side calls the closures; pretend it does so with known args. lookup_config("web-app-x", "services.sso.enabled", False) lookup_database("web-app-x", "id") return "RENDERED" with ( mock.patch( - "plugins.lookup.compose_networks.build_service_registry_from_applications", + "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), - mock.patch("plugins.lookup.compose_networks.lookup_loader") as loader_mock, + mock.patch("utils.networks.lookup_context.lookup_loader") as loader_mock, mock.patch( "plugins.lookup.compose_networks.render_compose_networks", side_effect=_exercise, diff --git a/tests/unit/plugins/lookup/test_container_networks.py b/tests/unit/plugins/lookup/test_container_networks.py index 75e9d52b98..5e2cbaa75e 100644 --- a/tests/unit/plugins/lookup/test_container_networks.py +++ b/tests/unit/plugins/lookup/test_container_networks.py @@ -51,11 +51,11 @@ class TestContainerNetworksLookup(unittest.TestCase): with ( mock.patch( - "plugins.lookup.container_networks.build_service_registry_from_applications", + "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), mock.patch( - "plugins.lookup.container_networks.lookup_loader" + "utils.networks.lookup_context.lookup_loader" ) as loader_mock, mock.patch( "plugins.lookup.container_networks.render_container_networks", @@ -77,11 +77,11 @@ class TestContainerNetworksLookup(unittest.TestCase): with ( mock.patch( - "plugins.lookup.container_networks.build_service_registry_from_applications", + "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), mock.patch( - "plugins.lookup.container_networks.lookup_loader" + "utils.networks.lookup_context.lookup_loader" ) as loader_mock, mock.patch( "plugins.lookup.container_networks.render_container_networks", @@ -94,11 +94,8 @@ class TestContainerNetworksLookup(unittest.TestCase): self.assertEqual(render_mock.call_args.kwargs["deployment_mode"], "compose") def test_lookup_closures_pass_arguments_in_expected_order(self): - # Pin the call shape of the closures that the plugin synthesises: - # config_lookup.run([app, path, default], variables=vars_) - # database_lookup.run([app, key], variables=vars_) - # A regression that swaps app/path or drops the variables kwarg would - # break at runtime but stay green with naive MagicMock stubs. + """config_lookup.run([app, path, default]) and + database_lookup.run([app, key]), both with variables=vars_.""" vars_ = { "application_id": "web-app-x", "DEPLOYMENT_MODE": "swarm", @@ -123,11 +120,11 @@ class TestContainerNetworksLookup(unittest.TestCase): with ( mock.patch( - "plugins.lookup.container_networks.build_service_registry_from_applications", + "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), mock.patch( - "plugins.lookup.container_networks.lookup_loader" + "utils.networks.lookup_context.lookup_loader" ) as loader_mock, mock.patch( "plugins.lookup.container_networks.render_container_networks", diff --git a/utils/networks/lookup_context.py b/utils/networks/lookup_context.py new file mode 100644 index 0000000000..910eaa35e4 --- /dev/null +++ b/utils/networks/lookup_context.py @@ -0,0 +1,98 @@ +"""Shared Ansible-side assembly for the network lookup plugins. + +Every one of them needs the same four things before it can call into +:mod:`utils.networks.render`: the resolved variables, the deployment mode, a +service registry built from the merged applications, and closures over the +``config`` and ``database`` lookups. Building that once means a change to how +the registry or the closures are obtained cannot reach one lookup and miss +another. + +Args of :func:`build_context` are documented on the function. +""" + +from __future__ import annotations + +import contextlib +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from ansible.plugins.loader import lookup_loader + +from utils.roles.applications.services.registry import ( + build_service_registry_from_applications, +) + +if TYPE_CHECKING: + from collections.abc import Callable + + +def resolve_var(templar: Any, value: Any) -> Any: + """Template ``value`` when a templar is available, else pass it through. + + Args: + templar: the plugin's templar, or None. + value: raw variable value. + """ + if templar is None: + return value + with contextlib.suppress(Exception): + return templar.template(value) + return value + + +@dataclass(frozen=True) +class NetworkLookupContext: + """What a network lookup needs to call the renderers.""" + + vars: dict[str, Any] + templar: Any + deployment_mode: str + registry: dict[str, dict[str, Any]] + lookup_config: Callable[[str, str, Any], Any] + lookup_database: Callable[[str, str], Any] + + +def build_context( + lookup: Any, + variables: dict[str, Any] | None, + *, + honour_mode_force: bool = True, +) -> NetworkLookupContext: + """Assemble the shared context for a network lookup. + + Args: + lookup: the LookupModule instance, for its templar and loader. + variables: the variables Ansible passed to ``run``. + honour_mode_force: let ``compose_mode_force`` override DEPLOYMENT_MODE. + """ + templar = getattr(lookup, "_templar", None) + vars_ = variables or getattr(templar, "available_variables", {}) or {} + + deployment_mode = str(resolve_var(templar, vars_.get("DEPLOYMENT_MODE", "compose"))) + if honour_mode_force: + mode_force = resolve_var(templar, vars_.get("compose_mode_force", "")) + deployment_mode = str(mode_force or deployment_mode).strip() + + applications = lookup_loader.get( + "applications", loader=lookup._loader, templar=templar + ).run([], variables=vars_)[0] + + config_lookup = lookup_loader.get("config", loader=lookup._loader, templar=templar) + database_lookup = lookup_loader.get( + "database", loader=lookup._loader, templar=templar + ) + + def _lookup_config(app: str, path: str, default: Any) -> Any: + return config_lookup.run([app, path, default], variables=vars_)[0] + + def _lookup_database(app: str, key: str) -> Any: + return database_lookup.run([app, key], variables=vars_)[0] + + return NetworkLookupContext( + vars=vars_, + templar=templar, + deployment_mode=deployment_mode, + registry=build_service_registry_from_applications(applications), + lookup_config=_lookup_config, + lookup_database=_lookup_database, + ) From 8df0ad4f5d1628ed83221c14febe97a09558a640 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 20:25:23 +0200 Subject: [PATCH 26/31] fix(compose): derive the network label from the renderer Two places decided independently what the pre-created network is called inside the compose project. render.py emits the key; create.yml asserted it was always `default`. They diverged in July and nobody noticed, because compose 5.3.1 resolved networks by name and never read the claim. Compose 5.4.0, published 2026-08-03T14:39:12Z, resolves them by label. For web-app-seaweedfs - the one deployed role that provides its own shared_net and therefore renders an unnamed `default` - the mislabelled `seaweedfs` network is adopted as the project default, `seaweedfs_default` is never created, and the containers fail to start against it. That failed web-app-nextcloud 0 and 3 in run 30830377785. _shared_network_key() is now the single derivation. render_compose_networks takes its branch from it, so the rendering decision IS the key decision; shared_network_compose_key() exports the same value, the shared_network_key lookup hands it to Ansible, and create.yml stamps it: `seaweedfs` for a self-provider, `default` for everyone else. Both true, both from the source that renders the file. Verified on one host with only the compose binary swapped: 5.4.0 network=default -> FAIL, network _default not found 5.4.0 network= -> OK 5.3.1 network=default -> OK 5.3.1 network= -> OK so this is not a fix that trades one version for the other. test_key_matches_the_key_the_renderer_emits renders the block and asserts the reported key appears in it, for both role shapes and both modes. The drift that sat unnoticed for a month now breaks a test. The move of the attachment computation into utils/networks/attachments.py rides along because render.py would otherwise be broken between two commits: it is a pure relocation, re-exported so no importer changes, and it brings the file from 352 to 243 lines. Co-Authored-By: Claude Opus 5 (1M context) --- plugins/lookup/shared_network_key.py | 60 ++++++ .../tasks/utils/network/create.yml | 4 +- .../plugins/lookup/test_shared_network_key.py | 114 +++++++++++ tests/unit/utils/networks/test_render.py | 87 ++++++++ utils/networks/attachments.py | 142 +++++++++++++ utils/networks/render.py | 188 ++++++------------ 6 files changed, 468 insertions(+), 127 deletions(-) create mode 100644 plugins/lookup/shared_network_key.py create mode 100644 tests/unit/plugins/lookup/test_shared_network_key.py create mode 100644 utils/networks/attachments.py diff --git a/plugins/lookup/shared_network_key.py b/plugins/lookup/shared_network_key.py new file mode 100644 index 0000000000..e4d98602aa --- /dev/null +++ b/plugins/lookup/shared_network_key.py @@ -0,0 +1,60 @@ +"""Lookup `shared_network_key`: the compose networks key of the pre-created +```` network of a role. + +Docker compose stores that key in the ``com.docker.compose.network`` label of +every network it owns, so a caller pre-creating the network out of band has to +stamp the same value or compose will resolve the project's networks against a +claim the rendered file does not make. The key is derived from +``utils.networks.render``, which renders the file itself, so the two cannot +drift. + +Examples: + + - name: create the shared network + ansible.builtin.command: + argv: + - container + - network + - create + - --label + - "com.docker.compose.network={{ lookup('shared_network_key', role_id) }}" +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from utils.networks.lookup_context import build_context, resolve_var +from utils.networks.render import shared_network_compose_key +from utils.roles.entity.name import get_entity_name + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[str]: + if not terms or len(terms) != 1: + raise AnsibleError( + "shared_network_key lookup requires exactly one term: application_id" + ) + + ctx = build_context(self, variables) + application_id = str(resolve_var(ctx.templar, terms[0])) + + return [ + shared_network_compose_key( + application_id=application_id, + deployment_mode=ctx.deployment_mode, + registry=ctx.registry, + get_entity_name=get_entity_name, + lookup_config=ctx.lookup_config, + lookup_database=ctx.lookup_database, + node_local=bool(kwargs.get("node_local", False)), + ) + ] diff --git a/roles/sys-svc-compose/tasks/utils/network/create.yml b/roles/sys-svc-compose/tasks/utils/network/create.yml index 185feb05dd..75d80f9235 100644 --- a/roles/sys-svc-compose/tasks/utils/network/create.yml +++ b/roles/sys-svc-compose/tasks/utils/network/create.yml @@ -36,7 +36,7 @@ - --subnet - "{{ lookup('config', network_role_id, 'networks.local.subnet') }}" - --label - - com.docker.compose.network=default + - "com.docker.compose.network={{ lookup('shared_network_key', network_role_id) }}" - --label - "com.docker.compose.project={{ network_role_id | get_entity_name }}" - "{{ network_role_id | get_entity_name }}" @@ -73,7 +73,7 @@ - --subnet - "{{ lookup('config', network_role_id, 'networks.local.subnet') }}" - --label - - com.docker.compose.network=default + - "com.docker.compose.network={{ lookup('shared_network_key', network_role_id) }}" - --label - "com.docker.compose.project={{ network_role_id | get_entity_name }}" - "{{ network_role_id | get_entity_name }}" diff --git a/tests/unit/plugins/lookup/test_shared_network_key.py b/tests/unit/plugins/lookup/test_shared_network_key.py new file mode 100644 index 0000000000..1ee755dd1c --- /dev/null +++ b/tests/unit/plugins/lookup/test_shared_network_key.py @@ -0,0 +1,114 @@ +"""Unit tests for plugins/lookup/shared_network_key.py. + +Mocks the Ansible-side machinery and asserts that the plugin glue resolves the +term and chains ``shared_network_compose_key`` correctly. The key derivation +itself is covered by tests.unit.utils.networks.test_render. +""" + +from __future__ import annotations + +import unittest +from unittest import mock + +from ansible.errors import AnsibleError + +from plugins.lookup.shared_network_key import LookupModule + + +class _Templar: + def __init__(self, vars_=None): + self.available_variables = vars_ or {} + + def template(self, value, **_): + return value + + +def _make_lookup(vars_=None): + lm = LookupModule() + lm._templar = _Templar(vars_ or {}) + lm._loader = mock.MagicMock() + return lm + + +def _patched(lm, vars_, return_value="default"): + return ( + mock.patch( + "utils.networks.lookup_context.build_service_registry_from_applications", + return_value={}, + ), + mock.patch("utils.networks.lookup_context.lookup_loader"), + mock.patch( + "plugins.lookup.shared_network_key.shared_network_compose_key", + return_value=return_value, + ), + ) + + +class TestSharedNetworkKeyLookup(unittest.TestCase): + def test_raises_without_a_term(self): + lm = _make_lookup({"DEPLOYMENT_MODE": "swarm"}) + with self.assertRaises(AnsibleError): + lm.run([], variables={}) + + def test_raises_with_more_than_one_term(self): + lm = _make_lookup({"DEPLOYMENT_MODE": "swarm"}) + with self.assertRaises(AnsibleError): + lm.run(["a", "b"], variables={}) + + def test_returns_the_derived_key(self): + vars_ = {"DEPLOYMENT_MODE": "compose"} + lm = _make_lookup(vars_) + registry_patch, loader_patch, key_patch = _patched(lm, vars_, "seaweedfs") + with registry_patch, loader_patch as loader_mock, key_patch as key_mock: + loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [{}]) + result = lm.run(["web-app-seaweedfs"], variables=vars_) + + self.assertEqual(result, ["seaweedfs"]) + kwargs = key_mock.call_args.kwargs + self.assertEqual(kwargs["application_id"], "web-app-seaweedfs") + self.assertEqual(kwargs["deployment_mode"], "compose") + self.assertFalse(kwargs["node_local"]) + + def test_compose_mode_force_overrides_deployment_mode(self): + vars_ = {"DEPLOYMENT_MODE": "swarm", "compose_mode_force": "compose"} + lm = _make_lookup(vars_) + registry_patch, loader_patch, key_patch = _patched(lm, vars_) + with registry_patch, loader_patch as loader_mock, key_patch as key_mock: + loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [{}]) + lm.run(["web-app-x"], variables=vars_) + + self.assertEqual(key_mock.call_args.kwargs["deployment_mode"], "compose") + + def test_node_local_is_forwarded(self): + vars_ = {"DEPLOYMENT_MODE": "swarm"} + lm = _make_lookup(vars_) + registry_patch, loader_patch, key_patch = _patched(lm, vars_) + with registry_patch, loader_patch as loader_mock, key_patch as key_mock: + loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [{}]) + lm.run(["web-app-x"], variables=vars_, node_local=True) + + self.assertTrue(key_mock.call_args.kwargs["node_local"]) + + def test_lookup_closures_pass_arguments_in_expected_order(self): + vars_ = {"DEPLOYMENT_MODE": "swarm"} + lm = _make_lookup(vars_) + seen: list[tuple] = [] + + def _runner(terms, variables=None): + seen.append((tuple(terms), variables is vars_)) + return [{}] + + registry_patch, loader_patch, key_patch = _patched(lm, vars_) + with registry_patch, loader_patch as loader_mock, key_patch as key_mock: + loader_mock.get.return_value = mock.MagicMock(run=_runner) + lm.run(["web-app-x"], variables=vars_) + kwargs = key_mock.call_args.kwargs + kwargs["lookup_config"]("app", "networks.local.subnet", "fallback") + kwargs["lookup_database"]("app", "name") + + self.assertIn((("app", "networks.local.subnet", "fallback"), True), seen) + self.assertIn((("app", "name"), True), seen) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/utils/networks/test_render.py b/tests/unit/utils/networks/test_render.py index 5f8e661dcb..013b94bdcb 100644 --- a/tests/unit/utils/networks/test_render.py +++ b/tests/unit/utils/networks/test_render.py @@ -21,6 +21,7 @@ from utils.networks.render import ( compute_external_network_roles, render_compose_networks, render_container_networks, + shared_network_compose_key, ) @@ -780,5 +781,91 @@ class TestOwnSharedNetProvider(unittest.TestCase): self.assertNotIn("- seaweedfs", sidecar) +class TestSharedNetworkComposeKey(unittest.TestCase): + """The key under which the pre-created ```` network appears in the + rendered file. Callers stamp it into ``com.docker.compose.network``; docker + compose resolves a project's networks against that label, so a key that does + not match the rendered file makes compose adopt the wrong network and skip + creating the right one.""" + + def _key(self, application_id, registry, deployment_mode="compose"): + return shared_network_compose_key( + application_id=application_id, + deployment_mode=deployment_mode, + registry=registry, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + ) + + def test_own_shared_net_provider_keys_on_its_entity(self): + for mode in ("compose", "swarm"): + with self.subTest(mode=mode): + self.assertEqual( + self._key("web-app-seaweedfs", _PROVIDER_REGISTRY, mode), + "seaweedfs", + ) + + def test_plain_app_keys_on_default(self): + for mode in ("compose", "swarm"): + with self.subTest(mode=mode): + self.assertEqual(self._key("web-app-baserow", {}, mode), "default") + + def test_consumer_of_a_foreign_provider_keys_on_default(self): + registry = { + "ldap": { + "role": "svc-db-openldap", + "entity_name": "openldap", + "provides": "ldap", + "overlay": {"modes": ["compose"], "topology": "shared_net"}, + }, + } + self.assertEqual(self._key("web-app-baserow", registry), "default") + + def test_node_local_forces_the_compose_answer(self): + self.assertEqual( + shared_network_compose_key( + application_id="web-app-seaweedfs", + deployment_mode="swarm", + registry=_PROVIDER_REGISTRY, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + node_local=True, + ), + "seaweedfs", + ) + + def test_key_matches_the_key_the_renderer_emits(self): + """The contract that makes this a single source: whatever key the + function reports must be the key the rendered networks block actually + uses for the entity network.""" + cases = ( + ("web-app-seaweedfs", _PROVIDER_REGISTRY), + ("web-app-baserow", {}), + ) + for application_id, registry in cases: + for mode in ("compose", "swarm"): + with self.subTest(application_id=application_id, mode=mode): + key = self._key(application_id, registry, mode) + rendered = render_compose_networks( + application_id=application_id, + deployment_mode=mode, + registry=registry, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config( + **{"networks.local.subnet": "192.168.206.0/24"} + ), + lookup_database=_const_lookup_database(), + ) + self.assertIn(f" {key}:", rendered) + entity = _entity_name(application_id) + if key == "default": + self.assertIn(f" name: {entity}", rendered) + else: + self.assertEqual(key, entity) + self.assertNotIn(f" name: {entity}", rendered) + + if __name__ == "__main__": unittest.main() diff --git a/utils/networks/attachments.py b/utils/networks/attachments.py new file mode 100644 index 0000000000..2fd52e8929 --- /dev/null +++ b/utils/networks/attachments.py @@ -0,0 +1,142 @@ +"""Attachment computation for the compose networks renderers. + +Which provider overlays a role attaches to, and which proxy aliases the +default network harvests, derived from the service_registry. Kept apart from +the emitters in :mod:`utils.networks.render` so a change to the consumer rules +cannot be confused with a change to the YAML they produce. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Callable + + +def _is_consumer( + entry: dict[str, Any], + application_id: str, + lookup_config: Callable[[str, str, Any], Any], + lookup_database: Callable[[str, str], Any], +) -> bool: + overlay = entry.get("overlay") or {} + consumer = overlay.get("consumer") or {} + kind = consumer.get("kind") or "services_flags" + if kind == "database": + if not _coerce_bool(lookup_database(application_id, "enabled")): + return False + if not _coerce_bool(lookup_database(application_id, "shared")): + return False + return lookup_database(application_id, "id") == entry.get("role") + if kind == "services_flags": + key = consumer.get("key") or entry.get("provides") or entry.get("entity_name") + flags = consumer.get("flags") or ["enabled", "shared"] + for flag in flags: + if not _coerce_bool( + lookup_config(application_id, f"services.{key}.{flag}", False) + ): + return False + return True + if kind == "web_facing": + return application_id.startswith(("web-app-", "web-svc-")) + return False + + +def _coerce_bool(value: Any) -> bool: + if isinstance(value, bool): + return value + if isinstance(value, str): + return value.strip().lower() in ("true", "1", "yes") + return bool(value) + + +def _compute_attachments( + registry: dict[str, dict[str, Any]], + application_id: str, + deployment_mode: str, + lookup_config: Callable[[str, str, Any], Any], + lookup_database: Callable[[str, str], Any], +) -> tuple[list[dict[str, Any]], list[str]]: + attachments: list[dict[str, Any]] = [] + default_aliases: list[str] = [] + + for entry in registry.values(): + if "canonical" in entry: + continue + overlay = entry.get("overlay") + if not overlay: + continue + if deployment_mode not in overlay.get("modes", []): + continue + + is_provider = application_id == entry.get("role") + topology = overlay.get("topology") + + if is_provider: + if topology == "default_net": + default_aliases.extend(overlay.get("aliases") or []) + for peer in registry.values(): + peer_overlay = peer.get("overlay") + if not peer_overlay: + continue + if not peer_overlay.get("proxy_resolvable"): + continue + if deployment_mode not in peer_overlay.get("modes", []): + continue + if "canonical" in peer: + continue + if peer.get("role") == entry.get("role"): + continue + default_aliases.extend( + peer_overlay.get("proxy_aliases") + or peer_overlay.get("aliases") + or [] + ) + elif topology: + aliases = list( + overlay.get("aliases", [entry.get("entity_name")]) + or [entry.get("entity_name")] + ) + if overlay.get("collect_proxy_resolvable"): + for peer in registry.values(): + peer_overlay = peer.get("overlay") + if not peer_overlay: + continue + if not peer_overlay.get("proxy_resolvable"): + continue + if deployment_mode not in peer_overlay.get("modes", []): + continue + if "canonical" in peer: + continue + if peer.get("role") == entry.get("role"): + continue + aliases.extend( + peer_overlay.get("proxy_aliases") + or peer_overlay.get("aliases") + or [] + ) + attachments.append( + { + "role": entry["role"], + "topology": topology, + "aliases": aliases, + "is_provider": True, + } + ) + continue + + if not topology: + continue + if _is_consumer(entry, application_id, lookup_config, lookup_database): + attachments.append( + { + "role": entry["role"], + "topology": topology, + "aliases": [], + "is_provider": False, + } + ) + + return attachments, default_aliases + diff --git a/utils/networks/render.py b/utils/networks/render.py index 2df5832f57..edd603daec 100644 --- a/utils/networks/render.py +++ b/utils/networks/render.py @@ -32,131 +32,22 @@ if TYPE_CHECKING: from collections.abc import Callable -def _is_consumer( - entry: dict[str, Any], - application_id: str, - lookup_config: Callable[[str, str, Any], Any], - lookup_database: Callable[[str, str], Any], -) -> bool: - overlay = entry.get("overlay") or {} - consumer = overlay.get("consumer") or {} - kind = consumer.get("kind") or "services_flags" - if kind == "database": - if not _coerce_bool(lookup_database(application_id, "enabled")): - return False - if not _coerce_bool(lookup_database(application_id, "shared")): - return False - return lookup_database(application_id, "id") == entry.get("role") - if kind == "services_flags": - key = consumer.get("key") or entry.get("provides") or entry.get("entity_name") - flags = consumer.get("flags") or ["enabled", "shared"] - for flag in flags: - if not _coerce_bool( - lookup_config(application_id, f"services.{key}.{flag}", False) - ): - return False - return True - if kind == "web_facing": - return application_id.startswith(("web-app-", "web-svc-")) - return False +from utils.networks.attachments import ( + _coerce_bool, + _compute_attachments, + _is_consumer, +) +__all__ = [ + "_coerce_bool", + "_compute_attachments", + "_is_consumer", + "compute_external_network_roles", + "render_compose_networks", + "render_container_networks", + "shared_network_compose_key", +] -def _coerce_bool(value: Any) -> bool: - if isinstance(value, bool): - return value - if isinstance(value, str): - return value.strip().lower() in ("true", "1", "yes") - return bool(value) - - -def _compute_attachments( - registry: dict[str, dict[str, Any]], - application_id: str, - deployment_mode: str, - lookup_config: Callable[[str, str, Any], Any], - lookup_database: Callable[[str, str], Any], -) -> tuple[list[dict[str, Any]], list[str]]: - attachments: list[dict[str, Any]] = [] - default_aliases: list[str] = [] - - for entry in registry.values(): - if "canonical" in entry: - continue - overlay = entry.get("overlay") - if not overlay: - continue - if deployment_mode not in overlay.get("modes", []): - continue - - is_provider = application_id == entry.get("role") - topology = overlay.get("topology") - - if is_provider: - if topology == "default_net": - default_aliases.extend(overlay.get("aliases") or []) - for peer in registry.values(): - peer_overlay = peer.get("overlay") - if not peer_overlay: - continue - if not peer_overlay.get("proxy_resolvable"): - continue - if deployment_mode not in peer_overlay.get("modes", []): - continue - if "canonical" in peer: - continue - if peer.get("role") == entry.get("role"): - continue - default_aliases.extend( - peer_overlay.get("proxy_aliases") - or peer_overlay.get("aliases") - or [] - ) - elif topology: - aliases = list( - overlay.get("aliases", [entry.get("entity_name")]) - or [entry.get("entity_name")] - ) - if overlay.get("collect_proxy_resolvable"): - for peer in registry.values(): - peer_overlay = peer.get("overlay") - if not peer_overlay: - continue - if not peer_overlay.get("proxy_resolvable"): - continue - if deployment_mode not in peer_overlay.get("modes", []): - continue - if "canonical" in peer: - continue - if peer.get("role") == entry.get("role"): - continue - aliases.extend( - peer_overlay.get("proxy_aliases") - or peer_overlay.get("aliases") - or [] - ) - attachments.append( - { - "role": entry["role"], - "topology": topology, - "aliases": aliases, - "is_provider": True, - } - ) - continue - - if not topology: - continue - if _is_consumer(entry, application_id, lookup_config, lookup_database): - attachments.append( - { - "role": entry["role"], - "topology": topology, - "aliases": [], - "is_provider": False, - } - ) - - return attachments, default_aliases def _suppress_default(application_id: str) -> bool: @@ -176,6 +67,53 @@ def _own_shared_net_provider( ) +def _shared_network_key( + attachments: list[dict[str, Any]], + own_entity: str, + get_entity_name: Callable[[str], str], +) -> str: + if _own_shared_net_provider(attachments, own_entity, get_entity_name): + return own_entity + return "default" + + +def shared_network_compose_key( + *, + application_id: str, + deployment_mode: str, + registry: dict[str, dict[str, Any]], + get_entity_name: Callable[[str], str], + lookup_config: Callable[[str, str, Any], Any], + lookup_database: Callable[[str, str], Any], + node_local: bool = False, +) -> str: + """Key under which the pre-created ```` network appears in the + rendered compose file, which is what docker compose stores in the + ``com.docker.compose.network`` label. An app that provides its own + ``shared_net`` gets that network under its entity key and renders a separate + unnamed ``default``; every other app renders ``default`` with the entity as + its name. :func:`render_compose_networks` derives its own branch from this + same call, so the label a caller stamps cannot drift from what is rendered. + + Args: + application_id: role the network belongs to. + deployment_mode: compose or swarm. + registry: service registry built from the merged applications. + get_entity_name: role id to entity name. + lookup_config: config value accessor. + lookup_database: database value accessor. + node_local: render as compose regardless of deployment_mode. + """ + if node_local: + deployment_mode = "compose" + attachments, _ = _compute_attachments( + registry, application_id, deployment_mode, lookup_config, lookup_database + ) + return _shared_network_key( + attachments, get_entity_name(application_id), get_entity_name + ) + + def compute_external_network_roles( *, application_id: str, @@ -229,8 +167,8 @@ def render_compose_networks( lines.append(" external: true") own_entity = get_entity_name(application_id) - is_own_shared_net_provider = _own_shared_net_provider( - attachments, own_entity, get_entity_name + is_own_shared_net_provider = ( + _shared_network_key(attachments, own_entity, get_entity_name) == own_entity ) if not _suppress_default(application_id): lines.append(" default:") From e3068a37d8b814be1bf3f5928a3f66bf7b1073a7 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 21:31:36 +0200 Subject: [PATCH 27/31] fix(nextcloud): render system config instead of setting it via occ Nine sequential `occ config:system:set` calls each open config.php exclusively. In swarm that file lives on the NFS share behind every replica, and the seventh call could not take the lock: In Config.php line 306: Could not acquire an exclusive lock on the config file /var/www/html/config/config.php stdout shows six values written before the abort, so the run left a partial configuration behind. That failed the swarm web-app-nextcloud 5 job in run 30830377785 while every PLAY RECAP on the other nodes reported failed=0. The same nine values now come from templates/config/system.config.php.j2, which rides the additional-config channel the role already uses for redis, ldap and the rest: rendered to NEXTCLOUD_HOST_CONF_ADD_PATH, mounted read-only, merged by zzz-infinito.config.php after config.php so its values win. That path never takes an exclusive lock, and it runs before the stack starts, since all nine values are statically derived and none needs a live container. Two behaviours are deliberately not carried over. The --type flags become native PHP types, which is stricter than the string coercion occ applied. And nothing confirms the file was accepted any more, where occ's exit code did; a read-only `config:system:get` would restore that assurance at the cost of an occ call, and is left out until someone wants it. php_str() escapes backslashes and single quotes, matching the idiom already used for the redis password in memcache.config.php.j2. Without it a quote in any value would be a PHP syntax error, and include_once would drop every additional config file, not just this one. vars/system.yml and 02_manager_ops/05_system_config.yml are gone; the later task files shift down one number so test_task_file_numbering stays satisfied. Co-Authored-By: Claude Opus 5 (1M context) --- .../tasks/02_manager_ops.yml | 10 ++---- .../{06_plugin.yml => 05_plugin.yml} | 2 +- .../{06_plugin => 05_plugin}/01_install.yml | 0 .../{06_plugin => 05_plugin}/02_enable.yml | 0 .../{06_plugin => 05_plugin}/03_configure.yml | 0 .../{06_plugin => 05_plugin}/README.md | 6 ++-- .../tasks/02_manager_ops/05_system_config.yml | 20 ------------ ...identities.yml => 06_admin_identities.yml} | 0 .../templates/config/README.md | 9 ++++-- .../templates/config/system.config.php.j2 | 22 +++++++++++++ roles/web-app-nextcloud/vars/system.yml | 32 ------------------- 11 files changed, 35 insertions(+), 66 deletions(-) rename roles/web-app-nextcloud/tasks/02_manager_ops/{06_plugin.yml => 05_plugin.yml} (91%) rename roles/web-app-nextcloud/tasks/02_manager_ops/{06_plugin => 05_plugin}/01_install.yml (100%) rename roles/web-app-nextcloud/tasks/02_manager_ops/{06_plugin => 05_plugin}/02_enable.yml (100%) rename roles/web-app-nextcloud/tasks/02_manager_ops/{06_plugin => 05_plugin}/03_configure.yml (100%) rename roles/web-app-nextcloud/tasks/02_manager_ops/{06_plugin => 05_plugin}/README.md (96%) delete mode 100644 roles/web-app-nextcloud/tasks/02_manager_ops/05_system_config.yml rename roles/web-app-nextcloud/tasks/02_manager_ops/{07_admin_identities.yml => 06_admin_identities.yml} (100%) create mode 100644 roles/web-app-nextcloud/templates/config/system.config.php.j2 delete mode 100644 roles/web-app-nextcloud/vars/system.yml diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops.yml b/roles/web-app-nextcloud/tasks/02_manager_ops.yml index b51fa1cc57..518f5b3082 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops.yml +++ b/roles/web-app-nextcloud/tasks/02_manager_ops.yml @@ -37,15 +37,9 @@ apply: delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" -- name: ⚙️ Apply the system configuration - include_tasks: - file: 02_manager_ops/05_system_config.yml - apply: - delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" - - name: 🔧 Setup Nextcloud Plugins include_tasks: - file: 02_manager_ops/06_plugin.yml + file: 02_manager_ops/05_plugin.yml apply: delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" loop: "{{ NEXTCLOUD_PLUGIN_ITEMS }}" @@ -58,6 +52,6 @@ - name: 🔧 Reconcile administrator identities after plugin setup include_tasks: - file: 02_manager_ops/07_admin_identities.yml + file: 02_manager_ops/06_admin_identities.yml apply: delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin.yml similarity index 91% rename from roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin.yml rename to roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin.yml index c8d294d83a..9b7e1649f6 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin.yml +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin.yml @@ -1,6 +1,6 @@ --- - block: - - include_tasks: 06_plugin/01_install.yml + - include_tasks: 05_plugin/01_install.yml when: plugin_value.enabled | bool - name: 🔴 disable {{ plugin_key }} nextcloud plugin diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/01_install.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin/01_install.yml similarity index 100% rename from roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/01_install.yml rename to roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin/01_install.yml diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_enable.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin/02_enable.yml similarity index 100% rename from roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_enable.yml rename to roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin/02_enable.yml diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/03_configure.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin/03_configure.yml similarity index 100% rename from roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/03_configure.yml rename to roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin/03_configure.yml diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md b/roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin/README.md similarity index 96% rename from roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md rename to roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin/README.md index 11290d5143..25abaf5415 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/05_plugin/README.md @@ -10,11 +10,11 @@ The pipeline owns three responsibilities for one Nextcloud plugin (app): 2. Enable the plugin so the in-app code paths are active. 3. Apply plugin-specific configuration keys and run any role-local hook. -When a plugin is marked `enabled: false`, `06_plugin.yml` runs `occ app:disable` for that plugin instead of entering the pipeline. +When a plugin is marked `enabled: false`, `05_plugin.yml` runs `occ app:disable` for that plugin instead of entering the pipeline. ## Pipeline stages -Each `tasks/02_manager_ops/06_plugin/.yml` file owns exactly one OCC stage and one decision about whether to continue. +Each `tasks/02_manager_ops/05_plugin/.yml` file owns exactly one OCC stage and one decision about whether to continue. | File | Stage | OCC command | Continues to next stage when | |---|---|---|---| @@ -67,5 +67,5 @@ This guarantees that mutually exclusive integrations such as the OIDC entry poin ## Entry point -The pipeline is invoked from [06_plugin.yml](../06_plugin.yml), which in turn runs once per iteration of the `NEXTCLOUD_PLUGIN_ITEMS` loop in [02_manager_ops.yml](../../02_manager_ops.yml). +The pipeline is invoked from [05_plugin.yml](../05_plugin.yml), which in turn runs once per iteration of the `NEXTCLOUD_PLUGIN_ITEMS` loop in [02_manager_ops.yml](../../02_manager_ops.yml). The loop variable `plugin_item` is unpacked into `plugin_key` (the OCC app name) and `plugin_value` (its meta entry). diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/05_system_config.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/05_system_config.yml deleted file mode 100644 index 578d206dc3..0000000000 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/05_system_config.yml +++ /dev/null @@ -1,20 +0,0 @@ ---- -- name: ⚙️ Load System Nextcloud configuration variables - include_vars: - file: system.yml - -- name: "📌 Apply Nextcloud system configs (batched shell)" - ansible.builtin.shell: | - set -euo pipefail - {% for item in nextcloud_system_config %} - {{ NEXTCLOUD_DOCKER_EXEC_OCC }} \ - config:system:set {{ item.parameter }}{% if item.type is defined %} --type {{ item.type }}{% endif %} \ - --value '{{ (item.value | string) | regex_replace("'", "'" ~ '"' ~ "'" ~ '"' ~ "'") }}' - {% endfor %} - args: - executable: /bin/bash - register: syscfg_shell - changed_when: > - ( ((syscfg_shell.stdout | default('')) ~ (syscfg_shell.stderr | default(''))) - is search(' set to ') ) - failed_when: syscfg_shell.rc != 0 diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/07_admin_identities.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/06_admin_identities.yml similarity index 100% rename from roles/web-app-nextcloud/tasks/02_manager_ops/07_admin_identities.yml rename to roles/web-app-nextcloud/tasks/02_manager_ops/06_admin_identities.yml diff --git a/roles/web-app-nextcloud/templates/config/README.md b/roles/web-app-nextcloud/templates/config/README.md index c3dc84bd8f..6ef0a9ff7f 100644 --- a/roles/web-app-nextcloud/templates/config/README.md +++ b/roles/web-app-nextcloud/templates/config/README.md @@ -1,4 +1,9 @@ # Nextcloud config templates -This folder contains configuration files which will be loaded direct into the config.php -If you don't use nested configuration, concider to use the vars/system.yml file instead, because it's a cleaner way to set the configuration. +Every `*.j2` here is rendered to the host-mounted config directory and merged +into `$CONFIG` by `zzz-infinito.config.php`, which Nextcloud applies after +`config.php`. Values set here therefore win. + +Put system configuration here rather than calling `occ config:system:set`: the +occ path takes an exclusive lock on `config.php`, which is a single NFS-shared +file behind every replica in swarm mode, while this path is read-only. diff --git a/roles/web-app-nextcloud/templates/config/system.config.php.j2 b/roles/web-app-nextcloud/templates/config/system.config.php.j2 new file mode 100644 index 0000000000..168edc4f76 --- /dev/null +++ b/roles/web-app-nextcloud/templates/config/system.config.php.j2 @@ -0,0 +1,22 @@ + {{ 'false' if _legacy_login else 'true' }}, + 'auth.webauthn.enabled' => {{ 'true' if _legacy_login else 'false' }}, + 'maintenance_window_start' => {{ SYS_SCHEDULE_MAINTANANCE_NEXTCLOUD | int }}, + 'default_phone_region' => {{ php_str(HOST_LL | upper) }}, + 'trusted_domains' => [ + {{ php_str(NEXTCLOUD_DOMAIN) }}, + ], + 'overwrite.cli.url' => {{ php_str(NEXTCLOUD_URL) }}, + 'overwriteprotocol' => {{ php_str(NEXTCLOUD_PROTOCOL) }}, + 'overwritehost' => {{ php_str(NEXTCLOUD_DOMAIN) }}, + 'trusted_proxies' => [ +{%- for _proxy in NEXTCLOUD_TRUSTED_PROXIES %} + {{ php_str(_proxy) }}, +{%- endfor %} + ], +]; diff --git a/roles/web-app-nextcloud/vars/system.yml b/roles/web-app-nextcloud/vars/system.yml deleted file mode 100644 index 3c509fa1bd..0000000000 --- a/roles/web-app-nextcloud/vars/system.yml +++ /dev/null @@ -1,32 +0,0 @@ ---- -nextcloud_system_config: - - parameter: "hide_login_form" - type: "boolean" - value: "{{ (not lookup('config', application_id, 'services.nextcloud.legacy_login_mask.enabled')) | lower }}" - - - parameter: "auth.webauthn.enabled" - type: "boolean" - value: "{{ lookup('config', application_id, 'services.nextcloud.legacy_login_mask.enabled') | lower }}" - - - parameter: "maintenance_window_start" - type: "integer" - value: "{{ SYS_SCHEDULE_MAINTANANCE_NEXTCLOUD }}" - - - parameter: "default_phone_region" - value: "{{ HOST_LL | upper }}" - - - parameter: "trusted_domains 0" - value: "{{ NEXTCLOUD_DOMAIN }}" - - - parameter: "overwrite.cli.url" - value: "{{ NEXTCLOUD_URL }}" - - - parameter: "overwriteprotocol" - value: "{{ NEXTCLOUD_PROTOCOL }}" - - - parameter: "overwritehost" - value: "{{ NEXTCLOUD_DOMAIN }}" - - - parameter: "trusted_proxies" - type: "json" - value: "{{ NEXTCLOUD_TRUSTED_PROXIES }}" From 04dfb98800cc0826b15a815d2b0944bd5a4869f8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 21:32:50 +0200 Subject: [PATCH 28/31] style(networks): apply the formatter to the split-out modules Leftovers from extracting lookup_context and attachments: the mock.patch target got short enough to fit on one line again, and the file split left a spare blank line in each module. Whitespace only, produced by autoformat during make quality, so the 298 tests of that run already covered this state. Co-Authored-By: Claude Opus 5 (1M context) --- .../plugins/lookup/test_compose_external_networks.py | 4 +--- tests/unit/plugins/lookup/test_container_networks.py | 12 +++--------- utils/networks/attachments.py | 1 - utils/networks/render.py | 1 - 4 files changed, 4 insertions(+), 14 deletions(-) diff --git a/tests/unit/plugins/lookup/test_compose_external_networks.py b/tests/unit/plugins/lookup/test_compose_external_networks.py index 0894a8cc9e..5b89da1842 100644 --- a/tests/unit/plugins/lookup/test_compose_external_networks.py +++ b/tests/unit/plugins/lookup/test_compose_external_networks.py @@ -50,9 +50,7 @@ class TestComposeExternalNetworksLookup(unittest.TestCase): "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), - mock.patch( - "utils.networks.lookup_context.lookup_loader" - ) as loader_mock, + mock.patch("utils.networks.lookup_context.lookup_loader") as loader_mock, mock.patch( "plugins.lookup.compose_external_networks.compute_external_network_roles", return_value=["svc-db-redis", "svc-db-openldap"], diff --git a/tests/unit/plugins/lookup/test_container_networks.py b/tests/unit/plugins/lookup/test_container_networks.py index 5e2cbaa75e..c93b32880c 100644 --- a/tests/unit/plugins/lookup/test_container_networks.py +++ b/tests/unit/plugins/lookup/test_container_networks.py @@ -54,9 +54,7 @@ class TestContainerNetworksLookup(unittest.TestCase): "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), - mock.patch( - "utils.networks.lookup_context.lookup_loader" - ) as loader_mock, + mock.patch("utils.networks.lookup_context.lookup_loader") as loader_mock, mock.patch( "plugins.lookup.container_networks.render_container_networks", return_value="RENDERED", @@ -80,9 +78,7 @@ class TestContainerNetworksLookup(unittest.TestCase): "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), - mock.patch( - "utils.networks.lookup_context.lookup_loader" - ) as loader_mock, + mock.patch("utils.networks.lookup_context.lookup_loader") as loader_mock, mock.patch( "plugins.lookup.container_networks.render_container_networks", return_value="RENDERED", @@ -123,9 +119,7 @@ class TestContainerNetworksLookup(unittest.TestCase): "utils.networks.lookup_context.build_service_registry_from_applications", return_value={}, ), - mock.patch( - "utils.networks.lookup_context.lookup_loader" - ) as loader_mock, + mock.patch("utils.networks.lookup_context.lookup_loader") as loader_mock, mock.patch( "plugins.lookup.container_networks.render_container_networks", side_effect=_exercise, diff --git a/utils/networks/attachments.py b/utils/networks/attachments.py index 2fd52e8929..32b750acf8 100644 --- a/utils/networks/attachments.py +++ b/utils/networks/attachments.py @@ -139,4 +139,3 @@ def _compute_attachments( ) return attachments, default_aliases - diff --git a/utils/networks/render.py b/utils/networks/render.py index edd603daec..4ff2747da0 100644 --- a/utils/networks/render.py +++ b/utils/networks/render.py @@ -49,7 +49,6 @@ __all__ = [ ] - def _suppress_default(application_id: str) -> bool: return application_id.startswith(("svc-db-", "svc-ai-")) From 32b0d3df947b0a05cabc1e896474bc54fa8f28bf Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 21:44:36 +0200 Subject: [PATCH 29/31] fix(swarm-drill): account for the watchdog floor in the space precondition The drill's space check required FREE >= PULLED, but the run is killed from outside by matrix.py's watchdog as soon as the runner drops below 6G free. The check knew nothing about that floor, so it waved through a drill that could not finish: 19008M free against a 13961M pulled tree passes FREE >= PULLED, and the sync then leaves 5047M, which is under the floor. That is what happened to the arch swarm drill in run 30830377785. The device sync reported the marker at 19:16:38.34, the watchdog fired at 19:16:39.73 on its next 30s tick, and the step died with rc 75 thirteen minutes into work that was already doomed when the precondition ran. The requirement is PULLED + FLOOR, not FREE >= PULLED and not 2 * PULLED. FREE is measured after the pull, so the first copy is already deducted; exactly one further copy is ever added on top of it - the device copy during the sync, and later the restore root, by which time base.sh has deleted the pulled tree. The two extra copies are sequential, never simultaneous. matrix.py owns the floor now and exports it as INFINITO_DISK_FLOOR_MB. It was previously a bare `6 * 2**30` the shell had no way to see, which is why the two sides could disagree about what "enough disk" means. This makes the failure honest and immediate; it does not create disk. The arch runner is short by about 1.1G, and closing that needs a capacity decision - bigger runner, smaller test dataset, or reclaiming build cache before the drill. Co-Authored-By: Claude Opus 5 (1M context) --- scripts/tests/deploy/swarm/routine/backup/base.sh | 6 ++++-- utils/tests/swarm/matrix.py | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/scripts/tests/deploy/swarm/routine/backup/base.sh b/scripts/tests/deploy/swarm/routine/backup/base.sh index f4735ce649..e6aa7df4f1 100755 --- a/scripts/tests/deploy/swarm/routine/backup/base.sh +++ b/scripts/tests/deploy/swarm/routine/backup/base.sh @@ -37,6 +37,7 @@ DR_TOKEN="${SWARM_NAME}-${APP_ID}-dr-drill" DR_VERIFY_ENV="/tmp/dr-drill-verify-${APP_ID}.env" rm -f "${DR_VERIFY_ENV}" SECRETS_DIR="${INFINITO_DIR_SECRETS:?INFINITO_DIR_SECRETS is not set - regenerate .env via make dotenv}" +DISK_FLOOR_MB="${INFINITO_DISK_FLOOR_MB:?INFINITO_DISK_FLOOR_MB is not set - utils.tests.swarm.matrix exports its watchdog floor}" VOLUME_REPO="backup-docker-to-local" NFS_REPO="backup-nfs-to-local" SECRETS_REPO="backup-secrets-to-local" @@ -166,8 +167,9 @@ if [ "${DEVICE_FREE_MB}" -lt "${PULLED_MB}" ]; then drill_device_teardown exit 1 fi -if [ "${FREE_MB}" -lt "${PULLED_MB}" ]; then - echo "FAILURE: the drill still has to allocate one more copy of the ${PULLED_MB}M pulled tree (the sync into the sparse image, later the restore root); ${FREE_MB}M free on ${BACKUP_NODE}:${DIR_BACKUPS}" +NEEDED_MB=$((PULLED_MB + DISK_FLOOR_MB)) +if [ "${FREE_MB}" -lt "${NEEDED_MB}" ]; then + echo "FAILURE: the sync holds the ${PULLED_MB}M pulled tree and its device copy at once (the restore root repeats that peak later), so ${NEEDED_MB}M must be free to stay above the ${DISK_FLOOR_MB}M watchdog floor; ${FREE_MB}M free on ${BACKUP_NODE}:${DIR_BACKUPS}" drill_device_teardown exit 1 fi diff --git a/utils/tests/swarm/matrix.py b/utils/tests/swarm/matrix.py index 5857bc39c1..202f23759c 100644 --- a/utils/tests/swarm/matrix.py +++ b/utils/tests/swarm/matrix.py @@ -33,6 +33,7 @@ _SWARM_SCRIPTS = _SWARM_DIR / "routine" _ROLES_DIR = str(PROJECT_ROOT / "roles") _SWARM_EXTRAS_VARS = "inventories/development/swarm.yml" _DEFAULT_INVENTORY_DIR = "/tmp/inv" # noqa: S108 - ephemeral swarm-test inventory base in CI +DISK_FLOOR_MB = 6 * 2**10 def _run(cmd: list[str], *, env: dict[str, str], label: str) -> int: @@ -40,7 +41,7 @@ def _run(cmd: list[str], *, env: dict[str, str], label: str) -> int: The Actions Worker dies silently on ENOSPC while writing its own logs, so a full disk truncates the job without diagnostics; terminating the step at - <6G free keeps enough room for rescue artifacts and the log upload. + DISK_FLOOR_MB keeps enough room for rescue artifacts and the log upload. """ print(f"=== swarm-matrix: {label} ===", flush=True) proc = subprocess.Popen(cmd, cwd=str(PROJECT_ROOT), env=env) @@ -48,10 +49,10 @@ def _run(cmd: list[str], *, env: dict[str, str], label: str) -> int: try: return int(proc.wait(timeout=30)) except subprocess.TimeoutExpired: - if shutil.disk_usage("/").free < 6 * 2**30: + if shutil.disk_usage("/").free < DISK_FLOOR_MB * 2**20: print( "=== swarm-matrix: DISK EXHAUSTION IMMINENT " - "(<6G free on /) - aborting step ===", + f"(<{DISK_FLOOR_MB}M free on /) - aborting step ===", flush=True, ) subprocess.run(["df", "-h", "/"], check=False) @@ -198,6 +199,7 @@ def _backup_restore_drill(*, app_id: str, inv_dir: str, extras_path: str) -> int env["APP_ID"] = app_id env["INFINITO_INVENTORY_DIR"] = inv_dir env["DRILL_EXTRAS"] = extras_path + env["INFINITO_DISK_FLOOR_MB"] = str(DISK_FLOOR_MB) return _run( ["bash", str(_SWARM_SCRIPTS / "backup" / "base.sh")], env=env, From 9ad1a1a8a4fa0e3a7f2beb9a3f5ce26f8554d44d Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 21:48:13 +0200 Subject: [PATCH 30/31] fix(swarm-drill): read the node name via uname hostname(1) is not installed in every node image. In run 30830377785 the arch drill printed trigger_units.sh: line 22: hostname: command not found starting svc-bkp-local-2-device.11.6.0.infinito.nexus.service on so the node name came out empty on all three call sites. The cosmetic one is the progress line; the damaging one is the journal dump path, which becomes "${unit}..journal.txt" and is identical on every node. Four hosts writing the same filename into the shared dumps directory means the artifact keeps whichever one wrote last, and a unit failure gets investigated against another host's journal. uname is coreutils and present wherever the drill runs. Reading it once also drops three subshells from the loop. Co-Authored-By: Claude Opus 5 (1M context) --- scripts/tests/deploy/swarm/utils/trigger_units.sh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/scripts/tests/deploy/swarm/utils/trigger_units.sh b/scripts/tests/deploy/swarm/utils/trigger_units.sh index c695c9f899..b7baed8773 100755 --- a/scripts/tests/deploy/swarm/utils/trigger_units.sh +++ b/scripts/tests/deploy/swarm/utils/trigger_units.sh @@ -17,14 +17,16 @@ DUMPS="${2:?usage: trigger_units.sh PATTERN DUMPS}" units="$(systemctl list-unit-files "${PATTERN}" --no-legend | awk '{print $1}' || true)" [ -n "${units}" ] || exit 2 +NODE="$(uname -n)" + while read -r unit; do [ -n "${unit}" ] || continue - echo " starting ${unit} on $(hostname)" + echo " starting ${unit} on ${NODE}" if ! systemctl start "${unit}"; then mkdir -p "${DUMPS}" - dump="${DUMPS}/${unit}.$(hostname).journal.txt" + dump="${DUMPS}/${unit}.${NODE}.journal.txt" journalctl -u "${unit}" --no-pager -o short-iso >"${dump}" 2>/dev/null || true - echo "FAILURE: ${unit} did not complete on $(hostname); full journal at ${dump}" + echo "FAILURE: ${unit} did not complete on ${NODE}; full journal at ${dump}" journalctl -u "${unit}" --no-pager -o cat -n 40 2>/dev/null || true exit 1 fi From 5940d3049faae26f04ec9706705d74ec89bc48c3 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Mon, 3 Aug 2026 22:02:23 +0200 Subject: [PATCH 31/31] fix(swarm-drill): keep the floor handoff out of the INFINITO namespace bdb3b29a9 passed the watchdog floor to the drill as INFINITO_DISK_FLOOR_MB and broke test-lint: AssertionError: INFINITO_* keys referenced in code without a registry entry INFINITO_DISK_FLOOR_MB The prefix is reserved for the deployment env registry, where every key needs a default in default.env or a handler that sets it. This value is neither: it is a handoff from matrix.py to the script matrix.py starts, and it only exists for the duration of that call. DRILL_EXTRAS, one line above, already goes the same way under an unprefixed name. So the key becomes DISK_FLOOR_MB and its declaration moves up beside DRILL_EXTRAS in the `: "${VAR:?...}"` form the file uses for matrix handoffs, leaving the INFINITO_* block below to the values that really come from .env. Registering it in default.env would have satisfied the lint by writing 6144 down a second time, which is the duplication bdb3b29a9 set out to remove; a nocheck would have hidden the naming mistake rather than fixed it. Co-Authored-By: Claude Opus 5 (1M context) --- scripts/tests/deploy/swarm/routine/backup/base.sh | 2 +- utils/tests/swarm/matrix.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/tests/deploy/swarm/routine/backup/base.sh b/scripts/tests/deploy/swarm/routine/backup/base.sh index e6aa7df4f1..9acfe68917 100755 --- a/scripts/tests/deploy/swarm/routine/backup/base.sh +++ b/scripts/tests/deploy/swarm/routine/backup/base.sh @@ -26,6 +26,7 @@ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" source "${SCRIPT_DIR}/../../utils/_context.sh" : "${DRILL_EXTRAS:?DRILL_EXTRAS required (matrix passes the round extras)}" +: "${DISK_FLOOR_MB:?DISK_FLOOR_MB required (matrix passes its watchdog floor)}" DIR_VAR_LIB="${INFINITO_DIR_VAR_LIB:?INFINITO_DIR_VAR_LIB is not set - source scripts/meta/env/load.sh first}" DIR_BACKUPS="${INFINITO_DIR_BACKUPS:?INFINITO_DIR_BACKUPS is not set - regenerate .env via make dotenv}" @@ -37,7 +38,6 @@ DR_TOKEN="${SWARM_NAME}-${APP_ID}-dr-drill" DR_VERIFY_ENV="/tmp/dr-drill-verify-${APP_ID}.env" rm -f "${DR_VERIFY_ENV}" SECRETS_DIR="${INFINITO_DIR_SECRETS:?INFINITO_DIR_SECRETS is not set - regenerate .env via make dotenv}" -DISK_FLOOR_MB="${INFINITO_DISK_FLOOR_MB:?INFINITO_DISK_FLOOR_MB is not set - utils.tests.swarm.matrix exports its watchdog floor}" VOLUME_REPO="backup-docker-to-local" NFS_REPO="backup-nfs-to-local" SECRETS_REPO="backup-secrets-to-local" diff --git a/utils/tests/swarm/matrix.py b/utils/tests/swarm/matrix.py index 202f23759c..20e5d9c760 100644 --- a/utils/tests/swarm/matrix.py +++ b/utils/tests/swarm/matrix.py @@ -199,7 +199,7 @@ def _backup_restore_drill(*, app_id: str, inv_dir: str, extras_path: str) -> int env["APP_ID"] = app_id env["INFINITO_INVENTORY_DIR"] = inv_dir env["DRILL_EXTRAS"] = extras_path - env["INFINITO_DISK_FLOOR_MB"] = str(DISK_FLOOR_MB) + env["DISK_FLOOR_MB"] = str(DISK_FLOOR_MB) return _run( ["bash", str(_SWARM_SCRIPTS / "backup" / "base.sh")], env=env,