From 92b03fca4e0ae626c2a5b5d7520437ac9b898c0f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 14 Nov 2026 18:16:56 +0100 Subject: [PATCH] Architecture gate: named exceptions list (crate, file, ratchet, reason) so a ratchet can be zero outside documented sites; unused or reasonless entries are errors --- architecture.json | 2 ++ scripts/archcheck/cli.py | 6 ++++-- scripts/archcheck/measure.py | 17 ++++++++++++----- scripts/archcheck/rules.py | 18 +++++++++++++++++- scripts/check_architecture_test.py | 16 ++++++++++++++++ 5 files changed, 51 insertions(+), 8 deletions(-) diff --git a/architecture.json b/architecture.json index fc2bbe36..eb6427da 100644 --- a/architecture.json +++ b/architecture.json @@ -49,6 +49,8 @@ "patterns": ["^impl_.*\\.rs$", "_fn\\.rs$", "_[0-9]+(_[0-9]+)*\\.rs$"], "allow": ["^(quantize_)?q[0-9]_[0-9k]\\.rs$"] }, + "_exceptions": "Sites that must stay, so the ratchet is zero outside this list (STRA-338 stage 10). Each entry: crate, file (relative to the crate directory), ratchet (a source_patterns id), reason. The file's hits of that ratchet are not counted; an entry that excuses nothing is an error.", + "exceptions": [], "source_patterns": [ {"id": "env-read", "regex": "\\benv::var(_os)?\\(", "why": "configuration must be parsed once into a Settings struct (S13), not read all over the code"}, {"id": "instant-now", "regex": "\\bInstant::now\\(\\)", "why": "time must come from an injected Clock in core logic (S14)"}, diff --git a/scripts/archcheck/cli.py b/scripts/archcheck/cli.py index f4d70c9e..edfe3e4d 100644 --- a/scripts/archcheck/cli.py +++ b/scripts/archcheck/cli.py @@ -66,9 +66,11 @@ def main(argv, default_root): old = bl.load(baseline_path) packages = measure.load_metadata(root) sizes = measure.file_lines(root, packages) - counts = measure.count_patterns(packages, config["source_patterns"]) + exceptions, excused = config.get("exceptions", []), {} + counts = measure.count_patterns(packages, config["source_patterns"], exceptions, excused) + exception_errors = rules.exception_findings(exceptions, excused, {p["id"] for p in config["source_patterns"]}) names = measure.mechanical_names(root, packages, config.get("mechanical_names", {})) - found = rules.evaluate(packages, config, old, rules.Measured(sizes, counts, names)) + found = rules.evaluate(packages, config, old, rules.Measured(sizes, counts, names, tuple(exception_errors))) if args.report: report(packages, config, sizes, counts) return 0 diff --git a/scripts/archcheck/measure.py b/scripts/archcheck/measure.py index 2fd2c4dd..f20a4929 100644 --- a/scripts/archcheck/measure.py +++ b/scripts/archcheck/measure.py @@ -94,13 +94,16 @@ def _after_block(lines, start): return len(lines) -def count_patterns(packages, patterns): +def count_patterns(packages, patterns, exceptions=(), excused=None): """{":": n} for the non-zero counts, over production code in src/ only - (test files and modules declared under a test cfg are skipped).""" + (test files and modules declared under a test cfg are skipped). A file named by an entry of `exceptions` + ({"crate", "file", "ratchet", "reason"}; `file` is relative to the crate directory) is not counted for that + ratchet; the hits it excused are added to `excused` ({(crate, file, ratchet): n}) when it is given.""" compiled = [(p["id"], re.compile(p["regex"]), bool(p.get("ignore_imports"))) for p in patterns] counts = {} for pkg in packages: - for pid, n in _package_counts(pkg["dir"] / "src", compiled).items(): + skip = {(e["file"], e["ratchet"]) for e in exceptions if e["crate"] == pkg["name"]} + for pid, n in _package_counts(pkg["dir"] / "src", compiled, skip, pkg["name"], excused).items(): counts[f"{pid}:{pkg['name']}"] = n return counts @@ -187,7 +190,7 @@ def _under_test_module(path, test_files): _USE_STATEMENT = re.compile(r"(?m)^[ \t]*(?:pub(?:\([^)]*\))?[ \t]+)?use\b[^;]*;[ \t]*\n?") -def _package_counts(src, compiled): +def _package_counts(src, compiled, skip=frozenset(), crate="", excused=None): totals = {} if not src.is_dir(): return totals @@ -198,8 +201,12 @@ def _package_counts(src, compiled): text = _text(path) rows = production_lines(text) rows_without_imports = production_lines(_USE_STATEMENT.sub("", text)) + relative = path.relative_to(src.parent).as_posix() for pid, rx, ignore_imports in compiled: n = sum(len(rx.findall(row)) for row in (rows_without_imports if ignore_imports else rows)) - if n: + if n and (relative, pid) in skip: + if excused is not None: + excused[(crate, relative, pid)] = n + elif n: totals[pid] = totals.get(pid, 0) + n return totals diff --git a/scripts/archcheck/rules.py b/scripts/archcheck/rules.py index a7e72e06..98e7fd28 100644 --- a/scripts/archcheck/rules.py +++ b/scripts/archcheck/rules.py @@ -126,12 +126,28 @@ def mechanical_findings(names, baseline): return errors, stale +def exception_findings(exceptions, excused, known_ratchets): + """Errors for the `exceptions` list of architecture.json: each needs a reason, a known ratchet and at least one + hit in its file; an entry that excuses nothing is a stale exception and must be removed.""" + errors = [] + for e in exceptions: + label = f"exception {e.get('crate')} {e.get('file')} {e.get('ratchet')}" + if not str(e.get("reason", "")).strip(): + errors.append(f"{label}: an exception needs a reason") + if e.get("ratchet") not in known_ratchets: + errors.append(f"{label}: unknown ratchet") + elif (e.get("crate"), e.get("file"), e.get("ratchet")) not in excused: + errors.append(f"{label}: the file has no such hit any more; remove the exception") + return errors + + @dataclass class Measured: """What was measured in the source tree: file line counts, source pattern counts, mechanical file names.""" sizes: dict counts: dict names: tuple = () + exception_errors: tuple = () def evaluate(packages, config, baseline, measured): @@ -143,6 +159,6 @@ def evaluate(packages, config, baseline, measured): size_errors, size_stale = size_findings(sizes, baseline, config["max_lines"]) ratchet_errors, ratchet_stale = ratchet_findings(counts, baseline) name_errors, name_stale = mechanical_findings(names, baseline) - result.errors += errors + size_errors + ratchet_errors + name_errors + result.errors += errors + size_errors + ratchet_errors + name_errors + list(measured.exception_errors) result.stale = stale + size_stale + ratchet_stale + name_stale return result diff --git a/scripts/check_architecture_test.py b/scripts/check_architecture_test.py index 1fdeea67..72915a28 100644 --- a/scripts/check_architecture_test.py +++ b/scripts/check_architecture_test.py @@ -220,6 +220,22 @@ class Measurement(unittest.TestCase): counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}]) self.assertEqual(counts, {"e:p": 4}) + def test_a_listed_exception_is_not_counted_and_an_unused_one_is_an_error(self): + with tempfile.TemporaryDirectory() as tmp: + src = pathlib.Path(tmp) / "src" + src.mkdir() + (src / "lib.rs").write_text('let a = env::var("A");\nmod clock;\n') + (src / "clock.rs").write_text('let b = env::var("B");\n') + package = dict(pkg("p"), dir=pathlib.Path(tmp)) + patterns = [{"id": "e", "regex": r"env::var\("}] + listed = {"crate": "p", "file": "src/clock.rs", "ratchet": "e", "reason": "the clock adapter"} + excused = {} + counts = measure.count_patterns([package], patterns, [listed], excused) + self.assertEqual((counts, excused), ({"e:p": 1}, {("p", "src/clock.rs", "e"): 1})) + self.assertEqual(rules.exception_findings([listed], excused, {"e"}), []) + unused = dict(listed, file="src/lib.rs", ratchet="x") + self.assertEqual(len(rules.exception_findings([unused, dict(listed, reason="")], excused, {"e"})), 2) + if __name__ == "__main__": unittest.main()