diff options
| author | aur-build <aur-build@localhost> | 2026-11-21 11:06:01 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-21 11:06:01 +0000 |
| commit | 4aaa0b87618ab3f41049a4da587421b758449f6f (patch) | |
| tree | 45f7918c3b126dd9339cd7a2cf64e7d474566f18 /tools | |
| parent | 7f5d3dc2ae540b7d4faf5e8c854e638fe70b9fd3 (diff) | |
| download | aur-build-4aaa0b87618ab3f41049a4da587421b758449f6f.tar.gz aur-build-4aaa0b87618ab3f41049a4da587421b758449f6f.zip | |
tools: the probe enumerates pub items itself instead of trusting the table
`release-surface-probe.py` used to take its candidate list from
`tools/test-surface.py`. That made it strictly downstream of the inference it
existed to audit: an item the detector dropped could never be probed, and the
tool reported "0 leaked" about a table that was missing the leak. The auditor was
right that "proven by compiling, not inferring" did not hold.
It now enumerates on its own — every `pub` declaration in `src/`, found by
scanning the files — and applies its own deliberately simpler production-use
rule (comments, strings and `use` lines do not count). Two independent rules that
must agree is a check; one rule consulted twice is not.
Three control experiments were run against it, and the first two failed before
the tool was correct:
- un-gating `review::approve::withdraw` initially reported nothing, because the
probe built paths from the census module (`aur_build::review::withdraw`)
instead of the real one (`aur_build::review::approve::withdraw`). A path that
cannot compile even with the feature was silently filed as "not nameable".
Paths are now derived from the declaring file, with the module-door and
intermediate re-export paths tried too.
- with that fixed, un-gating `withdraw` is caught by name and location.
- restoring `open_reviews_for` together with the test that used it is caught too.
Restoring only the function is correctly not caught: with no test naming it,
it is dead code, not a test-only leak.
That last distinction is a separate category now. A public item that nothing in
`src` or `tests` reaches — `reopen_rejected`'s shape — is reported and fails the
run, counted over the declaring file too so a helper used only by its own module
is not falsely called unreachable.
`db::Writer` stays reachable on purpose and is now probed for that claim: an item
listed in `test-surface-interface.json` must actually resolve, or the file is
stale and the probe says so.
Diffstat (limited to 'tools')
| -rw-r--r-- | tools/release-surface-probe.py | 392 |
1 files changed, 299 insertions, 93 deletions
diff --git a/tools/release-surface-probe.py b/tools/release-surface-probe.py index 2f6830b..ad87e1d 100644 --- a/tools/release-surface-probe.py +++ b/tools/release-surface-probe.py @@ -1,31 +1,34 @@ #!/usr/bin/env python3 -"""Prove what the release build actually exports, by compiling against it. +"""Prove what the release build exports, without asking the detector's permission. -`tools/test-surface.py` reads the source and *infers* which `pub` items exist -only for tests. Inference can be wrong — it already was, twice: a detector that -matched names inside string literals called `review::approve::withdraw` -production-used, and a detector keyed by bare name merged -`pipeline::dispatch::Pool::shutdown` into the gated `db::Writer::shutdown` row. +The first version of this tool took its candidate list from +`tools/test-surface.py`. That made it strictly downstream of the inference it +was meant to audit: an item the detector dropped could never be probed, and the +tool cheerfully reported "0 leaked" about a table that was missing the leak. +`db::candidates::open_reviews_for` was exactly that item — ungated, zero +production callers, named only by a test, reachable from an external release +build, and absent from the table. -This tool does not infer. It writes a throwaway crate that depends on -`aur-build` twice over — once without `test-support`, once with — and tries to -name every dispositioned item from outside. An item is honest only if: +So this version enumerates on its own: - * at least one candidate path compiles **with** the feature, which proves the - path is real and the item is genuinely reachable to the test tier, and - * every path that compiles with the feature fails **without** it, which proves - a release build does not export it. + 1. every `pub` declaration in `src/`, found by scanning the files directly; + 2. which of those names appear in `tests/`, so an item nobody outside the crate + is asked for is not this tool's business; + 3. for each candidate, a real compile against the library twice — once without + `test-support`, once with it. -A path that compiles in both builds is a leak and this tool exits non-zero. +An item fails if a release build lets an outside crate reach it, a test names +it, and it is not declared in `tools/test-surface-interface.json` as public +because a public signature requires it. Items the detector missed therefore show +up here as failures rather than as an empty table. -An item with no nameable path at all is not a pass and not a failure: a method -(`Config::store_dir`) or a const inside a private submodule cannot be named by a -`use` line whatever its visibility. Those are reported separately with the -source line that states their visibility, for a human to read. +The compile is the only part that is not inference. A path that compiles *with* +`test-support` proves the path is real; the same path failing *without* it proves +the release build does not export it. Usage: python3 tools/release-surface-probe.py # report - python3 tools/release-surface-probe.py --quiet # exit code only + python3 tools/release-surface-probe.py --quiet # exit status only """ import argparse import json @@ -36,37 +39,134 @@ import subprocess import sys ROOT = os.path.dirname(os.path.abspath(__file__)) + "/.." +SRC = os.path.join(ROOT, "src") +TESTS = os.path.join(ROOT, "tests") CACHE = os.path.join(ROOT, "target", "release-surface-probe") +DECL = re.compile(r"^\s*pub\s+(fn|struct|enum|trait|const|static|type|mod)\s+([A-Za-z0-9_]+)") +COMMENT = re.compile(r"^\s*(?://|//!|///)") +GATE = 'feature = "test-support"' -def table(): - out = subprocess.run([sys.executable, os.path.join(ROOT, "tools", "test-surface.py"), - "--json"], capture_output=True, text=True, cwd=ROOT) - if out.returncode != 0: - sys.exit("tools/test-surface.py failed: " + out.stderr) - return json.loads(out.stdout)["rows"] +def rust_files(d): + out = [] + for base, _, files in os.walk(d): + for f in sorted(files): + if f.endswith(".rs"): + out.append(os.path.join(base, f)) + return out -def candidates(row): - """Paths an outside crate could try for this item. - The declaring file's module path, and the top-level module the census groups - it under, because most items are re-exported up to the module door. Neither - reaches a method or an item inside a nested private module; those are - reported as not nameable rather than guessed at. +def module_of(path): + 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 strip_line(line): + """Drop comments and string literals: a mention inside either is not a call.""" + line = re.sub(r"//[^\"]*$", "", line) + line = re.sub(r'r#?"(?:[^"\\]|\\.)*"#?', '""', line) + line = re.sub(r'"(?:[^"\\]|\\.)*"', '""', line) + return line + + +def use_lines(text): + out, in_use, depth = set(), False, 0 + for i, raw in enumerate(text.split("\n")): + line = strip_line(raw) + if not in_use and re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?use\b", line): + in_use = True + if in_use: + out.add(i) + depth += line.count("{") - line.count("}") + if ";" in line and depth <= 0: + in_use, depth = False, 0 + return out + + +def declarations(): + """Every `pub` declaration in src/, found here rather than by asking anyone. + + Skips a declaration that a `use` statement shares (a re-export is not a new + item) and one whose attribute block carries the test-support gate, since a + release build does not compile it at all. """ - f = row["where"].rsplit(":", 1)[0] - mod = f[len("src/"):-len(".rs")] - if mod.endswith("/mod"): - mod = mod[: -len("/mod")] - top = mod.split("/")[0] - paths = {"aur_build::%s::%s" % (mod.replace("/", "::"), row["name"]), - "aur_build::%s::%s" % (top, row["name"])} - return sorted(paths) - - -def build(feature): - """Compile one probe binary per candidate path; return the set that failed.""" + out = [] + for path in rust_files(SRC): + text = open(path).read() + lines = text.split("\n") + used = use_lines(text) + for i, line in enumerate(lines): + if i in used or COMMENT.match(line): + continue + m = DECL.match(line) + if not m: + continue + k, gated = i - 1, False + while k >= max(0, i - 6) and (lines[k].strip().startswith("#[") + or lines[k].strip().startswith("//") + or not lines[k].strip()): + if GATE in lines[k]: + gated = True + k -= 1 + if gated: + continue + mod = module_of(path) + if mod.startswith("bin"): + continue + out.append({"name": m.group(2), "module": mod, "kind": m.group(1), + "file": path, + "where": "%s:%d" % (os.path.relpath(path, ROOT), i + 1)}) + return out + + +def test_named(): + """Names the test tier writes, with comments and strings removed.""" + names = set() + for path in rust_files(TESTS): + for line in open(path).read().split("\n"): + clean = strip_line(line) + for m in re.finditer(r"\b([A-Za-z_][A-Za-z0-9_]*)\b", clean): + names.add(m.group(1)) + return names + + +def paths_for(decl): + """Every path an outside crate could use to name this item. + + The declaring *file* gives the real module path — an item in + `src/review/approve.rs` is `aur_build::review::approve::name`, not + `aur_build::review::name`. Deriving the path from the census module instead + was a silent failure: the probe could not compile the path even with + `test-support`, filed the item as "not nameable", and reported no leak for + an item that was leaking. A path that fails to compile is only evidence when + the path is right, so the submodule path and the module-door re-export path + are both tried. + """ + rel = os.path.relpath(decl["file"], SRC) + parts = rel.split(os.sep) + if parts[-1] == "mod.rs": + parts = parts[:-1] + else: + parts[-1] = parts[-1][:-3] + real = "::".join(parts) + top = parts[0] + out = {"aur_build::%s::%s" % (real, decl["name"])} + # the module door, where most items are re-exported for callers + out.add("aur_build::%s::%s" % (top, decl["name"])) + # any intermediate directory that re-exports it, e.g. `aur_build::review::x::Name` + for i in range(1, len(parts)): + out.add("aur_build::%s::%s" % ("::".join(parts[:i]), decl["name"])) + return sorted(out) + + +def compile_probe(units, feature): + """Compile one tiny binary per path; return the set of names that failed.""" d = os.path.join(CACHE, "with" if feature else "no") shutil.rmtree(d, ignore_errors=True) os.makedirs(os.path.join(d, "src", "bin")) @@ -75,73 +175,179 @@ def build(feature): '[dependencies]\naur-build = { path = "%s"%s }\n' % (os.path.abspath(os.path.join(ROOT, ".")), ', features = ["test-support"]' if feature else "")) + os.makedirs(os.path.join(d, "src"), exist_ok=True) with open(os.path.join(d, "src", "main.rs"), "w") as h: h.write("fn main() {}\n") - - units = {} - rows = table() - for i, row in enumerate(rows): - for j, path in enumerate(candidates(row)): - name = "x%02d_%d" % (i, j) - units[name] = (row["module"], row["name"], path, row["disp"]) - with open(os.path.join(d, "src", "bin", name + ".rs"), "w") as h: - h.write("#![allow(unused_imports, dead_code)]\nuse %s;\nfn main() {}\n" % path) - + for name, path in units.items(): + with open(os.path.join(d, "src", "bin", name + ".rs"), "w") as h: + h.write("#![allow(unused_imports, dead_code)]\nuse %s;\nfn main() {}\n" % path) r = subprocess.run(["cargo", "build", "--bins", "--keep-going", "--message-format=short", "--target-dir", os.path.join(CACHE, "tgt-" + ("with" if feature else "no"))], cwd=d, capture_output=True, text=True) - if "error: could not compile `surface-probe`" not in r.stdout + r.stderr and not units: - sys.exit("probe build produced no output; cargo is not working") - failed = set(re.findall(r"\b(x\d+_\d+)\.rs", r.stdout + r.stderr)) - return units, failed + return set(re.findall(r"\b(p\d+)\.rs", r.stdout + r.stderr)) + + +def production_used(decls): + """{(module, name)} for items some module other than the declaring one writes. + + Deliberately a second, simpler implementation rather than a call into the + resolver in `tools/test-surface.py`. Two independent rules that must agree + is a check; one rule consulted twice is not. The only refinement over "the + name appears elsewhere" is the two things that made the first detector lie: + comments and string literals do not count, and neither does a `use` line — + a re-export is not a call. That one refinement is what makes + `open_reviews_for` visible here: its only outside mention was the line that + re-exported it. + """ + used = set() + texts = {p: open(p).read() for p in rust_files(SRC)} + stripped = {} + for p, t in texts.items(): + skip = use_lines(t) + stripped[p] = [strip_line(l) for i, l in enumerate(t.split("\n")) + if i not in skip and not COMMENT.match(l)] + for d in decls: + pat = re.compile(r"\b%s\b" % re.escape(d["name"])) + for p, lines in stripped.items(): + if module_of(p) == d["module"]: + continue + if any(pat.search(l) for l in lines): + used.add((d["module"], d["name"])) + break + # A `pub mod` is a namespace, not an item. Nothing outside `watch` writes the + # word `upstream` — they write `upstream::probe` — so a module declaration is + # credited by whether anything declared in the file it names is used. + files_in_use = {d["file"] for d in decls if (d["module"], d["name"]) in used} + for d in decls: + if d["kind"] != "mod" or (d["module"], d["name"]) in used: + continue + here = os.path.dirname(d["file"]) + for cand in (os.path.join(here, d["name"] + ".rs"), + os.path.join(here, d["name"], "mod.rs")): + if os.path.exists(cand) and cand in files_in_use: + used.add((d["module"], d["name"])) + break + return used def main(): ap = argparse.ArgumentParser() - ap.add_argument("--quiet", action="store_true", help="print nothing unless something leaked") + ap.add_argument("--quiet", action="store_true") args = ap.parse_args() - units_with, failed_with = build(True) - _, failed_without = build(False) - - real = set(units_with) - failed_with # paths that really exist - # An `interface` item is reachable in a release build on purpose: a public - # signature requires it and no test asked for it. The probe's job is to - # confirm the reachability is the declared kind, not to pretend it is gone. - declared = {u for u in real if units_with[u][3] == "interface"} - leaked = sorted(real - failed_without - declared) # ...and a release build still exports - unexpected = sorted(declared - real) # declared public, but not reachable - nameable = {} - for u in real: - mod, name, path, disp = units_with[u] - nameable.setdefault((mod, name), []).append(path) - silent = sorted({(units_with[u][0], units_with[u][1]) for u in failed_with} - set(nameable)) + decls = declarations() + named = test_named() + used = production_used(decls) + interface = json.load(open(os.path.join(ROOT, "tools", "test-surface-interface.json"))) + + # Public and reached by nobody: no other module writes the name and no test + # does either. That is not the goal's headline failure — it is not test-only — + # but it is public surface with no caller, and it hides behind the same + # re-export line that hid the test-only ones. `db::candidates::reopen_rejected` + # was exactly this: declared, re-exported by `review`, called by nothing. + # Counted over every file, including the declaring one: an item used only by + # its own module is over-exposed, which is a different complaint from + # "nothing reaches it at all". Only the latter belongs here. + anywhere = {} + for path in rust_files(SRC): + text = open(path).read() + skip = use_lines(text) + anywhere[path] = " ".join(strip_line(l) for i, l in enumerate(text.split("\n")) + if i not in skip and not COMMENT.match(l)) + tests_text = " ".join(strip_line(l) for p in rust_files(TESTS) + for l in open(p).read().split("\n")) + + def reached_from_anywhere(d): + """Does anything other than the declaration itself write this name? + + Same-file use counts: a helper called three times in its own module is + not "reached by nothing", it is over-exposed, which is a different + complaint. Only the declaration line is excluded. + """ + pat = re.compile(r"\b%s\b" % re.escape(d["name"])) + if pat.search(tests_text): + return True + decl_line = d["file"], d["where"].rsplit(":", 1)[1] + for p, text in anywhere.items(): + if p != d["file"]: + if pat.search(text): + return True + # in the declaring file, on a line that is not the declaration + text = open(d["file"]).read() + skip = use_lines(text) + decl_no = int(d["where"].rsplit(":", 1)[1]) - 1 + for i, l in enumerate(text.split("\n")): + if i == decl_no or i in skip or COMMENT.match(l): + continue + if pat.search(strip_line(l)): + return True + return False + + unreachable = [d for d in decls + if d["kind"] != "mod" + and "%s.%s" % (d["module"], d["name"]) not in interface + and not reached_from_anywhere(d)] + + # Candidates: public declarations a test writes by name and no other module + # needs. Something production uses is not this goal's problem, and neither + # is something no test asks for, however dead it is. + units, owner = {}, {} + n = 0 + used_elsewhere = 0 + for d in decls: + declared_public = "%s.%s" % (d["module"], d["name"]) in interface + if declared_public: + # Probe the claim: an item declared public-on-purpose must actually be + # reachable, or the interface file is stale and quietly rotting. + pass + elif d["name"] not in named or (d["module"], d["name"]) in used: + used_elsewhere += 1 + continue + for p in paths_for(d): + units["p%04d" % n] = p + owner["p%04d" % n] = d + n += 1 + + failed_with = compile_probe(units, True) + failed_without = compile_probe(units, False) + + real = set(units) - failed_with # paths a test build can name + leaked = sorted(u for u in real + if u not in failed_without + and "%s.%s" % (owner[u]["module"], owner[u]["name"]) not in interface) + declared = sorted(u for u in real + if "%s.%s" % (owner[u]["module"], owner[u]["name"]) in interface) if not args.quiet: - print("candidate paths probed: %d" % len(units_with)) - print("real external paths: %d (compile with test-support)" % len(real)) - print("of those, unreachable in a release build: %d" % len([u for u in real if u in failed_without])) - print("declared public interface (reachable on purpose): %d" % len(declared)) - print("items with a nameable path: %d" % len(nameable)) - print("items no `use` line can name (methods, private submodules): %d" % len(silent)) - for mod, name in silent: - print(" %s.%s" % (mod, name)) + print("pub declarations found here: %d" % len(decls)) + print("used by another module: %d" % used_elsewhere) + print("probed as test-only: %d paths" % len(units)) + print("paths a test build can actually name: %d" % len(real)) + print("declared public interface: %d" % len(declared)) + for u in declared: + print(" %s (%s)" % (units[u], "%s.%s" % (owner[u]["module"], owner[u]["name"]))) + print("public with no caller anywhere: %d" % len(unreachable)) + for d in unreachable: + print(" %-22s %s" % (d["name"], d["where"])) print() - if unexpected: - print("DECLARED PUBLIC BUT NOT REACHABLE — the interface file is stale:") - for u in unexpected: - print(" %s.%s %s" % (units_with[u][0], units_with[u][1], units_with[u][2])) - return 1 - - if leaked: - print("LEAKED INTO THE RELEASE BUILD — these paths compile with and without the feature:") - for u in leaked: - mod, name, path, disp = units_with[u] - print(" %-14s %-22s %s (disposition: %s)" % (mod, name, path, disp)) + if leaked or unreachable: + if leaked: + print("LEAKED — a release build exports these and only tests name them:") + for u in leaked: + d = owner[u] + print(" %-22s %-14s %s" % (d["name"], d["where"], units[u])) + print("\nEither close them, or add each to tools/test-surface-interface.json " + "with the public signature that forces it open.") + if unreachable: + print("PUBLIC WITH NO CALLER — nothing in src or tests reaches these:") + for d in unreachable: + print(" %-22s %s" % (d["name"], d["where"])) + print("\nDelete them, or say what they are for.") return 1 if not args.quiet: - print("nothing leaked: every path that reaches the test tier is closed in a release build") + print("nothing leaked: every path a test can name is closed in a release build, " + "except the ones declared public on purpose") return 0 |
