Files
leleka/scripts/check_architecture_test.py
T
Pavlo Ratushnyi 219238cd08 architecture gate: read the whole file after a cfg(test) mod declaration, find static cells by type, 64 new exceptions with reasons (STRA-338)
The scanner stopped at the first '#[cfg(test)] mod x;' of a file, so the code below was invisible. It now skips only the item under a test-only cfg (an inline mod body, a declaration, a fn, a use; any(test, feature) is not test-only) and reads on.

process-global counted the type name OnceLock/LazyLock/OnceCell, which also matched instance fields (six exceptions existed only for that) and missed Atomic*, Mutex, RwLock, Once, Cell and RefCell statics, thread_local! included. It now counts a static whose type is a cell or a workspace type that holds one (derived per crate and its dependencies), and static mut. Eight exceptions that only excused instance fields go; the rest of the file's hits are re-judged.

Newly visible: 123 static cells in 58 files, 15 allow(unused_imports) in 6 files and the engine settings::process() cell (read at about 78 sites). Each gets an exception whose reason starts kept: (the boundary that forces it) or debt: (what removes it); the settings cell is the largest debt and is not removed here because the engine does not compile on Windows. Entries 173 -> 229, baseline stays empty. 11 new self-tests (39 in all).
2026-11-24 08:51:58 +01:00

363 lines
19 KiB
Python

