From 28387a3b920d2ecff62d2ef267af6b875be9d28d Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 20 Nov 2026 16:49:20 +0000 Subject: tools: census how wide each module's interface actually is MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An interface is only as narrow as the items a module hands out, and nobody had counted them: 585 pub items across 27 modules, 146 of which nothing outside their own module ever names. That is not an interface, it is a hole in the module boundary, and every one of them is a thing a later refactor cannot change without a grep across the crate. The census counts pub items per module, how many of them are dead, how many of those a test does name (the integration tests are separate crates, so a name only they use is genuinely pub and the honest thing is to count it rather than pretend it is private), the glob re-exports that flatten a namespace, and the crate:: edge set between modules. The edge set is already acyclic, which is the useful surprise: a layer map can be declared over the graph as it stands rather than after breaking something. It also says where the width is — db hands out 226 items, http 68 of which 54 are dead — so the work has an order. Baseline for all of it: 273 tests passing, clippy -D warnings clean, release build clean. --- tools/arch-census.md | 67 ++++++++++++ tools/arch-census.py | 296 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 363 insertions(+) create mode 100644 tools/arch-census.md create mode 100755 tools/arch-census.py diff --git a/tools/arch-census.md b/tools/arch-census.md new file mode 100644 index 0000000..aedf952 --- /dev/null +++ b/tools/arch-census.md @@ -0,0 +1,67 @@ +# Architecture census + +The numbers below are what the module tree costs, measured by +`tools/arch-census.py`. `tests/architecture.rs` enforces them against +`tests/architecture-budget.json`, which may only shrink. + +Baseline verification, before any of this work: `cargo test --all-targets +--features test-support` 273 passed / 0 failed across 36 test binaries; +`cargo clippy --all-targets --features test-support -- -D warnings` clean; +`cargo build --release` clean. + +## 2026-11-20 16:48 + +totals: 585 pub, 219 dead (73 test-only, 146 named by nobody), 42 pub(crate), 4 glob re-exports, 80 edges, largest file 1501 (src/db/queries.rs) + +| module | pub | dead | test-only | dead-only | pub(crate) | glob | lines | largest file | +|---|---|---|---|---|---|---|---|---| +| bin/gpg | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 4 src/bin/gpg.rs | +| bin/makechrootpkg | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 4 src/bin/makechrootpkg.rs | +| bin/makepkg | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 4 src/bin/makepkg.rs | +| bin/mkarchroot | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 4 src/bin/mkarchroot.rs | +| bin/pacman | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 4 src/bin/pacman.rs | +| bin/repo-add | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 4 src/bin/repo-add.rs | +| bin/sandbox-agent | 0 | 0 | 0 | 0 | 0 | 0 | 50 | 50 src/bin/sandbox-agent.rs | +| config | 35 | 9 | 5 | 4 | 0 | 0 | 427 | 427 src/config.rs | +| db | 226 | 49 | 13 | 36 | 5 | 2 | 3687 | 1501 src/db/queries.rs | +| error | 15 | 0 | 0 | 0 | 0 | 0 | 124 | 124 src/error.rs | +| fetch | 3 | 1 | 0 | 1 | 0 | 0 | 56 | 56 src/fetch.rs | +| git | 19 | 5 | 0 | 5 | 0 | 0 | 280 | 280 src/git.rs | +| hash | 8 | 1 | 0 | 1 | 0 | 0 | 61 | 61 src/hash.rs | +| http | 68 | 54 | 11 | 43 | 32 | 2 | 1951 | 565 src/http/routes/pages.rs | +| lib | 0 | 0 | 0 | 0 | 0 | 0 | 22 | 22 src/lib.rs | +| main | 0 | 0 | 0 | 0 | 0 | 0 | 361 | 361 src/main.rs | +| ops | 13 | 5 | 3 | 2 | 0 | 0 | 415 | 415 src/ops.rs | +| pipeline | 30 | 15 | 6 | 9 | 2 | 0 | 1339 | 481 src/pipeline/steps.rs | +| pkginfo | 7 | 3 | 0 | 3 | 0 | 0 | 122 | 122 src/pkginfo.rs | +| pkgver | 18 | 9 | 5 | 4 | 0 | 0 | 347 | 347 src/pkgver/mod.rs | +| recipe | 11 | 4 | 0 | 4 | 0 | 0 | 467 | 467 src/recipe.rs | +| review | 29 | 10 | 4 | 6 | 0 | 0 | 792 | 295 src/review/diff.rs | +| sandbox | 35 | 23 | 15 | 8 | 3 | 0 | 1175 | 347 src/sandbox/kata.rs | +| shims | 19 | 12 | 4 | 8 | 0 | 0 | 603 | 603 src/shims/mod.rs | +| time | 16 | 7 | 3 | 4 | 0 | 0 | 221 | 221 src/time.rs | +| urlutil | 2 | 1 | 0 | 1 | 0 | 0 | 56 | 56 src/urlutil.rs | +| watch | 31 | 11 | 4 | 7 | 0 | 0 | 969 | 317 src/watch/detect.rs | + +``` +bin/gpg -> shims +bin/makechrootpkg -> shims +bin/makepkg -> shims +bin/mkarchroot -> shims +bin/pacman -> shims +bin/repo-add -> shims +bin/sandbox-agent -> sandbox +config -> error hash +db -> config error hash pkgver time +fetch -> error hash +git -> error +http -> config db hash ops pipeline pkgver review time watch +main -> config db http ops pipeline pkgver review watch +ops -> config db error time watch +pipeline -> config db error git hash pkginfo pkgver recipe review sandbox time watch +recipe -> db error +review -> config db error git hash pkgver recipe time urlutil +sandbox -> config error hash time +shims -> hash pkginfo pkgver recipe +watch -> config db error fetch git hash pkgver recipe review time +``` diff --git a/tools/arch-census.py b/tools/arch-census.py new file mode 100755 index 0000000..ca6d7b8 --- /dev/null +++ b/tools/arch-census.py @@ -0,0 +1,296 @@ +#!/usr/bin/env python3 +"""Census the module tree: how wide each interface is, and what reaches into what. + +An interface is only as narrow as the items a module actually hands out, so the +two numbers that matter are how many `pub` items a module declares and how many +of them nothing outside that module ever names. A `pub` item with no outside +reader is not an interface, it is a hole: every one of them is a thing a caller +may depend on and a thing a later refactor cannot change without a grep across +the crate. `tests/` counts as an outside reader on purpose — the integration +tests are separate crates, so a name only they use is genuinely `pub`, and the +honest way to say that is to count it rather than pretend it is private. + +Reported per module: + pub items declared `pub` (fn, struct, enum, trait, const, static, type) + dead of those, ones no file outside the module names — including tests/ + test of the dead ones, the ones a test does name: pub for the test tier + deadonly dead minus test: exported, and named by nobody at all + priv items declared `pub(crate)`: crate-internal on purpose + glob `use … ::*` re-exports, which flatten a namespace and hide width + lines total lines of the module, and its largest single file + +Reported for the crate: the `crate::x` edge set between modules, which is the +dependency graph the layer map in tests/architecture.rs is allowed to be. + +`tests/architecture.rs` enforces the same two definitions against a committed +budget and fails when a number grows; this tool is the human-facing report of +where the numbers are and where they moved. + +Usage: + tools/arch-census.py print the census + tools/arch-census.py --json the same numbers as JSON + tools/arch-census.py --record FILE append a dated section to a markdown file + tools/arch-census.py --budget FILE compare against a budget, exit 1 if over + tools/arch-census.py --write-budget FILE write the current numbers as budget +""" + +import argparse +import collections +import json +import os +import re +import sys +from datetime import datetime, timezone + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SRC = os.path.join(ROOT, "src") +TESTS = os.path.join(ROOT, "tests") + +# A declaration, not a re-export: `pub use` is counted separately as a glob. +PUB_RE = re.compile(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+([A-Za-z0-9_]+)") +PUB_CRATE_RE = re.compile(r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|static|type)\s+", re.M) +GLOB_RE = re.compile(r"^\s*pub(?:\(crate\))?\s+use\s+[^\n]*::\*", re.M) +EDGE_RE = re.compile(r"\bcrate::([a-z_][a-z0-9_]*)") +# The binaries are separate crates, so they name the library through its own +# name rather than through `crate::`. Those edges are part of the graph too. +LIB_EDGE_RE = re.compile(r"\baur_build::([a-z_][a-z0-9_]*)") +COMMENT = re.compile(r"^\s*(?://|//!|///)") + + +def rust_files(*dirs): + out = [] + for d in dirs: + for base, _, names in os.walk(d): + for name in names: + if name.endswith(".rs"): + out.append(os.path.join(base, name)) + return sorted(out) + + +def read_all(files): + texts = {} + for path in files: + with open(path, errors="replace") as handle: + texts[path] = handle.read() + return texts + + +def module_of(path): + """The module a file belongs to. + + A directory is one module (`src/db/*.rs` is `db`); a top-level file is a + module of its own (`src/ops.rs` is `ops`), because a layer map that lumps + eleven unrelated files into one box cannot say anything about them. The + binaries are separate crates and keep their own names. + """ + rel = os.path.relpath(path, SRC) + parts = rel.split(os.sep) + if parts[0] == "bin": + return os.path.join("bin", *parts[1:]).removesuffix(".rs") + if len(parts) > 1: + return parts[0] + return parts[0].removesuffix(".rs") + + +def declarations(texts): + """Every `pub` item name, with the modules that declare it and the files.""" + names = collections.defaultdict(list) + for path, text in texts.items(): + for line in text.splitlines(): + if COMMENT.match(line): + continue + m = PUB_RE.match(line) + if m: + names[m.group(1)].append(path) + return names + + +def census(): + src_files = rust_files(SRC) + test_files = rust_files(TESTS) + src_texts = read_all(src_files) + test_texts = read_all(test_files) + names = declarations(src_texts) + + mods = sorted({module_of(p) for p in src_files}) + rows = {} + for mod in mods: + rows[mod] = { + "pub": 0, + "dead": 0, + "test": 0, + "deadonly": 0, + "priv": 0, + "glob": 0, + "lines": 0, + "largest": 0, + "largest_file": "", + } + + for path, text in src_texts.items(): + row = rows[module_of(path)] + row["lines"] += text.count("\n") + 1 + row["priv"] += len(PUB_CRATE_RE.findall(text)) + row["glob"] += len(GLOB_RE.findall(text)) + size = text.count("\n") + 1 + if size > row["largest"]: + row["largest"] = size + row["largest_file"] = os.path.relpath(path, ROOT) + + # A name is dead when no file outside the module that declares it says it. + # A name declared in two modules is only dead if neither is referenced. + for name, paths in names.items(): + declaring = {module_of(p) for p in paths} + for mod in declaring: + rows[mod]["pub"] += 1 + outside = any( + module_of(p) not in declaring and re.search(r"\b%s\b" % re.escape(name), t) + for p, t in src_texts.items() + ) + if outside: + continue + used_by_tests = any(re.search(r"\b%s\b" % re.escape(name), t) for t in test_texts.values()) + for mod in declaring: + rows[mod]["dead"] += 1 + if used_by_tests: + rows[mod]["test"] += 1 + else: + rows[mod]["deadonly"] += 1 + + edges = collections.defaultdict(set) + for path, text in src_texts.items(): + src_mod = module_of(path) + pattern = LIB_EDGE_RE if src_mod.startswith("bin") or src_mod == "main" else EDGE_RE + for line in text.splitlines(): + if COMMENT.match(line): + continue + for target in pattern.findall(line): + if target in rows and target != src_mod: + edges[src_mod].add(target) + + return { + "modules": rows, + "edges": {k: sorted(v) for k, v in sorted(edges.items())}, + "totals": { + "pub": sum(r["pub"] for r in rows.values()), + "dead": sum(r["dead"] for r in rows.values()), + "test": sum(r["test"] for r in rows.values()), + "deadonly": sum(r["deadonly"] for r in rows.values()), + "priv": sum(r["priv"] for r in rows.values()), + "glob": sum(r["glob"] for r in rows.values()), + "edges": sum(len(v) for v in edges.values()), + "lines": sum(r["lines"] for r in rows.values()), + "largest": max((r["largest"] for r in rows.values()), default=0), + "largest_file": max(rows.values(), key=lambda r: r["largest"])["largest_file"] + if rows + else "", + }, + } + + +BUDGET_KEYS = ("pub", "dead", "test", "deadonly", "priv", "glob") + + +def check_budget(data, budget): + """Numbers over budget, as (module, key, budget, actual) tuples.""" + over = [] + mods = budget.get("modules", {}) + for mod, row in sorted(data["modules"].items()): + allowed = mods.get(mod) + if allowed is None: + over.append((mod, "module", "absent from budget", "present")) + continue + for key in BUDGET_KEYS: + if key in allowed and row[key] > allowed[key]: + over.append((mod, key, allowed[key], row[key])) + return over + + +def print_census(data): + totals = data["totals"] + width = max(len(m) for m in data["modules"]) + print(f"{'module'.ljust(width)} {'pub':>4} {'dead':>5} {'test':>5} {'deadon':>7} " + f"{'priv':>5} {'glob':>5} {'lines':>6} largest file") + print("-" * (width + 49)) + for mod, row in sorted(data["modules"].items()): + print(f"{mod.ljust(width)} {row['pub']:>4} {row['dead']:>5} {row['test']:>5} " + f"{row['deadonly']:>7} {row['priv']:>5} {row['glob']:>5} {row['lines']:>6} " + f"{row['largest']:>4} {row['largest_file']}") + print("-" * (width + 49)) + print(f"{'total'.ljust(width)} {totals['pub']:>4} {totals['dead']:>5} {totals['test']:>5} " + f"{totals['deadonly']:>7} {totals['priv']:>5} {totals['glob']:>5} {totals['lines']:>6} " + f"{totals['largest']:>4} {totals['largest_file']}") + print(f"\ncrate:: edges between modules: {totals['edges']}") + for src_mod, targets in sorted(data["edges"].items()): + print(f" {src_mod.ljust(width)} -> {' '.join(targets)}") + + +def record(data, path): + stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M") + totals = data["totals"] + new = not os.path.exists(path) + with open(path, "a") as handle: + if new: + handle.write("# Architecture census\n") + handle.write(f"\n## {stamp}\n\n") + handle.write(f"totals: {totals['pub']} pub, {totals['dead']} dead " + f"({totals['test']} test-only, {totals['deadonly']} named by nobody), " + f"{totals['priv']} pub(crate), " + f"{totals['glob']} glob re-exports, {totals['edges']} edges, " + f"largest file {totals['largest']} ({totals['largest_file']})\n\n") + handle.write("| module | pub | dead | test-only | dead-only | pub(crate) | glob | lines | largest file |\n") + handle.write("|---|---|---|---|---|---|---|---|---|\n") + for mod, row in sorted(data["modules"].items()): + handle.write(f"| {mod} | {row['pub']} | {row['dead']} | {row['test']} | " + f"{row['deadonly']} | " + f"{row['priv']} | {row['glob']} | {row['lines']} | " + f"{row['largest']} {row['largest_file']} |\n") + handle.write("\n```\n") + for src_mod, targets in sorted(data["edges"].items()): + handle.write(f"{src_mod} -> {' '.join(targets)}\n") + handle.write("```\n") + print(f"recorded in {path}") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--json", action="store_true", help="print the census as JSON") + ap.add_argument("--record", metavar="FILE", help="append a dated section to a markdown file") + ap.add_argument("--budget", metavar="FILE", help="fail if a number is over the committed budget") + ap.add_argument("--write-budget", metavar="FILE", help="write the current numbers as the budget") + args = ap.parse_args() + + data = census() + + if args.write_budget: + with open(args.write_budget, "w") as handle: + json.dump({"modules": data["modules"], "totals": data["totals"]}, handle, indent=2, + sort_keys=True) + handle.write("\n") + print(f"wrote {args.write_budget}") + return 0 + + if args.json: + print(json.dumps(data, indent=2, sort_keys=True)) + return 0 + + print_census(data) + + if args.budget: + with open(args.budget) as handle: + budget = json.load(handle) + over = check_budget(data, budget) + if over: + print("\nOVER BUDGET — these numbers grew:") + for mod, key, allowed, actual in over: + print(f" {mod}.{key}: {actual} > {allowed}") + return 1 + print(f"\nwithin budget: {args.budget}") + + if args.record: + record(data, args.record) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) -- cgit v1.2.3