//! 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"), ("usecase", 9, "the workflows both front ends run: orchestrates review, watch, pipeline and ops"), ("http", 10, "the UI: renders use-case results, so only the composition roots are above it"), ("main", 11, "the CLI: composition root"), ("lib", 11, "the crate root: declares the modules and re-exports the error type"), ("bin/sandbox-agent", 11, "the sandbox agent: composition root on the far side of the wire"), ("bin/gpg", 11, "a shim binary: composition root for one tool"), ("bin/makepkg", 11, "a shim binary: composition root for one tool"), ("bin/makechrootpkg", 11, "a shim binary: composition root for one tool"), ("bin/mkarchroot", 11, "a shim binary: composition root for one tool"), ("bin/pacman", 11, "a shim binary: composition root for one tool"), ("bin/repo-add", 11, "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. `db` used to need two; it /// now names every export, so the slot is closed rather than left at zero. const GLOB_ALLOWLIST: &[(&str, usize)] = &[("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) { 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 { 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 { 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 = 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 { 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 { pub_crate_decl(line).is_some() } /// The name a `pub(crate)` declaration introduces. A narrowed item is still a /// member of its module, which is what the allowlist is checked against. fn pub_crate_decl(line: &str) -> Option { if is_comment(line) { return None; } let rest = line.trim_start().strip_prefix("pub(crate) ")?; 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_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 { 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, over_wide: usize, globs: usize, lines: usize, } #[derive(Debug)] struct Census { modules: BTreeMap, edges: BTreeMap>, } 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 = test_files() .iter() .map(|f| std::fs::read_to_string(f).expect("read test")) .collect(); let mut modules: BTreeMap = BTreeMap::new(); let allowlist = allowed_pub_items(); 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> = 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 { // An item the budget file argues for is a decision, not a hole, // so it leaves the dead columns entirely. `deadonly` then means // *dead and unargued* — the one number that can stay at zero. if allowlist.contains(&format!("{module}.{name}")) { continue; } let module = modules.get_mut(module).unwrap(); module.dead += 1; if used_by_tests { module.test_only += 1; } else { module.dead_only += 1; } } } // A `pub(crate)` item is over-wide when no file except the one that // declares it writes its name: it offers the crate a thing nothing // outside its own file reaches, and plain private is what it should be. // `tests/` is not consulted — a separate crate cannot name a `pub(crate)` // item, so a mention there says nothing. As with `dead`, a name declared // in several files is flagged only when no file outside all of them says // it, and the compiler, not this count, gives the verdict. let mut pc_declared: BTreeMap> = BTreeMap::new(); for (path, text) in &texts { for line in text.lines() { if let Some(name) = pub_crate_decl(line) { pc_declared.entry(name).or_default().insert(path.clone()); } } } let over_allow = allowed_overwide_items(); for (name, files) in &pc_declared { let read_outside = texts .iter() .any(|(path, text)| !files.contains(path) && mentions(text, name)); if read_outside { continue; } for path in files { let module = module_of(path); // Argued, so not counted: the reason it stays `pub(crate)` is in // the budget file next to its name, exactly as on the `pub` side. if over_allow.contains(&format!("{module}.{name}")) { continue; } modules.get_mut(&module).unwrap().over_wide += 1; } } let mut edges: BTreeMap> = BTreeMap::new(); for (path, text) in &texts { let source = module_of(path); let known: BTreeSet = 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> { 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 } } /// The `dead_code.allowlist` keys — `module.item` for every item that stays /// `pub` by decision, with its reason next to it in the same file. fn allowed_pub_items() -> BTreeSet { 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"); value .get("dead_code") .and_then(|d| d.get("allowlist")) .and_then(|a| a.as_object()) .map(|a| { a.keys() .map(|k| { assert!(!k.trim().is_empty(), "an allowlist key cannot be blank"); k.clone() }) .collect() }) .unwrap_or_default() } /// The `over_visibility.allowlist` keys — `module.item` for every `pub(crate)` /// item that stays `pub(crate)` by decision, with the compiler fact beside it. fn allowed_overwide_items() -> BTreeSet { 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"); value .get("over_visibility") .and_then(|d| d.get("allowlist")) .and_then(|a| a.as_object()) .map(|a| { a.keys() .map(|k| { assert!(!k.trim().is_empty(), "an over-wide permission key cannot be blank"); k.clone() }) .collect() }) .unwrap_or_default() } /// A top-level section of the budget file, as `key -> allowed`. fn budget_section(section: &str) -> BTreeMap { 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 obj = value .get(section) .unwrap_or_else(|| panic!("budget file has no `{section}` section")) .as_object() .unwrap_or_else(|| panic!("budget `{section}` section is an object")); for (key, val) in obj { if let Some(n) = val.as_u64() { out.insert(key.clone(), n as usize); } } out } fn rank_of(module: &str) -> Option { 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); 5] { [ ("pub", row.pub_items), ("dead", row.dead), ("deadonly", row.dead_only), ("overwide", row.over_wide), ("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), ("overwide", mine.over_wide), ("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") ); } /// Every `pub` item that exists only because a test names it has a recorded /// disposition, and the counts may only shrink. /// /// `tools/test-surface.py` asks two questions the census cannot: whether a test /// actually *calls* the item or merely mentions it inside a string, and whether /// production code inside the declaring module calls it. The answers yield four /// dispositions — `gate`, `move-test`, `narrow`, `residue` — and this test holds /// the crate to them in three ways: /// /// - every row must carry a hand-written reason from /// `tools/test-surface-reasons.json`, so no item is disposed of by a heuristic /// nobody read; /// - the per-disposition counts, and `gate_pending` — items decided to be gated /// but not yet gated — may only shrink against the budget. /// /// `residue` is the honest column: items production needs inside their own module /// *and* a fixture-bound integration test needs from outside. Rust has no /// test-conditional visibility, so those cannot be narrowed without breaking one /// side or the other; ratcheting the count is what keeps the column from growing /// while it is worked down by changing tests rather than visibilities. #[test] fn the_test_surface_is_disposed_of() { if !std::process::Command::new("python3") .arg("--version") .output() .is_ok() { println!("python3 is not on PATH — skipping the test-surface check"); return; } let out = std::process::Command::new("python3") .arg("tools/test-surface.py") .arg("--json") .current_dir(root()) .output() .expect("run tools/test-surface.py"); assert!( out.status.success(), "tools/test-surface.py failed: {}", String::from_utf8_lossy(&out.stderr) ); let report: serde_json::Value = serde_json::from_slice(&out.stdout).expect("test-surface json"); let rows = report.get("rows").and_then(|r| r.as_array()).expect("rows"); let mut unreasoned = Vec::new(); let mut unconfirmed = Vec::new(); for row in rows { let name = row.get("name").and_then(|v| v.as_str()).unwrap_or("?"); let module = row.get("module").and_then(|v| v.as_str()).unwrap_or("?"); let disp = row.get("disp").and_then(|v| v.as_str()).unwrap_or("?"); if !row.get("hand_written").and_then(|v| v.as_bool()).unwrap_or(false) { unreasoned.push(format!("{module}.{name} ({disp})")); } // Every piece of in-module evidence for this item is a call in method // position on some receiver. A name match cannot tell `self.store_dir()` // from `listener.local_addr()` — the latter is std's, on a different // type, and it once made a function with no callers look production-used. // So these rows are named for a human and stay failing until confirmed. if row.get("dotted_only").and_then(|v| v.as_bool()).unwrap_or(false) && disp != "already-gated" && !row.get("confirmed").and_then(|v| v.as_bool()).unwrap_or(false) { unconfirmed.push(format!("{module}.{name} at {}", row.get("where").and_then(|v| v.as_str()).unwrap_or("?"))); } } assert!( unreasoned.is_empty(), "{} test-only items have no hand-written disposition reason in \ tools/test-surface-reasons.json:\n{}\n\ a disposition nobody argued for is not a decision.", unreasoned.len(), unreasoned.join("\n") ); assert!( unconfirmed.is_empty(), "{} items are counted as production-used only because something calls \ `.name()` somewhere in their module, and no human has confirmed that the \ receiver is the right type. Read each cited line and add it to \ tools/test-surface-confirmed.json, or gate the item:\n{}", unconfirmed.len(), unconfirmed.join("\n") ); // A row is `ambiguous` when the only evidence that production uses the item // is a bare mention of a name the detector cannot resolve — `new`, `open` // and `record` are declared in many modules, and a line saying `Foo::new()` // in http says nothing about `db::open`. The tool genuinely does not know, // so a human has to say which item the mention meant and record the verdict. let mut unadjudicated = Vec::new(); for row in rows { if row.get("ambiguous").and_then(|v| v.as_bool()).unwrap_or(false) && !row.get("adjudicated").and_then(|v| v.as_bool()).unwrap_or(false) { unadjudicated.push(format!( "{}:{} at {}", row.get("module").and_then(|v| v.as_str()).unwrap_or("?"), row.get("name").and_then(|v| v.as_str()).unwrap_or("?"), row.get("where").and_then(|v| v.as_str()).unwrap_or("?") )); } } assert!( unadjudicated.is_empty(), "{} items look production-used only because a bare mention of a colliding \n\ name could have meant them, and no human has said which item the mention \n\ referred to. Read the cited line and record the verdict in \n\ tools/test-surface-ambiguous.json:\n{}", unadjudicated.len(), unadjudicated.join("\n") ); let budget = budget_section("test_surface"); let surface = &budget; let counts = report.get("counts").and_then(|c| c.as_object()).expect("counts"); let mut looser = Vec::new(); let mut tighter = Vec::new(); for (key, ceiling) in surface { let actual = counts.get(key).and_then(|v| v.as_u64()).unwrap_or(0) as usize; if actual > *ceiling { looser.push(format!("{key}: budget {ceiling}, actual {actual}")); } else if actual < *ceiling { tighter.push(format!("{key}: budget {ceiling}, actual {actual}")); } } assert!( looser.is_empty(), "the test surface grew past its budget — a new `pub` item that only tests \ name needs a disposition and a lower ceiling elsewhere:\n{}", looser.join("\n") ); assert!( tighter.is_empty(), "these test-surface budgets are looser than the code, hiding ground already \ won (rewrite with `python3 tools/test-surface.py --write` and re-record):\n{}", tighter.join("\n") ); } /// The definitive check, and the slow one: compile a throwaway crate against /// `aur-build` twice, once without `test-support` and once with it, and try to /// name every dispositioned item from outside. /// /// `tools/test-surface.py` infers the test surface by reading source, and /// inference has been wrong before — a name matched inside a string literal /// made `review::approve::withdraw` look production-used, and keying rows by /// bare name merged `pipeline::dispatch::Pool::shutdown` into the gated /// `db::Writer::shutdown` row. This test does not read source. It asks the /// compiler what a release build actually lets an outside crate reach. /// /// `#[ignore]`d because it builds the library twice from scratch, roughly /// doubling the suite. Run it with `cargo test --test architecture -- --ignored` /// or `AUR_PROBE_RELEASE_SURFACE=1 cargo test --test architecture`. #[test] #[ignore = "builds the library twice; run with --ignored or AUR_PROBE_RELEASE_SURFACE=1"] fn the_release_build_exports_nothing_that_only_tests_reach() { let out = std::process::Command::new("python3") .arg("tools/release-surface-probe.py") .current_dir(root()) .output() .expect("run tools/release-surface-probe.py"); let text = String::from_utf8_lossy(&out.stdout).to_string(); assert!( out.status.success(), "a release build still exports something only the test tier needs:\n{text}{}", String::from_utf8_lossy(&out.stderr) ); assert!( text.contains("nothing leaked"), "the probe did not report success:\n{text}" ); } /// The `dead_code.allowlist` is a set of decisions, so it has to stay in step /// with the code in both directions. /// /// An entry that names nothing is the dangerous direction: it is an excuse that /// outlived the item it excused, and the next item to appear under that name /// inherits a permission nobody granted. The other direction — a blank reason — /// is an entry nobody read, which is the same thing as no entry. #[test] fn the_dead_code_allowlist_names_real_items() { 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 allow = value .get("dead_code") .and_then(|d| d.get("allowlist")) .and_then(|a| a.as_object()) .expect("budget file has a dead_code.allowlist object"); // Every name a module declares, `pub` or `pub(crate)`: a narrowed item keeps // its entry (the reason it is not named from outside still holds), an item // that no longer exists does not. let mut declared: BTreeMap> = BTreeMap::new(); for path in src_files() { let module = module_of(&path); for line in std::fs::read_to_string(&path).expect("read source").lines() { let name = match pub_decl(line) { Some(name) => name, None => match pub_crate_decl(line) { Some(name) => name, None => continue, }, }; if !name.is_empty() { declared.entry(module.clone()).or_default().insert(name); } } } let mut stale = Vec::new(); let mut blank = Vec::new(); for (key, reason) in allow { let Some((module, name)) = key.split_once('.') else { stale.push(format!("{key}: a key is `module.item`")); continue; }; if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) { blank.push(key.clone()); } if !declared.get(module).is_some_and(|names| names.contains(name)) { stale.push(format!("{key} at {reason}")); } } stale.sort(); blank.sort(); assert!( stale.is_empty(), "these allowlist entries name something the module no longer declares.\n\ A permission nobody can point at is how a dead item returns unnoticed:\n{}", stale.join("\n") ); assert!( blank.is_empty(), "these allowlist entries have no reason (or one too short to be a reason):\n{}\n\ an item is kept by an argument, not by a blank line.", blank.join("\n") ); } /// The `over_visibility.allowlist` is a set of decisions too, and it is checked /// the same two ways: an entry must name something that is still `pub(crate)` in /// the module it names, and it must carry a reason worth reading. /// /// The first direction matters more here than on the `pub` side. A `pub(crate)` /// item that has since gone private still matches a `module.item` key written /// against the module's declared names, so the check has to look at the /// `pub(crate)` declarations specifically — otherwise the permission quietly /// re-widens the item it was left behind by. #[test] fn the_over_visibility_allowlist_names_real_items() { 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 allow = value .get("over_visibility") .and_then(|d| d.get("allowlist")) .and_then(|a| a.as_object()) .expect("budget file has an over_visibility.allowlist object"); let mut pub_crate_declared: BTreeMap> = BTreeMap::new(); for path in src_files() { let module = module_of(&path); for line in std::fs::read_to_string(&path).expect("read source").lines() { if let Some(name) = pub_crate_decl(line) { pub_crate_declared.entry(module.clone()).or_default().insert(name); } } } let mut stale = Vec::new(); let mut blank = Vec::new(); for (key, reason) in allow { let Some((module, name)) = key.split_once('.') else { stale.push(format!("{key}: a key is `module.item`")); continue; }; if reason.as_str().map(|r| r.trim().len() < 20).unwrap_or(true) { blank.push(key.clone()); } if !pub_crate_declared .get(module) .is_some_and(|names| names.contains(name)) { stale.push(format!("{key} at {reason}")); } } stale.sort(); blank.sort(); assert!( stale.is_empty(), "these over-wide permissions name something that is no longer a `pub(crate)`\n\ item in that module — it went private, or it was never one:\n{}", stale.join("\n") ); assert!( blank.is_empty(), "these over-wide permissions have no reason (or one too short to be one):\n{}\n\ say what the compiler refuses to let go private, not that it felt safer.", blank.join("\n") ); } /// `tests/common/mod.rs` is compiled into every test binary, so the suite keeps /// a crate-level `allow(dead_code)` there — a helper used by one binary is dead /// code in the other twenty, and the lint would fire everywhere and mean /// nothing. That allowance is only honest if nothing is unused by *all* of them, /// which is what this checks. /// /// A name is used if anything under `tests/` writes it besides its own /// declaration. A type whose name nobody writes is still used if a field or /// method of it is: `Web::raw_request` hands back a `Raw` no test names, and /// reading `.status` off it is a use of the type. /// /// Private items are checked too. The blanket allowance in `tests/common` /// excuses a private helper exactly as thoroughly as a public one, and a /// private helper called by nothing is the harder case to notice, not the /// easier one. #[test] fn the_test_helpers_are_used() { let common = root().join("tests/common/mod.rs"); let text = std::fs::read_to_string(&common).expect("read tests/common/mod.rs"); let mut others = String::new(); for path in test_files() { others.push_str(&std::fs::read_to_string(&path).expect("read test")); } let lines: Vec<&str> = text.lines().collect(); let mut unused = Vec::new(); for (i, line) in lines.iter().enumerate() { // `pub` and private alike: the blanket `allow(dead_code)` at the top of // the file excuses both, so a private helper nobody calls is exactly as // dead as a public one, and just as invisible to the compiler here. let t = line.trim_start(); let indent = line.len() - t.len(); if indent > 4 { continue; } let rest = t.strip_prefix("pub ").unwrap_or(t); let Some(kind) = ["fn ", "struct ", "enum ", "const ", "static ", "type ", "trait "] .into_iter() .find(|k| rest.starts_with(k)) else { continue; }; let name = word_tail(&rest[kind.len()..]); if name.is_empty() { continue; } // Everything this declaration introduces, minus the declaration itself. let mut corpus = others .replace(&format!("pub {kind}{name}"), "") .replace(&format!("{kind}{name}"), ""); if kind != "fn " { // Members of a struct or enum count as uses of the type. let mut depth = 0; for follow in lines[i..].iter() { depth += follow.matches('{').count() as i32 - follow.matches('}').count() as i32; if depth > 1 { let member = follow .trim_start() .trim_start_matches("pub ") .split([':', '(']) .next() .unwrap_or("") .split_whitespace() .last() .unwrap_or(""); if !member.is_empty() && member != name { corpus.push('\n'); corpus.push_str(member); } } if depth <= 0 && follow != line { break; } } } if !mentions(&corpus, &name) { unused.push(format!("{name} ({})", &t[..t.len().min(60)])); } } unused.sort(); assert!( unused.is_empty(), "these test helpers are named by no test:\n{}\n\ delete them; `allow(dead_code)` in `tests/common` excuses per-binary \ noise, not dead weight.", unused.join("\n") ); } /// A fixture no test names is a corpus entry nobody maintains: it still costs /// the copy every `env_with_fixture` performs on its way to failing, and it /// drifts silently because nothing notices it drifting. #[test] fn every_fixture_is_referenced() { let corpus = root().join("testcorpus"); let mut names = String::new(); for path in test_files() { names.push_str(&std::fs::read_to_string(&path).expect("read test")); } let unreferenced: Vec = std::fs::read_dir(&corpus) .expect("read testcorpus") .filter_map(|e| e.ok()) .filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) .map(|e| e.file_name().to_string_lossy().to_string()) .filter(|name| !mentions(&names, name)) .collect(); assert!( unreferenced.is_empty(), "these fixtures in testcorpus/ are named by no test: {unreferenced:?}\n\ either drive one or delete the directory.", ); } /// The two places the budget states how many unargued dead items a module may /// have must say the same thing. /// /// `modules..deadonly` is the ratchet `interfaces_stay_within_budget` reads; /// `dead_code.deadonly.` is the one `tools/arch-census.py --budget` reads. /// They are written by the same invocation and disagree only if someone edited /// one by hand, which is exactly the moment a ratchet stops meaning anything. /// Both are zero, and zero is the point: an item that is dead, exported and /// unargued is not a budget question, it is a failure. #[test] fn the_dead_code_budget_matches_the_code() { let path = root().join("tests/architecture-budget.json"); let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("read budget")).expect("budget is json"); let modules = value.get("modules").and_then(|m| m.as_object()).expect("modules"); let dead_code = value .get("dead_code") .and_then(|d| d.get("deadonly")) .and_then(|d| d.as_object()) .expect("dead_code.deadonly"); let census = Census::take(); let mut mismatch = Vec::new(); for (module, row) in modules { let interface = row.get("deadonly").and_then(|v| v.as_u64()).unwrap_or(u64::MAX); let dead = dead_code.get(module).and_then(|v| v.as_u64()); let actual = census .modules .get(module) .map(|m| m.dead_only as u64) .unwrap_or(u64::MAX); if dead != Some(interface) || interface != actual { mismatch.push(format!( "{module}: dead_code.deadonly {:?}, modules.deadonly {interface}, actual {actual}", dead )); } } for module in dead_code.keys() { if !modules.contains_key(module) { mismatch.push(format!("{module}: in dead_code.deadonly, absent from modules")); } } mismatch.sort(); assert!( mismatch.is_empty(), "the budget contradicts itself about how many unargued dead items a module has:\n{}", mismatch.join("\n") ); } #[test] fn the_over_visibility_budget_matches_the_code() { // The same self-consistency the dead-code budget is held to: the accepted // count, the number in the `modules` section, and the number the census // actually measures have to be one number, or the ratchet is checking a // figure nothing reads. let path = root().join("tests/architecture-budget.json"); let value: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("read budget")).expect("budget is json"); let modules = value.get("modules").and_then(|m| m.as_object()).expect("modules"); let over = value .get("over_visibility") .and_then(|d| d.get("overwide")) .and_then(|d| d.as_object()) .expect("over_visibility.overwide"); let census = Census::take(); let mut mismatch = Vec::new(); for (module, row) in modules { let stated = row.get("overwide").and_then(|v| v.as_u64()).unwrap_or(u64::MAX); let accepted = over.get(module).and_then(|v| v.as_u64()); let actual = census .modules .get(module) .map(|m| m.over_wide as u64) .unwrap_or(u64::MAX); if accepted != Some(stated) || stated != actual { mismatch.push(format!( "{module}: over_visibility.overwide {:?}, modules.overwide {stated}, actual {actual}", accepted )); } } for module in over.keys() { if !modules.contains_key(module) { mismatch.push(format!("{module}: in over_visibility.overwide, absent from modules")); } } mismatch.sort(); assert!( mismatch.is_empty(), "the budget contradicts itself about how many over-wide `pub(crate)` items a\n\ module has:\n{}", mismatch.join("\n") ); } /// Two tools write one file, so neither may erase what the other owns. /// /// `tools/arch-census.py` writes the module numbers and the accepted dead-code /// counts; `tools/test-surface.py` writes the test-surface counts; a human owns /// the allowlist. A rewrite that drops a section does not fail anything until /// the ratchet quietly stops checking that axis, so this runs both writers /// against a copy and fails if either section disappears. #[test] fn the_budget_writers_preserve_each_other() { let source = std::fs::read_to_string(root().join("tests/architecture-budget.json")).expect("read budget"); let before: serde_json::Value = serde_json::from_str(&source).expect("budget is json"); let tmp = std::env::temp_dir().join(format!("aur-budget-preserve-{}.json", std::process::id())); std::fs::write(&tmp, &source).expect("write temp budget"); for tool in ["tools/arch-census.py", "tools/test-surface.py"] { let out = std::process::Command::new("python3") .arg(tool) .arg("--write-budget") .arg(&tmp) .current_dir(root()) .output() .unwrap_or_else(|e| panic!("run {tool}: {e}")); assert!(out.status.success(), "{tool} failed: {}", String::from_utf8_lossy(&out.stderr)); let after: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tmp).expect("read temp budget")) .expect("written budget is json"); for section in ["test_surface", "dead_code", "over_visibility"] { assert!( after.get(section).is_some(), "{tool} erased the `{section}` section it does not own" ); } assert_eq!( after["dead_code"]["allowlist"], before["dead_code"]["allowlist"], "{tool} rewrote the hand-written allowlist" ); } std::fs::remove_file(&tmp).ok(); }