rust_bench_cuda.rs and the native_expert_parity bin (the only users of leleka-cuda-driver in the CPU expert adapter) become the new tool crate crates/native-parity-bench (L4, cargo-checked in the product gate). leleka-native-cpu-expert no longer depends on leleka-cuda-driver; the architecture baseline drops that violation. Code moved byte-for-byte except the use paths. Verified (WSL x86_64-linux): cargo check --all-targets for the new crate, native-cpu-expert and leleka-runtime; cargo test -p leleka-native-cpu-expert all ok (22+2+4+... tests, 0 failed); check-architecture and check-ci-coverage pass.
273 lines
13 KiB
Python
273 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""Dependency-direction and size gate for the hexagonal architecture (LeaseVibe STRA-338, ADR on that item).
|
|
|
|
Rules, all read from `architecture.json` (the policy) and `architecture-baseline.json` (the debt that exists today):
|
|
|
|
layers every workspace package has exactly one layer (L0 contract .. L4 host); a normal dependency must point to the
|
|
same or a LOWER layer. A higher-layer edge is a violation.
|
|
adapters inside L3 a crate may depend on another L3 crate only through an edge listed in "adapter_edges"
|
|
(adapters point inward to ports, not sideways to each other).
|
|
pure packages in "pure_layers" (L0, L1) must not use the "forbidden_in_pure" external crates (async runtime, HTTP, ...).
|
|
size no .rs file over "max_lines"; a file already over it may not grow beyond its baseline entry.
|
|
ratchet counts of "source_patterns" (env reads, Instant::now, #[path] includes, process globals, dyn) per crate may only fall.
|
|
|
|
A violation that is listed in the baseline is reported as debt and does not fail. A baseline entry that no longer applies is
|
|
reported as "stale" (run --update-baseline to drop it). The baseline can only be lowered with --update-baseline; raising it needs
|
|
--allow-increase and is visible in review. Pure stdlib Python, no network, no GPU; it is a build-time check, never part of serving.
|
|
|
|
Usage:
|
|
scripts/check-architecture.py check (exit 1 on a new violation)
|
|
scripts/check-architecture.py --update-baseline rewrite the baseline to the current state; refuses to raise any number
|
|
scripts/check-architecture.py --update-baseline --allow-increase
|
|
scripts/check-architecture.py --report print the layer graph, the oversize census and the ratchet counts
|
|
"""
|
|
import argparse
|
|
import json
|
|
import pathlib
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
|
|
CONFIG = "architecture.json"
|
|
BASELINE = "architecture-baseline.json"
|
|
|
|
|
|
def load_metadata(root):
|
|
out = subprocess.run(["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"],
|
|
cwd=root, check=True, capture_output=True, text=True).stdout
|
|
meta = json.loads(out)
|
|
packages = []
|
|
internal = {p["name"] for p in meta["packages"]}
|
|
for p in meta["packages"]:
|
|
packages.append({
|
|
"name": p["name"],
|
|
"dir": pathlib.Path(p["manifest_path"]).parent,
|
|
"normal": sorted({d["name"] for d in p["dependencies"] if d["kind"] is None and d["name"] in internal}),
|
|
"external": sorted({d["name"] for d in p["dependencies"] if d["kind"] is None and d["name"] not in internal}),
|
|
})
|
|
return sorted(packages, key=lambda p: p["name"])
|
|
|
|
|
|
def rust_files(directory):
|
|
for path in sorted(directory.rglob("*.rs")):
|
|
if "target" in path.relative_to(directory).parts:
|
|
continue
|
|
yield path
|
|
|
|
|
|
def file_lines(root, packages):
|
|
"""{relative posix path: line count} for every .rs file in a workspace package."""
|
|
result = {}
|
|
for pkg in packages:
|
|
for path in rust_files(pkg["dir"]):
|
|
result[path.relative_to(root).as_posix()] = len(path.read_text(encoding="utf-8", errors="replace").splitlines())
|
|
return result
|
|
|
|
|
|
def count_patterns(root, packages, patterns):
|
|
"""{"<pattern id>:<crate>": n} for the non-zero counts. Only src/ files, and only the lines before the first
|
|
column-0 `#[cfg(test)]` of a file (test modules sit at the bottom by convention); comment lines are skipped."""
|
|
compiled = [(p["id"], re.compile(p["regex"])) for p in patterns]
|
|
counts = {}
|
|
for pkg in packages:
|
|
src = pkg["dir"] / "src"
|
|
if not src.is_dir():
|
|
continue
|
|
for path in rust_files(src):
|
|
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
|
if line.startswith("#[cfg(test)]"):
|
|
break
|
|
if line.lstrip().startswith("//"):
|
|
continue
|
|
for pid, rx in compiled:
|
|
n = len(rx.findall(line))
|
|
if n:
|
|
key = f"{pid}:{pkg['name']}"
|
|
counts[key] = counts.get(key, 0) + n
|
|
return counts
|
|
|
|
|
|
def layer_index(config):
|
|
index = {}
|
|
for layer, names in config["layers"].items():
|
|
for name in names:
|
|
index.setdefault(name, []).append(layer)
|
|
return index
|
|
|
|
|
|
def evaluate(packages, config, baseline, sizes, counts):
|
|
"""Pure function over plain data. Returns (errors, debt, stale, current_violations)."""
|
|
errors, debt, stale = [], [], []
|
|
layers = layer_index(config)
|
|
order = list(config["layers"])
|
|
rank = {layer: i for i, layer in enumerate(order)}
|
|
pure = set(config["pure_layers"])
|
|
forbidden = set(config["forbidden_in_pure"])
|
|
adapter_layer = config["adapter_layer"]
|
|
adapter_edges = {tuple(e) for e in config["adapter_edges"]}
|
|
known = {p["name"] for p in packages}
|
|
violations = {}
|
|
|
|
for name in sorted(layers):
|
|
if len(layers[name]) > 1:
|
|
errors.append(f"{name} is assigned to more than one layer: {layers[name]}")
|
|
if name not in known:
|
|
errors.append(f"{name} has a layer in {CONFIG} but is not a workspace package")
|
|
for pkg in packages:
|
|
name = pkg["name"]
|
|
if name not in layers:
|
|
errors.append(f"{name} has no layer in {CONFIG}: assign it to one of {order}")
|
|
continue
|
|
mine = layers[name][0]
|
|
for dep in pkg["normal"]:
|
|
if dep not in layers:
|
|
continue
|
|
theirs = layers[dep][0]
|
|
if rank[theirs] > rank[mine]:
|
|
violations[f"layer-up {name} -> {dep}"] = f"{name} ({mine}) depends on {dep} ({theirs})"
|
|
elif mine == theirs == adapter_layer and (name, dep) not in adapter_edges:
|
|
violations[f"adapter-sideways {name} -> {dep}"] = (
|
|
f"adapter {name} depends on adapter {dep}; add the edge to adapter_edges only if it is a real port")
|
|
if mine in pure:
|
|
for ext in pkg["external"]:
|
|
if ext in forbidden:
|
|
violations[f"forbidden-dep {name} {ext}"] = f"{name} ({mine}) must stay pure but depends on {ext}"
|
|
|
|
for key, message in sorted(violations.items()):
|
|
(debt if key in baseline["violations"] else errors).append(message if key not in baseline["violations"] else key)
|
|
stale += [f"violation no longer present: {key}" for key in baseline["violations"] if key not in violations]
|
|
|
|
limit = config["max_lines"]
|
|
for path, lines in sorted(sizes.items()):
|
|
if lines <= limit:
|
|
continue
|
|
allowed = baseline["oversize"].get(path)
|
|
if allowed is None:
|
|
errors.append(f"{path} has {lines} lines (limit {limit}); split it instead of adding a new large file")
|
|
elif lines > allowed:
|
|
errors.append(f"{path} grew to {lines} lines (baseline {allowed}); large files may only shrink")
|
|
for path, allowed in baseline["oversize"].items():
|
|
now = sizes.get(path)
|
|
if now is None:
|
|
stale.append(f"oversize entry for a file that is gone: {path}")
|
|
elif now <= limit:
|
|
stale.append(f"{path} is now {now} lines, under the limit: drop its baseline entry")
|
|
elif now < allowed:
|
|
stale.append(f"{path} shrank from {allowed} to {now} lines: tighten the baseline")
|
|
|
|
for key, n in sorted(counts.items()):
|
|
allowed = baseline["source"].get(key, 0)
|
|
if n > allowed:
|
|
errors.append(f"source ratchet {key} rose to {n} (baseline {allowed}); the count may only fall")
|
|
elif n < allowed:
|
|
stale.append(f"source ratchet {key} fell from {allowed} to {n}: tighten the baseline")
|
|
for key, allowed in baseline["source"].items():
|
|
if key not in counts:
|
|
stale.append(f"source ratchet {key} is now 0 (baseline {allowed}): tighten the baseline")
|
|
return errors, debt, stale, violations
|
|
|
|
|
|
def new_baseline(config, violations, sizes, counts):
|
|
limit = config["max_lines"]
|
|
return {
|
|
"_comment": "Debt that exists today. Every number may only fall (scripts/check-architecture.py --update-baseline refuses to raise one). "
|
|
"Do not edit by hand; regenerate. Policy: architecture.json.",
|
|
"violations": sorted(violations),
|
|
"oversize": {p: n for p, n in sorted(sizes.items()) if n > limit},
|
|
"source": dict(sorted(counts.items())),
|
|
}
|
|
|
|
|
|
def raised(old, new):
|
|
"""Entries of `new` that are absent from or larger than `old` (a baseline update may only lower)."""
|
|
problems = []
|
|
for v in new["violations"]:
|
|
if v not in old["violations"]:
|
|
problems.append(f"new violation {v}")
|
|
# a file that moved (same base name, no more lines than the entry that disappeared) is not an increase
|
|
gone = {}
|
|
for path, n in old["oversize"].items():
|
|
if path not in new["oversize"]:
|
|
gone.setdefault(path.rsplit("/", 1)[-1], []).append(n)
|
|
for path, n in new["oversize"].items():
|
|
if path in old["oversize"]:
|
|
if n > old["oversize"][path]:
|
|
problems.append(f"oversize {path}: {old['oversize'][path]} -> {n}")
|
|
elif not any(n <= before for before in gone.get(path.rsplit("/", 1)[-1], [])):
|
|
problems.append(f"oversize {path}: new file with {n} lines")
|
|
# code that moved to another crate raises the destination and lowers the source: compare the total per pattern
|
|
def totals(section):
|
|
result = {}
|
|
for key, n in section.items():
|
|
result[key.split(":", 1)[0]] = result.get(key.split(":", 1)[0], 0) + n
|
|
return result
|
|
before, after = totals(old["source"]), totals(new["source"])
|
|
for pid, n in after.items():
|
|
if n > before.get(pid, 0):
|
|
problems.append(f"source {pid}: total {before.get(pid, 0)} -> {n}")
|
|
return problems
|
|
|
|
|
|
def report(packages, config, sizes, counts):
|
|
layers = layer_index(config)
|
|
for layer, names in config["layers"].items():
|
|
print(f"{layer}: {', '.join(names) if names else '(none yet)'}")
|
|
print()
|
|
for pkg in packages:
|
|
print(f"{pkg['name']:28} {layers.get(pkg['name'], ['?'])[0]} -> {', '.join(pkg['normal'])}")
|
|
over = sorted(((n, p) for p, n in sizes.items() if n > config["max_lines"]), reverse=True)
|
|
print(f"\n{len(over)} files over {config['max_lines']} lines; total {sum(n for n, _ in over)} lines")
|
|
for n, p in over[:15]:
|
|
print(f" {n:6} {p}")
|
|
print("\nsource counts:")
|
|
for key, n in sorted(counts.items()):
|
|
print(f" {key} = {n}")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("--root", default=str(pathlib.Path(__file__).resolve().parent.parent))
|
|
parser.add_argument("--update-baseline", action="store_true")
|
|
parser.add_argument("--allow-increase", action="store_true")
|
|
parser.add_argument("--report", action="store_true")
|
|
args = parser.parse_args()
|
|
root = pathlib.Path(args.root).resolve()
|
|
|
|
config = json.loads((root / CONFIG).read_text(encoding="utf-8"))
|
|
baseline_path = root / BASELINE
|
|
baseline = (json.loads(baseline_path.read_text(encoding="utf-8")) if baseline_path.exists()
|
|
else {"violations": [], "oversize": {}, "source": {}})
|
|
packages = load_metadata(root)
|
|
sizes = file_lines(root, packages)
|
|
counts = count_patterns(root, packages, config["source_patterns"])
|
|
errors, debt, stale, violations = evaluate(packages, config, baseline, sizes, counts)
|
|
|
|
if args.report:
|
|
report(packages, config, sizes, counts)
|
|
return 0
|
|
if args.update_baseline:
|
|
updated = new_baseline(config, violations, sizes, counts)
|
|
problems = [] if args.allow_increase else raised(baseline, updated)
|
|
if baseline_path.exists() and problems:
|
|
print("refusing to raise the baseline (use --allow-increase and justify it in review):", file=sys.stderr)
|
|
print("\n".join(f" {p}" for p in problems), file=sys.stderr)
|
|
return 1
|
|
with open(baseline_path, "w", encoding="utf-8", newline="\n") as handle:
|
|
handle.write(json.dumps(updated, indent=1) + "\n")
|
|
print(f"wrote {BASELINE}: {len(updated['violations'])} violations, {len(updated['oversize'])} oversize files, "
|
|
f"{len(updated['source'])} ratchets")
|
|
return 0
|
|
|
|
for line in debt:
|
|
print(f"debt (baseline): {line}")
|
|
for line in stale:
|
|
print(f"stale baseline: {line} (scripts/check-architecture.py --update-baseline)")
|
|
for line in errors:
|
|
print(f"ERROR: {line}", file=sys.stderr)
|
|
print(f"architecture: {len(errors)} errors, {len(debt)} baselined violations, {len(stale)} stale baseline entries")
|
|
return 1 if errors else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|