fix(env): keep the .env generator stdlib-only

The env generator runs on the bare bootstrap python, before any
dependency is installed. utils/distros.py reached PyYAML through
utils.cache.yaml, so `python -m cli.meta.env` died with
ModuleNotFoundError on every dev-runtime image that ships python3
without PyYAML.

utils/yaml_bootstrap.load_block reads the block-YAML subset the SPOT
files use with stdlib only. It raises BootstrapYamlError on anything it
cannot parse identically to yaml.safe_load, so meta/distros.yml fails
loud instead of drifting.

The per-line regex lint meant to guard this is gone: one hop of
indirection defeated it and it stayed green while the invariant was
broken. It is replaced by a test that runs the real generator with
every non-stdlib import blocked.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
kevinveenbirkenbachandClaude Opus 5 committed 2026-07-28 19:47:01 +02:00
1 parent 7c83cfb583
commit 79ba511bb7
8 files changed
+420 -78

No files matched your search

+6
View File
@@ -5,6 +5,12 @@
# here exactly once. Consumers read it through utils/distros.py; nothing may
# re-spell a distro list or an image reference locally.
#
# Read by a stdlib block reader on the bare bootstrap python, before PyYAML
# exists. Only plain block mappings and block lists of string scalars are
# supported here. An unquoted scalar must start with a letter, an underscore
# or a slash and must not be a boolean or null word; everything else MUST be
# double-quoted.
#
# images: reference templates rendered by utils/distros.py.
# {slug} comes from this file
# {owner} {repository} {tag} come from default.env, which stays the SPOT
+69
View File
@@ -0,0 +1,69 @@
"""The .env generator must import and run without any third-party module.
The dev-environment suite runs the generator inside a bare distro image,
before any dependency is installed. This probes the whole import closure of
``cli.meta.env`` plus every handler call, with non-stdlib imports blocked.
"""
from __future__ import annotations
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from . import PROJECT_ROOT
PROBE = PROJECT_ROOT / "tests" / "utils" / "bare_bootstrap_probe.py"
GUIDANCE = (
"The .env generator must import and run on the bare bootstrap python, "
"so every module it reaches at import time and at call time has to be "
"stdlib-only. Read SPOT files with utils.cache.files.read_text plus "
"utils.yaml_bootstrap.load_block or a stdlib line parse, never through "
"utils.cache.yaml."
)
class TestBareBootstrap(unittest.TestCase):
def _run(self, overlay: dict[str, str]) -> str:
env = {
k: v
for k, v in os.environ.items()
if not k.startswith(("INFINITO_", "GITHUB_")) and k != "ACT"
}
env.update(overlay)
with tempfile.TemporaryDirectory() as td:
result = subprocess.run(
[
sys.executable,
"-I",
str(PROBE),
str(PROJECT_ROOT),
str(Path(td) / ".env"),
],
env=env,
cwd=str(PROJECT_ROOT),
text=True,
capture_output=True,
check=False,
)
self.assertEqual(
result.returncode,
0,
f"{GUIDANCE}\n\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}",
)
return result.stdout.strip()
def test_generator_runs_without_third_party_modules(self) -> None:
self.assertTrue(int(self._run({})) > 0)
def test_generator_runs_on_the_github_actions_branch(self) -> None:
overlay = {"GITHUB_ACTIONS": "true", "GITHUB_REPOSITORY_OWNER": "acme"}
self.assertTrue(int(self._run(overlay)) > 0)
if __name__ == "__main__":
unittest.main()
@@ -1,74 +0,0 @@
"""Lint guard: env handlers MUST NOT use ``utils.cache.yaml``.
The handlers under ``utils/env/handlers/`` feed the ``.env`` generation,
which bootstraps fresh hosts before PyYAML is installed; importing the
YAML cache there breaks the bootstrap. Read SPOT files with
``utils.cache.files.read_text`` and a stdlib line parse instead (see
``utils/storage/nfs.py`` for the canonical pattern).
Suppress on a per-line basis with a same-line ``# nocheck: <reason>``
marker only when the handler provably never runs in the bootstrap path.
"""
from __future__ import annotations
import re
import unittest
from dataclasses import dataclass
from pathlib import Path
from utils.cache.files import iter_project_files, read_text
from . import PROJECT_ROOT
_HANDLERS_DIR = PROJECT_ROOT / "utils" / "env" / "handlers"
_YAML_CACHE_RE = re.compile(r"\butils\.cache\.yaml\b")
_NOCHECK_RE = re.compile(r"#\s*nocheck\b")
@dataclass(frozen=True)
class Violation:
file: str
line_no: int
detail: str
def _scan_file(path: Path) -> list[Violation]:
violations: list[Violation] = []
rel = path.relative_to(PROJECT_ROOT).as_posix()
for idx, raw in enumerate(read_text(str(path)).splitlines(), 1):
if _NOCHECK_RE.search(raw):
continue
if _YAML_CACHE_RE.search(raw):
violations.append(Violation(rel, idx, raw.strip()))
return violations
class TestNoYamlCacheInEnvHandlers(unittest.TestCase):
def test_env_handlers_dont_use_yaml_cache(self) -> None:
targets = sorted(
Path(p)
for p in iter_project_files(extensions=(".py",))
if Path(p).is_relative_to(_HANDLERS_DIR)
)
self.assertTrue(targets, "no handler modules found to scan")
all_violations: list[Violation] = []
for path in targets:
all_violations.extend(_scan_file(path))
if all_violations:
lines = [
(
f"utils.cache.yaml used in env handlers "
f"({len(all_violations)} violation(s)):"
),
"",
"Env handlers feed the .env generation, which bootstraps fresh hosts before PyYAML is initialised - utils.cache.yaml is unavailable at that point. Use utils.cache.files.read_text with a stdlib line parse instead (canonical pattern: utils/storage/nfs.py). Suppress per line with `# nocheck: <reason>` only when the handler provably never runs in the bootstrap path.",
"",
"Offenders:",
]
lines.extend(f" {v.file}:{v.line_no}: {v.detail}" for v in all_violations)
self.fail("\n".join(lines))
if __name__ == "__main__":
unittest.main()
+167
View File
@@ -0,0 +1,167 @@
"""The stdlib block reader agrees with PyYAML on its subset and rejects the rest."""
from __future__ import annotations
import unittest
import yaml
from utils.cache import PROJECT_ROOT
from utils.cache.files import read_text
from utils.cache.yaml import load_yaml, load_yaml_str
from utils.distros import FILE_META_DISTROS
from utils.yaml_bootstrap import BootstrapYamlError, load_block
IN_SUBSET = (
"a: b\n",
"a:\n b: c\n d: e\n",
'b: "c:d"\n',
"x: quay.io/centos/centos:latest\n",
"a:\n - one\n - two\n",
"# leading comment\na: b # trailing comment\n",
"---\na: b\n",
'tpl: "example.test/{owner}/{slug}:{tag}"\n',
"a:\n b:\n - x\nc: d\n",
)
OUT_OF_SUBSET = (
"a: 1\n",
"a: true\n",
"a: null\n",
"a: [1, 2]\n",
"a: {b: c}\n",
"a: &anchor v\n",
"a: |\n block\n",
"a: 'single'\n",
"a:\nb: v\n",
"a: b\na: c\n",
"a:\n\tb: c\n",
"a: b\n---\nc: d\n",
"a:\n - one\n - two\n",
)
_UNPARSEABLE = object()
TOKENS = (
"1",
"1_000",
"0x10",
"0o17",
".5",
"-1",
"+1",
"1e3",
".inf",
".nan",
"12:30",
"2021-01-01",
"true",
"True",
"On",
"off",
"y",
"n",
"null",
"~",
"b",
"b c",
"b:c",
"b: c",
"b#c",
"b #c",
'"b"',
'"b: c"',
"'b'",
"[1]",
"{a: b}",
"&x v",
"*x",
"!!str v",
"a/b",
"quay.io/c/c:latest",
"-b",
"%y",
"@x",
">-",
"|",
"",
)
TEMPLATES = (
"k: {t}\n",
"{t}: v\n",
"k:\n - {t}\n",
"k:\n {t}: v\n",
"k:\n - {t}\n - z\n",
)
STRUCTURES = (
"",
"\n",
"# only a comment\n",
"---\n",
"matrix:\n - name: arch\n - name: debian\n",
"a:\n- x\n- y\n",
"- a\n- b\n",
"plain\n",
"a: b\nc:\n d: e\n",
"a:\n b: c\n d: e\n",
"a: b\n\n\nc: d\n",
'a: "b" trailing\n',
'a: "b\\nc"\n',
"a: b \n",
"a : b\n",
"a: see this: here\n",
"a:b\n",
"a: # note\n",
)
class TestNoSilentDivergence(unittest.TestCase):
"""Every accepted document parses exactly as PyYAML parses it."""
def test_reader_equals_pyyaml_or_raises(self) -> None:
documents = [tpl.format(t=token) for tpl in TEMPLATES for token in TOKENS]
documents.extend(STRUCTURES)
accepted = 0
for document in documents:
with self.subTest(document=document):
try:
expected = load_yaml_str(document)
except yaml.YAMLError:
expected = _UNPARSEABLE
try:
parsed = load_block(document)
except BootstrapYamlError:
continue
accepted += 1
self.assertEqual(parsed, expected)
self.assertGreater(accepted, 0)
class TestSpotStaysInSubset(unittest.TestCase):
def test_reader_matches_pyyaml_on_the_distro_spot(self) -> None:
path = str(PROJECT_ROOT / FILE_META_DISTROS)
parsed = load_block(read_text(path))
expected = load_yaml(path)
self.assertEqual(parsed, expected)
self.assertEqual(list(parsed["distros"]), list(expected["distros"]))
class TestSupportedSubset(unittest.TestCase):
def test_reader_matches_pyyaml(self) -> None:
for snippet in IN_SUBSET:
with self.subTest(snippet=snippet):
self.assertEqual(load_block(snippet), load_yaml_str(snippet))
class TestRejectedConstructs(unittest.TestCase):
def test_out_of_subset_fails_loud(self) -> None:
for snippet in OUT_OF_SUBSET:
with self.subTest(snippet=snippet), self.assertRaises(BootstrapYamlError):
load_block(snippet)
if __name__ == "__main__":
unittest.main()
+41
View File
@@ -0,0 +1,41 @@
"""Run the .env generator with every non-stdlib, non-repo import blocked.
Executed as a subprocess, never imported. Argv is ``<repo-root> <out-path>``.
A blocked import propagates so the traceback names the offending chain.
"""
from __future__ import annotations
import sys
from pathlib import Path
REPO = Path(sys.argv[1]).resolve()
OUT = Path(sys.argv[2])
sys.path.insert(0, str(REPO))
REPO_TOP = frozenset(
{"cli", "utils", "plugins", "filter_plugins", "lookup_plugins", "module_utils"}
)
STDLIB = frozenset(sys.stdlib_module_names)
class Blocker:
def find_spec(self, fullname, path=None, target=None):
top = fullname.split(".")[0]
if top in STDLIB or top in REPO_TOP:
return
raise ModuleNotFoundError(f"No module named {fullname!r}", name=fullname)
sys.meta_path.insert(0, Blocker())
from cli.meta.env.__main__ import ( # noqa: E402
build_env,
parse_static_env_with_comments,
write_dotenv,
)
static, comments = parse_static_env_with_comments(REPO / "default.env")
eb = build_env(static, repo_root=REPO, comments=comments)
write_dotenv(eb, OUT)
print(len(eb.values))
+6 -3
View File
@@ -17,13 +17,16 @@ the templates.
Keep this module free of Ansible imports and cheap to import: it is pulled
in by the env layer and by ``utils.packages.schema``, which reach contexts
where Ansible is not installed.
where Ansible is not installed. It must also stay importable on the bare
bootstrap python, so the SPOT is read with the stdlib block reader instead
of PyYAML.
"""
from __future__ import annotations
from utils.cache import PROJECT_ROOT
from utils.cache.yaml import load_yaml
from utils.cache.files import read_text
from utils.yaml_bootstrap import load_block
FILE_META_DISTROS: str = "meta/distros.yml"
@@ -37,7 +40,7 @@ class UnknownDistroError(ValueError):
def _doc() -> dict:
return load_yaml(str(PROJECT_ROOT / FILE_META_DISTROS))
return load_block(read_text(str(PROJECT_ROOT / FILE_META_DISTROS)))
def _specs() -> dict[str, dict]:
+6 -1
View File
@@ -49,7 +49,12 @@ def apply(eb: EnvBuilder, ctx: BuildContext) -> None: ...
- A handler MUST NOT import another handler.
Cross-handler data flows through `eb.get(...)` / `eb.set(...)` only.
- A handler MAY import from [parser.py](../parser.py), [runtime.py](../runtime.py), and stdlib.
- A handler MAY import stdlib, [parser.py](../parser.py), [runtime.py](../runtime.py), and any repo module whose own import closure is stdlib-only.
The whole closure MUST import and run on the bare bootstrap python, before any dependency is installed.
`utils.cache.files` and [yaml_bootstrap.py](../../yaml_bootstrap.py) qualify; `utils.cache.yaml` does not, because it imports PyYAML.
Read SPOT files with `utils.cache.files.read_text` plus `utils.yaml_bootstrap.load_block` or a stdlib line parse.
`load_block` accepts block mappings, block lists and string scalars only, and raises `BootstrapYamlError` on everything else, so a SPOT file read this way MUST stay inside that subset.
[test_bare_bootstrap.py](../../../tests/integration/meta/env/test_bare_bootstrap.py) enforces this by running the generator with every non-stdlib import blocked.
- A handler MUST NOT import from [writer.py](../writer.py) or [builder.py](../builder.py) at runtime.
The `EnvBuilder` and `BuildContext` types MAY be referenced under `TYPE_CHECKING` for annotations only.
+125
View File
@@ -0,0 +1,125 @@
"""Stdlib reader for the block-YAML subset the bootstrap SPOT files use.
This is a deliberate second YAML touchpoint outside ``utils.cache.yaml``:
the modules that read the distro SPOT must import on the bare bootstrap
python, which runs the ``.env`` generator before any dependency is
installed, so they cannot reach the PyYAML-backed cache.
Supported: nested block mappings, block sequences of scalars, plain and
double-quoted string scalars, full-line and trailing comments, a single
leading document marker. Every other construct raises
:class:`BootstrapYamlError`, so ``load_block(text)`` either equals
``yaml.safe_load(text)`` or fails loud.
The plain-scalar rule is deliberately narrower than YAML's: a plain scalar
must start with a letter, an underscore or a slash, and may then carry only
``[A-Za-z0-9_./+@:-]`` and spaces. That excludes every leading character
PyYAML's implicit resolvers key off, so no accepted plain scalar can come
back as an int, float, bool, timestamp or null.
"""
from __future__ import annotations
import re
_PLAIN = re.compile(r"^[A-Za-z_/][A-Za-z0-9_./+@:\- ]*$")
_RESERVED = re.compile(r"^(?:true|false|yes|no|on|off|y|n|null)$", re.IGNORECASE)
class BootstrapYamlError(ValueError):
"""Raised for a construct outside the supported block subset."""
def _plain(text: str, lineno: int) -> str:
if not _PLAIN.match(text) or ": " in text or text.endswith(":"):
raise BootstrapYamlError(f"line {lineno}: unsupported plain scalar {text!r}")
if _RESERVED.match(text):
raise BootstrapYamlError(f"line {lineno}: {text!r} is not a string, quote it")
return text
def _scalar(raw: str, lineno: int) -> str:
if raw.startswith('"'):
end = raw.find('"', 1)
if end < 0 or "\\" in raw[1:end]:
raise BootstrapYamlError(
f"line {lineno}: unsupported quoted scalar {raw!r}"
)
trailer = raw[end + 1 :].strip()
if trailer and not trailer.startswith("#"):
raise BootstrapYamlError(f"line {lineno}: trailing text after {raw!r}")
return raw[1:end]
return _plain(raw.split(" #", 1)[0].strip(), lineno)
def load_block(text: str) -> dict:
"""Parse *text* as a block mapping and return it.
Args:
text: YAML source restricted to the supported block subset.
Returns:
The root mapping, with every scalar as a ``str``.
Raises:
BootstrapYamlError: for any construct outside the subset.
"""
root: dict = {}
stack: list[tuple[int, object]] = [(0, root)]
pending: tuple[dict, str, int] | None = None
for lineno, line in enumerate(text.splitlines(), 1):
if "\t" in line:
raise BootstrapYamlError(f"line {lineno}: tab indentation")
body = line.strip()
if not body or body.startswith("#"):
continue
if body == "---":
if lineno != 1:
raise BootstrapYamlError(f"line {lineno}: second document")
continue
indent = len(line) - len(line.lstrip(" "))
if pending is not None:
parent, key, parent_indent = pending
if indent <= parent_indent:
raise BootstrapYamlError(
f"line {lineno}: {key!r} has neither a value nor a block"
)
child: object = [] if body.startswith("- ") else {}
parent[key] = child
stack.append((indent, child))
pending = None
else:
while indent < stack[-1][0]:
stack.pop()
if indent != stack[-1][0]:
raise BootstrapYamlError(f"line {lineno}: unexpected indent")
container = stack[-1][1]
if body.startswith("- "):
if not isinstance(container, list):
raise BootstrapYamlError(f"line {lineno}: sequence entry in a mapping")
container.append(_scalar(body[2:], lineno))
continue
if isinstance(container, list):
raise BootstrapYamlError(f"line {lineno}: mapping entry in a sequence")
key, sep, rest = body.partition(": ")
if not sep:
if not body.endswith(":"):
raise BootstrapYamlError(
f"line {lineno}: not a mapping entry: {body!r}"
)
key, rest = body[:-1], ""
if key != key.strip():
raise BootstrapYamlError(f"line {lineno}: not a mapping entry: {body!r}")
_plain(key, lineno)
if key in container:
raise BootstrapYamlError(f"line {lineno}: duplicate key {key!r}")
rest = rest.strip()
if not rest or rest.startswith("#"):
pending = (container, key, indent)
continue
container[key] = _scalar(rest, lineno)
if pending is not None:
raise BootstrapYamlError(f"{pending[1]!r} has neither a value nor a block")
if not root:
raise BootstrapYamlError("empty document")
return root