#!/usr/bin/env python3
"""Negative and positive proofs for the architecture gate: each rule must fail on a synthetic violation.
Usage: python3 scripts/check_architecture_test.py (no cargo, no network)
"""
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from archcheck import baseline as bl # noqa: E402
from archcheck import measure, rules # noqa: E402
CONFIG = {
"max_lines": 400,
"adapter_layer": "L3",
"pure_layers": ["L0", "L1"],
"forbidden_in_pure": ["tokio"],
"layers": {"L0": ["api"], "L1": ["lib"], "L2": ["core"], "L3": ["adapter-a", "adapter-b"], "L4": ["host"]},
"adapter_edges": [["adapter-b", "adapter-a"]],
}
EMPTY = {"violations": [], "oversize": {}, "source": {}}
def pkg(name, normal=(), external=()):
return {"name": name, "dir": pathlib.Path(name), "normal": list(normal), "external": list(external)}
def packages(**overrides):
base = {
"api": pkg("api"), "lib": pkg("lib", ["api"]), "core": pkg("core", ["lib"]),
"adapter-a": pkg("adapter-a", ["core"]), "adapter-b": pkg("adapter-b", ["core", "adapter-a"]),
"host": pkg("host", ["adapter-a", "adapter-b", "core"]),
}
base.update(overrides)
return list(base.values())
def run(pkgs, baseline=None, sizes=None, counts=None):
return rules.evaluate(pkgs, CONFIG, baseline or EMPTY, rules.Measured(sizes or {}, counts or {}))
def base(violations=(), oversize=None, source=None):
return {"violations": list(violations), "oversize": oversize or {}, "source": source or {}}
class GraphRules(unittest.TestCase):
def test_clean_graph_passes(self):
found = run(packages())
self.assertEqual((found.errors, found.debt, found.stale), ([], [], []))
def test_upward_edge_fails(self):
found = run(packages(core=pkg("core", ["host"])))
self.assertIn("layer-up core -> host", found.violations)
self.assertEqual(len(found.errors), 1)
def test_core_may_not_depend_on_an_adapter(self):
found = run(packages(core=pkg("core", ["adapter-a"])))
self.assertTrue(any("core (L2) depends on adapter-a (L3)" in e for e in found.errors))
def test_sideways_adapter_edge_fails_unless_listed(self):
found = run(packages(**{"adapter-a": pkg("adapter-a", ["adapter-b"])}))
self.assertIn("adapter-sideways adapter-a -> adapter-b", found.violations)
self.assertEqual(run(packages()).errors, [])
def test_unassigned_package_fails(self):
found = run(packages(extra=pkg("extra")))
self.assertTrue(any("extra has no layer" in e for e in found.errors))
def test_pure_crate_with_forbidden_dependency_fails_but_an_adapter_may_use_it(self):
found = run(packages(lib=pkg("lib", ["api"], ["tokio"])))
self.assertIn("forbidden-dep lib tokio", found.violations)
self.assertEqual(run(packages(**{"adapter-a": pkg("adapter-a", ["core"], ["tokio"])})).errors, [])
def test_baselined_violation_is_debt_and_a_fixed_one_is_stale(self):
known = base(violations=["layer-up core -> host"])
found = run(packages(core=pkg("core", ["host"])), known)
self.assertEqual((found.errors, found.debt), ([], ["layer-up core -> host"]))
self.assertEqual(len(run(packages(), known).stale), 1)
class SizeAndRatchetRules(unittest.TestCase):
def test_new_large_file_fails_and_a_file_at_the_limit_passes(self):
self.assertEqual(len(run(packages(), sizes={"big.rs": 401}).errors), 1)
self.assertEqual(run(packages(), sizes={"ok.rs": 400}).errors, [])
def test_baselined_large_file_may_not_grow_and_shrinking_is_stale(self):
known = base(oversize={"big.rs": 900})
self.assertEqual(run(packages(), known, {"big.rs": 900}).errors, [])
self.assertEqual(len(run(packages(), known, {"big.rs": 901}).errors), 1)
self.assertEqual(len(run(packages(), known, {"big.rs": 700}).stale), 1)
def test_ratchet_may_only_fall(self):
known = base(source={"env-read:host": 10})
self.assertEqual(run(packages(), known, counts={"env-read:host": 10}).errors, [])
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 11}).errors), 1)
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 9}).stale), 1)
def test_new_ratchet_key_starts_at_zero(self):
self.assertEqual(len(run(packages(), counts={"env-read:host": 1}).errors), 1)
class BaselineRewrite(unittest.TestCase):
def test_refuses_increase_and_accepts_decrease(self):
old = base(oversize={"a.rs": 500}, source={"env-read:host": 3})
higher = base(["layer-up a -> b"], {"a.rs": 501}, {"env-read:host": 4})
self.assertEqual(len(bl.raised(old, higher)), 3)
self.assertEqual(bl.raised(old, base(oversize={"a.rs": 450}, source={"env-read:host": 2})), [])
def test_code_that_moved_between_crates_keeps_its_total(self):
old = base(source={"env-read:host": 3})
self.assertEqual(bl.raised(old, base(source={"env-read:other": 3})), [])
def test_a_moved_file_is_accepted_but_a_new_large_one_is_not(self):
old = base(oversize={"src/a.rs": 500})
self.assertEqual(bl.raised(old, base(oversize={"src/sub/a.rs": 500})), [])
self.assertEqual(len(bl.raised(old, base(oversize={"src/sub/a.rs": 501}))), 1)
self.assertEqual(len(bl.raised(old, base(oversize={"src/a.rs": 500, "src/b.rs": 450}))), 1)
def test_a_split_may_add_only_its_module_declaration(self):
old = base(oversize={"src/big.rs": 1000})
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 503, "src/big/tests.rs": 500})), [])
def test_a_split_into_a_same_stem_directory_may_not_gain_lines(self):
old = base(oversize={"src/big.rs": 1000})
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 500, "src/big/part.rs": 480})), [])
self.assertEqual(len(bl.raised(old, base(oversize={"src/big.rs": 600, "src/big/part.rs": 480}))), 1)
class MechanicalNames(unittest.TestCase):
"""A file named by a mechanical split (impl_*, *_fn, numbered) may not be new; the baselined ones only go."""
DOT = chr(92) + ".rs$"
SPEC = {"patterns": ["^impl_.*" + DOT, "_fn" + DOT, "_[0-9]+(_[0-9]+)*" + DOT], "allow": ["^q[0-9]_[0-9]" + DOT]}
def test_a_new_mechanical_name_is_an_error_and_a_baselined_one_is_debt(self):
known = dict(EMPTY, mechanical_names=["src/impl_old.rs"])
found = run(packages(), known).errors
self.assertEqual(found, [])
errors, _ = rules.mechanical_findings(["src/impl_old.rs", "src/impl_new.rs"], known)
self.assertEqual(len(errors), 1)
self.assertIn("src/impl_new.rs", errors[0])
def test_a_file_that_was_renamed_makes_its_baseline_entry_stale(self):
known = dict(EMPTY, mechanical_names=["src/impl_old.rs"])
self.assertEqual(rules.mechanical_findings([], known)[0], [])
self.assertEqual(len(rules.mechanical_findings([], known)[1]), 1)
def test_the_rewrite_may_not_add_a_mechanical_name(self):
old = dict(base(), mechanical_names=["a/impl_x.rs"])
self.assertEqual(bl.raised(old, dict(base(), mechanical_names=[])), [])
self.assertEqual(len(bl.raised(old, dict(base(), mechanical_names=["a/impl_x.rs", "a/b_fn.rs"]))), 1)
def test_the_measurement_matches_the_patterns_and_honours_the_allow_list(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
src.mkdir()
for name in ("impl_a.rs", "b_fn.rs", "c_2.rs", "d_2_3.rs", "q4_0.rs", "plain.rs", "tests.rs"):
(src / name).write_text("")
package = dict(pkg("p"), dir=pathlib.Path(tmp))
found = measure.mechanical_names(pathlib.Path(tmp), [package], self.SPEC)
self.assertEqual(found, ["src/b_fn.rs", "src/c_2.rs", "src/d_2_3.rs", "src/impl_a.rs"])
class Measurement(unittest.TestCase):
def test_an_inline_test_module_is_skipped_and_comments_are_dropped_but_the_code_after_it_counts(self):
text = 'let a = std::env::var("A");\n// env::var("B")\n#[cfg(test)]\nmod t {}\nlet c = env::var("C");\n'
self.assertEqual(measure.production_lines(text), ['let a = std::env::var("A");', 'let c = env::var("C");'])
def test_a_cfg_test_function_is_skipped_as_a_whole_and_the_code_after_it_counts(self):
text = '#[cfg(test)]\nfn only_tests() {\n env::var("T");\n}\nlet a = env::var("A");\n'
self.assertEqual(measure.production_lines(text), ['let a = env::var("A");'])
def test_code_after_a_cfg_test_module_declaration_and_after_an_inline_test_module_counts(self):
text = ('let a = env::var("A");\n#[cfg(test)]\nmod tests;\nlet b = env::var("B");\n'
'#[cfg(test)]\nmod inline {\n let t = env::var("T");\n}\nlet c = env::var("C");\n')
kept = [row for row in measure.production_lines(text) if "env::var" in row]
self.assertEqual(kept, ['let a = env::var("A");', 'let b = env::var("B");', 'let c = env::var("C");'])
def test_an_indented_test_item_is_skipped_up_to_its_own_closing_brace(self):
text = ('impl X {\n #[cfg(test)]\n fn probe() {\n env::var("T");\n }\n'
' fn real() {\n env::var("R");\n }\n}\n')
kept = [row for row in measure.production_lines(text) if "env::var" in row]
self.assertEqual(kept, [' env::var("R");'])
def test_a_test_only_cfg_needs_test_in_every_build_that_compiles_the_item(self):
self.assertTrue(measure.requires_test("#[cfg(test)]"))
self.assertTrue(measure.requires_test('#[cfg(all(test, target_os = "linux"))]'))
self.assertTrue(measure.requires_test("#[cfg(all(\n unix,\n test\n))]"))
self.assertFalse(measure.requires_test('#[cfg(any(test, feature = "testing"))]'))
self.assertFalse(measure.requires_test("#[cfg(not(test))]"))
self.assertFalse(measure.requires_test("#[cfg(all(unix, not(test)))]"))
self.assertFalse(measure.requires_test("#[cfg_attr(test, derive(Debug))]"))
self.assertFalse(measure.requires_test('#[cfg(feature = "test")]'))
def test_an_item_that_is_also_compiled_in_production_stays_visible(self):
text = '#[cfg(any(test, feature = "probe"))]\nfn probe() {\n env::var("P");\n}\n'
self.assertEqual(len(measure.production_lines(text)), 4)
def test_a_file_under_an_inner_cfg_test_attribute_has_no_production_lines(self):
self.assertEqual(measure.production_lines('#![cfg(test)]\nlet a = env::var("A");\n'), [])
def test_a_test_only_import_does_not_hide_the_item_after_it_from_an_import_blind_pattern(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
src.mkdir()
(src / "lib.rs").write_text("#[cfg(test)]\nuse std::sync::OnceLock;\nstatic A: OnceLock<u8> = x;\n")
package = dict(pkg("p"), dir=pathlib.Path(tmp))
pattern = {"id": "g", "regex": r"\bOnceLock\b", "ignore_imports": True}
self.assertEqual(measure.count_patterns([package], [pattern]), {"g:p": 1})
def test_an_inline_module_under_another_test_cfg_is_skipped_but_the_code_after_it_counts(self):
text = ('let a = env::var("A");\n#[cfg(all(test, unix))]\nmod proof {\n let b = env::var("B");\n}\n'
'#[cfg(not(test))]\nmod live {\n let c = env::var("C");\n}\nlet d = env::var("D");\n')
rows = measure.production_lines(text)
self.assertEqual([r for r in rows if "env::var" in r], [
'let a = env::var("A");', ' let c = env::var("C");', 'let d = env::var("D");'])
def test_a_module_declared_inside_a_test_only_file_is_not_production_either(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
(src / "proofs" / "top").mkdir(parents=True)
(src / "lib.rs").write_text('let a = env::var("A");\n#[cfg(test)]\n#[path = "proofs/top.rs"]\nmod top;\n')
top = '#[path = "nested.rs"]\nmod nested;\nmod sibling;\nlet b = env::var("B");\n'
(src / "proofs" / "top.rs").write_text(top)
(src / "proofs" / "nested.rs").write_text('let c = env::var("C");\n')
(src / "proofs" / "top" / "sibling.rs").write_text('let d = env::var("D");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 1})
def test_counts_are_per_crate_and_skip_test_files(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
src.mkdir()
(src / "lib.rs").write_text('let a = env::var("A");\n')
(src / "tests.rs").write_text('let b = env::var("B");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 1})
def test_modules_declared_under_a_test_cfg_are_not_production(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
(src / "a" / "proofs").mkdir(parents=True)
(src / "lib.rs").write_text('mod a;\nmod b;\nlet a = env::var("A");\n')
(src / "b.rs").write_text('let b = env::var("B");\n')
(src / "a.rs").write_text(
'let c = env::var("C");\n#[cfg(not(test))]\nmod live;\n'
'#[cfg(all(\n test,\n target_os = "linux"\n))]\n#[path = "a/proofs/x.rs"]\nmod proof;\n'
'#[cfg(test)]\nmod helper;\n')
(src / "a" / "proofs" / "x.rs").write_text('let d = env::var("D");\n')
(src / "a" / "helper.rs").write_text('let e = env::var("E");\n')
(src / "a" / "live.rs").write_text('let f = env::var("F");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
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)
def test_a_test_module_declaration_with_a_path_attribute_is_not_production(self):
text = "\n".join(["#[cfg(test)]", '#[path = "../tests/x.rs"]', "mod tests;", "let a = 1;"]) + "\n"
self.assertEqual(measure.production_lines(text), ["let a = 1;"])
class ProcessGlobals(unittest.TestCase):
"""The `process-global` pattern of architecture.json: a static cell is a process global, not an instance field."""
@staticmethod
def pattern():
config = json.loads((pathlib.Path(__file__).resolve().parent.parent / "architecture.json").read_text("utf-8"))
return next(p for p in config["source_patterns"] if p["id"] == "process-global")
@classmethod
def count(cls, source):
pattern = cls.pattern()
with tempfile.TemporaryDirectory() as tmp:
(pathlib.Path(tmp) / "src").mkdir()
(pathlib.Path(tmp) / "src" / "lib.rs").write_text(source)
return measure.count_patterns([dict(pkg("p"), dir=pathlib.Path(tmp))], [pattern]).get("process-global:p", 0)
def test_statics_of_every_cell_type_count_also_inside_thread_local(self):
source = "\n".join([
"static A: AtomicU32 = AtomicU32::new(0);",
"static B: std::sync::Mutex<Vec<u8>> = Mutex::new(Vec::new());",
"pub(crate) static C: [AtomicUsize; 4] = [const { AtomicUsize::new(0) }; 4];",
"static D: std::sync::OnceLock<u8> = std::sync::OnceLock::new();",
"thread_local! {",
" static E: RefCell<Option<u8>> = const { RefCell::new(None) };",
" static F: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };",
"}",
"static mut G: u8 = 0;",
])
self.assertEqual(self.count(source), 7)
def test_immutable_statics_lifetimes_instance_fields_and_imports_do_not_count(self):
source = "\n".join([
"use std::sync::{OnceLock, atomic::AtomicU32};",
'static A: &[u8] = b"x";',
"static B: [Entry; 2] = [Entry(1), Entry(2)];",
"static C: [&'static str; 2] = [\"a\", \"b\"];",
"fn name(x: &'static str) -> &'static str { x }",
"struct Archive { handles: OnceLock<Vec<u8>>, hits: AtomicU32 }",
"fn build() -> Archive { Archive { handles: OnceLock::new(), hits: AtomicU32::new(0) } }",
])
self.assertEqual(self.count(source), 0)
def test_a_static_of_a_type_that_holds_a_cell_counts_through_any_number_of_wrappers(self):
source = "\n".join([
"pub struct EnvSwitch { cell: OnceLock<bool>, name: &'static str }",
"pub struct Setting<T> { switch: EnvSwitch, parse: fn(&str) -> T }",
"pub struct Plain { n: u32 }",
"static A: EnvSwitch = EnvSwitch::new(\"A\");",
"static B: Setting<usize> = Setting::new();",
"static C: Plain = Plain { n: 1 };",
])
self.assertEqual(self.count(source), 2)
def test_the_wrapper_type_is_found_in_another_file_of_the_crate_but_not_in_test_code(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
src.mkdir()
(src / "lib.rs").write_text("mod cell;\nstatic A: Lazy2 = Lazy2::new();\nstatic B: Fake = Fake::new();\n")
fake_in_tests = "#[cfg(test)]\nstruct Fake { v: Cell<u8> }\n"
(src / "cell.rs").write_text("pub struct Lazy2 { v: Mutex<u8> }\n" + fake_in_tests)
counts = measure.count_patterns([dict(pkg("p"), dir=pathlib.Path(tmp))], [self.pattern()])
self.assertEqual(counts, {"process-global:p": 1})
def test_a_holder_counts_only_in_the_crates_that_can_name_it_and_a_local_type_shadows_a_dependency_one(self):
sources = {
"low": "pub struct Gate { v: Mutex<u8> }\npub struct Entry { v: Cell<u8> }\n",
"app": "static A: Gate = Gate::new();\nstruct Entry { n: u8 }\nstatic E: [Entry; 1] = [Entry { n: 1 }];\n",
"other": "static B: Gate = Gate::new();\n",
}
pattern = self.pattern()
with tempfile.TemporaryDirectory() as tmp:
packages = []
for name, text in sources.items():
(pathlib.Path(tmp) / name / "src").mkdir(parents=True)
(pathlib.Path(tmp) / name / "src" / "lib.rs").write_text(text)
packages.append(dict(pkg(name, ["low"] if name == "app" else []), dir=pathlib.Path(tmp) / name))
self.assertEqual(measure.count_patterns(packages, [pattern]), {"process-global:app": 1})
if __name__ == "__main__":
unittest.main()