Coverage for scripts/library_gate.py: 100%
124 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""The library gate (V6.6.4): every public function or class in a shipped package is either in `aether_quant` or listed with a reason.
3`aether_quant` is the toolkit people import. It was updated by hand, so a new capability could ship without reaching it. This reads the source with `ast` and imports nothing, so it runs in
4a pre-commit hook in about a second, and CI runs the same check. It fails when:
61. `aether_quant/*.py` and the list in `tests/test_aether_quant_api.py` or `scripts/wheel_smoke.py::check_library` disagree about which facade modules exist;
72. a public name in a shipped package is not exported by any facade and not listed in `tests/data/aether_quant_unexported.json`;
83. that file lists a name that is now exported or no longer exists (so the backlog can only shrink), or its legacy list grows past `LEGACY_CEILING`.
10A public name is a top-level `def` or `class` without a leading underscore. Names are matched without their module, because the facades import through packages as well as through modules.
11Lower `LEGACY_CEILING` whenever the legacy list shrinks; never raise it. A new name that stays out gets an entry under `unexported` with a one-line reason.
13 python scripts/library_gate.py # exit 1 with the violations
14 python scripts/library_gate.py --report # counts only
15"""
17from __future__ import annotations
19import ast
20import fnmatch
21import json
22import re
23import sys
24from collections.abc import Iterable, Mapping
25from pathlib import Path
27ROOT = Path(__file__).resolve().parents[1]
28ALLOWLIST = ROOT / "tests" / "data" / "aether_quant_unexported.json"
29LEGACY_CEILING = 0 # V6.6.7: the backlog of V6.6.4 (288) is gone, every name exported or explained; it stays 0
32def shipped_roots(root: Path = ROOT) -> tuple[list[str], list[str]]:
33 """(packages, top-level modules) from pyproject.toml, as the wheel ships them."""
34 text = (root / "pyproject.toml").read_text(encoding="utf-8")
35 packages = re.search(r"^packages\s*=\s*\[(.*?)\]", text, re.M | re.S)
36 modules = re.search(r"^py-modules\s*=\s*\[(.*?)\]", text, re.M | re.S)
37 names = lambda match: re.findall(r'"([^"]+)"', match.group(1)) if match else [] # noqa: E731
38 return [name for name in names(packages) if name != "aether_quant"], names(modules)
41def _public_defs_in(path: Path) -> set[str]:
42 tree = ast.parse(path.read_text(encoding="utf-8"))
43 return {node.name for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and not node.name.startswith("_")}
46def public_defs(root: Path = ROOT) -> dict[str, set[str]]:
47 """{dotted module: its public top-level names}, over every shipped package and top-level module."""
48 packages, modules = shipped_roots(root)
49 found: dict[str, set[str]] = {}
50 for name in modules:
51 path = root / f"{name}.py"
52 if path.exists():
53 found[name] = _public_defs_in(path)
54 for package in packages:
55 base = root / package
56 if not base.exists():
57 continue
58 for path in sorted(base.rglob("*.py")):
59 if "__pycache__" in path.parts:
60 continue
61 relative = path.relative_to(root).with_suffix("")
62 dotted = ".".join(relative.parts[:-1] if relative.name == "__init__" else relative.parts)
63 names = _public_defs_in(path)
64 if names:
65 found[dotted] = names
66 return found
69def facade_modules(root: Path = ROOT) -> set[str]:
70 return {path.stem for path in (root / "aether_quant").glob("*.py") if path.stem != "__init__"}
73def facade_exports(root: Path = ROOT) -> set[str]:
74 """Every name a facade exports: its `__all__` strings and the original names it imports (an alias counts as the name it re-exports)."""
75 exported: set[str] = set()
76 for path in (root / "aether_quant").glob("*.py"):
77 if path.stem == "__init__":
78 continue
79 tree = ast.parse(path.read_text(encoding="utf-8"))
80 for node in ast.walk(tree):
81 if isinstance(node, ast.ImportFrom):
82 exported.update(alias.name for alias in node.names)
83 elif (
84 isinstance(node, ast.Assign) and any(isinstance(target, ast.Name) and target.id == "__all__" for target in node.targets)
85 and isinstance(node.value, (ast.List, ast.Tuple))
86 ):
87 exported.update(element.value for element in node.value.elts if isinstance(element, ast.Constant) and isinstance(element.value, str))
88 return exported
91def api_test_modules(root: Path = ROOT) -> list[str]:
92 """The `MODULES` tuple of tests/test_aether_quant_api.py, read without importing it."""
93 tree = ast.parse((root / "tests" / "test_aether_quant_api.py").read_text(encoding="utf-8"))
94 for node in tree.body:
95 if isinstance(node, ast.Assign) and any(isinstance(target, ast.Name) and target.id == "MODULES" for target in node.targets):
96 return [element.value for element in node.value.elts if isinstance(element, ast.Constant)]
97 return []
100def wheel_check_modules(root: Path = ROOT) -> list[str]:
101 """The keys of the `checks` dict in scripts/wheel_smoke.py::check_library: the modules the built wheel calls once each."""
102 tree = ast.parse((root / "scripts" / "wheel_smoke.py").read_text(encoding="utf-8"))
103 for function in ast.walk(tree):
104 if isinstance(function, ast.FunctionDef) and function.name == "check_library":
105 for node in ast.walk(function):
106 if isinstance(node, ast.Assign) and any(isinstance(target, ast.Name) and target.id == "checks" for target in node.targets) and isinstance(node.value, ast.Dict):
107 return [key.value for key in node.value.keys if isinstance(key, ast.Constant)]
108 return []
111def load_allowlist(path: Path = ALLOWLIST) -> dict:
112 if not path.exists():
113 return {"modules": {}, "unexported": {}, "legacy_names": []}
114 return json.loads(path.read_text(encoding="utf-8"))
117def _module_excluded(module: str, patterns: Iterable[str]) -> bool:
118 return any(fnmatch.fnmatchcase(module, pattern) for pattern in patterns)
121def unexported(root: Path = ROOT, allow: Mapping | None = None) -> list[str]:
122 """Qualified `module:name` of every public name that no facade exports and no module-level exclusion covers."""
123 allow = allow if allow is not None else load_allowlist(root / "tests" / "data" / "aether_quant_unexported.json")
124 exported = facade_exports(root)
125 out = []
126 for module, names in public_defs(root).items():
127 if _module_excluded(module, (allow.get("modules") or {}).keys()):
128 continue
129 out.extend(f"{module}:{name}" for name in sorted(names) if name not in exported)
130 return sorted(out)
133def check(root: Path = ROOT, allow: Mapping | None = None, *, ceiling: int | None = None, listed_modules: Iterable[str] | None = None, wheel_modules: Iterable[str] | None = None) -> list[str]:
134 """The violations, readable. Empty means the library is up to date."""
135 allow = allow if allow is not None else load_allowlist(root / "tests" / "data" / "aether_quant_unexported.json")
136 ceiling = LEGACY_CEILING if ceiling is None else ceiling
137 problems: list[str] = []
138 modules = facade_modules(root)
139 for label, other in (("tests/test_aether_quant_api.py MODULES", listed_modules), ("scripts/wheel_smoke.py check_library", wheel_modules)):
140 if other is not None and set(other) != modules:
141 problems.append(f"aether_quant/*.py and {label} disagree: only in files {sorted(modules - set(other))}, only in {label} {sorted(set(other) - modules)}")
142 missing = unexported(root, allow)
143 known = set(allow.get("unexported") or {}) | set(allow.get("legacy_names") or [])
144 for name in missing:
145 if name not in known:
146 problems.append(f"{name} is public but not in aether_quant: export it from a facade, or add it to tests/data/aether_quant_unexported.json under \"unexported\" with a reason")
147 current = set(missing)
148 for name in sorted(known - current):
149 problems.append(f"{name} is listed in tests/data/aether_quant_unexported.json but is now exported or gone: remove the entry")
150 for name, reason in (allow.get("unexported") or {}).items():
151 if not str(reason).strip():
152 problems.append(f"{name} is listed under \"unexported\" without a reason")
153 legacy = list(allow.get("legacy_names") or [])
154 if len(legacy) > ceiling:
155 problems.append(f"the legacy list holds {len(legacy)} names, above the ceiling {ceiling}: it can only shrink")
156 return problems
159def main(argv: list[str] | None = None) -> int:
160 args = list(sys.argv[1:] if argv is None else argv)
161 allow = load_allowlist()
162 if "--report" in args:
163 packages, modules = shipped_roots()
164 defs = public_defs()
165 count = sum(len(names) for names in defs.values())
166 print(json.dumps({
167 "facade_modules": len(facade_modules()), "facade_names": len(facade_exports()), "public_defs": count, "unexported_now": len(unexported(ROOT, allow)),
168 "legacy_listed": len(allow.get("legacy_names") or []), "deliberate_listed": len(allow.get("unexported") or {}), "module_exclusions": len(allow.get("modules") or {}),
169 "packages": len(packages), "top_level_modules": len(modules), "ceiling": LEGACY_CEILING,
170 }, indent=1))
171 return 0
172 problems = check(ROOT, allow, listed_modules=api_test_modules(), wheel_modules=wheel_check_modules())
173 for line in problems:
174 print(f"library gate: {line}", file=sys.stderr)
175 if problems:
176 print(f"library gate: {len(problems)} problem(s); aether_quant must be updated with this change", file=sys.stderr)
177 return 1
178 return 0
181if __name__ == "__main__":
182 raise SystemExit(main())