forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB4c07cbcTahinli2 months ago3583 commits

pin-gate-audit.py470 lines, 20.4 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
89RAW_STR_OPEN_RE = re.compile(r'(?:b?r|rb)(#*)"')
90CHAR_RE = re.compile(r"'(?:\\.|[^\\'])'")
91
92
93def _blank(out, lo, hi):
94 """Blank [lo, hi) in place, preserving newlines so line numbers survive."""
95 for k in range(lo, hi):
96 if out[k] != "\n":
97 out[k] = " "
98
99
100def mask_embedded_source(text):
101 """Blank the INTERIOR of every string literal that SPANS LINES.
102
103 THE RULE: a match inside a string literal that spans lines is not a gate.
104 Rust has no line-spanning non-raw string, so a literal containing a newline
105 is EMBEDDED SOURCE -- the input to a scanner's own capability test, or a
106 doc blob. `pin_inventory_tests` holds exactly that: a `r#"..."#` whose body
107 is a synthetic gate reproducing the forbidden `/../../fixtures` root, fed
108 to `pins_read` as DATA. Read as code it is a live violation, and it made
109 this audit red on a tree with no real violation in it -- the audit reading
110 its own test data, the mirror of the class the same script already fixed
111 for prose ("a doc comment reproducing a root literal invented a gate").
112
113 Why this rule and not a path allowlist: a path allowlist is a second list
114 of places to remember, and the next scanner test lands somewhere else.
115 The property that actually separates the two cases is structural -- a real
116 pin read names a path in a single-line literal; only test data wraps Rust
117 source across lines -- and that property is checkable, not a location.
118
119 Why it cannot hide a real violation: a non-raw literal aborts on the first
120 newline, so it can only ever blank within one line, and a one-line literal
121 holds no Rust source. A char literal is matched only when it really closes
122 within three characters, so a LIFETIME (`&'a str`) is not mistaken for the
123 start of a string and cannot swallow the rest of a line.
124 """
125 out = list(text)
126 i, n = 0, len(text)
127 while i < n:
128 m = RAW_STR_OPEN_RE.match(text, i)
129 if m:
130 close = '"' + m.group(1)
131 end = text.find(close, m.end())
132 if end == -1:
133 i = m.end()
134 continue
135 if "\n" in text[m.end():end]:
136 _blank(out, m.end(), end)
137 i = end + len(close)
138 continue
139 if text[i] == '"':
140 j = i + 1
141 closed = None
142 while j < n:
143 c = text[j]
144 if c == "\\":
145 j += 2
146 continue
147 if c == '"':
148 closed = j
149 break
150 if c == "\n":
151 break
152 j += 1
153 if closed is not None:
154 i = closed + 1
155 else:
156 i += 1
157 continue
158 c = CHAR_RE.match(text, i)
159 i = c.end() if c else i + 1
160 return "".join(out)
161
162
163def code_of(body):
164 """Comment-stripped, embedded-source-masked body -- the thing the shapes
165 are matched against. Comment stripping removes PROSE reproducing a shape;
166 this removes SOURCE reproducing a shape."""
167 code = re.sub(r"/\*.*?\*/", "", body, flags=re.S)
168 code = "\n".join(l.split("//", 1)[0] for l in code.splitlines())
169 return mask_embedded_source(code)
170
171
172def read_source(path):
173 """Read a Rust source with every line-spanning string literal's interior
174 blanked. The mask has to happen at FILE level, not per body: `fn_bodies`
175 finds `fn` lines by regex, so a synthetic gate inside a test's `r#"..."#`
176 input is picked up as if it were a real fn, and its body -- the raw
177 string's own text -- is then scanned as CODE. Masking first means that
178 region is blank before any gate attribution happens, which is the only
179 place the distinction can be made."""
180 with open(path, encoding="utf-8", errors="replace") as fh:
181 return mask_embedded_source(fh.read())
182
183
184ROOT_RE = re.compile(
185 r'concat!\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*,\s*"([^"]*)"\s*\)'
186)
187JOIN_RE = re.compile(
188 r'Path::(?:new|buf_from)\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*\)\s*'
189 r'(?:\.join\("([^"]*)"\)\s*)+'
190)
191LIST_RE = re.compile(r'\[\s*((?:[^\[\]"]*"[^"]*"\s*,?\s*)+)\]')
192FMT_VAR_RE = re.compile(r'format!\(\s*"\{([a-z_0-9]+)\}/\{([a-z_0-9]+)\}(?:\.([a-z0-9]+))?"\s*\)')
193FMT_LIT_RE = re.compile(r'format!\(\s*"\{([a-z_0-9]+)\}(/[A-Za-z0-9._-]+)"\s*\)')
194HELPER_RE = re.compile(r'\b([a-z_0-9]+)\s*\(')
195
196
197def tracked(path):
198 if not os.path.exists(os.path.join(ROOT, ".git")):
199 return "->"
200 r = subprocess.run(
201 ["git", "-C", ROOT, "ls-files", "--error-unmatch", "--", path],
202 stdout=subprocess.DEVNULL,
203 stderr=subprocess.DEVNULL,
204 )
205 return "yes" if r.returncode == 0 else "no"
206
207
208
209SELFTEST_CRATE = "__pin_audit_selftest__"
210
211
212def self_test():
213 """A POSITIVE CONTROL for the census itself, in the exact shape that cost a
214 gate: a doc comment reproducing the forbidden root literal, sitting between
215 two gates, one of which reads crate_pin.
216
217 It runs the REAL pipeline -- a synthetic crate written into the tree, the
218 normal scan, the normal records -- because a control that re-implements the
219 decision order would pass while the real path is broken, which is the failure
220 this control exists to catch. Losing a gate to a comment is SILENT: the
221 census count drops and nothing goes red, so only a control that asserts the
222 count can see it.
223 """
224 # Build the synthetic tree in a temp dir and point the scan at it, so the
225 # control runs even where the staged tree is read-only.
226 import tempfile
227 sandbox = tempfile.mkdtemp(prefix="pin-audit-selftest-")
228 saved_root = globals()["ROOT"]
229 globals()["ROOT"] = sandbox
230 d = os.path.join(sandbox, "crates", SELFTEST_CRATE, "src")
231 os.makedirs(d, exist_ok=True)
232 body = """//! self-test crate, removed by the audit itself.
233pub fn helper() {}
234
235#[test]
236fn selftest_a_reads_a_pin() {
237 // Reproduces the forbidden literal verbatim, INSIDE this gate's captured
238 // span -- exactly the shape that cost a real gate: fn_bodies runs a body
239 // from its `fn` line to the NEXT `fn` line, so a comment between two gates
240 // belongs to the earlier one.
241 // concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/selftest.obu")
242 let p = crate_pin("golden3-pin.obu");
243 helper();
244 assert!(!p.as_os_str().is_empty());
245}
246
247#[test]
248fn selftest_b_reads_a_pin() {
249 let p = crate_pin("sbpart-pin.obu");
250 helper();
251 assert!(!p.as_os_str().is_empty());
252}
253"""
254 path = os.path.join(d, "lib.rs")
255 try:
256 with open(path, "w", encoding="utf-8") as fh:
257 fh.write(body)
258 rows = []
259 for c, p in sources():
260 text = read_source(p)
261 rel = os.path.relpath(p, ROOT)
262 for line, name, b, attrs in fn_bodies(text):
263 if not any(a.startswith("#[test") for a in attrs):
264 continue
265 if not name.startswith("selftest_"):
266 continue
267 code = code_of(b)
268 kind = "root-literal" if (ROOT_RE.search(code) or JOIN_RE.search(code)) else "crate_pin"
269 rows.append((name, kind))
270 bad = [r for r in rows if r[1] != "crate_pin"]
271 missing = [n for n in ("selftest_a_reads_a_pin", "selftest_b_reads_a_pin")
272 if n not in [r[0] for r in rows]]
273 ok = not bad and not missing
274 for n, k in sorted(rows):
275 print("SELFTEST\t{}\t{}".format(n, k))
276 if ok:
277 print("SELFTEST\tPASS\ta doc comment between two gates left both counted as crate_pin")
278 else:
279 print("SELFTEST\tFAIL\treclassified={} missing={}".format(bad, missing))
280 return 0 if ok else 1
281 finally:
282 globals()["ROOT"] = saved_root
283 import shutil
284 shutil.rmtree(sandbox, ignore_errors=True)
285
286
287def main():
288 helpers = {} # fn name -> body (all fns in the tree)
289 for crate, path in sources():
290 text = read_source(path)
291 for _line, name, body, _attrs in fn_bodies(text):
292 helpers.setdefault(name, body)
293
294 total = committed = uncommitted = ignored = assertless = 0
295 bad = []
296
297 for crate, path in sources():
298 text = read_source(path)
299 rel = os.path.relpath(path, ROOT)
300 for line, name, body, attrs in fn_bodies(text):
301 if not any(a.startswith("#[test") for a in attrs):
302 continue
303 # Match every shape on a COMMENT-STRIPPED body. A doc comment that
304 # reproduces a root literal to explain the shape it removed used to
305 # invent a gate here, the same blindness invariant 1 had.
306 code = code_of(body)
307 root_lit = None
308 root_kind = "none"
309 var = None
310 m = ROOT_RE.search(code)
311 if m:
312 root_lit, var = m.group(1), None
313 root_kind = "concat!"
314 else:
315 m = JOIN_RE.search(code)
316 if m:
317 joined = re.findall(r'\.join\("([^"]*)"\)', m.group(0))
318 root_lit = "".join(joined)
319 root_kind = "join"
320 if root_lit is None:
321 # The single-name shapes the FIRST invariant matched, kept so
322 # the census counts every pin-reading gate, not only the ones
323 # reached through a root literal.
324 ign_s = "yes" if any("ignore" in a for a in attrs) else "no"
325 singles = re.findall(r'crate_pin\(\s*"([^"]+)"', code)
326 # A gate that builds the pin name at runtime (crate_pin(&format!(..)))
327 # matches no single-name shape and would VANISH from the census --
328 # the same blind spot in a new place. Surface it instead.
329 for dyn_call in re.findall(r'crate_pin\(\s*&?\s*(?!")', code):
330 print("BADCALL\t{}\t{}\tcrate_pin argument is not a string literal: {}"
331 .format("{}:{}".format(rel, line), name, dyn_call.strip()[:60]))
332 bad.append("BADROW\t{}\t{}\tcrate_pin\tname built at runtime -- this census "
333 "cannot resolve it, so the gate is UNPROVEN here".format(
334 "{}:{}".format(rel, line), name))
335 singles += re.findall(
336 r'pin_dir\(\)\.join\(\s*"([^"]+)"', code)
337 if not singles:
338 continue
339 total += 1
340 if ign_s == "yes":
341 ignored += 1
342 print("GATE\t{}\t{}\tcrate_pin\tyes\t{}\t{}".format(
343 "{}:{}".format(rel, line), name, ign_s, len(singles)))
344 for n in singles:
345 committed_rel = "crates/{}/fixtures/{}".format(crate, n)
346 present = os.path.isfile(os.path.join(ROOT, committed_rel))
347 tr = tracked(committed_rel) if present else "no"
348 print("NAME\t{}\t{}\t{}\t{}\t{}\t{}".format(
349 "{}:{}".format(rel, line), name, n,
350 "present" if present else "absent", tr, "yes"))
351 if present and tr in ("yes", "->"):
352 committed += 1
353 else:
354 uncommitted += 1
355 bad.append("BADROW\t{}\t{}\tcrate_pin\t{} not committed+tracked".format(
356 "{}:{}".format(rel, line), name, n))
357 continue
358
359 # the variable the root is bound to, if any
360 v = re.search(
361 r'let\s+([a-z_0-9]+)\s*=\s*(?:concat!\(\s*env!\("CARGO_MANIFEST_DIR"\)|'
362 r'Path::(?:new|buf_from)\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*\)\s*(?:\.join\("[^"]*"\)\s*)+)',
363 code,
364 )
365 if v:
366 var = v.group(1)
367
368 # names: ONLY the two shapes that matter.
369 # (i) a runtime NAME LIST formatted against the root variable --
370 # the shape the weak invariant was blind to
371 # (ii) a single file literal appended to the root
372 # Anything else (a format! over some other variable, a scratch dump
373 # path) is not a pin read and is left to the manifest scan.
374 names = []
375 if var:
376 # The name list is bracketed, but comments sit between its
377 # items ("lane-rect r2: HORP strip ..."), so strip line
378 # comments before parsing the list and anchor on the format!
379 # that consumes it. It is `code` and not `body` that feeds
380 # this: `code` is the comment-stripped, embedded-source-masked
381 # text, and reading the RAW body here re-imported the shape
382 # out of a scanner test's own `r#"..."#` input -- the same
383 # gate resurrected through a different match.
384 body_nc = code
385 for lit in LIST_RE.finditer(body_nc):
386 items = re.findall(r'"([A-Za-z0-9._-]+)"', lit.group(1))
387 if len(items) < 3:
388 continue
389 fm = FMT_VAR_RE.search(body_nc[lit.end():lit.end() + 400])
390 if not fm or fm.group(1) != var:
391 continue
392 ext = fm.group(3) or ""
393 for n in items:
394 names.append((n, ext))
395 if not names:
396 lit = re.search(r'"(/[A-Za-z0-9._/-]+\.[A-Za-z0-9]+)"', code)
397 # a lane dump under lanes/ is not a fixture and is not this gate
398 if lit and "/fixtures/" in lit.group(1):
399 names.append((os.path.basename(lit.group(1)), ""))
400 if not names:
401 continue
402
403 # assertion classification through the CALL GRAPH
404 asserts = "assert" in code
405 via = ""
406 if not asserts:
407 for h in HELPER_RE.findall(code):
408 hb = helpers.get(h)
409 if hb and "assert" in hb:
410 asserts = True
411 via = h
412 break
413 ign = "yes" if any("ignore" in a for a in attrs) else "no"
414 if not names:
415 continue
416 total += 1
417 if ign == "yes":
418 ignored += 1
419 if not asserts:
420 assertless += 1
421 kind = "yes" if asserts else "no"
422 if asserts and via:
423 kind = "via-" + via
424 print("GATE\t{}\t{}\t{}\t{}\t{}\t{}".format(
425 "{}:{}".format(rel, line), name, root_kind, kind, ign, len(names)))
426 missing = []
427 missing = []
428 missing = []
429 for n, _ext in names:
430 committed_rel = "crates/{}/fixtures/{}".format(crate, n)
431 present = os.path.isfile(os.path.join(ROOT, committed_rel))
432 tr = tracked(committed_rel) if present else "no"
433 under_root = os.path.isfile(os.path.join(ROOT, root_lit.strip("/"), n)) \
434 if root_lit.startswith("..") else os.path.isfile(
435 os.path.join(ROOT, "fixtures", n))
436 print("NAME\t{}\t{}\t{}\t{}\t{}\t{}".format(
437 "{}:{}".format(rel, line), name, n,
438 "present" if present else "absent", tr,
439 "yes" if under_root else "no"))
440 if present and tr in ("yes", "->"):
441 committed += 1
442 else:
443 uncommitted += 1
444 missing.append(n)
445 if missing:
446 bad.append("BADROW\t{}\t{}\t{}\t{}/{} pin(s) not committed+tracked, e.g. {}".format(
447 "{}:{}".format(rel, line), name, root_kind, len(missing), len(names), missing[0]))
448 # a bare directory root feeding a runtime name list can never be
449 # satisfied by a committed tree
450 if names and root_lit.rstrip("/").endswith("fixtures"):
451 print("BARDIR\t{}\t{}\t{} + {} runtime name(s)".format(
452 "{}:{}".format(rel, line), name, root_lit, len(names)))
453 bad.append("BADROW\t{}\t{}\t{}\tbare directory literal feeding {} runtime name(s): no committed tree satisfies it".format(
454 "{}:{}".format(rel, line), name, root_lit, len(names)))
455
456 print("COUNT\ttotal={}\tcommitted={}\tuncommitted={}\tignored={}\tassertless={}".format(
457 total, committed, uncommitted, ignored, assertless))
458 if bad:
459 print("BAD\t{}".format(len(bad)))
460 for b in sorted(set(bad)):
461 print(b)
462 if os.environ.get("PIN_AUDIT_STRICT") == "1" and bad:
463 return 1
464 return 0
465
466
467if __name__ == "__main__":
468 if "--self-test" in sys.argv:
469 sys.exit(self_test())
470 sys.exit(main())