forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB7e097feTahinli2 months ago3472 commits

pin-gate-audit.py290 lines, 13.3 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.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
49
50
51def sources():
52 for crate in sorted(os.listdir(os.path.join(ROOT, "crates"))):
53 for sub in ("src", "tests"):
54 d = os.path.join(ROOT, "crates", crate, sub)
55 if not os.path.isdir(d):
56 continue
57 for name in sorted(os.listdir(d)):
58 if name.endswith(".rs"):
59 yield crate, os.path.join(d, name)
60
61
62def fn_bodies(text):
63 """Yield (start_line, name, body, preceding_attrs) for every fn.
64
65 The body runs from the `fn` line to the NEXT `fn` line rather than to a
66 brace-balanced end: brace counting over 39k lines of Rust miscounts the
67 moment one string literal or macro contains an unbalanced brace, and a
68 single bad walk swallows every gate after it. Over-capturing trailing
69 attributes of the next fn is harmless here -- attributes are read from the
70 lines immediately above the `fn` line, which this method never crosses.
71 """
72 lines = text.splitlines()
73 starts = []
74 for i, line in enumerate(lines):
75 m = re.match(r"\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([a-z_0-9]+)", line)
76 if m:
77 starts.append((i, m.group(1)))
78 for n, (i, name) in enumerate(starts):
79 end = starts[n + 1][0] if n + 1 < len(starts) else len(lines)
80 attrs = []
81 j = i - 1
82 while j >= 0 and lines[j].lstrip().startswith("#["):
83 attrs.append(lines[j].strip())
84 j -= 1
85 yield i + 1, name, "\n".join(lines[i:end]), attrs
86
87
88ROOT_RE = re.compile(
89 r'concat!\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*,\s*"([^"]*)"\s*\)'
90)
91JOIN_RE = re.compile(
92 r'Path::(?:new|buf_from)\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*\)\s*'
93 r'(?:\.join\("([^"]*)"\)\s*)+'
94)
95LIST_RE = re.compile(r'\[\s*((?:[^\[\]"]*"[^"]*"\s*,?\s*)+)\]')
96FMT_VAR_RE = re.compile(r'format!\(\s*"\{([a-z_0-9]+)\}/\{([a-z_0-9]+)\}(?:\.([a-z0-9]+))?"\s*\)')
97FMT_LIT_RE = re.compile(r'format!\(\s*"\{([a-z_0-9]+)\}(/[A-Za-z0-9._-]+)"\s*\)')
98HELPER_RE = re.compile(r'\b([a-z_0-9]+)\s*\(')
99
100
101def tracked(path):
102 if not os.path.exists(os.path.join(ROOT, ".git")):
103 return "->"
104 r = subprocess.run(
105 ["git", "-C", ROOT, "ls-files", "--error-unmatch", "--", path],
106 stdout=subprocess.DEVNULL,
107 stderr=subprocess.DEVNULL,
108 )
109 return "yes" if r.returncode == 0 else "no"
110
111
112def main():
113 helpers = {} # fn name -> body (all fns in the tree)
114 for crate, path in sources():
115 text = open(path, encoding="utf-8", errors="replace").read()
116 for _line, name, body, _attrs in fn_bodies(text):
117 helpers.setdefault(name, body)
118
119 total = committed = uncommitted = ignored = assertless = 0
120 bad = []
121
122 for crate, path in sources():
123 text = open(path, encoding="utf-8", errors="replace").read()
124 rel = os.path.relpath(path, ROOT)
125 for line, name, body, attrs in fn_bodies(text):
126 if not any(a.startswith("#[test") for a in attrs):
127 continue
128 # Match every shape on a COMMENT-STRIPPED body. A doc comment that
129 # reproduces a root literal to explain the shape it removed used to
130 # invent a gate here, the same blindness invariant 1 had.
131 code = re.sub(r"/\*.*?\*/", "", body, flags=re.S)
132 code = "\n".join(l.split("//", 1)[0] for l in code.splitlines())
133 root_lit = None
134 root_kind = "none"
135 var = None
136 m = ROOT_RE.search(code)
137 if m:
138 root_lit, var = m.group(1), None
139 root_kind = "concat!"
140 else:
141 m = JOIN_RE.search(code)
142 if m:
143 joined = re.findall(r'\.join\("([^"]*)"\)', m.group(0))
144 root_lit = "".join(joined)
145 root_kind = "join"
146 if root_lit is None:
147 # The single-name shapes the FIRST invariant matched, kept so
148 # the census counts every pin-reading gate, not only the ones
149 # reached through a root literal.
150 ign_s = "yes" if any("ignore" in a for a in attrs) else "no"
151 singles = re.findall(r'crate_pin\(\s*"([^"]+)"', code)
152 # A gate that builds the pin name at runtime (crate_pin(&format!(..)))
153 # matches no single-name shape and would VANISH from the census --
154 # the same blind spot in a new place. Surface it instead.
155 for dyn_call in re.findall(r'crate_pin\(\s*&?\s*(?!")', code):
156 print("BADCALL\t{}\t{}\tcrate_pin argument is not a string literal: {}"
157 .format("{}:{}".format(rel, line), name, dyn_call.strip()[:60]))
158 bad.append("BADROW\t{}\t{}\tcrate_pin\tname built at runtime -- this census "
159 "cannot resolve it, so the gate is UNPROVEN here".format(
160 "{}:{}".format(rel, line), name))
161 singles += re.findall(
162 r'pin_dir\(\)\.join\(\s*"([^"]+)"', code)
163 if not singles:
164 continue
165 total += 1
166 if ign_s == "yes":
167 ignored += 1
168 print("GATE\t{}\t{}\tcrate_pin\tyes\t{}\t{}".format(
169 "{}:{}".format(rel, line), name, ign_s, len(singles)))
170 for n in singles:
171 committed_rel = "crates/{}/fixtures/{}".format(crate, n)
172 present = os.path.isfile(os.path.join(ROOT, committed_rel))
173 tr = tracked(committed_rel) if present else "no"
174 print("NAME\t{}\t{}\t{}\t{}\t{}\t{}".format(
175 "{}:{}".format(rel, line), name, n,
176 "present" if present else "absent", tr, "yes"))
177 if present and tr in ("yes", "->"):
178 committed += 1
179 else:
180 uncommitted += 1
181 bad.append("BADROW\t{}\t{}\tcrate_pin\t{} not committed+tracked".format(
182 "{}:{}".format(rel, line), name, n))
183 continue
184
185 # the variable the root is bound to, if any
186 v = re.search(
187 r'let\s+([a-z_0-9]+)\s*=\s*(?:concat!\(\s*env!\("CARGO_MANIFEST_DIR"\)|'
188 r'Path::(?:new|buf_from)\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*\)\s*(?:\.join\("[^"]*"\)\s*)+)',
189 code,
190 )
191 if v:
192 var = v.group(1)
193
194 # names: ONLY the two shapes that matter.
195 # (i) a runtime NAME LIST formatted against the root variable --
196 # the shape the weak invariant was blind to
197 # (ii) a single file literal appended to the root
198 # Anything else (a format! over some other variable, a scratch dump
199 # path) is not a pin read and is left to the manifest scan.
200 names = []
201 if var:
202 # The name list is bracketed, but comments sit between its
203 # items ("lane-rect r2: HORP strip ..."), so strip line
204 # comments before parsing the list and anchor on the format!
205 # that consumes it.
206 body_nc = re.sub(r"//[^\n]*", "", body)
207 for lit in LIST_RE.finditer(body_nc):
208 items = re.findall(r'"([A-Za-z0-9._-]+)"', lit.group(1))
209 if len(items) < 3:
210 continue
211 fm = FMT_VAR_RE.search(body_nc[lit.end():lit.end() + 400])
212 if not fm or fm.group(1) != var:
213 continue
214 ext = fm.group(3) or ""
215 for n in items:
216 names.append((n, ext))
217 if not names:
218 lit = re.search(r'"(/[A-Za-z0-9._/-]+\.[A-Za-z0-9]+)"', code)
219 # a lane dump under lanes/ is not a fixture and is not this gate
220 if lit and "/fixtures/" in lit.group(1):
221 names.append((os.path.basename(lit.group(1)), ""))
222 if not names:
223 continue
224
225 # assertion classification through the CALL GRAPH
226 asserts = "assert" in code
227 via = ""
228 if not asserts:
229 for h in HELPER_RE.findall(code):
230 hb = helpers.get(h)
231 if hb and "assert" in hb:
232 asserts = True
233 via = h
234 break
235 ign = "yes" if any("ignore" in a for a in attrs) else "no"
236 if not names:
237 continue
238 total += 1
239 if ign == "yes":
240 ignored += 1
241 if not asserts:
242 assertless += 1
243 kind = "yes" if asserts else "no"
244 if asserts and via:
245 kind = "via-" + via
246 print("GATE\t{}\t{}\t{}\t{}\t{}\t{}".format(
247 "{}:{}".format(rel, line), name, root_kind, kind, ign, len(names)))
248 missing = []
249 missing = []
250 missing = []
251 for n, _ext in names:
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 under_root = os.path.isfile(os.path.join(ROOT, root_lit.strip("/"), n)) \
256 if root_lit.startswith("..") else os.path.isfile(
257 os.path.join(ROOT, "fixtures", n))
258 print("NAME\t{}\t{}\t{}\t{}\t{}\t{}".format(
259 "{}:{}".format(rel, line), name, n,
260 "present" if present else "absent", tr,
261 "yes" if under_root else "no"))
262 if present and tr in ("yes", "->"):
263 committed += 1
264 else:
265 uncommitted += 1
266 missing.append(n)
267 if missing:
268 bad.append("BADROW\t{}\t{}\t{}\t{}/{} pin(s) not committed+tracked, e.g. {}".format(
269 "{}:{}".format(rel, line), name, root_kind, len(missing), len(names), missing[0]))
270 # a bare directory root feeding a runtime name list can never be
271 # satisfied by a committed tree
272 if names and root_lit.rstrip("/").endswith("fixtures"):
273 print("BARDIR\t{}\t{}\t{} + {} runtime name(s)".format(
274 "{}:{}".format(rel, line), name, root_lit, len(names)))
275 bad.append("BADROW\t{}\t{}\t{}\tbare directory literal feeding {} runtime name(s): no committed tree satisfies it".format(
276 "{}:{}".format(rel, line), name, root_lit, len(names)))
277
278 print("COUNT\ttotal={}\tcommitted={}\tuncommitted={}\tignored={}\tassertless={}".format(
279 total, committed, uncommitted, ignored, assertless))
280 if bad:
281 print("BAD\t{}".format(len(bad)))
282 for b in sorted(set(bad)):
283 print(b)
284 if os.environ.get("PIN_AUDIT_STRICT") == "1" and bad:
285 return 1
286 return 0
287
288
289if __name__ == "__main__":
290 sys.exit(main())