summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--README.md8
-rw-r--r--tests/architecture-budget.json313
-rw-r--r--tests/architecture.rs579
-rw-r--r--tests/layers.rs74
-rwxr-xr-xtools/arch-census.py13
5 files changed, 909 insertions, 78 deletions
diff --git a/README.md b/README.md
index b020ebe..8e9e20b 100644
--- a/README.md
+++ b/README.md
@@ -206,3 +206,11 @@ These are not suggestions:
with no signature, a symlink in the srcdir: the build stops and says why. A
change that is real but not publishable becomes a `notice` — never a candidate,
never silently dropped.
+* One direction of dependence. Every module in `src/` carries a rank in
+ `tests/architecture.rs`, and a module may name only modules ranked below it,
+ so the tree is written down rather than remembered. The same file holds each
+ module's interface budget in `tests/architecture-budget.json`: how many `pub`
+ items it hands out, and how many of them nothing outside the module ever
+ names. Budgets may only shrink — a number that grows fails the suite, and a
+ number that quietly got smaller has to be written back at the lower value.
+ `tools/arch-census.py` prints the same numbers for a human to read.
diff --git a/tests/architecture-budget.json b/tests/architecture-budget.json
new file mode 100644
index 0000000..b2bc33b
--- /dev/null
+++ b/tests/architecture-budget.json
@@ -0,0 +1,313 @@
+{
+ "modules": {
+ "bin/gpg": {
+ "dead": 0,
+ "deadonly": 0,
+ "glob": 0,
+ "largest": 4,
+ "largest_file": "src/bin/gpg.rs",
+ "lines": 4,
+ "priv": 0,
+ "pub": 0,
+ "test": 0
+ },
+ "bin/makechrootpkg": {
+ "dead": 0,
+ "deadonly": 0,
+ "glob": 0,
+ "largest": 4,
+ "largest_file": "src/bin/makechrootpkg.rs",
+ "lines": 4,
+ "priv": 0,
+ "pub": 0,
+ "test": 0
+ },
+ "bin/makepkg": {
+ "dead": 0,
+ "deadonly": 0,
+ "glob": 0,
+ "largest": 4,
+ "largest_file": "src/bin/makepkg.rs",
+ "lines": 4,
+ "priv": 0,
+ "pub": 0,
+ "test": 0
+ },
+ "bin/mkarchroot": {
+ "dead": 0,
+ "deadonly": 0,
+ "glob": 0,
+ "largest": 4,
+ "largest_file": "src/bin/mkarchroot.rs",
+ "lines": 4,
+ "priv": 0,
+ "pub": 0,
+ "test": 0
+ },
+ "bin/pacman": {
+ "dead": 0,
+ "deadonly": 0,
+ "glob": 0,
+ "largest": 4,
+ "largest_file": "src/bin/pacman.rs",
+ "lines": 4,
+ "priv": 0,
+ "pub": 0,
+ "test": 0
+ },
+ "bin/repo-add": {
+ "dead": 0,
+ "deadonly": 0,
+ "glob": 0,
+ "largest": 4,
+ "largest_file": "src/bin/repo-add.rs",
+ "lines": 4,
+ "priv": 0,
+ "pub": 0,
+ "test": 0
+ },
+ "bin/sandbox-agent": {
+ "dead": 0,
+ "deadonly": 0,
+ "glob": 0,
+ "largest": 50,
+ "largest_file": "src/bin/sandbox-agent.rs",
+ "lines": 50,
+ "priv": 0,
+ "pub": 0,
+ "test": 0
+ },
+ "config": {
+ "dead": 9,
+ "deadonly": 4,
+ "glob": 0,
+ "largest": 427,
+ "largest_file": "src/config.rs",
+ "lines": 427,
+ "priv": 0,
+ "pub": 35,
+ "test": 5
+ },
+ "db": {
+ "dead": 49,
+ "deadonly": 36,
+ "glob": 2,
+ "largest": 1501,
+ "largest_file": "src/db/queries.rs",
+ "lines": 3687,
+ "priv": 5,
+ "pub": 226,
+ "test": 13
+ },
+ "error": {
+ "dead": 0,
+ "deadonly": 0,
+ "glob": 0,
+ "largest": 124,
+ "largest_file": "src/error.rs",
+ "lines": 124,
+ "priv": 0,
+ "pub": 15,
+ "test": 0
+ },
+ "fetch": {
+ "dead": 1,
+ "deadonly": 1,
+ "glob": 0,
+ "largest": 56,
+ "largest_file": "src/fetch.rs",
+ "lines": 56,
+ "priv": 0,
+ "pub": 3,
+ "test": 0
+ },
+ "git": {
+ "dead": 5,
+ "deadonly": 5,
+ "glob": 0,
+ "largest": 280,
+ "largest_file": "src/git.rs",
+ "lines": 280,
+ "priv": 0,
+ "pub": 19,
+ "test": 0
+ },
+ "hash": {
+ "dead": 1,
+ "deadonly": 1,
+ "glob": 0,
+ "largest": 61,
+ "largest_file": "src/hash.rs",
+ "lines": 61,
+ "priv": 0,
+ "pub": 8,
+ "test": 0
+ },
+ "http": {
+ "dead": 54,
+ "deadonly": 43,
+ "glob": 2,
+ "largest": 565,
+ "largest_file": "src/http/routes/pages.rs",
+ "lines": 1951,
+ "priv": 32,
+ "pub": 68,
+ "test": 11
+ },
+ "lib": {
+ "dead": 0,
+ "deadonly": 0,
+ "glob": 0,
+ "largest": 22,
+ "largest_file": "src/lib.rs",
+ "lines": 22,
+ "priv": 0,
+ "pub": 0,
+ "test": 0
+ },
+ "main": {
+ "dead": 0,
+ "deadonly": 0,
+ "glob": 0,
+ "largest": 361,
+ "largest_file": "src/main.rs",
+ "lines": 361,
+ "priv": 0,
+ "pub": 0,
+ "test": 0
+ },
+ "ops": {
+ "dead": 5,
+ "deadonly": 2,
+ "glob": 0,
+ "largest": 415,
+ "largest_file": "src/ops.rs",
+ "lines": 415,
+ "priv": 0,
+ "pub": 13,
+ "test": 3
+ },
+ "pipeline": {
+ "dead": 15,
+ "deadonly": 9,
+ "glob": 0,
+ "largest": 481,
+ "largest_file": "src/pipeline/steps.rs",
+ "lines": 1339,
+ "priv": 2,
+ "pub": 30,
+ "test": 6
+ },
+ "pkginfo": {
+ "dead": 3,
+ "deadonly": 3,
+ "glob": 0,
+ "largest": 122,
+ "largest_file": "src/pkginfo.rs",
+ "lines": 122,
+ "priv": 0,
+ "pub": 7,
+ "test": 0
+ },
+ "pkgver": {
+ "dead": 9,
+ "deadonly": 4,
+ "glob": 0,
+ "largest": 347,
+ "largest_file": "src/pkgver/mod.rs",
+ "lines": 347,
+ "priv": 0,
+ "pub": 18,
+ "test": 5
+ },
+ "recipe": {
+ "dead": 4,
+ "deadonly": 4,
+ "glob": 0,
+ "largest": 467,
+ "largest_file": "src/recipe.rs",
+ "lines": 467,
+ "priv": 0,
+ "pub": 11,
+ "test": 0
+ },
+ "review": {
+ "dead": 10,
+ "deadonly": 6,
+ "glob": 0,
+ "largest": 295,
+ "largest_file": "src/review/diff.rs",
+ "lines": 792,
+ "priv": 0,
+ "pub": 29,
+ "test": 4
+ },
+ "sandbox": {
+ "dead": 23,
+ "deadonly": 8,
+ "glob": 0,
+ "largest": 347,
+ "largest_file": "src/sandbox/kata.rs",
+ "lines": 1175,
+ "priv": 3,
+ "pub": 35,
+ "test": 15
+ },
+ "shims": {
+ "dead": 12,
+ "deadonly": 8,
+ "glob": 0,
+ "largest": 603,
+ "largest_file": "src/shims/mod.rs",
+ "lines": 603,
+ "priv": 0,
+ "pub": 19,
+ "test": 4
+ },
+ "time": {
+ "dead": 7,
+ "deadonly": 4,
+ "glob": 0,
+ "largest": 221,
+ "largest_file": "src/time.rs",
+ "lines": 221,
+ "priv": 0,
+ "pub": 16,
+ "test": 3
+ },
+ "urlutil": {
+ "dead": 1,
+ "deadonly": 1,
+ "glob": 0,
+ "largest": 56,
+ "largest_file": "src/urlutil.rs",
+ "lines": 56,
+ "priv": 0,
+ "pub": 2,
+ "test": 0
+ },
+ "watch": {
+ "dead": 11,
+ "deadonly": 7,
+ "glob": 0,
+ "largest": 317,
+ "largest_file": "src/watch/detect.rs",
+ "lines": 969,
+ "priv": 0,
+ "pub": 31,
+ "test": 4
+ }
+ },
+ "totals": {
+ "dead": 219,
+ "deadonly": 146,
+ "edges": 80,
+ "glob": 4,
+ "largest": 1501,
+ "largest_file": "src/db/queries.rs",
+ "lines": 13549,
+ "priv": 42,
+ "pub": 585,
+ "test": 73
+ }
+}
diff --git a/tests/architecture.rs b/tests/architecture.rs
new file mode 100644
index 0000000..919728c
--- /dev/null
+++ b/tests/architecture.rs
@@ -0,0 +1,579 @@
+//! The layer map, in one place, checked on every test run.
+//!
+//! `tests/layers.rs` grew four greps for four mistakes. Four greps cannot say
+//! what the architecture *is*, cannot tell you where a new module belongs, and
+//! say nothing at all about the modules nobody has tripped over yet. This
+//! declares the whole map instead: every module in `src/` gets a rank, and a
+//! module may name only modules ranked strictly below it. One rule, every
+//! module, and the direction of dependence is written down rather than
+//! remembered.
+//!
+//! The same file holds the interface budgets. An interface is only as narrow as
+//! the items a module hands out, so each module is budgeted on how many `pub`
+//! items it declares and how many of them nothing outside the module ever
+//! names. Budgets live in `architecture-budget.json` and may only shrink: a
+//! number that grows fails the suite, and a number that has quietly got smaller
+//! has to be written back at the lower value, which is what stops a widening
+//! being mistaken for progress.
+//!
+//! `tools/arch-census.py` computes the same numbers for a human to read.
+//! `the_census_tool_and_this_test_agree` is the seam between them.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+
+/// A module may name only modules ranked strictly below it. The order is the
+/// dependency graph itself, so each rank is written with the reason it sits
+/// there — a bare number invites someone to slot a module in wherever it is
+/// convenient.
+const RANKS: &[(&str, u8, &str)] = &[
+ ("error", 0, "the crate's error type: nothing in the crate is beneath it"),
+ ("hash", 1, "sha256 and canonical json: pure"),
+ ("time", 1, "the clock seam: pure"),
+ ("urlutil", 1, "url and name shapes: pure"),
+ ("pkgver", 1, "vercmp and the dependency grammar: pure, and the oracle test proves it"),
+ ("pkginfo", 1, ".PKGINFO and .BUILDINFO parsing: pure"),
+ ("config", 2, "config.json: needs an error type and a hash, nothing else"),
+ ("fetch", 2, "the HTTP seam: an adapter over the outside world"),
+ ("git", 2, "the git seam: an adapter over the git binary"),
+ ("db", 3, "persistence: owns the schema, so it may use config, hash, pkgver and time"),
+ ("sandbox", 3, "where build code runs: config and the clock, no knowledge of what gets built"),
+ ("recipe", 4, "PKGBUILD parsing: needs the row types it fills in"),
+ ("review", 5, "candidates, diff, risk, approval: reads persisted state and recipes"),
+ ("shims", 5, "the fake toolchain: emulates tools over pkgver, pkginfo and recipe — test-only"),
+ ("watch", 6, "detection: turns a moved upstream into a candidate, so it needs review"),
+ ("pipeline", 7, "the step machine: orchestrates watch, review and sandbox"),
+ ("ops", 8, "retention, metrics, backup: reads across the modules it reports on"),
+ ("http", 9, "the UI: the top of the tree, everything is beneath it"),
+ ("main", 10, "the CLI: composition root"),
+ ("lib", 10, "the crate root: declares the modules and re-exports the error type"),
+ ("bin/sandbox-agent", 10, "the sandbox agent: composition root on the far side of the wire"),
+ ("bin/gpg", 10, "a shim binary: composition root for one tool"),
+ ("bin/makepkg", 10, "a shim binary: composition root for one tool"),
+ ("bin/makechrootpkg", 10, "a shim binary: composition root for one tool"),
+ ("bin/mkarchroot", 10, "a shim binary: composition root for one tool"),
+ ("bin/pacman", 10, "a shim binary: composition root for one tool"),
+ ("bin/repo-add", 10, "a shim binary: composition root for one tool"),
+];
+
+/// `pub use … ::*` a module is still allowed to keep, as `module -> count`.
+/// This is the allowlist, and the ratchet is what empties it: a glob re-export
+/// flattens a namespace so a reader cannot see a module's width from its
+/// exports, which is the whole point of the budgets.
+const GLOB_ALLOWLIST: &[(&str, usize)] = &[("db", 2), ("http", 2)];
+
+const DECL_KEYWORDS: [&str; 7] = ["fn", "struct", "enum", "trait", "const", "static", "type"];
+
+fn root() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf()
+}
+
+fn src_root() -> PathBuf {
+ root().join("src")
+}
+
+fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
+ for entry in std::fs::read_dir(dir).expect("read_dir") {
+ let path = entry.expect("entry").path();
+ if path.is_dir() {
+ rust_files(&path, out);
+ } else if path.extension().is_some_and(|e| e == "rs") {
+ out.push(path);
+ }
+ }
+}
+
+fn src_files() -> Vec<PathBuf> {
+ let mut out = Vec::new();
+ rust_files(&src_root(), &mut out);
+ out.sort();
+ assert!(out.len() > 40, "found only {} source files — the walk is wrong", out.len());
+ out
+}
+
+fn test_files() -> Vec<PathBuf> {
+ let mut out = Vec::new();
+ rust_files(&root().join("tests"), &mut out);
+ out.sort();
+ out
+}
+
+/// The module a file belongs to: a directory is one module, a top-level file is
+/// a module of its own, and a binary keeps its own name. A map that lumped
+/// eleven unrelated top-level files into one box could not say anything about
+/// any of them.
+fn module_of(path: &Path) -> String {
+ let rel = path.strip_prefix(src_root()).unwrap();
+ let parts: Vec<String> = rel
+ .components()
+ .map(|c| c.as_os_str().to_string_lossy().into_owned())
+ .collect();
+ match parts.as_slice() {
+ [only] => only.trim_end_matches(".rs").to_string(),
+ [head, rest @ ..] if head == "bin" => {
+ format!("bin/{}", rest.last().unwrap().trim_end_matches(".rs"))
+ }
+ [head, ..] => head.clone(),
+ [] => unreachable!("a walked file always has a name"),
+ }
+}
+
+fn is_comment(line: &str) -> bool {
+ line.trim_start().starts_with("//")
+}
+
+fn word_tail(rest: &str) -> String {
+ rest.chars()
+ .take_while(|c| c.is_alphanumeric() || *c == '_')
+ .collect()
+}
+
+/// The name a `pub` declaration introduces, if this line declares one. `pub
+/// use` is a re-export and is counted separately, never as a declaration.
+fn pub_decl(line: &str) -> Option<String> {
+ if is_comment(line) {
+ return None;
+ }
+ let rest = line.trim_start().strip_prefix("pub ")?;
+ let keyword = DECL_KEYWORDS.into_iter().find(|kw| rest.starts_with(&format!("{kw} ")))?;
+ let name = word_tail(&rest[keyword.len() + 1..]);
+ (!name.is_empty()).then_some(name)
+}
+
+fn is_pub_crate_decl(line: &str) -> bool {
+ if is_comment(line) {
+ return false;
+ }
+ let Some(rest) = line.trim_start().strip_prefix("pub(crate) ") else {
+ return false;
+ };
+ DECL_KEYWORDS.into_iter().any(|kw| rest.starts_with(&format!("{kw} ")))
+}
+
+fn is_glob_reexport(line: &str) -> bool {
+ if is_comment(line) {
+ return false;
+ }
+ let t = line.trim_start();
+ let after = match t
+ .strip_prefix("pub(crate) use ")
+ .or_else(|| t.strip_prefix("pub use "))
+ {
+ Some(after) => after,
+ None => return false,
+ };
+ after.contains("::*")
+}
+
+fn path_edges(line: &str, prefix: &str) -> Vec<String> {
+ if is_comment(line) {
+ return Vec::new();
+ }
+ let mut out = Vec::new();
+ let bytes = line.as_bytes();
+ let mut from = 0;
+ while let Some(pos) = line[from..].find(prefix).map(|p| p + from) {
+ from = pos + prefix.len();
+ // A leading word character means this is `foo::crate::`, not a path root.
+ if pos > 0 {
+ let prev = bytes[pos - 1];
+ if prev.is_ascii_alphanumeric() || prev == b'_' {
+ continue;
+ }
+ }
+ let name = word_tail(&line[from..]);
+ if !name.is_empty() {
+ out.push(name);
+ }
+ }
+ out
+}
+
+/// Whole-word mention, the same test the census tool applies.
+fn mentions(hay: &str, needle: &str) -> bool {
+ let word = |c: u8| c.is_ascii_alphanumeric() || c == b'_';
+ let h = hay.as_bytes();
+ if needle.is_empty() {
+ return false;
+ }
+ let mut from = 0;
+ while let Some(pos) = hay[from..].find(needle).map(|p| p + from) {
+ let before_ok = pos == 0 || !word(h[pos - 1]);
+ let after = pos + needle.len();
+ let after_ok = after >= h.len() || !word(h[after]);
+ if before_ok && after_ok {
+ return true;
+ }
+ from = pos + 1;
+ }
+ false
+}
+
+#[derive(Default, Debug)]
+struct Module {
+ pub_items: usize,
+ dead: usize,
+ test_only: usize,
+ dead_only: usize,
+ pub_crate: usize,
+ globs: usize,
+ lines: usize,
+}
+
+#[derive(Debug)]
+struct Census {
+ modules: BTreeMap<String, Module>,
+ edges: BTreeMap<String, BTreeSet<String>>,
+}
+
+impl Census {
+ fn take() -> Census {
+ let files = src_files();
+ let texts: Vec<(PathBuf, String)> = files
+ .iter()
+ .map(|f| (f.clone(), std::fs::read_to_string(f).expect("read source")))
+ .collect();
+ let test_texts: Vec<String> = test_files()
+ .iter()
+ .map(|f| std::fs::read_to_string(f).expect("read test"))
+ .collect();
+
+ let mut modules: BTreeMap<String, Module> = BTreeMap::new();
+ for (path, text) in &texts {
+ let module = modules.entry(module_of(path)).or_default();
+ module.lines += text.lines().count();
+ for line in text.lines() {
+ if is_pub_crate_decl(line) {
+ module.pub_crate += 1;
+ }
+ if is_glob_reexport(line) {
+ module.globs += 1;
+ }
+ }
+ }
+
+ // name -> the modules that declare it. A name declared in two modules
+ // is only dead when neither is read from outside either of them.
+ let mut declared: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
+ for (path, text) in &texts {
+ let module = module_of(path);
+ for line in text.lines() {
+ if let Some(name) = pub_decl(line) {
+ declared.entry(name).or_default().insert(module.clone());
+ }
+ }
+ }
+
+ for (name, declaring) in &declared {
+ for module in declaring {
+ modules.get_mut(module).unwrap().pub_items += 1;
+ }
+ let read_outside = texts
+ .iter()
+ .any(|(path, text)| !declaring.contains(&module_of(path)) && mentions(text, name));
+ if read_outside {
+ continue;
+ }
+ let used_by_tests = test_texts.iter().any(|t| mentions(t, name));
+ for module in declaring {
+ let module = modules.get_mut(module).unwrap();
+ module.dead += 1;
+ if used_by_tests {
+ module.test_only += 1;
+ } else {
+ module.dead_only += 1;
+ }
+ }
+ }
+
+ let mut edges: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
+ for (path, text) in &texts {
+ let source = module_of(path);
+ let known: BTreeSet<String> = modules.keys().cloned().collect();
+ for line in text.lines() {
+ let named = if source.starts_with("bin/") || source == "main" {
+ path_edges(line, "aur_build::")
+ } else {
+ path_edges(line, "crate::")
+ };
+ for target in named {
+ if target != source && known.contains(&target) {
+ edges.entry(source.clone()).or_default().insert(target);
+ }
+ }
+ }
+ }
+
+ Census { modules, edges }
+ }
+
+ /// The budget file, as `module -> key -> allowed`.
+ fn budget() -> BTreeMap<String, BTreeMap<String, usize>> {
+ let path = root().join("tests/architecture-budget.json");
+ let text = std::fs::read_to_string(&path).unwrap_or_else(|e| {
+ panic!(
+ "read {}: {}",
+ path.display(),
+ e
+ )
+ });
+ let value: serde_json::Value = serde_json::from_str(&text).expect("budget file is json");
+ let mut out = BTreeMap::new();
+ let modules = value
+ .get("modules")
+ .and_then(|m| m.as_object())
+ .expect("budget file has a modules object");
+ for (module, row) in modules {
+ let mut keys = BTreeMap::new();
+ if let Some(row) = row.as_object() {
+ for (key, val) in row {
+ if let Some(n) = val.as_u64() {
+ keys.insert(key.clone(), n as usize);
+ }
+ }
+ }
+ out.insert(module.clone(), keys);
+ }
+ out
+ }
+}
+
+fn rank_of(module: &str) -> Option<u8> {
+ RANKS
+ .iter()
+ .find(|(name, _, _)| *name == module)
+ .map(|(_, rank, _)| *rank)
+}
+
+#[test]
+fn every_module_is_on_the_map() {
+ let census = Census::take();
+ let unmapped: Vec<&String> = census
+ .modules
+ .keys()
+ .filter(|m| rank_of(m).is_none())
+ .collect();
+ assert!(
+ unmapped.is_empty(),
+ "these modules have no rank, so nothing says what they may depend on: {unmapped:#?}\n\
+ add each to RANKS with the reason a module below it cannot serve as its home"
+ );
+}
+
+#[test]
+fn the_map_names_no_module_twice() {
+ let mut seen = BTreeSet::new();
+ let dupes: Vec<&str> = RANKS
+ .iter()
+ .filter(|(name, _, _)| !seen.insert(*name))
+ .map(|(name, _, _)| *name)
+ .collect();
+ assert!(dupes.is_empty(), "RANKS lists {dupes:?} twice; the second entry is dead weight");
+ for (_, _, reason) in RANKS {
+ assert!(reason.len() > 12, "a rank needs a reason, not a shrug: {reason:?}");
+ }
+}
+
+#[test]
+fn dependence_only_points_downward() {
+ let mut violations = Vec::new();
+ for path in src_files() {
+ let text = std::fs::read_to_string(&path).expect("read source");
+ let source = module_of(&path);
+ let Some(from) = rank_of(&source) else { continue };
+ for line in text.lines() {
+ let named = if source.starts_with("bin/") || source == "main" {
+ path_edges(line, "aur_build::")
+ } else {
+ path_edges(line, "crate::")
+ };
+ for target in named {
+ if target == source {
+ // `crate::review::risk` from inside review is a path, not a
+ // dependence on another module.
+ continue;
+ }
+ let Some(to) = rank_of(&target) else { continue };
+ if to >= from {
+ violations.push(format!(
+ "{}: {source} (rank {from}) names {target} (rank {to})",
+ path.strip_prefix(root()).unwrap().display()
+ ));
+ }
+ }
+ }
+ }
+ violations.sort();
+ violations.dedup();
+ assert!(
+ violations.is_empty(),
+ "a module may only name modules ranked strictly below it:\n{}",
+ violations.join("\n")
+ );
+}
+
+#[test]
+fn the_map_admits_no_cycle() {
+ // Strictly downward edges make a cycle impossible by construction, which is
+ // the whole trick — so this asserts the property the map is trusted for,
+ // over the edges that actually exist, rather than trusting the ranks.
+ let census = Census::take();
+ let mut offenders = Vec::new();
+ for (source, targets) in &census.edges {
+ for target in targets {
+ let (Some(from), Some(to)) = (rank_of(source), rank_of(target)) else {
+ continue;
+ };
+ if to >= from {
+ offenders.push(format!("{source} -> {target}"));
+ }
+ }
+ }
+ assert!(
+ offenders.is_empty(),
+ "these edges close a cycle, so neither module can be understood alone:\n{}",
+ offenders.join("\n")
+ );
+}
+
+#[test]
+fn glob_reexports_stay_on_the_allowlist() {
+ let census = Census::take();
+ let mut offenders = Vec::new();
+ for (module, row) in &census.modules {
+ let allowed = GLOB_ALLOWLIST
+ .iter()
+ .find(|(m, _)| m == module)
+ .map(|(_, n)| *n)
+ .unwrap_or(0);
+ if row.globs > allowed {
+ offenders.push(format!("{module}: {} glob re-exports, {allowed} allowed", row.globs));
+ }
+ }
+ assert!(
+ offenders.is_empty(),
+ "a glob re-export hides how wide a module is; name the items you export:\n{}",
+ offenders.join("\n")
+ );
+}
+
+/// The four comparisons the ratchet makes, as `(key, actual)` pairs.
+fn budgeted(row: &Module) -> [(&'static str, usize); 4] {
+ [
+ ("pub", row.pub_items),
+ ("dead", row.dead),
+ ("deadonly", row.dead_only),
+ ("glob", row.globs),
+ ]
+}
+
+#[test]
+fn interfaces_stay_within_budget() {
+ // A `pub` item with no reader outside its module is not an interface, it is
+ // a hole: a thing a caller may depend on and a thing a later refactor cannot
+ // change without a grep across the crate. Zero holes is the destination, not
+ // the starting point, so the rule is the ratchet — `deadonly` is how many
+ // holes a module still has, and the only direction it may move is down.
+ let census = Census::take();
+ let budget = Census::budget();
+ let mut over = Vec::new();
+ for (module, row) in &census.modules {
+ let Some(allowed) = budget.get(module) else {
+ over.push(format!("{module}: absent from the budget file"));
+ continue;
+ };
+ for (key, actual) in budgeted(row) {
+ if let Some(max) = allowed.get(key) {
+ if actual > *max {
+ over.push(format!("{module}.{key}: {actual} > {max}"));
+ }
+ }
+ }
+ }
+ over.sort();
+ assert!(
+ over.is_empty(),
+ "these numbers grew. An interface may shrink freely; widening one is a\n\
+ decision to make in the open — lower the number in the budget file and\n\
+ say why in the commit message:\n{}",
+ over.join("\n")
+ );
+}
+
+#[test]
+fn a_shrunk_interface_is_written_back() {
+ // The ratchet cuts both ways. A stale, generous budget is how a later
+ // widening slips through unnoticed, so the file has to say what is true.
+ let census = Census::take();
+ let budget = Census::budget();
+ let mut stale = Vec::new();
+ for (module, row) in &census.modules {
+ let Some(allowed) = budget.get(module) else { continue };
+ for (key, actual) in budgeted(row) {
+ if let Some(max) = allowed.get(key) {
+ if *max > actual {
+ stale.push(format!("{module}.{key}: budget {max}, actual {actual}"));
+ }
+ }
+ }
+ }
+ stale.sort();
+ assert!(
+ stale.is_empty(),
+ "these budgets are looser than the code, hiding ground already won:\n{}",
+ stale.join("\n")
+ );
+}
+
+#[test]
+fn the_census_tool_and_this_test_agree() {
+ // Two implementations of one definition will drift, and a drift means the
+ // ratchet is measuring the wrong thing. Gated the way the vercmp oracle is:
+ // without python3 the note prints and the suite moves on.
+ let available = std::process::Command::new("python3")
+ .arg("--version")
+ .output()
+ .is_ok();
+ if !available {
+ println!("python3 is not on PATH — skipping the census cross-check");
+ return;
+ }
+ let out = std::process::Command::new("python3")
+ .arg("tools/arch-census.py")
+ .arg("--json")
+ .current_dir(root())
+ .output()
+ .expect("run tools/arch-census.py");
+ assert!(out.status.success(), "census tool failed: {}", String::from_utf8_lossy(&out.stderr));
+ let report: serde_json::Value = serde_json::from_slice(&out.stdout).expect("census json");
+ let census = Census::take();
+
+ let mut disagreements = Vec::new();
+ let mods = report.get("modules").and_then(|m| m.as_object()).expect("modules");
+ for (module, row) in mods {
+ let Some(mine) = census.modules.get(module) else {
+ disagreements.push(format!("{module}: the census tool sees a module this test does not"));
+ continue;
+ };
+ for (key, theirs) in [
+ ("pub", mine.pub_items),
+ ("dead", mine.dead),
+ ("test", mine.test_only),
+ ("deadonly", mine.dead_only),
+ ("priv", mine.pub_crate),
+ ("glob", mine.globs),
+ ] {
+ let got = row.get(key).and_then(|v| v.as_u64()).unwrap_or(u64::MAX) as usize;
+ if got != theirs {
+ disagreements.push(format!("{module}.{key}: tool {got}, test {theirs}"));
+ }
+ }
+ }
+ disagreements.sort();
+ assert!(
+ disagreements.is_empty(),
+ "tools/arch-census.py and this test disagree about what a module exports;\n\
+ one of them is wrong, and the budget cannot be trusted until they match:\n{}",
+ disagreements.join("\n")
+ );
+}
diff --git a/tests/layers.rs b/tests/layers.rs
deleted file mode 100644
index 1856462..0000000
--- a/tests/layers.rs
+++ /dev/null
@@ -1,74 +0,0 @@
-use std::path::{Path, PathBuf};
-
-fn src_root() -> PathBuf {
- Path::new(env!("CARGO_MANIFEST_DIR")).join("src")
-}
-
-fn rust_files(dir: &Path) -> Vec<PathBuf> {
- let mut out = Vec::new();
- let mut stack = vec![dir.to_path_buf()];
- while let Some(d) = stack.pop() {
- for entry in std::fs::read_dir(&d).expect("read dir") {
- let path = entry.expect("entry").path();
- if path.is_dir() {
- stack.push(path);
- } else if path.extension().is_some_and(|e| e == "rs") {
- out.push(path);
- }
- }
- }
- out.sort();
- out
-}
-
-fn edges(dir: &str, forbidden: &[&str]) -> Vec<String> {
- let mut hits = Vec::new();
- for file in rust_files(&src_root().join(dir)) {
- let text = std::fs::read_to_string(&file).expect("read file");
- for (n, line) in text.lines().enumerate() {
- let line = line.trim();
- if line.starts_with("//") {
- continue;
- }
- for m in forbidden {
- if line.contains(&format!("crate::{m}")) {
- hits.push(format!(
- "{}:{}: {line}",
- file.strip_prefix(src_root()).unwrap().display(),
- n + 1
- ));
- }
- }
- }
- }
- hits
-}
-
-#[test]
-fn persistence_names_nothing_above_itself() {
- let hits = edges("db", &["watch", "review", "pipeline", "http", "ops", "shims"]);
- assert!(hits.is_empty(), "src/db depends upward on the modules above it:\n{hits:#?}");
-}
-
-#[test]
-fn review_does_not_call_back_into_the_watcher() {
- let hits = edges("review", &["watch", "pipeline", "http"]);
- assert!(hits.is_empty(), "src/review depends on modules beside or above it:\n{hits:#?}");
-}
-
-#[test]
-fn the_watcher_does_not_reach_into_the_pipeline_or_the_ui() {
- let hits = edges("watch", &["pipeline", "http", "shims"]);
- assert!(hits.is_empty(), "src/watch depends on modules above it:\n{hits:#?}");
-}
-
-#[test]
-fn the_recipe_leaf_depends_on_nothing_above_it() {
- let text = std::fs::read_to_string(src_root().join("recipe.rs")).expect("read recipe.rs");
- for m in ["watch", "review", "pipeline", "http", "ops", "shims"] {
- assert!(
- !text.contains(&format!("crate::{m}")),
- "src/recipe.rs must not name crate::{m}"
- );
- }
-}
diff --git a/tools/arch-census.py b/tools/arch-census.py
index ca6d7b8..e6a8300 100755
--- a/tools/arch-census.py
+++ b/tools/arch-census.py
@@ -48,8 +48,8 @@ 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)
+PUB_CRATE_RE = re.compile(r"^\s*pub\(crate\)\s+(?:fn|struct|enum|trait|const|static|type)\s+")
+GLOB_RE = re.compile(r"^\s*pub(?:\(crate\))?\s+use\s+[^\n]*::\*")
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.
@@ -130,8 +130,13 @@ def census():
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))
+ for line in text.splitlines():
+ if COMMENT.match(line):
+ continue
+ if PUB_CRATE_RE.match(line):
+ row["priv"] += 1
+ if GLOB_RE.match(line):
+ row["glob"] += 1
size = text.count("\n") + 1
if size > row["largest"]:
row["largest"] = size