forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB22cda1bTahinli2 months ago3457 commits

pin-gate-audit.py274 lines, 12.1 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 root_lit = None
129 root_kind = "none"
130 var = None
131 m = ROOT_RE.search(body)
132 if m:
133 root_lit, var = m.group(1), None
134 root_kind = "concat!"
135 else:
136 m = JOIN_RE.search(body)
137 if m:
138 joined = re.findall(r'\.join\("([^"]*)"\)', m.group(0))
139 root_lit = "".join(joined)
140 root_kind = "join"
141 if root_lit is None:
142 # The single-name shapes the FIRST invariant matched, kept so
143 # the census counts every pin-reading gate, not only the ones
144 # reached through a root literal.
145 singles = re.findall(r'crate_pin\(\s*"([^"]+)"', body)
146 singles += re.findall(
147 r'pin_dir\(\)\.join\(\s*"([^"]+)"', body)
148 if not singles:
149 continue
150 total += 1
151 for n in singles:
152 committed_rel = "crates/{}/fixtures/{}".format(crate, n)
153 present = os.path.isfile(os.path.join(ROOT, committed_rel))
154 tr = tracked(committed_rel) if present else "no"
155 total_names = 1
156 print("GATE\t{}\t{}\tcrate_pin\tyes\tno\t{}".format(
157 "{}:{}".format(rel, line), name, len(singles)))
158 print("NAME\t{}\t{}\t{}\t{}\t{}\t{}".format(
159 "{}:{}".format(rel, line), name, n,
160 "present" if present else "absent", tr, "yes"))
161 if present and tr in ("yes", "->"):
162 committed += 1
163 else:
164 uncommitted += 1
165 bad.append("BADROW\t{}\t{}\tcrate_pin\t{} not committed+tracked".format(
166 "{}:{}".format(rel, line), name, n))
167 continue
168
169 # the variable the root is bound to, if any
170 v = re.search(
171 r'let\s+([a-z_0-9]+)\s*=\s*(?:concat!\(\s*env!\("CARGO_MANIFEST_DIR"\)|'
172 r'Path::(?:new|buf_from)\(\s*env!\("CARGO_MANIFEST_DIR"\)\s*\)\s*(?:\.join\("[^"]*"\)\s*)+)',
173 body,
174 )
175 if v:
176 var = v.group(1)
177
178 # names: ONLY the two shapes that matter.
179 # (i) a runtime NAME LIST formatted against the root variable --
180 # the shape the weak invariant was blind to
181 # (ii) a single file literal appended to the root
182 # Anything else (a format! over some other variable, a scratch dump
183 # path) is not a pin read and is left to the manifest scan.
184 names = []
185 if var:
186 # The name list is bracketed, but comments sit between its
187 # items ("lane-rect r2: HORP strip ..."), so strip line
188 # comments before parsing the list and anchor on the format!
189 # that consumes it.
190 body_nc = re.sub(r"//[^\n]*", "", body)
191 for lit in LIST_RE.finditer(body_nc):
192 items = re.findall(r'"([A-Za-z0-9._-]+)"', lit.group(1))
193 if len(items) < 3:
194 continue
195 fm = FMT_VAR_RE.search(body_nc[lit.end():lit.end() + 400])
196 if not fm or fm.group(1) != var:
197 continue
198 ext = fm.group(3) or ""
199 for n in items:
200 names.append((n, ext))
201 if not names:
202 lit = re.search(r'"(/[A-Za-z0-9._/-]+\.[A-Za-z0-9]+)"', body)
203 # a lane dump under lanes/ is not a fixture and is not this gate
204 if lit and "/fixtures/" in lit.group(1):
205 names.append((os.path.basename(lit.group(1)), ""))
206 if not names:
207 continue
208
209 # assertion classification through the CALL GRAPH
210 asserts = "assert" in body
211 via = ""
212 if not asserts:
213 for h in HELPER_RE.findall(body):
214 hb = helpers.get(h)
215 if hb and "assert" in hb:
216 asserts = True
217 via = h
218 break
219 ign = "yes" if any("ignore" in a for a in attrs) else "no"
220 if not names:
221 continue
222 total += 1
223 if ign == "yes":
224 ignored += 1
225 if not asserts:
226 assertless += 1
227 kind = "yes" if asserts else "no"
228 if asserts and via:
229 kind = "via-" + via
230 print("GATE\t{}\t{}\t{}\t{}\t{}\t{}".format(
231 "{}:{}".format(rel, line), name, root_kind, kind, ign, len(names)))
232 missing = []
233 missing = []
234 missing = []
235 for n, _ext in names:
236 committed_rel = "crates/{}/fixtures/{}".format(crate, n)
237 present = os.path.isfile(os.path.join(ROOT, committed_rel))
238 tr = tracked(committed_rel) if present else "no"
239 under_root = os.path.isfile(os.path.join(ROOT, root_lit.strip("/"), n)) \
240 if root_lit.startswith("..") else os.path.isfile(
241 os.path.join(ROOT, "fixtures", n))
242 print("NAME\t{}\t{}\t{}\t{}\t{}\t{}".format(
243 "{}:{}".format(rel, line), name, n,
244 "present" if present else "absent", tr,
245 "yes" if under_root else "no"))
246 if present and tr in ("yes", "->"):
247 committed += 1
248 else:
249 uncommitted += 1
250 missing.append(n)
251 if missing:
252 bad.append("BADROW\t{}\t{}\t{}\t{}/{} pin(s) not committed+tracked, e.g. {}".format(
253 "{}:{}".format(rel, line), name, root_kind, len(missing), len(names), missing[0]))
254 # a bare directory root feeding a runtime name list can never be
255 # satisfied by a committed tree
256 if names and root_lit.rstrip("/").endswith("fixtures"):
257 print("BARDIR\t{}\t{}\t{} + {} runtime name(s)".format(
258 "{}:{}".format(rel, line), name, root_lit, len(names)))
259 bad.append("BADROW\t{}\t{}\t{}\tbare directory literal feeding {} runtime name(s): no committed tree satisfies it".format(
260 "{}:{}".format(rel, line), name, root_lit, len(names)))
261
262 print("COUNT\ttotal={}\tcommitted={}\tuncommitted={}\tignored={}\tassertless={}".format(
263 total, committed, uncommitted, ignored, assertless))
264 if bad:
265 print("BAD\t{}".format(len(bad)))
266 for b in sorted(set(bad)):
267 print(b)
268 if os.environ.get("PIN_AUDIT_STRICT") == "1" and bad:
269 return 1
270 return 0
271
272
273if __name__ == "__main__":
274 sys.exit(main())