From 92ecaabd7c62d029eba239e95cc8a7d2520fe4a9 Mon Sep 17 00:00:00 2001 From: aur-build Date: Fri, 20 Nov 2026 22:13:44 +0000 Subject: tools: the test-surface detector credited four items with callers they lack MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An audit found that `internal` — the check deciding whether a test-only item has a real production caller — was crediting non-calls. Four items were sorted into `residue` on false evidence, and each false credit was a different mistake: db::cas_accepted_release a `pub use` continuation line at db/mod.rs:55. Production does this CAS through `cas_accepted_release_in` inside a transaction; the two names differ by three characters. shims::invocations the string "invocations.jsonl", plus a call from `called_with`, which is itself test-support gated. A test-only function cannot be evidence that another function is production-used. sandbox::LocalAgentProvisioner its own struct and impl headers. Production selects `K8sSandboxProvisioner`. sandbox::local_addr `listener.local_addr()` — std's method on a TcpListener, in sibling files. The census treats all of src/sandbox as one module, and a name match cannot tell a receiver's type. All four are gated now. `KataBackend::local_addr` had zero callers in src and zero in tests — `tests/remote_agent.rs` calls `RemoteBackend::local_addr`, a different type — so it is deleted rather than gated. The detector now strips string literals and comments, skips `use` statements including the continuation lines of a brace-delimited block, skips an item's own impl headers, and refuses to count a call made inside a `#[cfg(test)]` module or a `test-support`-gated item. The case a regex cannot resolve is `self.store_dir()` versus `listener.local_addr()`: identical to a name match. Rows whose only evidence is a call in method position are flagged `⚑`, listed in `tools/test-surface-confirmed.json` only after a human read the cited line, and `the_test_surface_is_disposed_of` fails on any unconfirmed one. Four rows are confirmed that way — `config.store_dir`, `http.cookie`, `ops.build_success_rate`, `watch.needs_stage_b`. The table now prints each item's in-module call sites as its own column, because the residue count is the one number this work cannot eliminate and the claim underneath it has to be checkable rather than asserted. Suite: 284 passed, 0 failed. Clippy clean. Release build clean. --- tools/test-surface.py | 172 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 137 insertions(+), 35 deletions(-) (limited to 'tools/test-surface.py') diff --git a/tools/test-surface.py b/tools/test-surface.py index f51c26e..16929bd 100644 --- a/tools/test-surface.py +++ b/tools/test-surface.py @@ -46,6 +46,13 @@ HARNESS = ("Env::new", "env_with_fixture", "Fixture", "tempdir", "Command::new", # evidence the analysis already has. REASONS = json.load(open(os.path.join(ROOT, "tools", "test-surface-reasons.json"))) +# Rows whose only in-module evidence is a call in method position on some +# receiver. A name match cannot tell `self.store_dir()` from +# `listener.local_addr()`; a human has to. Each entry below was read at the +# cited line and confirmed to be a call of the item itself. Anything dotted-only +# and absent from this list fails `tests/architecture.rs`. +CONFIRMED = set(json.load(open(os.path.join(ROOT, "tools", "test-surface-confirmed.json")))) + def rust_files(d): out = [] @@ -66,28 +73,87 @@ def module_of(path): return parts[0].removesuffix(".rs") -def strip_test_modules(path): - """Lines of `path` with `#[cfg(test)] mod ... {}` blocks removed.""" +def line_context(path): + """Per line: (inside_cfg_test_mod, inside_test_support_gate). + + Both are tracked by brace depth from the attribute that opens them, so a + mention inside a `#[cfg(test)] mod tests {}` or a + `#[cfg(feature = "test-support")] fn ... {}` is not evidence that + production code uses the name. Getting this wrong is what once let a + test-only function be classified as production-used because its only + caller was another test-only function. + """ lines = open(path).read().split("\n") - out, i = [], 0 + ctx = [] + depth = 0 + test_mod_depth = None + gate_stack = [] # depths at which a test-support-gated block opened + pending = None # "test" | "gate" | None, from a pending attribute + i = 0 while i < len(lines): - if lines[i].strip() == "#[cfg(test)]": - j = i + 1 - while j < len(lines) and lines[j].strip().startswith("//"): - j += 1 - if j < len(lines) and re.match(r"\s*(?:pub(?:\(crate\))?\s+)?mod\s+\w+", lines[j]): - depth, started, k = 0, False, j - while k < len(lines): - depth += lines[k].count("{") - lines[k].count("}") - if "{" in lines[k]: - started = True - if started and depth <= 0: - break - k += 1 - i = k + 1 - continue - out.append(lines[i]) + line = lines[i] + stripped = line.strip() + if stripped.startswith("#[") and "test-support" in stripped: + pending = "gate" + elif stripped == "#[cfg(test)]": + pending = "test" + + opens = line.count("{") + closes = line.count("}") + is_decl = bool(re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?(?:fn|mod|struct|enum|trait|impl|const|static|type|use)\b", line)) + + # An attribute only attaches to the declaration on the next code line. + if pending and is_decl: + if pending == "test" and re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?mod\b", line): + test_mod_depth = depth + elif pending == "gate": + gate_stack.append(depth) + if pending and (is_decl or not stripped.startswith("#")): + if not is_decl: + pending = None + + ctx.append((test_mod_depth is not None, bool(gate_stack))) + + depth += opens - closes + if test_mod_depth is not None and depth <= test_mod_depth: + test_mod_depth = None + while gate_stack and depth <= gate_stack[-1]: + gate_stack.pop() + if not stripped.startswith("#"): + pending = None i += 1 + return ctx + + +def strip_noise(line): + """Drop comments and string literals, so a mention inside either is not a + call. `\binvocations.jsonl\b` matching a filename is what made a shim + reader look production-used when nothing read it.""" + line = re.sub(r"//[^\"]*$", "", line) + line = re.sub(r'"(?:[^"\\]|\\.)*"', '""', line) + line = re.sub(r"r#\".*?\"#", '""', line) + return line + + +def use_block_lines(path): + """Line numbers that are part of a `use ...;` statement, including the + continuation lines of a brace-delimited `use foo::{\\n ... };` block. A + re-export is not a call: `pub use pkgbases::{ ..., cas_accepted_release, ... };` + once made a function with no production caller look production-used.""" + lines = open(path).read().split("\n") + out = set() + depth = 0 + in_use = False + for i, raw in enumerate(lines): + line = strip_noise(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 = False + depth = 0 return out @@ -173,19 +239,46 @@ def analyse(): mod = module_of(paths[0]) base = os.path.join(SRC, mod) files = rust_files(base) if os.path.isdir(base) else [os.path.join(SRC, mod + ".rs")] + pat = re.compile(r"\b%s\b" % re.escape(name)) + self_impl = re.compile( + r"^\s*(?:pub(?:\(crate\))?\s+)?impl\s+(?:<[^>]*>\s*)?%s\b" % re.escape(name)) + self_impl_for = re.compile( + r"^\s*(?:pub(?:\(crate\))?\s+)?impl\s+[^{]*\bfor\s+(?:<[^>]*>\s*)?%s\b" % re.escape(name)) for p in files: - for i, line in enumerate(strip_test_modules(p), 1): - if not re.search(r"\b%s\b" % re.escape(name), line): - continue - s = line.strip() - if s.startswith("//") or s.startswith("///"): + ctx = line_context(p) + uses = use_block_lines(p) + for i, raw in enumerate(open(p).read().split("\n")): + if i in uses: + continue # a re-export is not a call + if i < len(ctx) and ctx[i][0]: + continue # inside #[cfg(test)] mod tests + if i < len(ctx) and ctx[i][1]: + continue # inside a test-support-gated item + line = strip_noise(raw) + if not line.strip(): continue + if self_impl.match(raw) or self_impl_for.match(raw): + continue # the item's own impl header if re.match(r"^\s*pub\s+(?:fn|struct|enum|trait|const|static|type)\s+%s\b" - % re.escape(name), line): - continue - if re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?use\s+", line): - continue - internal.append("%s:%d" % (os.path.relpath(p, ROOT), i)) + % re.escape(name), raw): + continue # the item's own declaration + for m in pat.finditer(line): + # A mention in method-call position on some receiver + # (`.name(`) is not evidence that *this* item is used: + # `KataBackend::local_addr` was credited to + # `listener.local_addr()`, a std method on a different + # type. Bare calls and qualified paths are evidence. + before = line[:m.start()].rstrip() + dotted = before.endswith(".") + internal.append(("%s:%d" % (os.path.relpath(p, ROOT), i + 1), dotted)) + + bare = [h for h, dotted in internal if not dotted] + # Every piece of in-module evidence for this item is a call in method + # position on some receiver. That is usually real (`self.store_dir()`, + # `req.cookie("sid")`) but it is the one shape a name match cannot + # resolve, so such rows are named for a human rather than trusted. + dotted_only = bool(internal) and not bare + internal = [h for h, _ in internal] if gated: disp = "already-gated" @@ -202,11 +295,14 @@ def analyse(): module=mod, name=name, where=("%s:%d" % (occ[0][0], occ[0][1])) if occ else "?", gated=gated, string_only=string_only, tests=users, - internal=internal, sites=[list(s) for s in sites], + internal=internal, dotted_only=dotted_only, + confirmed=("%s.%s" % (mod, name)) in CONFIRMED, + sites=[list(s) for s in sites], disp=disp, reason=(REASONS.get("%s.%s" % (mod, name)) - or ("production uses it at %s; the test that names it needs a fixture." - % internal[0] if internal + or ("production uses it at %s (%d sites in-module); the test that " + "names it needs a fixture." + % ("`, `".join(internal[:3]), len(internal)) if internal else "nothing in src calls it; a test does.")), hand_written=("%s.%s" % (mod, name)) in REASONS, )) @@ -262,12 +358,18 @@ def render(rows): if not sel: continue A("\n## %s — %d items\n" % (title[d], len(sel))) - A("| module | item | declared at | test files | why |\n|---|---|---|---|---|") + A("| module | item | declared at | test files | in-module call sites | why |\n" + "|---|---|---|---|---|---|") for r in sel: - A("| `%s` | `%s` | `%s` | %s | %s |" % ( + cites = ", ".join("`%s`" % c for c in r["internal"][:3]) or "—" + if len(r["internal"]) > 3: + cites += " +%d" % (len(r["internal"]) - 3) + if r["dotted_only"]: + cites += " ⚑" + A("| `%s` | `%s` | `%s` | %s | %s | %s |" % ( r["module"], r["name"], r["where"], ", ".join("`%s`" % t for t in r["tests"][:4]) + (" …" if len(r["tests"]) > 4 else ""), - r["reason"].replace("|", "\\|"))) + cites, r["reason"].replace("|", "\\|"))) A("\n## Totals\n\n| disposition | count |\n|---|---|") for d in order: if tot[d]: -- cgit v1.2.3