|
| 1 | +"""A falsifier must fail the budget it targets, not an earlier check. |
| 2 | +
|
| 3 | +A falsifier that exits non-zero on some *earlier* budget proves nothing |
| 4 | +about the budget it was built for. The exit code is right there to catch |
| 5 | +it, so this makes the flag -> budget -> exit-code mapping machine-checked |
| 6 | +instead of prose. |
| 7 | +
|
| 8 | +Worked example, from the run that motivated this file: `stone-archway`'s |
| 9 | +arch falsifier began as ``--flat-arch``, laying the voussoirs as a flat |
| 10 | +lintel. A lintel is 0.62 m shorter than the arch, so it tripped the |
| 11 | +bounding-box budget (exit 8) and never reached the intrados circle fit |
| 12 | +(exit 19) it existed to break. It was replaced by ``--off-circle``, which |
| 13 | +keeps the angles, joints, materials, triangle count and envelope |
| 14 | +identical and wanders only the intrados radius. Four other falsifiers |
| 15 | +needed the same treatment in the same run. |
| 16 | +
|
| 17 | +The fix is always to change the model or the falsifier. Never widen a |
| 18 | +band so an ill-aimed falsifier lands. |
| 19 | +
|
| 20 | +Two modes |
| 21 | +--------- |
| 22 | +
|
| 23 | +**Static (default, no Blender).** Reads each piece's README and script and |
| 24 | +asserts they agree: |
| 25 | +
|
| 26 | +1. every falsifier flag in the README table is a real argparse flag; |
| 27 | +2. every declared exit code appears in that README's exit-code table; |
| 28 | +3. every falsifier row names the budget it targets, in its own column; |
| 29 | +4. every falsifier-shaped flag in the script is documented. |
| 30 | +
|
| 31 | +**Runtime (``--run BLENDER``).** Executes each falsifier and asserts the |
| 32 | +*observed* exit equals the declared one. This is the mode that catches a |
| 33 | +falsifier tripping an earlier check. It costs one Blender launch per |
| 34 | +falsifier — roughly 150 s for the showcase tree on one version — so it is |
| 35 | +an authoring and cron tool, not a per-PR smoke step. |
| 36 | +
|
| 37 | +Exit codes: 0 clean, 1 a mapping disagrees, 2 usage. |
| 38 | +""" |
| 39 | +from __future__ import annotations |
| 40 | + |
| 41 | +import argparse |
| 42 | +import ast |
| 43 | +import io |
| 44 | +import os |
| 45 | +import re |
| 46 | +import subprocess |
| 47 | +import sys |
| 48 | + |
| 49 | +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 50 | +SHOWCASE = os.path.join(ROOT, "showcase") |
| 51 | + |
| 52 | +# Pieces that predate the falsifier-table convention. Tracked for backfill; |
| 53 | +# a NEW piece without a table is an error, not an entry here. |
| 54 | +KNOWN_UNDOCUMENTED = {"cart", "hay-bale", "stone-well"} |
| 55 | + |
| 56 | +# Flags that select a code path rather than break a contract. Per |
| 57 | +# CONTRIBUTING.md these are explicitly not falsifiers. |
| 58 | +NOT_FALSIFIERS = { |
| 59 | + "--output", "--engine", "--api", "--check-pixels", "--obj", |
| 60 | + "--samples", "--width", "--height", "--force-run", "--expect-sidecar", |
| 61 | + "--seed", "--quality", "--verbose", "--no-render", |
| 62 | +} |
| 63 | + |
| 64 | +FLAG_RE = re.compile(r"`?(--[a-z0-9][a-z0-9-]*)`?") |
| 65 | + |
| 66 | + |
| 67 | +def _tables(text): |
| 68 | + """Every markdown table as (headers, rows-of-cells).""" |
| 69 | + out = [] |
| 70 | + lines = text.split("\n") |
| 71 | + i = 0 |
| 72 | + while i < len(lines): |
| 73 | + if lines[i].strip().startswith("|") and i + 1 < len(lines) and re.match( |
| 74 | + r"^\|[\s:|-]+\|$", lines[i + 1].strip() |
| 75 | + ): |
| 76 | + headers = [c.strip() for c in lines[i].strip().strip("|").split("|")] |
| 77 | + rows = [] |
| 78 | + j = i + 2 |
| 79 | + while j < len(lines) and lines[j].strip().startswith("|"): |
| 80 | + rows.append([c.strip() for c in lines[j].strip().strip("|").split("|")]) |
| 81 | + j += 1 |
| 82 | + out.append((headers, rows)) |
| 83 | + i = j |
| 84 | + else: |
| 85 | + i += 1 |
| 86 | + return out |
| 87 | + |
| 88 | + |
| 89 | +def _column(headers, *patterns): |
| 90 | + for idx, h in enumerate(headers): |
| 91 | + low = h.lower() |
| 92 | + if any(re.search(p, low) for p in patterns): |
| 93 | + return idx |
| 94 | + return None |
| 95 | + |
| 96 | + |
| 97 | +def parse_readme(path): |
| 98 | + """(falsifiers {flag: (exit, target)}, exit_table {code: meaning}).""" |
| 99 | + text = io.open(path, encoding="utf-8").read() |
| 100 | + falsifiers, exits = {}, {} |
| 101 | + for headers, rows in _tables(text): |
| 102 | + code_col = _column(headers, r"^exit$", r"exit code", r"^code$") |
| 103 | + if code_col is None: |
| 104 | + continue |
| 105 | + flag_col = _column(headers, r"falsifier", r"^flag$") |
| 106 | + if flag_col is not None: |
| 107 | + # The remaining column is the declared target budget. Every |
| 108 | + # falsifier has to say what it aims at; that is the whole point. |
| 109 | + target_col = next( |
| 110 | + (i for i in range(len(headers)) if i not in (flag_col, code_col)), |
| 111 | + None, |
| 112 | + ) |
| 113 | + for r in rows: |
| 114 | + if len(r) <= max(flag_col, code_col): |
| 115 | + continue |
| 116 | + m = FLAG_RE.search(r[flag_col]) |
| 117 | + if not m or not r[code_col].strip().strip("`").isdigit(): |
| 118 | + continue |
| 119 | + target = "" |
| 120 | + if target_col is not None and len(r) > target_col: |
| 121 | + target = r[target_col].strip() |
| 122 | + falsifiers[m.group(1)] = ( |
| 123 | + int(r[code_col].strip().strip("`")), target |
| 124 | + ) |
| 125 | + continue |
| 126 | + # exit-code table: code column plus a meaning column |
| 127 | + mean_col = _column(headers, r"meaning", r"description") |
| 128 | + if mean_col is None: |
| 129 | + mean_col = 1 if len(headers) > 1 else None |
| 130 | + if mean_col is None: |
| 131 | + continue |
| 132 | + for r in rows: |
| 133 | + if len(r) <= max(code_col, mean_col): |
| 134 | + continue |
| 135 | + c = r[code_col].strip().strip("`") |
| 136 | + if c.isdigit(): |
| 137 | + exits[int(c)] = r[mean_col] |
| 138 | + return falsifiers, exits |
| 139 | + |
| 140 | + |
| 141 | +def script_flags(path): |
| 142 | + """store_true argparse flags declared in the script.""" |
| 143 | + src = io.open(path, encoding="utf-8").read() |
| 144 | + flags = set() |
| 145 | + try: |
| 146 | + tree = ast.parse(src) |
| 147 | + except SyntaxError: |
| 148 | + return flags |
| 149 | + for node in ast.walk(tree): |
| 150 | + if not isinstance(node, ast.Call): |
| 151 | + continue |
| 152 | + fn = node.func |
| 153 | + if not (isinstance(fn, ast.Attribute) and fn.attr == "add_argument"): |
| 154 | + continue |
| 155 | + store_true = any( |
| 156 | + kw.arg == "action" |
| 157 | + and isinstance(kw.value, ast.Constant) |
| 158 | + and kw.value.value == "store_true" |
| 159 | + for kw in node.keywords |
| 160 | + ) |
| 161 | + for arg in node.args: |
| 162 | + if isinstance(arg, ast.Constant) and isinstance(arg.value, str): |
| 163 | + if arg.value.startswith("--") and store_true: |
| 164 | + flags.add(arg.value) |
| 165 | + return flags |
| 166 | + |
| 167 | + |
| 168 | +def piece_paths(): |
| 169 | + for name in sorted(os.listdir(SHOWCASE)): |
| 170 | + d = os.path.join(SHOWCASE, name) |
| 171 | + if not os.path.isdir(d): |
| 172 | + continue |
| 173 | + readme = os.path.join(d, "README.md") |
| 174 | + script = os.path.join(d, name.replace("-", "_") + ".py") |
| 175 | + if os.path.isfile(readme) and os.path.isfile(script): |
| 176 | + yield name, readme, script |
| 177 | + |
| 178 | + |
| 179 | +def check_static(): |
| 180 | + failures, checked, pieces = [], 0, 0 |
| 181 | + undocumented_only = [] |
| 182 | + undocumented_pieces = [] |
| 183 | + for name, readme, script in piece_paths(): |
| 184 | + falsifiers, exits = parse_readme(readme) |
| 185 | + if not falsifiers: |
| 186 | + if name in KNOWN_UNDOCUMENTED: |
| 187 | + undocumented_pieces.append(name) |
| 188 | + continue |
| 189 | + failures.append( |
| 190 | + (name, "no falsifier table mapping flag to target budget to " |
| 191 | + "exit code") |
| 192 | + ) |
| 193 | + continue |
| 194 | + pieces += 1 |
| 195 | + flags = script_flags(script) |
| 196 | + for flag, (code, target) in sorted(falsifiers.items()): |
| 197 | + checked += 1 |
| 198 | + if flag not in flags: |
| 199 | + failures.append( |
| 200 | + (name, f"{flag} documented but not an argparse flag") |
| 201 | + ) |
| 202 | + continue |
| 203 | + if code not in exits: |
| 204 | + failures.append( |
| 205 | + (name, f"{flag} declares exit {code}, absent from the " |
| 206 | + "exit-code table") |
| 207 | + ) |
| 208 | + continue |
| 209 | + if not target: |
| 210 | + failures.append( |
| 211 | + (name, f"{flag} names no target budget in its row") |
| 212 | + ) |
| 213 | + for flag in sorted(flags - set(falsifiers) - NOT_FALSIFIERS): |
| 214 | + undocumented_only.append((name, flag)) |
| 215 | + return failures, undocumented_only, checked, pieces, undocumented_pieces |
| 216 | + |
| 217 | + |
| 218 | +def check_runtime(blender, only=None): |
| 219 | + failures, checked = [], 0 |
| 220 | + for name, readme, script in piece_paths(): |
| 221 | + if only and name not in only: |
| 222 | + continue |
| 223 | + falsifiers, _exits = parse_readme(readme) |
| 224 | + for flag, (want, _target) in sorted(falsifiers.items()): |
| 225 | + checked += 1 |
| 226 | + proc = subprocess.run( |
| 227 | + [blender, "--background", "--python", script, "--", flag], |
| 228 | + capture_output=True, |
| 229 | + ) |
| 230 | + got = proc.returncode |
| 231 | + status = "ok" if got == want else "MISMATCH" |
| 232 | + print(f" {status:9} {name} {flag}: want {want}, got {got}") |
| 233 | + if got != want: |
| 234 | + failures.append( |
| 235 | + (name, f"{flag} declared exit {want} but exited {got}") |
| 236 | + ) |
| 237 | + return failures, checked |
| 238 | + |
| 239 | + |
| 240 | +def main(argv=None): |
| 241 | + p = argparse.ArgumentParser(description=__doc__.split("\n")[0]) |
| 242 | + p.add_argument("--run", metavar="BLENDER", default=None, |
| 243 | + help="also execute each falsifier with this Blender binary") |
| 244 | + p.add_argument("--only", action="append", default=None, |
| 245 | + help="limit the runtime mode to these piece names") |
| 246 | + args = p.parse_args(argv) |
| 247 | + |
| 248 | + failures, undocumented, checked, pieces, skipped = check_static() |
| 249 | + for name, flag in undocumented: |
| 250 | + failures.append((name, f"{flag} looks like a falsifier but is not in " |
| 251 | + "the falsifier table")) |
| 252 | + |
| 253 | + if skipped: |
| 254 | + print( |
| 255 | + f"note: {len(skipped)} piece(s) predate the falsifier table and are " |
| 256 | + f"tracked for backfill: {', '.join(sorted(skipped))}" |
| 257 | + ) |
| 258 | + |
| 259 | + if args.run: |
| 260 | + print(f"runtime falsifier sweep with {args.run}") |
| 261 | + rt_failures, rt_checked = check_runtime(args.run, set(args.only or []) or None) |
| 262 | + failures.extend(rt_failures) |
| 263 | + checked += rt_checked |
| 264 | + |
| 265 | + if failures: |
| 266 | + print(f"\n{len(failures)} falsifier mapping problem(s):", file=sys.stderr) |
| 267 | + for name, detail in failures: |
| 268 | + print(f" ERROR: showcase/{name}: {detail}", file=sys.stderr) |
| 269 | + print( |
| 270 | + "\nA falsifier must fail the budget it targets. Fix a collision by " |
| 271 | + "changing the model or the falsifier, never by widening a band.", |
| 272 | + file=sys.stderr, |
| 273 | + ) |
| 274 | + return 1 |
| 275 | + |
| 276 | + print( |
| 277 | + f"falsifier-target checks passed: {checked} falsifier(s) across " |
| 278 | + f"{pieces} showcase piece(s)." |
| 279 | + ) |
| 280 | + return 0 |
| 281 | + |
| 282 | + |
| 283 | +if __name__ == "__main__": |
| 284 | + sys.exit(main()) |
0 commit comments