feat(ci): run the molecule scenarios of the roles that use a changed role
Build / build (pull_request) Successful in 13s
Lint / lint (pull_request) Successful in 1m1s
Molecule / molecule (pull_request) Successful in 9m45s

The scenario picker assumed the roles were independent and a test enforced it. Wave 2
roles call other Collection roles (traefik includes ufw and the internal _binary_update),
so a change to the called role must also run the callers' scenarios.

A role uses another when a file under its directory names it as mortis.kamino.<role>;
the relation is followed transitively and read from the tree under test. A role the
pull request deletes or renames still counts as used by the roles that name it, so
their scenarios run and show the break.

The independence test becomes a test that fails a bare or templated role name in an
include, import (also in the k=v form), play roles: entry or meta dependency, and task
includes that reach outside the role through '..'. It walks .yml and .yaml files and has
its own cases for each form. This lands before the first such role because the workflow
runs the picker from the base branch's copy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
This commit is contained in:
Defame1297andClaude Opus 5.5 committed 2026-11-20 18:33:02 +00:00
1 parent 30ce518f00
commit fcb51da065
3 files changed
+271 -25

No files matched your search

+2 -1
View File
@@ -73,7 +73,8 @@ Single-context: `GLOSSARY.md` and `docs/adr/` at the root, both created lazily.
- Molecule runs on every same-repo pull request, Renovate's included (a new image is tested by its own pin
pull request), with no workflow path filter, so that it can be a required check. Fork pull requests are skipped.
What a pull request runs is chosen by `scripts/select_molecule_scenarios.py`, run from the base branch's copy
(a pull request cannot edit its own rules): only the scenarios of the roles it changes, none for a diff of
(a pull request cannot edit its own rules): only the scenarios of the roles it changes and of the roles
that use them (any file naming `mortis.kamino.<role>`, transitively; a test fails a bare or templated role name in an include, import, play `roles:` entry or meta dependency), none for a diff of
only its IGNORED paths, a failure for a changed role with no scenario, and every scenario for any other file,
for every push to `main`, for manual dispatch and for the nightly run (04:43 UTC, after Renovate's). A new file outside `roles/<role>/` runs everything until it
is added to IGNORED, which is right only when no scenario reads it. A new commit cancels the pull request's
+64 -7
View File
@@ -11,15 +11,21 @@ workflow runs `molecule test` in each.
Only a pull request is narrowed, and only when <base-ref> is given and EVENT_NAME is
`pull_request`. Then the diff of <base-ref>...HEAD decides:
* a file under roles/<role>/ selects that role's scenarios, and nothing else;
* a file under roles/<role>/ selects that role's scenarios, and those of every role that
uses it (below);
* a file on the IGNORED list (documentation, changelog, repository tooling that no
scenario reads) selects nothing;
* any other file selects every scenario.
The roles do not depend on one another, so a change inside one role cannot alter another
role's result. If one ever does (a role calling another, a shared plugin), the shared file
sits outside roles/<role>/ and so already selects everything; only an explicit role-to-role
dependency would need a rule here.
A role uses another when any file under its directory names it as `mortis.kamino.<other>`
(an include_role, a scenario's prepare play, a comment). The relation is transitive: when
`a` names `b` and `b` names `c`, a change to `c` selects all three. The roles call each other
by that full name only (a test checks includes, imports, play `roles:` entries and meta
dependencies for a bare or templated role name), so the text search finds every use. It reads the
tree under test, not the base: a pull request that drops a use also changes the using role,
which then selects itself, and a role the pull request deletes or renames still counts as used
by the roles that name it. A shared file outside roles/<role>/ (a plugin) already selects
everything.
Every other case runs everything: a push, a manual dispatch, a scheduled run, no <base-ref>, a git
failure.
@@ -42,6 +48,7 @@ control characters in paths escaped so a crafted file name cannot inject a log c
import fnmatch
import os
import re
import subprocess
import sys
@@ -123,6 +130,48 @@ def discover(root="."):
return found
ROLE_REFERENCE = re.compile(r"mortis\.kamino\.([A-Za-z0-9_]+)")
def users(root=".", gone=()):
"""Map each role to the roles whose files name it as mortis.kamino.<role>.
Self-references (a scenario converging its own role) are left out, and so are names that
are neither a role directory nor in `gone`: the changed roles, so that a role deleted or
renamed by the pull request still selects the roles that call it.
"""
base = os.path.join(root, "roles")
if not os.path.isdir(base):
return {}
roles = {r for r in os.listdir(base) if os.path.isdir(os.path.join(base, r))}
known = roles | set(gone)
used_by = {}
for role in roles:
for dirpath, _dirs, files in os.walk(os.path.join(base, role)):
for name in files:
try:
with open(os.path.join(dirpath, name), "rb") as f:
text = f.read().decode("utf-8", "ignore")
except OSError:
continue
for other in ROLE_REFERENCE.findall(text):
if other != role and other in known:
used_by.setdefault(other, set()).add(role)
return used_by
def with_users(roles, used_by):
"""`roles` plus every role that uses one of them, directly or through another."""
found = set(roles)
todo = list(roles)
while todo:
for user in used_by.get(todo.pop(), ()):
if user not in found:
found.add(user)
todo.append(user)
return found
def is_ignored(path):
return any(fnmatch.fnmatchcase(path, pattern) for pattern in IGNORED)
@@ -141,6 +190,8 @@ def select(all_scenarios, changed, root="."):
roles.add(parts[1])
continue
return list(all_scenarios), f"{printable(path)} can affect every scenario"
changed_roles = roles
roles = with_users(changed_roles, users(root, changed_roles))
chosen = [
s for s in all_scenarios if s.startswith("roles/") and s.split("/")[1] in roles
]
@@ -150,11 +201,17 @@ def select(all_scenarios, changed, root="."):
)
if bare:
raise ValueError(
"changed role without a molecule scenario: "
"role without a molecule scenario (changed, or a user of a changed role): "
+ ", ".join(printable(r) for r in bare)
)
if roles:
reason = "only roles changed: " + ", ".join(printable(r) for r in sorted(roles))
reason = "only roles changed: " + ", ".join(
printable(r) for r in sorted(changed_roles)
)
if roles - changed_roles:
reason += "; their users: " + ", ".join(
printable(r) for r in sorted(roles - changed_roles)
)
else:
reason = "no change that a scenario reads"
return chosen, reason
+205 -17
View File
@@ -6,6 +6,7 @@ import contextlib
import io
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
@@ -18,6 +19,75 @@ REPO = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO / "scripts"))
import select_molecule_scenarios as sel
ROLE_KEYS = {
f"{prefix}{verb}"
for prefix in ("", "ansible.builtin.", "ansible.legacy.")
for verb in ("include_role", "import_role")
}
TASK_KEYS = {
f"{prefix}{verb}"
for prefix in ("", "ansible.builtin.", "ansible.legacy.")
for verb in ("include_tasks", "import_tasks")
}
def _arg(value, key):
"""`key` of a module argument given as a mapping, a k=v string or a bare string."""
if isinstance(value, dict):
return value.get(key)
if not isinstance(value, str):
return None
for word in value.split():
if word.startswith(f"{key}="):
return word[len(key) + 1 :]
return None if "=" in value else value
def _name_problem(name, how, roles):
if not isinstance(name, str):
return []
if "{{" in name:
return [f"{how} a templated role name {name!r}"]
if name in roles:
return [f"{how} {name} by its bare name"]
return []
def _play_roles_problems(play, roles):
problems = []
for entry in play.get("roles") if isinstance(play.get("roles"), list) else []:
name = (
entry.get("role", entry.get("name")) if isinstance(entry, dict) else entry
)
problems += _name_problem(name, "a play's roles: uses", roles)
return problems
def _key_problems(key, value, roles):
if key in ROLE_KEYS:
return _name_problem(_arg(value, "name"), f"{key} uses", roles)
if key in TASK_KEYS:
target = _arg(value, "file")
if isinstance(target, str) and ".." in target:
return [f"{key} reaches outside the role: {target!r}"]
return []
def role_use_problems(node, roles, in_list=False):
"""The ways `node` (parsed YAML) uses a role that users() could not see."""
problems = []
if isinstance(node, dict):
if in_list:
problems += _play_roles_problems(node, roles)
for key, value in node.items():
problems += _key_problems(key, value, roles)
problems += role_use_problems(value, roles)
elif isinstance(node, list):
for item in node:
problems += role_use_problems(item, roles, in_list=True)
return problems
ALL = [
"extensions/molecule/image-smoke",
"extensions/molecule/image-smoke-2604",
@@ -83,6 +153,104 @@ class SelectTest(unittest.TestCase):
self.assertEqual(chosen, ALL)
class UsersTest(unittest.TestCase):
SCENARIOS = (
"roles/base/molecule/default",
"roles/_helper/molecule/default",
"roles/service/molecule/default",
"roles/other/molecule/default",
)
def tree(self, root, files):
for rel, text in files.items():
f = pathlib.Path(root, rel)
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text(text)
for s in self.SCENARIOS:
pathlib.Path(root, s).mkdir(parents=True, exist_ok=True)
pathlib.Path(root, s, "molecule.yml").write_text("---\n")
def chain(self, root):
# service uses _helper, _helper uses base; other uses nothing and names itself.
self.tree(
root,
{
"roles/service/tasks/main.yml": "name: mortis.kamino._helper\n",
"roles/_helper/tasks/main.yml": "name: mortis.kamino.base\n",
"roles/base/tasks/main.yml": "---\n",
"roles/other/molecule/default/converge.yml": "mortis.kamino.other\n",
},
)
def test_a_change_selects_its_users_transitively(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
chosen, reason = sel.select(
self.SCENARIOS, ["roles/base/tasks/main.yml"], root
)
self.assertEqual(
sorted(chosen),
[
"roles/_helper/molecule/default",
"roles/base/molecule/default",
"roles/service/molecule/default",
],
)
self.assertIn("their users: _helper, service", reason)
def test_a_user_change_does_not_select_what_it_uses(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
chosen, _reason = sel.select(
self.SCENARIOS, ["roles/service/tasks/main.yml"], root
)
self.assertEqual(chosen, ["roles/service/molecule/default"])
def test_self_and_unknown_names_are_not_uses(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
pathlib.Path(root, "roles/other/tasks").mkdir(parents=True)
pathlib.Path(root, "roles/other/tasks/main.yml").write_text(
"mortis.kamino.nosuchrole\n"
)
self.assertEqual(
sel.users(root), {"_helper": {"service"}, "base": {"_helper"}}
)
chosen, _reason = sel.select(
self.SCENARIOS, ["roles/other/tasks/main.yml"], root
)
self.assertEqual(chosen, ["roles/other/molecule/default"])
def test_a_user_without_a_scenario_fails(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
self.tree(root, {"roles/bare/tasks/main.yml": "mortis.kamino.base\n"})
with self.assertRaisesRegex(ValueError, "bare"):
sel.select(self.SCENARIOS, ["roles/base/tasks/main.yml"], root)
def test_a_deleted_role_still_selects_its_users(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
shutil.rmtree(pathlib.Path(root, "roles/base"))
scenarios = [s for s in self.SCENARIOS if not s.startswith("roles/base/")]
chosen, _reason = sel.select(scenarios, ["roles/base/tasks/main.yml"], root)
self.assertEqual(
sorted(chosen),
["roles/_helper/molecule/default", "roles/service/molecule/default"],
)
def test_cycles_terminate(self):
with tempfile.TemporaryDirectory() as root:
self.chain(root)
pathlib.Path(root, "roles/base/tasks/main.yml").write_text(
"mortis.kamino.service\n"
)
chosen, _reason = sel.select(
self.SCENARIOS, ["roles/base/tasks/main.yml"], root
)
self.assertEqual(len(chosen), 3)
class MainTest(unittest.TestCase):
def setUp(self):
# main() runs git in the current directory: a hook's GIT_DIR must not redirect it.
@@ -193,7 +361,8 @@ class MainTest(unittest.TestCase):
code, out, err = self.run_main(["main"], {"EVENT_NAME": "pull_request"})
self.assertEqual((code, out), (1, []))
self.assertIn(
"::error::changed role without a molecule scenario: newrole", err
"::error::role without a molecule scenario (changed, or a user of a changed role): newrole",
err,
)
def test_deleted_role_is_not_an_error(self):
@@ -272,24 +441,20 @@ class MainTest(unittest.TestCase):
chosen, _reason = sel.select(scenarios, [path], str(REPO))
self.assertEqual(chosen, scenarios, path)
def test_no_role_refers_to_another_role(self):
# The selection assumes roles are independent: a role that includes another would need a
# dependency rule in select(). Fail here instead of silently skipping the other's scenario.
def test_roles_call_each_other_by_full_name_only(self):
# The selection finds a role's users by the text mortis.kamino.<role> (users()). A use
# by a bare or templated name, a meta dependency, or tasks reached by a relative path
# into another role would be one it cannot see, so its users' scenarios would be
# skipped. Fail here instead.
roles = sorted(p.name for p in (REPO / "roles").iterdir() if p.is_dir())
for role in roles:
others = [r for r in roles if r != role]
for path in (REPO / "roles" / role).rglob("*"):
if not path.is_file():
continue
text = path.read_text(errors="ignore")
for other in others:
self.assertNotIn(
f"mortis.kamino.{other}",
text,
f"{path.relative_to(REPO)} refers to {other}",
)
meta = REPO / "roles" / role / "meta" / "main.yml"
if meta.is_file():
for path in sorted((REPO / "roles" / role).rglob("*")):
if path.suffix in (".yml", ".yaml") and path.is_file():
for problem in role_use_problems(
yaml.safe_load(path.read_text()), roles
):
self.fail(f"{path.relative_to(REPO)}: {problem}")
for meta in (REPO / "roles" / role / "meta").glob("main.y*ml"):
data = yaml.safe_load(meta.read_text()) or {}
self.assertEqual(
data.get("dependencies") or [],
@@ -297,6 +462,29 @@ class MainTest(unittest.TestCase):
f"{role} declares role dependencies",
)
def test_role_use_problems_catches_the_hidden_forms(self):
roles = ["ufw", "traefik"]
for doc in (
[{"ansible.builtin.include_role": {"name": "ufw"}}],
[{"import_role": "name=ufw tasks_from=x"}],
[{"include_role": {"name": "{{ dep }}"}}],
[{"include_role": {"name": "mortis.kamino.{{ dep }}"}}],
[{"hosts": "all", "roles": ["ufw"]}],
[{"hosts": "all", "roles": [{"role": "ufw"}]}],
[{"hosts": "all", "roles": [{"name": "{{ r }}"}]}],
[{"ansible.builtin.include_tasks": "../../ufw/tasks/x.yml"}],
[{"import_tasks": {"file": "{{ role_path }}/../ufw/tasks/x.yml"}}],
):
self.assertTrue(role_use_problems(doc, roles), doc)
for doc in (
[{"include_role": {"name": "mortis.kamino.ufw"}}],
[{"hosts": "all", "roles": ["mortis.kamino.traefik"]}],
[{"include_role": {"name": "community.general.thing"}}],
[{"include_tasks": "download.yml"}],
{"roles": "not a play"},
):
self.assertEqual(role_use_problems(doc, roles), [], doc)
def test_literal_ignored_entries_exist(self):
for pattern in sel.IGNORED:
if "*" not in pattern: