forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe03cd90Tahinli2 months ago3530 commits

pin-gate-audit.py373 lines, 16.6 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""pin-gate-audit.py — census of the gates that read a PINNED fixture.
3
4The r1 invariant was too weak: it matched only single-name call shapes
5(`crate_pin("X")`, `pin_dir().join("X")`). It is blind to a much worse shape
6that exists in the crate right now -- a gate that reads N pins through a
7DIRECTORY literal plus a runtime-formatted name list:
8
9 let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures");
10 ["warp-mismatch", "warp-flake-5", ...].iter().map(|n| format!("{fixtures}/{n}.obu"))
11
12Fourteen names, none committed under the crate, so no clean tree and no runner
13can satisfy them, and the gate is #[ignore]d -- a no-op that reports nothing.
14A preflight that passes it is the silent shape again.
15
16This audit, for every `#[test]` fn in crates/*/src and crates/*/tests that
17reaches for a fixture:
18
19 * resolves the fixture ROOT literal (concat! or Path::new(env!).join chain)
20 * enumerates every runtime name built from that root
21 - a `[..].iter().map(|n| format!("{var}/{n}.obu"))` name list
22 - a `format!` naming the root variable directly
23 * for each name, checks the path under the ROOT (gitignored, so never tracked)
24 and under crates/<crate>/fixtures/ (the committed copy)
25 * counts pin-reading gates, how many resolve through a committed copy, and how
26 many do not -- printed as numbers, not prose
27
28ASSERTION CLASSIFICATION uses the helper CALL GRAPH, not the gate body: a gate
29that delegates to a helper (the warp gate calls check_pinned_warp_stream, which
30asserts all three planes per frame) is NOT a no-assert gate, and reading only the
31body gets that wrong -- which is exactly the mistake that produced the
32"asserts nothing" classification earlier today.
33
34Output (one record per line, tab separated fields):
35 GATE <file>:<line>\t<fn>\t<root-kind>\t<asserts:yes|no|via-helper NAME>\t<ignored:yes|no>\t<names>
36 NAME <file>:<line>\t<gate-fn>\t<name>\t<committed-copy:present|absent>\t<tracked:yes|no|->\t<exists-under-root:yes|no>
37 COUNT total=<n>\tcommitted=<n>\tuncommitted=<n>\tignored=<n>\tassertless=<n>
38
39Exit 0 always: the caller decides what is a failure. Set PIN_AUDIT_STRICT=1 to
40exit 1 when any name lacks a tracked committed copy.
41"""
42
43import os
44import re
45import subprocess
46import sys
47
48ROOT = os.environ.get("PIN_AUDIT_ROOT") or os.path.abspath(
49 os.path.join(os.path.dirname(__file__), ".."))
50
51
52def sources():
53 for crate in sorted(os.listdir(os.path.join(ROOT, "crates"))):
54 for sub in ("src", "tests"):
55 d = os.path.join(ROOT, "crates", crate, sub)
56 if not os.path.isdir(d):
57 continue
58 for name in sorted(os.listdir(d)):
59 if name.endswith(".rs"):
60 yield crate, os.path.join(d, name)
61
62
63def fn_bodies(text):
64 """Yield (start_line, name, body, preceding_attrs) for every fn.
65
66 The body runs from the `fn` line to the NEXT `fn` line rather than to a
67 brace-balanced end: brace counting over 39k lines of Rust miscounts the
68 moment one string literal or macro contains an unbalanced brace, and a
69 single bad walk swallows every gate after it. Over-capturing trailing
70 attributes of the next fn is harmless here -- attributes are read from the
71 lines immediately above the `fn` line, which this method never crosses.
72 """
73 lines = text.splitlines()
74 starts = []
75 for i, line in enumerate(lines):
76 m = re.match(r"\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([a-z_0-9]+)", line)
77 if m:
78 starts.append((i, m.group(1)))
79 for n, (i, name) in enumerate(starts):
80 end = starts[n + 1][0] if n + 1 < len(starts) else len(lines)
81 attrs = []
82 j = i - 1
83 while j >= 0 and lines[j].lstrip().startswith("#["):
84 attrs.append(lines[j].strip())
85 j -= 1
86 yield i + 1, name, "\n".join(lines[i:end]), attrs
87
88
89ROOT_RE = re.compile(
90 r'concat!\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*,\s*"([^"]*)"\s*\)'
91)
92JOIN_RE = re.compile(
93 r'Path::(?:new|buf_from)\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*\)\s*'
94 r'(?:\.join\("([^"]*)"\)\s*)+'
95)
96LIST_RE = re.compile(r'\[\s*((?:[^\[\]"]*"[^"]*"\s*,?\s*)+)\]')
97FMT_VAR_RE = re.compile(r'format!\(\s*"\{([a-z_0-9]+)\}/\{([a-z_0-9]+)\}(?:\.([a-z0-9]+))?"\s*\)')
98FMT_LIT_RE = re.compile(r'format!\(\s*"\{([a-z_0-9]+)\}(/[A-Za-z0-9._-]+)"\s*\)')
99HELPER_RE = re.compile(r'\b([a-z_0-9]+)\s*\(')
100
101
102def tracked(path):
103 if not os.path.exists(os.path.join(ROOT, ".git")):
104 return "->"
105 r = subprocess.run(
106 ["git", "-C", ROOT, "ls-files", "--error-unmatch", "--", path],
107 stdout=subprocess.DEVNULL,
108 stderr=subprocess.DEVNULL,
109 )
110 return "yes" if r.returncode == 0 else "no"
111
112
113
114SELFTEST_CRATE = "__pin_audit_selftest__"
115
116
117def self_test():
118 """A POSITIVE CONTROL for the census itself, in the exact shape that cost a
119 gate: a doc comment reproducing the forbidden root literal, sitting between
120 two gates, one of which reads crate_pin.
121
122 It runs the REAL pipeline -- a synthetic crate written into the tree, the
123 normal scan, the normal records -- because a control that re-implements the
124 decision order would pass while the real path is broken, which is the failure
125 this control exists to catch. Losing a gate to a comment is SILENT: the
126 census count drops and nothing goes red, so only a control that asserts the
127 count can see it.
128 """
129 # Build the synthetic tree in a temp dir and point the scan at it, so the
130 # control runs even where the staged tree is read-only.
131 import tempfile
132 sandbox = tempfile.mkdtemp(prefix="pin-audit-selftest-")
133 saved_root = globals()["ROOT"]
134 globals()["ROOT"] = sandbox
135 d = os.path.join(sandbox, "crates", SELFTEST_CRATE, "src")
136 os.makedirs(d, exist_ok=True)
137 body = """//! self-test crate, removed by the audit itself.
138pub fn helper() {}
139
140#[test]
141fn selftest_a_reads_a_pin() {
142 // Reproduces the forbidden literal verbatim, INSIDE this gate's captured
143 // span -- exactly the shape that cost a real gate: fn_bodies runs a body
144 // from its `fn` line to the NEXT `fn` line, so a comment between two gates
145 // belongs to the earlier one.
146 // concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/selftest.obu")
147 let p = crate_pin("golden3-pin.obu");
148 helper();
149 assert!(!p.as_os_str().is_empty());
150}
151
152#[test]
153fn selftest_b_reads_a_pin() {
154 let p = crate_pin("sbpart-pin.obu");
155 helper();
156 assert!(!p.as_os_str().is_empty());
157}
158"""
159 path = os.path.join(d, "lib.rs")
160 try:
161 with open(path, "w", encoding="utf-8") as fh:
162 fh.write(body)
163 rows = []
164 for c, p in sources():
165 text = open(p, encoding="utf-8", errors="replace").read()
166 rel = os.path.relpath(p, ROOT)
167 for line, name, b, attrs in fn_bodies(text):
168 if not any(a.startswith("#[test") for a in attrs):
169 continue
170 if not name.startswith("selftest_"):
171 continue
172 code = re.sub(r"/\*.*?\*/", "", b, flags=re.S)
173 code = "\n".join(x.split("//", 1)[0] for x in code.splitlines())
174 kind = "root-literal" if (ROOT_RE.search(code) or JOIN_RE.search(code)) else "crate_pin"
175 rows.append((name, kind))
176 bad = [r for r in rows if r[1] != "crate_pin"]
177 missing = [n for n in ("selftest_a_reads_a_pin", "selftest_b_reads_a_pin")
178 if n not in [r[0] for r in rows]]
179 ok = not bad and not missing
180 for n, k in sorted(rows):
181 print("SELFTEST\t{}\t{}".format(n, k))
182 if ok:
183 print("SELFTEST\tPASS\ta doc comment between two gates left both counted as crate_pin")
184 else:
185 print("SELFTEST\tFAIL\treclassified={} missing={}".format(bad, missing))
186 return 0 if ok else 1
187 finally:
188 globals()["ROOT"] = saved_root
189 import shutil
190 shutil.rmtree(sandbox, ignore_errors=True)
191
192
193def main():
194 helpers = {} # fn name -> body (all fns in the tree)
195 for crate, path in sources():
196 text = open(path, encoding="utf-8", errors="replace").read()
197 for _line, name, body, _attrs in fn_bodies(text):
198 helpers.setdefault(name, body)
199
200 total = committed = uncommitted = ignored = assertless = 0
201 bad = []
202
203 for crate, path in sources():
204 text = open(path, encoding="utf-8", errors="replace").read()
205 rel = os.path.relpath(path, ROOT)
206 for line, name, body, attrs in fn_bodies(text):
207 if not any(a.startswith("#[test") for a in attrs):
208 continue
209 # Match every shape on a COMMENT-STRIPPED body. A doc comment that
210 # reproduces a root literal to explain the shape it removed used to
211 # invent a gate here, the same blindness invariant 1 had.
212 code = re.sub(r"/\*.*?\*/", "", body, flags=re.S)
213 code = "\n".join(l.split("//", 1)[0] for l in code.splitlines())
214 root_lit = None
215 root_kind = "none"
216 var = None
217 m = ROOT_RE.search(code)
218 if m:
219 root_lit, var = m.group(1), None
220 root_kind = "concat!"
221 else:
222 m = JOIN_RE.search(code)
223 if m:
224 joined = re.findall(r'\.join\("([^"]*)"\)', m.group(0))
225 root_lit = "".join(joined)
226 root_kind = "join"
227 if root_lit is None:
228 # The single-name shapes the FIRST invariant matched, kept so
229 # the census counts every pin-reading gate, not only the ones
230 # reached through a root literal.
231 ign_s = "yes" if any("ignore" in a for a in attrs) else "no"
232 singles = re.findall(r'crate_pin\(\s*"([^"]+)"', code)
233 # A gate that builds the pin name at runtime (crate_pin(&format!(..)))
234 # matches no single-name shape and would VANISH from the census --
235 # the same blind spot in a new place. Surface it instead.
236 for dyn_call in re.findall(r'crate_pin\(\s*&?\s*(?!")', code):
237 print("BADCALL\t{}\t{}\tcrate_pin argument is not a string literal: {}"
238 .format("{}:{}".format(rel, line), name, dyn_call.strip()[:60]))
239 bad.append("BADROW\t{}\t{}\tcrate_pin\tname built at runtime -- this census "
240 "cannot resolve it, so the gate is UNPROVEN here".format(
241 "{}:{}".format(rel, line), name))
242 singles += re.findall(
243 r'pin_dir\(\)\.join\(\s*"([^"]+)"', code)
244 if not singles:
245 continue
246 total += 1
247 if ign_s == "yes":
248 ignored += 1
249 print("GATE\t{}\t{}\tcrate_pin\tyes\t{}\t{}".format(
250 "{}:{}".format(rel, line), name, ign_s, len(singles)))
251 for n in singles:
252 committed_rel = "crates/{}/fixtures/{}".format(crate, n)
253 present = os.path.isfile(os.path.join(ROOT, committed_rel))
254 tr = tracked(committed_rel) if present else "no"
255 print("NAME\t{}\t{}\t{}\t{}\t{}\t{}".format(
256 "{}:{}".format(rel, line), name, n,
257 "present" if present else "absent", tr, "yes"))
258 if present and tr in ("yes", "->"):
259 committed += 1
260 else:
261 uncommitted += 1
262 bad.append("BADROW\t{}\t{}\tcrate_pin\t{} not committed+tracked".format(
263 "{}:{}".format(rel, line), name, n))
264 continue
265
266 # the variable the root is bound to, if any
267 v = re.search(
268 r'let\s+([a-z_0-9]+)\s*=\s*(?:concat!\(\s*env!\("CARGO_MANIFEST_DIR"\)|'
269 r'Path::(?:new|buf_from)\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*\)\s*(?:\.join\("[^"]*"\)\s*)+)',
270 code,
271 )
272 if v:
273 var = v.group(1)
274
275 # names: ONLY the two shapes that matter.
276 # (i) a runtime NAME LIST formatted against the root variable --
277 # the shape the weak invariant was blind to
278 # (ii) a single file literal appended to the root
279 # Anything else (a format! over some other variable, a scratch dump
280 # path) is not a pin read and is left to the manifest scan.
281 names = []
282 if var:
283 # The name list is bracketed, but comments sit between its
284 # items ("lane-rect r2: HORP strip ..."), so strip line
285 # comments before parsing the list and anchor on the format!
286 # that consumes it.
287 body_nc = re.sub(r"//[^\n]*", "", body)
288 for lit in LIST_RE.finditer(body_nc):
289 items = re.findall(r'"([A-Za-z0-9._-]+)"', lit.group(1))
290 if len(items) < 3:
291 continue
292 fm = FMT_VAR_RE.search(body_nc[lit.end():lit.end() + 400])
293 if not fm or fm.group(1) != var:
294 continue
295 ext = fm.group(3) or ""
296 for n in items:
297 names.append((n, ext))
298 if not names:
299 lit = re.search(r'"(/[A-Za-z0-9._/-]+\.[A-Za-z0-9]+)"', code)
300 # a lane dump under lanes/ is not a fixture and is not this gate
301 if lit and "/fixtures/" in lit.group(1):
302 names.append((os.path.basename(lit.group(1)), ""))
303 if not names:
304 continue
305
306 # assertion classification through the CALL GRAPH
307 asserts = "assert" in code
308 via = ""
309 if not asserts:
310 for h in HELPER_RE.findall(code):
311 hb = helpers.get(h)
312 if hb and "assert" in hb:
313 asserts = True
314 via = h
315 break
316 ign = "yes" if any("ignore" in a for a in attrs) else "no"
317 if not names:
318 continue
319 total += 1
320 if ign == "yes":
321 ignored += 1
322 if not asserts:
323 assertless += 1
324 kind = "yes" if asserts else "no"
325 if asserts and via:
326 kind = "via-" + via
327 print("GATE\t{}\t{}\t{}\t{}\t{}\t{}".format(
328 "{}:{}".format(rel, line), name, root_kind, kind, ign, len(names)))
329 missing = []
330 missing = []
331 missing = []
332 for n, _ext in names:
333 committed_rel = "crates/{}/fixtures/{}".format(crate, n)
334 present = os.path.isfile(os.path.join(ROOT, committed_rel))
335 tr = tracked(committed_rel) if present else "no"
336 under_root = os.path.isfile(os.path.join(ROOT, root_lit.strip("/"), n)) \
337 if root_lit.startswith("..") else os.path.isfile(
338 os.path.join(ROOT, "fixtures", n))
339 print("NAME\t{}\t{}\t{}\t{}\t{}\t{}".format(
340 "{}:{}".format(rel, line), name, n,
341 "present" if present else "absent", tr,
342 "yes" if under_root else "no"))
343 if present and tr in ("yes", "->"):
344 committed += 1
345 else:
346 uncommitted += 1
347 missing.append(n)
348 if missing:
349 bad.append("BADROW\t{}\t{}\t{}\t{}/{} pin(s) not committed+tracked, e.g. {}".format(
350 "{}:{}".format(rel, line), name, root_kind, len(missing), len(names), missing[0]))
351 # a bare directory root feeding a runtime name list can never be
352 # satisfied by a committed tree
353 if names and root_lit.rstrip("/").endswith("fixtures"):
354 print("BARDIR\t{}\t{}\t{} + {} runtime name(s)".format(
355 "{}:{}".format(rel, line), name, root_lit, len(names)))
356 bad.append("BADROW\t{}\t{}\t{}\tbare directory literal feeding {} runtime name(s): no committed tree satisfies it".format(
357 "{}:{}".format(rel, line), name, root_lit, len(names)))
358
359 print("COUNT\ttotal={}\tcommitted={}\tuncommitted={}\tignored={}\tassertless={}".format(
360 total, committed, uncommitted, ignored, assertless))
361 if bad:
362 print("BAD\t{}".format(len(bad)))
363 for b in sorted(set(bad)):
364 print(b)
365 if os.environ.get("PIN_AUDIT_STRICT") == "1" and bad:
366 return 1
367 return 0
368
369
370if __name__ == "__main__":
371 if "--self-test" in sys.argv:
372 sys.exit(self_test())
373 sys.exit(main())