forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBbb7bd46Tahinli2 months ago3685 commits

pin-gate-audit.py496 lines, 21.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
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// The SECOND shape, the one that made this audit RED on a tree with no real
255// violation in it: a scanner capability test whose INPUT is embedded source.
256// The phantom gate below carries the `selftest_` prefix on purpose -- the
257// filter above would drop a differently-named one and the control would pass
258// for the wrong reason.
259#[test]
260fn selftest_c_embeds_a_raw_string_input() {
261 let synthetic = r#"
262 #[test]
263 fn selftest_phantom_inside_a_raw_string() {
264 let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/phantom.obu");
265 check(&fixtures);
266 }
267"#;
268 let p = crate_pin("embedded-pin.obu");
269 helper();
270 assert!(!synthetic.is_empty() && !p.as_os_str().is_empty());
271}
272"""
273 path = os.path.join(d, "lib.rs")
274 try:
275 with open(path, "w", encoding="utf-8") as fh:
276 fh.write(body)
277 rows = []
278 for c, p in sources():
279 text = read_source(p)
280 rel = os.path.relpath(p, ROOT)
281 for line, name, b, attrs in fn_bodies(text):
282 if not any(a.startswith("#[test") for a in attrs):
283 continue
284 if not name.startswith("selftest_"):
285 continue
286 code = code_of(b)
287 kind = "root-literal" if (ROOT_RE.search(code) or JOIN_RE.search(code)) else "crate_pin"
288 singles = re.findall(r'crate_pin\(\s*"([^"]+)"', code)
289 rows.append((name, kind, singles))
290 bad = [r for r in rows if r[1] != "crate_pin"]
291 missing = [n for n in ("selftest_a_reads_a_pin", "selftest_b_reads_a_pin")
292 if n not in [r[0] for r in rows]]
293 phantom = [r for r in rows if r[0] == "selftest_phantom_inside_a_raw_string"]
294 leaked = [r for r in rows if any("phantom" in s for s in r[2])]
295 missing = missing + ["selftest_c_embeds_a_raw_string_input"] \
296 if "selftest_c_embeds_a_raw_string_input" not in [r[0] for r in rows] else missing
297 ok = not bad and not missing and not phantom and not leaked
298 for n, k, s in sorted(rows):
299 print("SELFTEST\t{}\t{}\t{}".format(n, k, ",".join(s)))
300 if ok:
301 print("SELFTEST\tPASS\ta doc comment between two gates left both counted as "
302 "crate_pin, and a raw-string input did not become a gate")
303 else:
304 print("SELFTEST\tFAIL\tphantom_gate_counted={} phantom_name_leaked={} "
305 "reclassified={} missing={}".format(phantom, leaked, bad, missing))
306 return 0 if ok else 1
307 finally:
308 globals()["ROOT"] = saved_root
309 import shutil
310 shutil.rmtree(sandbox, ignore_errors=True)
311
312
313def main():
314 helpers = {} # fn name -> body (all fns in the tree)
315 for crate, path in sources():
316 text = read_source(path)
317 for _line, name, body, _attrs in fn_bodies(text):
318 helpers.setdefault(name, body)
319
320 total = committed = uncommitted = ignored = assertless = 0
321 bad = []
322
323 for crate, path in sources():
324 text = read_source(path)
325 rel = os.path.relpath(path, ROOT)
326 for line, name, body, attrs in fn_bodies(text):
327 if not any(a.startswith("#[test") for a in attrs):
328 continue
329 # Match every shape on a COMMENT-STRIPPED body. A doc comment that
330 # reproduces a root literal to explain the shape it removed used to
331 # invent a gate here, the same blindness invariant 1 had.
332 code = code_of(body)
333 root_lit = None
334 root_kind = "none"
335 var = None
336 m = ROOT_RE.search(code)
337 if m:
338 root_lit, var = m.group(1), None
339 root_kind = "concat!"
340 else:
341 m = JOIN_RE.search(code)
342 if m:
343 joined = re.findall(r'\.join\("([^"]*)"\)', m.group(0))
344 root_lit = "".join(joined)
345 root_kind = "join"
346 if root_lit is None:
347 # The single-name shapes the FIRST invariant matched, kept so
348 # the census counts every pin-reading gate, not only the ones
349 # reached through a root literal.
350 ign_s = "yes" if any("ignore" in a for a in attrs) else "no"
351 singles = re.findall(r'crate_pin\(\s*"([^"]+)"', code)
352 # A gate that builds the pin name at runtime (crate_pin(&format!(..)))
353 # matches no single-name shape and would VANISH from the census --
354 # the same blind spot in a new place. Surface it instead.
355 for dyn_call in re.findall(r'crate_pin\(\s*&?\s*(?!")', code):
356 print("BADCALL\t{}\t{}\tcrate_pin argument is not a string literal: {}"
357 .format("{}:{}".format(rel, line), name, dyn_call.strip()[:60]))
358 bad.append("BADROW\t{}\t{}\tcrate_pin\tname built at runtime -- this census "
359 "cannot resolve it, so the gate is UNPROVEN here".format(
360 "{}:{}".format(rel, line), name))
361 singles += re.findall(
362 r'pin_dir\(\)\.join\(\s*"([^"]+)"', code)
363 if not singles:
364 continue
365 total += 1
366 if ign_s == "yes":
367 ignored += 1
368 print("GATE\t{}\t{}\tcrate_pin\tyes\t{}\t{}".format(
369 "{}:{}".format(rel, line), name, ign_s, len(singles)))
370 for n in singles:
371 committed_rel = "crates/{}/fixtures/{}".format(crate, n)
372 present = os.path.isfile(os.path.join(ROOT, committed_rel))
373 tr = tracked(committed_rel) if present else "no"
374 print("NAME\t{}\t{}\t{}\t{}\t{}\t{}".format(
375 "{}:{}".format(rel, line), name, n,
376 "present" if present else "absent", tr, "yes"))
377 if present and tr in ("yes", "->"):
378 committed += 1
379 else:
380 uncommitted += 1
381 bad.append("BADROW\t{}\t{}\tcrate_pin\t{} not committed+tracked".format(
382 "{}:{}".format(rel, line), name, n))
383 continue
384
385 # the variable the root is bound to, if any
386 v = re.search(
387 r'let\s+([a-z_0-9]+)\s*=\s*(?:concat!\(\s*env!\("CARGO_MANIFEST_DIR"\)|'
388 r'Path::(?:new|buf_from)\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*\)\s*(?:\.join\("[^"]*"\)\s*)+)',
389 code,
390 )
391 if v:
392 var = v.group(1)
393
394 # names: ONLY the two shapes that matter.
395 # (i) a runtime NAME LIST formatted against the root variable --
396 # the shape the weak invariant was blind to
397 # (ii) a single file literal appended to the root
398 # Anything else (a format! over some other variable, a scratch dump
399 # path) is not a pin read and is left to the manifest scan.
400 names = []
401 if var:
402 # The name list is bracketed, but comments sit between its
403 # items ("lane-rect r2: HORP strip ..."), so strip line
404 # comments before parsing the list and anchor on the format!
405 # that consumes it. It is `code` and not `body` that feeds
406 # this: `code` is the comment-stripped, embedded-source-masked
407 # text, and reading the RAW body here re-imported the shape
408 # out of a scanner test's own `r#"..."#` input -- the same
409 # gate resurrected through a different match.
410 body_nc = code
411 for lit in LIST_RE.finditer(body_nc):
412 items = re.findall(r'"([A-Za-z0-9._-]+)"', lit.group(1))
413 if len(items) < 3:
414 continue
415 fm = FMT_VAR_RE.search(body_nc[lit.end():lit.end() + 400])
416 if not fm or fm.group(1) != var:
417 continue
418 ext = fm.group(3) or ""
419 for n in items:
420 names.append((n, ext))
421 if not names:
422 lit = re.search(r'"(/[A-Za-z0-9._/-]+\.[A-Za-z0-9]+)"', code)
423 # a lane dump under lanes/ is not a fixture and is not this gate
424 if lit and "/fixtures/" in lit.group(1):
425 names.append((os.path.basename(lit.group(1)), ""))
426 if not names:
427 continue
428
429 # assertion classification through the CALL GRAPH
430 asserts = "assert" in code
431 via = ""
432 if not asserts:
433 for h in HELPER_RE.findall(code):
434 hb = helpers.get(h)
435 if hb and "assert" in hb:
436 asserts = True
437 via = h
438 break
439 ign = "yes" if any("ignore" in a for a in attrs) else "no"
440 if not names:
441 continue
442 total += 1
443 if ign == "yes":
444 ignored += 1
445 if not asserts:
446 assertless += 1
447 kind = "yes" if asserts else "no"
448 if asserts and via:
449 kind = "via-" + via
450 print("GATE\t{}\t{}\t{}\t{}\t{}\t{}".format(
451 "{}:{}".format(rel, line), name, root_kind, kind, ign, len(names)))
452 missing = []
453 missing = []
454 missing = []
455 for n, _ext in names:
456 committed_rel = "crates/{}/fixtures/{}".format(crate, n)
457 present = os.path.isfile(os.path.join(ROOT, committed_rel))
458 tr = tracked(committed_rel) if present else "no"
459 under_root = os.path.isfile(os.path.join(ROOT, root_lit.strip("/"), n)) \
460 if root_lit.startswith("..") else os.path.isfile(
461 os.path.join(ROOT, "fixtures", n))
462 print("NAME\t{}\t{}\t{}\t{}\t{}\t{}".format(
463 "{}:{}".format(rel, line), name, n,
464 "present" if present else "absent", tr,
465 "yes" if under_root else "no"))
466 if present and tr in ("yes", "->"):
467 committed += 1
468 else:
469 uncommitted += 1
470 missing.append(n)
471 if missing:
472 bad.append("BADROW\t{}\t{}\t{}\t{}/{} pin(s) not committed+tracked, e.g. {}".format(
473 "{}:{}".format(rel, line), name, root_kind, len(missing), len(names), missing[0]))
474 # a bare directory root feeding a runtime name list can never be
475 # satisfied by a committed tree
476 if names and root_lit.rstrip("/").endswith("fixtures"):
477 print("BARDIR\t{}\t{}\t{} + {} runtime name(s)".format(
478 "{}:{}".format(rel, line), name, root_lit, len(names)))
479 bad.append("BADROW\t{}\t{}\t{}\tbare directory literal feeding {} runtime name(s): no committed tree satisfies it".format(
480 "{}:{}".format(rel, line), name, root_lit, len(names)))
481
482 print("COUNT\ttotal={}\tcommitted={}\tuncommitted={}\tignored={}\tassertless={}".format(
483 total, committed, uncommitted, ignored, assertless))
484 if bad:
485 print("BAD\t{}".format(len(bad)))
486 for b in sorted(set(bad)):
487 print(b)
488 if os.environ.get("PIN_AUDIT_STRICT") == "1" and bad:
489 return 1
490 return 0
491
492
493if __name__ == "__main__":
494 if "--self-test" in sys.argv:
495 sys.exit(self_test())
496 sys.exit(main())