From 2ebb94bb22abdb34079e8a24eaeb97d758bc239b Mon Sep 17 00:00:00 2001 From: Yifei Sun Date: Thu, 27 Aug 2026 15:32:31 +0200 Subject: [PATCH] nix,rules: extract selector and prune excluded configs --- pyproject.toml | 3 + src/atelier/nix.py | 134 ++++++++--------------------------------- src/atelier/rules.py | 16 ++++- src/atelier/select.nix | 92 ++++++++++++++++++++++++++++ tests/test_nix.py | 60 +++++++++++++++++- tests/test_rules.py | 23 ++++++- 6 files changed, 214 insertions(+), 114 deletions(-) create mode 100644 src/atelier/select.nix diff --git a/pyproject.toml b/pyproject.toml index a443418..f4fffc1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,6 +10,9 @@ dependencies = ["click"] requires = ["setuptools"] build-backend = "setuptools.build_meta" +[tool.setuptools.package-data] +atelier = ["*.nix"] + [dependency-groups] dev = ["pytest"] diff --git a/src/atelier/nix.py b/src/atelier/nix.py index bdd3da7..790c976 100644 --- a/src/atelier/nix.py +++ b/src/atelier/nix.py @@ -2,6 +2,7 @@ import json import re import subprocess from collections.abc import Iterable, Mapping, Sequence +from importlib import resources from typing import Any from atelier.types import ( @@ -17,97 +18,9 @@ from atelier.types import ( _SKIP_RE = re.compile(SKIP_PATTERN, re.IGNORECASE) -# embedded nix that roots the requested output sets into one attrset for -# nix-eval-jobs to recurse -# per system sets become "." = sanitize flake.. -# config sets become "" = mapAttrs toplevel flake. -# leaf sets become "." = flake.. (a drv) -# per system sets are sanitized first: a re-exported nixpkgs package set carries -# scope plumbing (the whole `lib`, callPackage/newScope functions, a self -# referential alias) that force-recurse would otherwise dive into, burning the -# runner's memory until it is OOM killed. sanitize prunes that plumbing and bounds -# the recursion to the include globs' depth, leaving only buildable leaves. -# the @TOKENS@ are replaced with allowlisted nix string lists, never raw input -_SELECT_TEMPLATE = r"""flake: -let - o = flake.outputs; - systems = [ @SYSTEMS@ ]; - perSystemSets = [ @PER_SYSTEM@ ]; - configSets = [ @CONFIG@ ]; - leafSets = [ @LEAF@ ]; - # nested exclude trees per set and rooted system, "*" rules already folded - # into each concrete system by the generator - # a true leaf drops the attribute and everything below it before recursion - # an attrset descends alongside the scope so nix-eval-jobs never forces - # (and never fetches or builds) a manually excluded attribute at any depth - excludes = { @EXCLUDES@ }; - # the deepest attribute path the include globs can match; recursion below it can - # never be selected, so it stops there (a `**` glob raises this to a hard cap). - # a per system set roots at "." (two path segments), so its children - # are at depth three and the remaining attrset recursion budget is maxDepth - 3 - maxDepth = @MAXDEPTH@; - startDepth = if maxDepth > 3 then maxDepth - 3 else 0; - # scope-internal attrset names that are never buildable; function valued plumbing - # is dropped structurally below, so this only names the attrset valued plumbing - denylist = [ @DENYLIST@ ]; - # prune scope plumbing before nix-eval-jobs force-recurses: keep derivations as - # leaves, drop functions (callPackage, newScope, ...) and self referential - # aliases (recurseForDerivations = false), recurse plain attrsets only while the - # include depth can still match, and keep an attr that throws on classification - # so nix-eval-jobs reports it as that attribute's own eval error rather than - # dropping it silently. forcing a child to classify it stays inside tryEval, so - # a broken attribute cannot abort the whole evaluation - # excl is this level's exclude tree, its true entries are removed before any - # probe can force them and its subtrees descend with the recursion - sanitize = remaining: excl: set: - let - dropped = builtins.filter (n: excl.${n} == true) (builtins.attrNames excl); - cleaned = builtins.removeAttrs set (denylist ++ dropped); - in builtins.listToAttrs (builtins.concatMap (name: - let - raw = cleaned.${name}; - probe = builtins.tryEval ( - if builtins.isFunction raw then "fn" - else if (raw.type or null) == "derivation" then "drv" - else if builtins.isAttrs raw then - (if (raw.recurseForDerivations or true) == false then "norec" else "attrs") - else "other"); - kind = if probe.success then probe.value else "throws"; - in - if kind == "drv" || kind == "throws" - then [ { inherit name; value = raw; } ] - else if kind == "attrs" && remaining > 0 - then [ { inherit name; value = sanitize (remaining - 1) (excl.${name} or { }) raw; } ] - else [ ] - ) (builtins.attrNames cleaned)); - ps = builtins.foldl' (acc: set: - builtins.foldl' (a: sys: - if (o ? ${set}) && (o.${set} ? ${sys}) - then a // { "${set}.${sys}" = sanitize startDepth (excludes.${set}.${sys} or { }) o.${set}.${sys}; } - else a - ) acc systems - ) { } perSystemSets; - cs = builtins.foldl' (acc: set: - if o ? ${set} - then acc // { "${set}" = builtins.mapAttrs (_: c: c.config.system.build.toplevel) o.${set}; } - else acc - ) { } configSets; - # a leaf set's system attribute is the derivation itself, so it roots - # directly with nothing below it to recurse into or prune. a non derivation - # value (a schema violation) throws lazily so it surfaces as that attribute's - # eval error instead of being recursed into and silently dropped - ls = builtins.foldl' (acc: set: - builtins.foldl' (a: sys: - if (o ? ${set}) && (o.${set} ? ${sys}) - then a // { "${set}.${sys}" = - let v = o.${set}.${sys}; in - if (v.type or null) == "derivation" then v - else throw "flake output ${set}.${sys} is not a derivation"; } - else a - ) acc systems - ) { } leafSets; -in ps // cs // ls -""" +# quoted placeholders keep select.nix parseable before substitution +# generated literals contain only allowlisted or escaped values +_SELECT_TEMPLATE = (resources.files("atelier") / "select.nix").read_text() def _nix_str(value: str) -> str: @@ -154,15 +67,18 @@ def _nix_tree(tree: Mapping[str, Any]) -> str: def _nix_excludes( excludes: Mapping[str, Mapping[str, Mapping[str, Any]]], systems: Sequence[str] ) -> str: - """Render ``"set" = { "sys" = ; ... };`` for the ``excludes`` attrset. + """Render exclude trees as a Nix attrset. - A ``"*"`` entry (drop from every system) is folded into each requested - system here, so the embedded nix reads exactly one tree per rooted - ``.`` and never merges. + Per system sets contain one tree per requested system after folding ``"*"``. + Configuration sets contain the flat ``"*"`` host tree. """ sets = [] for set_name, by_system in sorted(excludes.items()): star = by_system.get("*", {}) + if set_name in CONFIG_SETS: + if star: + sets.append(f"{_nix_str(set_name)} = {_nix_tree(star)};") + continue pairs = [] for system in systems: tree = _merge_trees(by_system.get(system, {}), star) @@ -170,7 +86,8 @@ def _nix_excludes( pairs.append(f"{_nix_str(system)} = {_nix_tree(tree)};") if pairs: sets.append(f"{_nix_str(set_name)} = {{ {' '.join(pairs)} }};") - return " ".join(sets) + rendered = " ".join(sets) + return f"{{ {rendered} }}" if rendered else "{ }" def _build_select( @@ -181,9 +98,7 @@ def _build_select( excludes: Mapping[str, Mapping[str, Mapping[str, Any]]] | None = None, max_depth: int = MAX_RECURSE_DEPTH, ) -> str: - # fail closed if an unallowlisted value ever reaches the embedded nix - # the discover layer already filters these, this guards against a future - # refactor dropping that filtering and allowing nix injection + # revalidate discovery values before embedding them in the expression for system in systems: if system not in RUNNERS: raise ValueError(f"unknown system {system!r}") @@ -195,19 +110,20 @@ def _build_select( ): raise ValueError(f"unknown output set {output!r}") trees = excludes or {} - # set names are allowlisted, tree names are escaped (they are arbitrary) + # set names are allowlisted and attribute names are escaped for output in trees: - if output not in PER_SYSTEM_SETS: + if output not in PER_SYSTEM_SETS and output not in CONFIG_SETS: raise ValueError(f"unknown output set {output!r}") return ( - _SELECT_TEMPLATE.replace("@SYSTEMS@", _nix_list(systems)) - .replace("@PER_SYSTEM@", _nix_list(per_system_sets)) - .replace("@CONFIG@", _nix_list(config_sets)) - .replace("@LEAF@", _nix_list(leaf_sets)) - .replace("@EXCLUDES@", _nix_excludes(trees, systems)) - # an int, so it cannot carry an injection; clamped to the hard cap - .replace("@MAXDEPTH@", str(min(int(max_depth), MAX_RECURSE_DEPTH))) - .replace("@DENYLIST@", _nix_list(SCOPE_DENYLIST)) + _SELECT_TEMPLATE.replace('"@SYSTEMS@"', _nix_list(systems)) + .replace('"@PER_SYSTEM@"', _nix_list(per_system_sets)) + .replace('"@CONFIG@"', _nix_list(config_sets)) + .replace('"@LEAF@"', _nix_list(leaf_sets)) + # max_depth is an integer clamped to the hard cap + .replace('"@MAXDEPTH@"', str(min(int(max_depth), MAX_RECURSE_DEPTH))) + .replace('"@DENYLIST@"', _nix_list(SCOPE_DENYLIST)) + # replace arbitrary names last so names matching tokens stay literal + .replace('"@EXCLUDES@"', _nix_excludes(trees, systems)) ) diff --git a/src/atelier/rules.py b/src/atelier/rules.py index ec00e26..f422f25 100644 --- a/src/atelier/rules.py +++ b/src/atelier/rules.py @@ -5,6 +5,7 @@ from pathlib import Path from typing import Any from atelier.types import ( + CONFIG_SETS, DEFAULT_INCLUDE, DEFAULT_SYSTEMS, MAX_RECURSE_DEPTH, @@ -134,6 +135,10 @@ def prunable_excludes(rules: Rules) -> dict[str, dict[str, dict[str, Any]]]: nix-eval-jobs never forces, fetches, or builds an excluded attribute. Any other glob stays a post-eval filter. + A literal config host (``.``), optionally followed by ``**``, + is stored in the ``"*"`` tree because hosts have no system dimension. Other + config patterns remain filters applied after evaluation. + Shape: ``{set: {("*" | system): tree}}`` where a tree maps an attribute name to ``True`` (drop it and everything below) or to a subtree to descend into. ``True`` wins over a subtree when rules overlap, since dropping the parent @@ -142,10 +147,17 @@ def prunable_excludes(rules: Rules) -> dict[str, dict[str, dict[str, Any]]]: out: dict[str, dict[str, dict[str, Any]]] = {} for pattern in rules.exclude: parts = pattern.split(".") + if parts[0] in CONFIG_SETS: + path = parts[1:] + if path and path[-1] == "**": + path = path[:-1] + if len(path) == 1 and _GLOB_CHARS.isdisjoint(path[0]): + out.setdefault(parts[0], {}).setdefault("*", {})[path[0]] = True + continue if len(parts) < 3 or parts[0] not in PER_SYSTEM_SETS: continue system = parts[1] - if system != "*" and _GLOB_CHARS & set(system): + if system != "*" and not _GLOB_CHARS.isdisjoint(system): continue path = parts[2:] # a trailing ** means drop the parent attrset wholesale @@ -153,7 +165,7 @@ def prunable_excludes(rules: Rules) -> dict[str, dict[str, dict[str, Any]]]: # system root would mean not rooting it at all if path[-1] == "**": path = path[:-1] - if not path or any(_GLOB_CHARS & set(seg) for seg in path): + if not path or any(not _GLOB_CHARS.isdisjoint(seg) for seg in path): continue node = out.setdefault(parts[0], {}).setdefault(system, {}) for seg in path[:-1]: diff --git a/src/atelier/select.nix b/src/atelier/select.nix new file mode 100644 index 0000000..de209d3 --- /dev/null +++ b/src/atelier/select.nix @@ -0,0 +1,92 @@ +# roots requested outputs for nix-eval-jobs +# quoted placeholders keep this template parseable before substitution +# generated literals contain only allowlisted or escaped values +flake: +let + o = flake.outputs; + systems = [ "@SYSTEMS@" ]; + perSystemSets = [ "@PER_SYSTEM@" ]; + configSets = [ "@CONFIG@" ]; + leafSets = [ "@LEAF@" ]; + # system entries contain concrete trees after "*" folding + # configuration entries contain flat host trees + excludes = "@EXCLUDES@"; + # recursion below the deepest include path cannot produce a selected job + maxDepth = "@MAXDEPTH@"; + startDepth = if maxDepth > 3 then maxDepth - 3 else 0; + # attrset scope plumbing that cannot contain buildable leaves + denylist = [ "@DENYLIST@" ]; + dropped = excl: builtins.filter (n: excl.${n} == true) (builtins.attrNames excl); + # remove excludes before probing values so excluded thunks are never forced + # failed probes stay as leaves for nix-eval-jobs to report + # attrsets recurse only within the include depth budget + sanitize = remaining: excl: set: + let + cleaned = builtins.removeAttrs set (denylist ++ dropped excl); + in + builtins.listToAttrs (builtins.concatMap + (name: + let + raw = cleaned.${name}; + probe = builtins.tryEval ( + if builtins.isFunction raw then "fn" + else if (raw.type or null) == "derivation" then "drv" + else if builtins.isAttrs raw then + (if (raw.recurseForDerivations or true) == false then "norec" else "attrs") + else "other" + ); + kind = if probe.success then probe.value else "throws"; + in + if kind == "drv" || kind == "throws" + then [{ inherit name; value = raw; }] + else if kind == "attrs" && remaining > 0 + then [{ inherit name; value = sanitize (remaining - 1) (excl.${name} or { }) raw; }] + else [ ] + ) + (builtins.attrNames cleaned)); + ps = builtins.foldl' + (acc: set: + builtins.foldl' + (a: sys: + if (o ? ${set}) && (o.${set} ? ${sys}) + then a // { "${set}.${sys}" = sanitize startDepth (excludes.${set}.${sys} or { }) o.${set}.${sys}; } + else a + ) + acc + systems + ) + { } + perSystemSets; + # remove excluded hosts before mapAttrs can force their configurations + cs = builtins.foldl' + (acc: set: + if o ? ${set} + then acc // { + "${set}" = builtins.mapAttrs (_: c: c.config.system.build.toplevel) + (builtins.removeAttrs o.${set} (dropped (excludes.${set} or { }))); + } + else acc + ) + { } + configSets; + # leaf set values must be derivations and cannot be recursively sanitized + ls = builtins.foldl' + (acc: set: + builtins.foldl' + (a: sys: + if (o ? ${set}) && (o.${set} ? ${sys}) + then a // { + "${set}.${sys}" = + let v = o.${set}.${sys}; in + if (v.type or null) == "derivation" then v + else throw "flake output ${set}.${sys} is not a derivation"; + } + else a + ) + acc + systems + ) + { } + leafSets; +in +ps // cs // ls diff --git a/tests/test_nix.py b/tests/test_nix.py index 1bc961c..93db487 100644 --- a/tests/test_nix.py +++ b/tests/test_nix.py @@ -243,6 +243,8 @@ def test_build_select_prunes_excluded_trees() -> None: assert "cider-2" not in expr + + def test_build_select_escapes_exclude_names() -> None: # a crafted attribute name must stay inside its nix string, not break out expr = _build_select( @@ -284,7 +286,11 @@ def test_select_drops_excluded_subtrees_without_forcing() -> None: [], excludes={ "legacyPackages": { - "*": {"spotify": True, "ocamlPackages": {"yocaml_unix": True}} + "*": { + "@MAXDEPTH@": True, + "spotify": True, + "ocamlPackages": {"yocaml_unix": True}, + } } }, ) @@ -292,6 +298,7 @@ def test_select_drops_excluded_subtrees_without_forcing() -> None: { outputs.legacyPackages.x86_64-linux = { caddy = { type = "derivation"; name = "caddy"; }; + "@MAXDEPTH@" = throw "forced a token-shaped excluded attribute"; spotify = throw "forced an excluded attribute"; ocamlPackages = { yocaml = { type = "derivation"; name = "yocaml"; }; @@ -314,3 +321,54 @@ def test_select_drops_excluded_subtrees_without_forcing() -> None: "top": ["caddy", "ocamlPackages"], "ocaml": ["yocaml"], } + + +def test_select_drops_excluded_configs_without_forcing() -> None: + import json + import shutil + import subprocess + + import pytest + + if shutil.which("nix") is None: + pytest.skip("nix not on PATH") + select = _build_select( + ["x86_64-linux"], + [], + ["nixosConfigurations"], + excludes={"nixosConfigurations": {"*": {"iso": True}}}, + ) + flake = """ + { + outputs.nixosConfigurations = { + baldy.config.system.build.toplevel = { type = "derivation"; name = "toplevel"; }; + iso = throw "forced an excluded configuration"; + }; + } + """ + expr = f""" + let s = ({select}) ({flake}); r = s.nixosConfigurations; in + {{ hosts = builtins.attrNames r; kept = r.baldy.name; }} + """ + proc = subprocess.run( + ["nix", "eval", "--json", "--expr", expr], + capture_output=True, + text=True, + check=True, + ) + assert json.loads(proc.stdout) == {"hosts": ["baldy"], "kept": "toplevel"} + + +def test_select_template_resource_parses() -> None: + import shutil + import subprocess + from importlib import resources + + import pytest + + if shutil.which("nix-instantiate") is None: + pytest.skip("nix-instantiate not on PATH") + with resources.as_file(resources.files("atelier") / "select.nix") as path: + subprocess.run( + ["nix-instantiate", "--parse", str(path)], capture_output=True, check=True + ) diff --git a/tests/test_rules.py b/tests/test_rules.py index 42ba25c..4dc9235 100644 --- a/tests/test_rules.py +++ b/tests/test_rules.py @@ -195,14 +195,33 @@ def test_prunable_excludes_groups_by_set_and_system() -> None: "legacyPackages.aarch64-darwin.bird3", # specific system, prunable "legacyPackages.*.ripe-atlas-*", # glob leaf, stays a post filter "legacyPackages.*.ocamlPackages.*", # glob descendant, stays a post filter - "nixosConfigurations.host", # not a per system set + "nixosConfigurations.host", # config set, hosts collect under "*" ), ) assert prunable_excludes(rules) == { "legacyPackages": { "*": {"spotify": True, "verus": True}, "aarch64-darwin": {"bird3": True}, - } + }, + "nixosConfigurations": {"*": {"host": True}}, + } + + +def test_prunable_excludes_config_hosts() -> None: + rules = Rules( + systems=(), + include=(), + exclude=( + "nixosConfigurations.iso", + "darwinConfigurations.laptop.**", + "nixosConfigurations.cloud-*", # glob host, stays a post filter + "nixosConfigurations.iso.config", # deeper than a host, prunes nothing + "nixosConfigurations.**", # whole set root, stays a post filter + ), + ) + assert prunable_excludes(rules) == { + "nixosConfigurations": {"*": {"iso": True}}, + "darwinConfigurations": {"*": {"laptop": True}}, } -- knotmirror 0.0.1