summaryrefslogtreecommitdiffstats
path: root/tools/test-surface.py
diff options
context:
space:
mode:
Diffstat (limited to 'tools/test-surface.py')
-rw-r--r--tools/test-surface.py211
1 files changed, 166 insertions, 45 deletions
diff --git a/tools/test-surface.py b/tools/test-surface.py
index 6121889..b8e856b 100644
--- a/tools/test-surface.py
+++ b/tools/test-surface.py
@@ -17,12 +17,32 @@ Those two questions yield the four dispositions written to
`tools/test-surface.md`. Run with `--json` for the machine-readable form, whose
`residue` count `tests/architecture.rs` ratchets.
-Rust has no test-conditional visibility: no attribute makes an item `pub` under
-one feature and `pub(crate)` under another, and `pub use` cannot re-export a
-`pub(crate)` item. An item that production needs inside its own module *and* a
-fixture-bound integration test needs from outside therefore cannot be narrowed
-without breaking one or the other. Those rows are `residue`, and the only way to
-shrink them is to change the tests, not the visibility.
+Two shapes make visibility feature-conditional, and the table records which one
+an item uses. For a free function, method, const or static, one body sits behind
+two declarations:
+
+ #[cfg(feature = "test-support")] pub fn probe(..) -> .. { probe_impl(..) }
+ #[cfg(not(feature = "test-support"))] pub(crate) fn probe(..) -> .. { probe_impl(..) }
+ fn probe_impl(..) -> .. { .. }
+
+For a type, the real definition lives in a private module and a gated `pub use`
+is the only path to it:
+
+ mod kata_backend { pub struct KataBackend { .. } }
+ #[cfg(feature = "test-support")] pub use kata_backend::KataBackend;
+ #[cfg(not(feature = "test-support"))] pub(crate) use kata_backend::KataBackend;
+
+A `pub` item in a private module has no nameable path from outside, yet is
+visible enough to appear in a public trait signature — which is why the return
+type of `Sandbox::run` narrows this way when a plain `pub(crate) struct` would
+be a private-in-public error.
+
+`residue` is therefore a failure, not a verdict: it means an item is still
+ungated and nothing has argued it should be. The only honest dispositions are
+the ones that close the release build, plus `interface` for the rare item a
+public signature forces open. Whether the table is telling the truth is checked
+by compiling against the library, not by reading it — see
+`tools/release-surface-probe.py`.
"""
import argparse, collections, json, os, re, sys
@@ -53,6 +73,19 @@ REASONS = json.load(open(os.path.join(ROOT, "tools", "test-surface-reasons.json"
# and absent from this list fails `tests/architecture.rs`.
CONFIRMED = set(json.load(open(os.path.join(ROOT, "tools", "test-surface-confirmed.json"))))
+# Rows whose production-use verdict rests on a bare mention of a name the
+# detector cannot resolve to one item. Each entry is a human verdict on the
+# cited line; a row that is ambiguous and absent here fails the architecture
+# test, because "the tool could not tell" is not a disposition.
+AMBIGUOUS = json.load(open(os.path.join(ROOT, "tools", "test-surface-ambiguous.json")))
+
+# Items that stay `pub` in a release build because a public signature requires
+# them, not because a test asked. Each entry states the signature. This is the
+# one disposition that admits reachability, so it is declared by hand and the
+# probe verifies it: `db::Writer` is public because `Db.writer` is a `pub` field
+# and Rust will not type a public field with a private type.
+INTERFACE = json.load(open(os.path.join(ROOT, "tools", "test-surface-interface.json")))
+
def rust_files(d):
out = []
@@ -248,24 +281,83 @@ def integration_tests(path):
return out
+def enclosing_mods_are_private(lines, idx):
+ """True when every module enclosing `lines[idx]` is a private `mod`.
+
+ A `pub` item inside a private module has no nameable path from outside the
+ parent, so it is not a public declaration. This is the second half of the
+ inner-module narrowing; without it the detector reads `pub fn new` inside
+ `mod log_tail` and reports an `http::new` that nothing can reach.
+ """
+ depth, enclosed = 0, []
+ for k in range(idx - 1, -1, -1):
+ depth += lines[k].count("{") - lines[k].count("}")
+ if depth > 0:
+ m = re.match(r"^\s*(pub(?:\(crate\))?\s+)?mod\s+\w+", lines[k])
+ if m:
+ enclosed.append(m.group(1))
+ depth -= 1
+ return bool(enclosed) and not any(enclosed)
+
+
def analyse():
src = {p: open(p).read() for p in rust_files(SRC)}
tests = {p: open(p).read() for p in rust_files(TESTS)}
+
+ # Rows are keyed by (module, name), not by bare name. `pipeline::dispatch::
+ # Pool::shutdown` and `db::Writer::shutdown` are two items; keyed by name
+ # alone they merged into one row, and because the `db` one is gated the
+ # ungated one was reported `already-gated`.
names = collections.defaultdict(list)
for path, text in src.items():
- for line in text.splitlines():
+ lines = text.splitlines()
+ for line_no, line in enumerate(lines):
if COMMENT.match(line):
continue
m = PUB_RE.match(line)
- if m:
- names[m.group(1)].append(path)
+ if m and not enclosing_mods_are_private(lines, line_no):
+ names[(module_of(path), m.group(1))].append(path)
+
+ # A production mention, counted per line with comments and string literals
+ # removed. Searching raw text is what made `review::approve::withdraw` look
+ # production-used: the only src/ hits for the bare word outside `review`
+ # were the route pattern "packages/{name}/withdraw" and an audit action
+ # string, and every real caller named `withdraw_package` or
+ # `withdraw_release_in`, which are different items.
+ stripped = {p: "\n".join("" if COMMENT.match(l) else strip_noise(l)
+ for l in t.splitlines())
+ for p, t in src.items()}
+
+ # A bare mention in another module cannot be resolved to one item when the
+ # same name is declared in several modules — `new`, `parse` and `open` are
+ # declared all over the crate, and a line saying `Foo::new()` in `http` says
+ # nothing about `db::open`. For a colliding name a mention counts only if
+ # the line actually routes through the declaring module: a qualified path
+ # (`db::open`, `crate::db::open`) or a `use` that imports from it. A
+ # colliding name with unqualified mentions is kept and flagged, because the
+ # honest answer is "a line-based tool cannot tell" and a human should.
+ collisions = {name for (mod, name) in names if
+ len({m for (m, n) in names if n == name}) > 1}
+
+ def mentioned(line, mod, name):
+ if not re.search(r"\b%s\b" % re.escape(name), line):
+ return None # not a mention at all
+ if name not in collisions:
+ return True # only one item could mean this
+ top = mod.split(os.sep)[0]
+ if re.search(r"\b%s\s*::[^;]*\b%s\b" % (re.escape(top), re.escape(name)), line):
+ return True # qualified path through the module
+ if re.match(r"^\s*(pub\s+)?use\b", line) and re.search(r"\b%s\s*::" % re.escape(top), line):
+ return True # an import from the module
+ return False # colliding and unqualified: unknown
rows = []
- for name, paths in sorted(names.items()):
- declaring = {module_of(p) for p in paths}
- if any(module_of(p) not in declaring and re.search(r"\b%s\b" % re.escape(name), t)
- for p, t in src.items()):
- continue
+ for (mod, name), paths in sorted(names.items()):
+ hits = [v for p, text in stripped.items() if module_of(p) != mod
+ for v in [mentioned(text, mod, name)] if v is not None]
+ if any(hits):
+ continue # production uses it outside the module
+ ambiguous_collision = any(v is False for v in hits)
users = sorted(os.path.relpath(f, TESTS) for f, t in tests.items()
if re.search(r"\b%s\b" % re.escape(name), t))
if not users:
@@ -290,7 +382,6 @@ def analyse():
sites.append((f, tname, any(k in body for k in HARNESS)))
internal = []
- 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))
@@ -344,7 +435,9 @@ def analyse():
for t in (open(pp).read() for pp in paths)
)
- if gated and narrowed:
+ if ("%s.%s" % (mod, name)) in INTERFACE:
+ disp = "interface"
+ elif gated and narrowed:
disp = "narrowed"
elif gated:
disp = "already-gated"
@@ -358,30 +451,35 @@ def analyse():
disp = "residue"
rows.append(dict(
- module=mod, name=name,
+ module=mod, name=name, ambiguous=ambiguous_collision,
where=("%s:%d" % (occ[0][0], occ[0][1])) if occ else "?",
gated=gated, narrowed=narrowed, string_only=string_only, tests=users,
internal=internal, dotted_only=dotted_only,
confirmed=("%s.%s" % (mod, name)) in CONFIRMED,
+ adjudicated=("%s.%s" % (mod, name)) in AMBIGUOUS,
+ justified=("%s.%s" % (mod, name)) in INTERFACE,
sites=[list(s) for s in sites],
disp=disp,
reason=(REASONS.get("%s.%s" % (mod, name))
+ or INTERFACE.get("%s.%s" % (mod, name))
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,
+ hand_written=("%s.%s" % (mod, name)) in REASONS
+ or ("%s.%s" % (mod, name)) in INTERFACE,
))
return rows
def render(rows):
- order = ["gate", "move-test", "narrow", "residue", "narrowed", "already-gated"]
+ order = ["gate", "move-test", "narrow", "residue", "interface", "narrowed", "already-gated"]
title = {"gate": "Gate behind `test-support`",
"move-test": "Move the test into the module, then narrow",
"narrow": "Narrow — no test actually calls it",
- "residue": "Residue — `pub` because Rust has no test-conditional visibility",
+ "residue": "Residue — ungated and unargued; a failure, not a verdict",
"already-gated": "Already gated",
+ "interface": "Public because a public signature requires it; no test asked for it",
"narrowed": "Feature-conditional visibility — production uses it, only from inside its module"}
out = [open(DOC).read().split("## gate-marker")[0]] if False else []
L = []
@@ -406,19 +504,34 @@ def render(rows):
A("| `gate` | add `#[cfg(feature = \"test-support\")]` | production never calls it; a test does |")
A("| `move-test` | move the test into the module, then make the item private | the test that names it builds no fixture, so it is a unit test in the wrong file |")
A("| `narrow` | `pub(crate)` or private | no test calls it at all (string-only mention) |")
- A("| `residue` | stays `pub`, documented, counted | production needs it *inside* its module **and** a fixture-bound integration test needs it from outside |\n")
- A("### Why `residue` exists at all\n")
- A("Rust has no test-conditional visibility. No attribute makes an item `pub`\n"
- "under one feature and `pub(crate)` under another, and `pub use` cannot\n"
- "re-export a `pub(crate)` item. An item that production needs inside its own\n"
- "module *and* an integration test needs from outside cannot be narrowed\n"
- "without breaking one or the other.\n")
- A("The way to shrink that column is not a visibility change. It is to make the\n"
- "integration tests stop reaching in — by moving them into the module, or by\n"
- "exercising the behaviour through the module's real entry point. That is a\n"
- "test-design change with a real cost per row, recorded here rather than\n"
- "attempted blind.\n")
- A("The `residue` count is ratcheted by `tests/architecture.rs`, so it can only\nshrink.\n")
+ A("| `interface` | stays `pub`, and the probe proves it is reachable | a public signature requires it; no test asked for it |")
+ A("| `residue` | **a failure** | ungated, and nothing has argued why it should be |\n")
+ A("### How visibility becomes feature-conditional\n")
+ A("For a free function, method, const or static, one body sits behind two\n"
+ "declarations, exactly one of which compiles:\n")
+ A("```rust\n"
+ "#[cfg(feature = \"test-support\")] pub fn probe(..) -> .. { probe_impl(..) }\n"
+ "#[cfg(not(feature = \"test-support\"))] pub(crate) fn probe(..) -> .. { probe_impl(..) }\n"
+ "fn probe_impl(..) -> .. { .. }\n"
+ "```\n")
+ A("For a type, the real definition lives in a private module and a gated\n"
+ "`pub use` is the only path to it:\n")
+ A("```rust\n"
+ "mod kata_backend { pub struct KataBackend { .. } }\n"
+ "#[cfg(feature = \"test-support\")] pub use kata_backend::KataBackend;\n"
+ "#[cfg(not(feature = \"test-support\"))] pub(crate) use kata_backend::KataBackend;\n"
+ "```\n")
+ A("A `pub` item in a private module has no nameable path from outside, yet is\n"
+ "visible enough to appear in a public trait signature — which is how the\n"
+ "return type of `Sandbox::run` narrows when a plain `pub(crate) struct`\n"
+ "would be a private-in-public error.\n")
+ A("`residue` is not a verdict, it is an unargued row. The column is shrunk by\n"
+ "applying one of the two shapes above, by moving the test into the module,\n"
+ "or by deleting the item.\n")
+ A("Whether this table tells the truth is not checked by reading it.\n"
+ "`tools/release-surface-probe.py` compiles a throwaway crate against the\n"
+ "library twice, with and without `test-support`, and fails if any path that\n"
+ "reaches the test tier also reaches a release build.\n")
tot = collections.Counter(r["disp"] for r in rows)
for d in order:
sel = sorted([r for r in rows if r["disp"] == d], key=lambda r: (r["module"], r["name"]))
@@ -449,6 +562,22 @@ def render(rows):
return "\n".join(L) + "\n"
+def tally(rows):
+ """The one definition of the test-surface counts.
+
+ Two copies of this rule drifted the first time the `interface` exclusion was
+ added to only one of them, and the budget then recorded as ungated an item
+ the report called justified.
+ """
+ counts = collections.Counter(r["disp"] for r in rows)
+ counts["gate_pending"] = sum(1 for r in rows if r["disp"] == "gate" and not r["gated"])
+ counts["ungated"] = sum(1 for r in rows
+ if not r["gated"] and r["disp"] != "interface")
+ counts["total"] = len(rows)
+ counts["release_exposed"] = counts["ungated"]
+ return counts
+
+
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--json", action="store_true")
@@ -458,25 +587,17 @@ if __name__ == "__main__":
a = ap.parse_args()
rows = analyse()
if a.json:
- counts = collections.Counter(r["disp"] for r in rows)
- counts["gate_pending"] = sum(1 for r in rows if r["disp"] == "gate" and not r["gated"])
- counts["ungated"] = sum(1 for r in rows if not r["gated"])
- counts["total"] = len(rows)
- counts["release_exposed"] = sum(1 for r in rows if not r["gated"])
- print(json.dumps({"rows": rows, "counts": counts}, indent=1))
+ print(json.dumps({"rows": rows, "counts": tally(rows)}, indent=1))
elif a.write_budget:
- rows = analyse()
- counts = collections.Counter(r["disp"] for r in rows)
- counts["gate_pending"] = sum(1 for r in rows if r["disp"] == "gate" and not r["gated"])
- counts["ungated"] = sum(1 for r in rows if not r["gated"])
- counts["total"] = len(rows)
+ counts = tally(rows)
path = a.write_budget
if not os.path.isabs(path):
path = os.path.join(ROOT, path)
budget = json.load(open(path))
budget["test_surface"] = {k: counts[k] for k in
("gate", "gate_pending", "move-test", "narrow",
- "residue", "narrowed", "already-gated", "total", "ungated")
+ "residue", "interface", "narrowed", "already-gated",
+ "total", "ungated")
if counts[k]}
with open(path, "w") as handle:
json.dump(budget, handle, indent=2, sort_keys=True)