upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authorZack <zmasi21@gmail.com>2026-11-28 03:05:44 -0800
committerZack <zmasi21@gmail.com>2026-11-28 03:05:44 -0800
commitf77b4d80d0483027a978511d1d77d58a9523e43a (patch)
tree1b92d1f61844221177f7cd697133bea23c28e5f6 /scripts
parenta5d954a4a789591ec57330ced9705096fedefba0 (diff)
parent1fb0744735b82a2cf3961e6d850fe0aeab32ed8d (diff)
Merge remote-tracking branch 'origin/main' into fix/rdna2spirv-f16-interp-computed-ij
Diffstat (limited to 'scripts')
-rw-r--r--scripts/bench_translate.py309
-rw-r--r--scripts/bench_wave64.py3
-rw-r--r--scripts/build_runtime.ps12
-rw-r--r--scripts/check_apt_key.py41
-rw-r--r--scripts/check_no_game_data.py11
-rw-r--r--scripts/dev.py12
-rw-r--r--scripts/export_old_pr_manifest.py123
-rw-r--r--scripts/merge_check.py10
-rw-r--r--scripts/run_address_guard_gpu_test.py10
-rw-r--r--scripts/run_gpu_tests.py26
-rw-r--r--scripts/run_semantic_tests.py176
-rw-r--r--scripts/run_wine_tests.py20
-rw-r--r--scripts/shader_stats.py34
-rw-r--r--scripts/smoke.py332
14 files changed, 1003 insertions, 106 deletions
diff --git a/scripts/bench_translate.py b/scripts/bench_translate.py
new file mode 100644
index 000000000..b639098b9
--- /dev/null
+++ b/scripts/bench_translate.py
@@ -0,0 +1,309 @@
1#!/usr/bin/env python3
2"""Throughput of the translator (tools/rdna2spirv.py): microseconds per instruction, so a slowdown is visible.
3
4 python -I scripts/bench_translate.py # fixtures + synthetic programs, best of 3
5 python -I scripts/bench_translate.py --json # the same numbers as JSON
6 python -I scripts/bench_translate.py --runs 5 --max-slowdown 1.5
7
8The repository tests what the translator *emits*; nothing measures how long it takes. A change to the parser or the
9instruction table can cost a large share of the build time and still pass every test, and about 26,503 shaders are
10translated per build. This script is the cheap check for that: it times `rdna2spirv.translate()` on inputs that
11need no game data, no LLVM and no SPIRV-Tools:
12
13- `corpus`: every fixture in tests/semantic/fixtures/disasm, the hand-written listings the semantic tests use.
14 Pixel and vertex listings translate as they are; compute listings need the FSSM header the tests pass separately,
15 so they are counted as skipped.
16- `synthetic`: generated straight-line programs (ALU, s_nop) at fixed instruction counts. The ALU program is the
17 instruction work, the s_nop program is mostly per-instruction overhead, and the two together separate a slower
18 parser from a slower code generator.
19
20Times are best-of-`--runs` seconds of one `translate()` call per program; medians are not used because a single
21unlucky run (another process taking the CPU) is what dominates the tail. The numbers are machine-specific: compare
22them with a run of the same commit, not with the table in the pull request that added this script.
23"""
24import argparse
25import json
26import os
27import statistics
28import struct
29import subprocess
30import sys
31import tempfile
32import time
33import warnings
34
35ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
36TOOLS = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
37FIXTURES = os.path.join(ROOT, "tests", "semantic", "fixtures", "disasm")
38sys.dont_write_bytecode = True
39sys.path.insert(0, TOOLS)
40import rdna2spirv # noqa: E402
41
42# A DXBC container with zero parts declares no inputs, which is enough for a listing that reads no attribute
43# (tests/semantic/support.py uses the same stub).
44STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
45
46ALU_BODY = ("\tv_add_f32 v1, v1, 1.0\n"
47 "\tv_mul_f32 v2, v1, 2.0\n"
48 "\tv_cndmask_b32 v3, v1, v2, vcc\n"
49 "\tv_and_b32 v4, v3, 0xff\n")
50NOP_BODY = "\ts_nop 0\n"
51
52
53def synthetic(name, body, instructions):
54 """A whole pixel shader: comment, the repeated body, and the export the stage needs to be a shader."""
55 lines = [f"; ps_{name} synthetic benchmark program\n"]
56 lines.extend([body] * ((instructions + body.count("\n") - 1) // body.count("\n")))
57 lines.extend(["\tv_mov_b32 v1, 1\n",
58 "\texp mrt0 v1, v1, v1, v1 done\n",
59 "\ts_waitcnt expcnt(0)\n",
60 "\ts_endpgm\n"])
61 return "".join(lines).encode("utf-8")
62
63
64def translate_bytes(stem, listing, runs):
65 """Best of `runs` wall-clock seconds for one translate() of this listing, and the instruction count."""
66 with tempfile.TemporaryDirectory() as tmp:
67 os.mkdir(os.path.join(tmp, "disasm"))
68 with open(os.path.join(tmp, "disasm", stem + ".s"), "wb") as f:
69 f.write(listing)
70 with open(os.path.join(tmp, stem + ".dxbc"), "wb") as f:
71 f.write(STUB_DXBC)
72 path = os.path.join(tmp, "disasm", stem + ".s")
73 best = None
74 for _ in range(runs):
75 start = time.perf_counter()
76 with warnings.catch_warnings():
77 # The translator leaves its .dxbc handle to the garbage collector; that is its own business here.
78 warnings.simplefilter("ignore")
79 rdna2spirv.translate(path)
80 elapsed = time.perf_counter() - start
81 best = elapsed if best is None else min(best, elapsed)
82 return best
83
84
85def instruction_count(listing):
86 return sum(1 for line in listing.decode("utf-8", "replace").splitlines()
87 if line.startswith("\t") and line.strip())
88
89
90def corpus_rows(runs):
91 """Time every fixture that translates on its own, and count the ones that need an FSSM header."""
92 rows, skipped = [], []
93 for name in sorted(os.listdir(FIXTURES)):
94 if not name.endswith(".s"):
95 continue
96 stem = name[:-2]
97 if stem.startswith("cs_"):
98 # A compute listing reads its group size and RSRC2 out of the FSSM header, which translate() takes from
99 # <dir>/../fssm/<stem>.fssm; the semantic tests pass it per fixture (tests/semantic/support.py).
100 skipped.append(f"{stem}: compute listing, needs a FSSM header")
101 continue
102 with open(os.path.join(FIXTURES, name), "rb") as f:
103 listing = f.read()
104 try:
105 seconds = translate_bytes(stem, listing, runs)
106 except Exception as error: # a listing this run cannot translate: report it, never count it as fast
107 skipped.append(f"{stem}: {type(error).__name__}: {error}")
108 continue
109 instructions = instruction_count(listing)
110 rows.append({"name": stem, "instructions": instructions, "seconds": seconds,
111 "us_per_instruction": seconds / instructions * 1e6 if instructions else 0.0})
112 return rows, skipped
113
114
115def synthetic_rows(runs, size):
116 rows = []
117 for name, body, instructions in (("alu", ALU_BODY, size), ("nop", NOP_BODY, size)):
118 listing = synthetic(name, body, instructions)
119 seconds = translate_bytes("ps_" + name, listing, runs)
120 count = instruction_count(listing)
121 rows.append({"name": name, "instructions": count, "seconds": seconds,
122 "us_per_instruction": seconds / count * 1e6})
123 return rows
124
125
126def summarise(rows):
127 if not rows:
128 return {"programs": 0, "instructions": 0, "seconds": 0.0, "us_per_instruction": 0.0}
129 instructions = sum(r["instructions"] for r in rows)
130 seconds = sum(r["seconds"] for r in rows)
131 return {"programs": len(rows), "instructions": instructions, "seconds": seconds,
132 "us_per_instruction": seconds / instructions * 1e6 if instructions else 0.0}
133
134
135# Recorded on this machine (AMD Ryzen 9 desktop, Windows 11, Python 3.12.4, commit 1cc6e3c) with --runs 3: the numbers
136# to compare a later run against on the same machine. A different machine moves the absolute value; the shape does not.
137BASELINE = {"corpus_us_per_instruction": 55.4, "alu_us_per_instruction": 32.3, "nop_us_per_instruction": 14.0}
138
139
140def compare(reference, candidate, runs, size, rounds, max_slowdown=None):
141 """Interleaved A/B over two tools/ trees: each round measures both, and the best per side is kept.
142
143 Loading the tree is the subprocess's job (LEONIDA_TOOLS_DIR, as tests/semantic/support.py does it), so the two
144 versions never share a module. Alternating the two in the same round is the point: a machine that slows down or
145 speeds up between measurements moves both sides, not just one.
146 """
147 def measure(path):
148 env = dict(os.environ, LEONIDA_TOOLS_DIR=os.path.abspath(path))
149 result = subprocess.run([sys.executable, "-I", os.path.abspath(__file__), "--json",
150 "--runs", str(runs), "--size", str(size)],
151 capture_output=True, text=True, env=env)
152 if result.returncode != 0:
153 raise SystemExit(f"{path}: the benchmark failed\n{result.stderr.strip()}")
154 return json.loads(result.stdout)["measured"]
155
156 best = {"reference": {}, "candidate": {}}
157 measured_any = False
158 for round_index in range(rounds + 1): # the first round warms the caches and is not counted
159 order = [("reference", reference), ("candidate", candidate)]
160 if round_index % 2:
161 order.reverse() # whoever runs first pays the cold file cache, so the order alternates
162 for side, path in order:
163 measured = measure(path)
164 measured_any = measured_any or bool(measured)
165 if round_index == 0:
166 continue
167 for key, value in measured.items():
168 best[side][key] = min(best[side].get(key, value), value)
169 if not measured_any:
170 raise SystemExit("both trees measured nothing (an empty corpus?); nothing to compare")
171 if sorted(best["reference"]) != sorted(best["candidate"]):
172 only_reference = sorted(set(best["reference"]) - set(best["candidate"]))
173 only_candidate = sorted(set(best["candidate"]) - set(best["reference"]))
174 raise SystemExit("the two trees do not cover the same measurements"
175 + (f"; only in the reference: {', '.join(only_reference)}" if only_reference else "")
176 + (f"; only in the candidate: {', '.join(only_candidate)}" if only_candidate else "")
177 + "; a missing program would read as a ratio that looks like a win")
178 rows = []
179 for key in best["reference"]:
180 ref = best["reference"][key]
181 cand = best["candidate"].get(key, float("nan"))
182 rows.append({"name": key, "reference": ref, "candidate": cand, "ratio": cand / ref if ref else None})
183 print(f"{'measurement':<32} {'reference':>10} {'candidate':>10} {'ratio':>7}")
184 for row in rows:
185 ratio = f"{row['ratio']:>6.2f}x" if row["ratio"] is not None else " n/a"
186 print(f"{row['name']:<32} {row['reference']:>10.1f} {row['candidate']:>10.1f} {ratio}")
187 print(f"\nreference {os.path.abspath(reference)}\ncandidate {os.path.abspath(candidate)}")
188 print("ratio below 1.00 is the candidate being faster; rounds %d, min per side" % rounds)
189 if max_slowdown is not None:
190 # The limit means here what it means against a baseline: a measurement over it is a failure. The ratio is
191 # already candidate/reference, so the limit applies to it directly.
192 slow = [row for row in rows if row["ratio"] is not None and row["ratio"] > max_slowdown]
193 if slow:
194 for row in slow:
195 print(f"slower than the reference by {row['ratio']:.2f}x (limit {max_slowdown:.2f}x): {row['name']}",
196 file=sys.stderr)
197 return 1
198 return 0
199
200
201def main(argv=None):
202 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
203 parser.add_argument("--runs", type=int, default=3, help="translate() calls per program, best one counted")
204 parser.add_argument("--size", type=int, default=2000, help="instructions in each synthetic program")
205 parser.add_argument("--json", action="store_true", help="print one JSON object instead of the tables")
206 parser.add_argument("--max-slowdown", type=float, default=None,
207 help="exit 1 when a per-instruction time exceeds the baseline by this factor, in every output "
208 "format")
209 parser.add_argument("--baseline", metavar="FILE", default=None,
210 help="compare against a baseline written by --write-baseline instead of the committed one; "
211 "the committed numbers are from one machine and mean nothing on another")
212 parser.add_argument("--write-baseline", metavar="FILE", default=None,
213 help="write this run's numbers to FILE as a baseline for --baseline")
214 parser.add_argument("--compare", nargs=2, metavar=("REFERENCE", "CANDIDATE"), default=None,
215 help="time two tools/ trees against each other, interleaved; prints a ratio per measurement")
216 parser.add_argument("--rounds", type=int, default=3, help="rounds of --compare; the best per side is kept")
217 arguments = parser.parse_args(argv)
218 if arguments.rounds < 1:
219 parser.error("--rounds must be at least 1")
220 if arguments.baseline and arguments.write_baseline and \
221 os.path.abspath(arguments.baseline) == os.path.abspath(arguments.write_baseline):
222 # One file for both: a run that fails the limit would still replace the reference it failed against, and the
223 # same workload would pass on the retry.
224 parser.error("--baseline and --write-baseline name the same file; write to a different one")
225 if arguments.compare:
226 for flag, value in (("--json", arguments.json), ("--write-baseline", arguments.write_baseline),
227 ("--baseline", arguments.baseline)):
228 if value:
229 parser.error(f"{flag} does not apply to --compare, which times two trees and prints its own table")
230 return compare(*arguments.compare, arguments.runs, arguments.size, arguments.rounds,
231 arguments.max_slowdown)
232 if arguments.baseline and not os.path.isfile(arguments.baseline):
233 parser.error(f"--baseline {arguments.baseline} does not exist; --write-baseline records one")
234 if arguments.runs < 1:
235 parser.error("--runs must be at least 1")
236 if arguments.size < 1:
237 parser.error("--size must be at least 1")
238
239 corpus, skipped = corpus_rows(arguments.runs)
240 synthetic_programs = synthetic_rows(arguments.runs, arguments.size)
241 corpus_summary = summarise(corpus)
242 synthetic_summary = summarise(synthetic_programs)
243
244 measured = {"corpus_us_per_instruction": corpus_summary["us_per_instruction"]}
245 measured.update({f"{row['name']}_us_per_instruction": row["us_per_instruction"]
246 for row in synthetic_programs})
247
248 baseline, baseline_source = BASELINE, "committed"
249 if arguments.baseline:
250 with open(arguments.baseline, encoding="utf-8") as handle:
251 loaded = json.load(handle)
252 baseline = {key: float(value) for key, value in (loaded.get("measured") or loaded).items()}
253 baseline_source = os.path.abspath(arguments.baseline)
254 if arguments.write_baseline:
255 with open(arguments.write_baseline, "w", encoding="utf-8", newline="\n") as handle:
256 json.dump({"measured": measured, "runs": arguments.runs, "size": arguments.size}, handle,
257 indent=2, sort_keys=True)
258 handle.write("\n")
259 print(f"baseline written to {os.path.abspath(arguments.write_baseline)}", file=sys.stderr)
260
261 # The limit is part of the contract of every output format: a job that collects --json must not read a success
262 # code for a run whose numbers are over the limit. It is evaluated here, once, before either format prints.
263 slow = {}
264 if arguments.max_slowdown is not None:
265 slow = {key: value / baseline[key] for key, value in measured.items()
266 if baseline.get(key) and value > baseline[key] * arguments.max_slowdown}
267
268 if arguments.json:
269 print(json.dumps({
270 "runs": arguments.runs,
271 "corpus": {"summary": corpus_summary, "programs": corpus, "skipped": skipped},
272 "synthetic": {"summary": synthetic_summary, "programs": synthetic_programs, "size": arguments.size},
273 "baseline": baseline,
274 "baseline_source": baseline_source,
275 "measured": measured,
276 "slowdown": {k: (measured[k] / baseline[k] if baseline.get(k) else None) for k in measured},
277 "over_limit": sorted(slow),
278 "max_slowdown": arguments.max_slowdown,
279 }, indent=2, sort_keys=True))
280 return 1 if slow else 0
281
282 print(f"corpus: {corpus_summary['programs']} fixtures, {corpus_summary['instructions']} instructions, "
283 f"{corpus_summary['seconds']:.3f} s, {corpus_summary['us_per_instruction']:.1f} us/instruction "
284 f"({len(skipped)} skipped)")
285 worst = sorted(corpus, key=lambda r: -r["us_per_instruction"])[:5]
286 for row in worst:
287 print(f" {row['name']:<28} {row['instructions']:>5} instr {row['seconds'] * 1e3:>8.2f} ms "
288 f"{row['us_per_instruction']:>6.1f} us/instr")
289 print(f"\nsynthetic ({arguments.size} instructions):")
290 for row in synthetic_programs:
291 reference = baseline.get(row["name"] + "_us_per_instruction")
292 compared = (f"({measured[row['name'] + '_us_per_instruction'] / reference:.2f}x the {baseline_source} baseline)"
293 if reference else "(no baseline for this measurement)")
294 print(f" {row['name']:<28} {row['instructions']:>5} instr {row['seconds'] * 1e3:>8.2f} ms "
295 f"{row['us_per_instruction']:>6.1f} us/instr {compared}")
296 if skipped:
297 print("\nskipped (need the FSSM header, which these runs do not pass):")
298 for line in skipped:
299 print(" " + line)
300
301 if slow:
302 for name, factor in sorted(slow.items()):
303 print(f"slower than baseline ({baseline_source}) by {factor:.2f}x: {name}", file=sys.stderr)
304 return 1
305 return 0
306
307
308if __name__ == "__main__":
309 sys.exit(main())
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py
index 57253cb57..3a566ebfd 100644
--- a/scripts/bench_wave64.py
+++ b/scripts/bench_wave64.py
@@ -97,7 +97,8 @@ def main():
97 ap = argparse.ArgumentParser() 97 ap = argparse.ArgumentParser()
98 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), 98 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"),
99 help="CMake build directory or a configuration directory such as RelWithDebInfo") 99 help="CMake build directory or a configuration directory such as RelWithDebInfo")
100 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc")) 100 # Empty means unset to build.py: mc_command() then finds llvm-mc on PATH or a versioned llvm-mc-<N>.
101 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", ""))
101 # Vulkan guarantees support for at least 65,535 groups along X in one dispatch. 102 # Vulkan guarantees support for at least 65,535 groups along X in one dispatch.
102 ap.add_argument("--groups", type=positive_int, default=65535) 103 ap.add_argument("--groups", type=positive_int, default=65535)
103 ap.add_argument("--reps", type=positive_int, default=30) 104 ap.add_argument("--reps", type=positive_int, default=30)
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index bb25cccd7..d386ba052 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -116,7 +116,7 @@ if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNO
116rem tools/sandbox.py starts vk_sandbox, and tools/ps_sweep.py --exe / tools/ab_control_flow.py --all-attachments start 116rem tools/sandbox.py starts vk_sandbox, and tools/ps_sweep.py --exe / tools/ab_control_flow.py --all-attachments start
117rem vk_ps_sweep, by name from runtime\build; without them the sandbox says "vk_sandbox is not built" and the sweep has 117rem vk_ps_sweep, by name from runtime\build; without them the sandbox says "vk_sandbox is not built" and the sweep has
118rem no harness to pass. CMake builds both in its Vulkan tools loop (EGEN-FALLBACK-SANDBOX-SWEEP). 118rem no harness to pass. CMake builds both in its Vulkan tools loop (EGEN-FALLBACK-SANDBOX-SWEEP).
119if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_sandbox.cpp" /Fe:vk_sandbox.exe || exit /b 1 119if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_sandbox.cpp" /Fe:vk_sandbox.exe /link user32.lib || exit /b 1
120if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_ps_sweep.cpp" /Fe:vk_ps_sweep.exe || exit /b 1 120if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_ps_sweep.cpp" /Fe:vk_ps_sweep.exe || exit /b 1
121"@ 121"@
122} 122}
diff --git a/scripts/check_apt_key.py b/scripts/check_apt_key.py
index 160f0203a..f06ce8629 100644
--- a/scripts/check_apt_key.py
+++ b/scripts/check_apt_key.py
@@ -20,6 +20,8 @@ import sys
20 20
21def normalize(fingerprint): 21def normalize(fingerprint):
22 """`fingerprint` as 40 upper-case hex digits, or None if it isn't a v4 fingerprint.""" 22 """`fingerprint` as 40 upper-case hex digits, or None if it isn't a v4 fingerprint."""
23 if not isinstance(fingerprint, str):
24 return None
23 digits = re.sub(r"\s+", "", fingerprint).upper() 25 digits = re.sub(r"\s+", "", fingerprint).upper()
24 return digits if re.fullmatch(r"[0-9A-F]{40}", digits) else None 26 return digits if re.fullmatch(r"[0-9A-F]{40}", digits) else None
25 27
@@ -30,19 +32,26 @@ def primary_fingerprints(colons):
30 expect_primary_fpr = False 32 expect_primary_fpr = False
31 for line in colons.splitlines(): 33 for line in colons.splitlines():
32 fields = line.split(":") 34 fields = line.split(":")
33 if fields[0] == "pub": 35 tag = fields[0]
36 if tag == "pub":
37 if expect_primary_fpr:
38 out.append("")
34 expect_primary_fpr = True 39 expect_primary_fpr = True
35 elif fields[0] == "fpr" and expect_primary_fpr: 40 elif tag == "fpr" and expect_primary_fpr:
36 out.append(fields[9].upper() if len(fields) > 9 else "") 41 out.append(fields[9].strip().upper() if len(fields) > 9 else "")
37 expect_primary_fpr = False 42 expect_primary_fpr = False
38 elif fields[0] in ("sub", "ssb", "sec"): 43 elif tag in ("sub", "ssb", "sec"):
44 if expect_primary_fpr:
45 out.append("")
39 expect_primary_fpr = False 46 expect_primary_fpr = False
47 if expect_primary_fpr:
48 out.append("")
40 return out 49 return out
41 50
42 51
43def show_keys(path, gpg=("gpg",)): 52def show_keys(path, gpg=("gpg",)):
44 """`gpg --show-keys --with-colons` output for the key file at `path` (it lists the file, importing nothing).""" 53 """`gpg --show-keys --with-colons` output for the key file at `path` (it lists the file, importing nothing)."""
45 result = subprocess.run([*gpg, "--batch", "--show-keys", "--with-colons", path], 54 result = subprocess.run([*gpg, "--batch", "--show-keys", "--with-colons", "--", path],
46 capture_output=True, text=True, encoding="utf-8", errors="replace") 55 capture_output=True, text=True, encoding="utf-8", errors="replace")
47 if result.returncode != 0: 56 if result.returncode != 0:
48 raise ValueError(f"gpg could not read {path}: {result.stderr.strip() or 'exit ' + str(result.returncode)}") 57 raise ValueError(f"gpg could not read {path}: {result.stderr.strip() or 'exit ' + str(result.returncode)}")
@@ -52,20 +61,32 @@ def show_keys(path, gpg=("gpg",)):
52def check(path, expected, gpg=("gpg",)): 61def check(path, expected, gpg=("gpg",)):
53 """None if the key file at `path` holds exactly the one primary key `expected`, else why not. `gpg` is the command 62 """None if the key file at `path` holds exactly the one primary key `expected`, else why not. `gpg` is the command
54 that runs GnuPG (a list, so a test can stand another program in).""" 63 that runs GnuPG (a list, so a test can stand another program in)."""
64 norm_expected = normalize(expected)
65 if not norm_expected:
66 return f"not a 40-digit key fingerprint: {expected!r}"
55 try: 67 try:
56 found = primary_fingerprints(show_keys(path, gpg)) 68 colons = show_keys(path, gpg)
57 except (OSError, ValueError) as e: 69 except (OSError, ValueError) as e:
58 return str(e) 70 return str(e)
71 if any(line.split(":", 1)[0] in ("sec", "ssb") for line in colons.splitlines()):
72 return f"{path} holds secret key material; expected a public key only"
73 found = primary_fingerprints(colons)
59 if not found: 74 if not found:
60 return f"{path} holds no public key" 75 return f"{path} holds no public key"
61 if len(found) > 1: 76 if len(found) > 1:
62 return f"{path} holds {len(found)} primary keys ({', '.join(found)}); expected only {expected}" 77 labels = ", ".join(fp or "<missing>" for fp in found)
63 if found[0] != expected: 78 return f"{path} holds {len(found)} primary keys ({labels}); expected only {norm_expected}"
64 return f"{path} is key {found[0]}, expected {expected}" 79 if found[0] != norm_expected:
80 got = found[0] or "<missing>"
81 return f"{path} is key {got}, expected {norm_expected}"
65 return None 82 return None
66 83
67 84
68def main(argv): 85def main(argv=None):
86 argv = sys.argv[1:] if argv is None else list(argv)
87 if argv in (["-h"], ["--help"]):
88 print(__doc__)
89 return 0
69 if len(argv) != 2: 90 if len(argv) != 2:
70 print("usage: check_apt_key.py KEYFILE FINGERPRINT", file=sys.stderr) 91 print("usage: check_apt_key.py KEYFILE FINGERPRINT", file=sys.stderr)
71 return 2 92 return 2
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py
index ae3d06e77..595fc7b1c 100644
--- a/scripts/check_no_game_data.py
+++ b/scripts/check_no_game_data.py
@@ -14,8 +14,8 @@ notes). Text formats (disassembly, .obj, .spvasm)
14have no magic and stay with the extension check. 14have no magic and stay with the extension check.
15 15
16A compressed file hides those magics from both checks, so the script looks inside what the standard library opens: 16A compressed file hides those magics from both checks, so the script looks inside what the standard library opens:
17each member of a zip (found by its central directory too, so with bytes in front of it) or a tar, and the stream of 17each member of a zip (found by its central directory too, so with bytes in front of it) or a tar (including V7), and
18a gzip, bzip2 or xz file, nested up to three levels, is matched the same way. What's inside is read into memory 18the stream of a gzip, bzip2 or xz file, nested up to three levels, is matched the same way. What's inside is read into memory
19under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb can't make the check run long. 19under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb can't make the check run long.
207-Zip, Zstandard and RAR files, which it can't open, archives that fail to open and archives over the budget are 207-Zip, Zstandard and RAR files, which it can't open, archives that fail to open and archives over the budget are
21reported as archives that can't be checked. 21reported as archives that can't be checked.
@@ -184,6 +184,13 @@ def archive_kind(f, head):
184 return stream[0] 184 return stream[0]
185 if head[TAR_MAGIC[0]:TAR_MAGIC[0] + len(TAR_MAGIC[1])] == TAR_MAGIC[1]: 185 if head[TAR_MAGIC[0]:TAR_MAGIC[0] + len(TAR_MAGIC[1])] == TAR_MAGIC[1]:
186 return "tar archive" 186 return "tar archive"
187 # V7 tar has no ustar marker. Validate only its first header here; member reads still use the shared budget.
188 try:
189 tarfile.TarInfo.frombuf(head[:tarfile.BLOCKSIZE], tarfile.ENCODING, "surrogateescape")
190 except tarfile.HeaderError:
191 pass
192 else:
193 return "tar archive"
187 # is_zipfile finds the end-of-central-directory record, so a zip with bytes in front of it (a self-extracting 194 # is_zipfile finds the end-of-central-directory record, so a zip with bytes in front of it (a self-extracting
188 # archive, a spanned zip starting PK\x07\x08) is found as zipfile itself would open it. 195 # archive, a spanned zip starting PK\x07\x08) is found as zipfile itself would open it.
189 if head.startswith(ZIP) or zipfile.is_zipfile(f): 196 if head.startswith(ZIP) or zipfile.is_zipfile(f):
diff --git a/scripts/dev.py b/scripts/dev.py
index fada30da4..4170aac63 100644
--- a/scripts/dev.py
+++ b/scripts/dev.py
@@ -13,6 +13,7 @@ from pathlib import Path
13ROOT = Path(__file__).resolve().parents[1] 13ROOT = Path(__file__).resolve().parents[1]
14BOOT_TRACE = "tools/boot_trace.py" 14BOOT_TRACE = "tools/boot_trace.py"
15GUEST_SCENE = "scripts/run_guest_scene.py" 15GUEST_SCENE = "scripts/run_guest_scene.py"
16SMOKE = "scripts/smoke.py"
16TOOLS = ( 17TOOLS = (
17 ( 18 (
18 "boot-trace", 19 "boot-trace",
@@ -29,6 +30,14 @@ TOOLS = (
29 "Wine when running the Windows loader outside Windows", 30 "Wine when running the Windows loader outside Windows",
30 ), 31 ),
31 ), 32 ),
33 (
34 "smoke",
35 SMOKE,
36 (
37 "Python 3.10+",
38 "Synthetic source-only smoke suite (compilation, clean-room, CLI help, fast tests)",
39 ),
40 ),
32) 41)
33 42
34 43
@@ -94,6 +103,8 @@ def main() -> int:
94 return run_producer(BOOT_TRACE, argv[1:]) 103 return run_producer(BOOT_TRACE, argv[1:])
95 if argv[:1] == ["guest-scene"]: 104 if argv[:1] == ["guest-scene"]:
96 return guest_scene(argv[1:]) 105 return guest_scene(argv[1:])
106 if argv[:1] == ["smoke"]:
107 return run_producer(SMOKE, argv[1:])
97 108
98 parser = argparse.ArgumentParser(description=__doc__) 109 parser = argparse.ArgumentParser(description=__doc__)
99 commands = parser.add_subparsers(dest="command", required=True) 110 commands = parser.add_subparsers(dest="command", required=True)
@@ -101,6 +112,7 @@ def main() -> int:
101 inventory.add_argument("--json", action="store_true", help="write a JSON inventory to stdout") 112 inventory.add_argument("--json", action="store_true", help="write a JSON inventory to stdout")
102 commands.add_parser("boot-trace", help="summarize startup and D3D12 boot traces") 113 commands.add_parser("boot-trace", help="summarize startup and D3D12 boot traces")
103 commands.add_parser("guest-scene", help="run the synthetic guest scene with a required --out") 114 commands.add_parser("guest-scene", help="run the synthetic guest scene with a required --out")
115 commands.add_parser("smoke", help="run the synthetic source-only smoke suite (DX-07)")
104 args = parser.parse_args(argv) 116 args = parser.parse_args(argv)
105 117
106 result = discover() 118 result = discover()
diff --git a/scripts/export_old_pr_manifest.py b/scripts/export_old_pr_manifest.py
new file mode 100644
index 000000000..66d99f1ac
--- /dev/null
+++ b/scripts/export_old_pr_manifest.py
@@ -0,0 +1,123 @@
1"""Write a portable, verifiable manifest of the original repository's surviving history (issue #563).
2
3The original `ItsNotRexed/Leonida` repository went private in November 2026. Its pull requests survive only as the
4`old-pr/<old number>` branches kept here (issue #17) and its issues only as the title/author index in issue #18. Both
5live on GitHub, which is the single point of failure this manifest removes: the branch tips, their authors and dates
6are recorded as a sorted TSV with a SHA-256 beside it, so the record can be checked after the branches themselves are
7gone, and fed to a migration (Radicle, issue #563) without re-reading GitHub.
8
9 python -I scripts/export_old_pr_manifest.py branches --out docs/history --remote origin
10 python -I scripts/export_old_pr_manifest.py issues --index issue-18.md --out docs/history
11
12`branches` reads `refs/remotes/<remote>/old-pr/*` from the local clone; `issues` reads the markdown table posted in
13issue #18. Both write `<kind>.tsv` and `<kind>.sha256` in the output directory, and both are deterministic: the same
14input gives the same bytes, sorting numerically by old number so the order does not depend on ref iteration. Commit
15dates are kept as the commit's own ISO-8601 author date, not as a generation timestamp, for the same reason.
16
17Nothing of the game is read: a branch number, a SHA, a name, a date and a subject line.
18"""
19import argparse
20import hashlib
21import os
22import re
23import subprocess
24import sys
25
26# A subject can contain a tab or a newline; the TSV keeps one record per line with single spaces.
27_WHITESPACE = re.compile(r"\s+")
28
29# | 4 | Would you consider MIT License? | `Ahmet-Dedeler` | |
30_ISSUE_ROW = re.compile(r"^\|\s*(\d+)\s*\|(.+?)\|(.+?)\|(.*?)\|\s*$")
31
32
33def collapse(text: str) -> str:
34 return _WHITESPACE.sub(" ", text).strip()
35
36
37def git(branch_format: str, pattern: str) -> list:
38 r = subprocess.run(
39 ["git", "for-each-ref", "--format=" + branch_format, pattern],
40 capture_output=True, text=True, encoding="utf-8",
41 )
42 if r.returncode:
43 raise SystemExit(f"git for-each-ref failed: {r.stderr.strip()}")
44 return r.stdout.splitlines()
45
46
47def branches(remote: str) -> list:
48 """Rows (number, tip sha, author date, author, subject) for every surviving old pull request branch."""
49 pattern = f"refs/remotes/{remote}/old-pr/*"
50 fmt = "%(refname:lstrip=3)%09%(objectname)%09%(authordate:iso-strict)%09%(authorname)%09%(subject)"
51 rows = []
52 for line in git(fmt, pattern):
53 if not line.strip():
54 continue
55 ref, sha, date, author, subject = (line.split("\t", 4) + [""] * 5)[:5]
56 number = ref.partition("old-pr/")[2]
57 if not number.isdigit() or not re.fullmatch(r"[0-9a-f]{40}", sha):
58 raise SystemExit(f"unexpected ref line: {line!r}")
59 rows.append((int(number), sha, date, collapse(author), collapse(subject)))
60 if not rows:
61 raise SystemExit(f"no refs matched {pattern}; fetch the branches first (git fetch {remote})")
62 numbers = [r[0] for r in rows]
63 if len(set(numbers)) != len(numbers):
64 raise SystemExit("two refs share an old number")
65 return sorted(rows)
66
67
68def issues(text: str) -> list:
69 """Rows (number, title, author, labels) from the markdown table of issue #18."""
70 rows = []
71 for line in text.splitlines():
72 if not line.startswith("|"):
73 continue
74 m = _ISSUE_ROW.match(line)
75 if not m:
76 continue
77 number, title, author, labels = m.groups()
78 if not title.strip() or set(title.strip()) <= set("-: "):
79 continue
80 rows.append((int(number), collapse(title), collapse(author), collapse(labels)))
81 if not rows:
82 raise SystemExit("no issue rows found; is this the table from issue #18?")
83 return sorted(rows)
84
85
86def write_tsv(out_dir: str, kind: str, header: tuple, rows: list) -> str:
87 os.makedirs(out_dir, exist_ok=True)
88 body = "\t".join(header) + "\n"
89 body += "".join("\t".join(str(c) for c in row) + "\n" for row in rows)
90 path = os.path.join(out_dir, kind + ".tsv")
91 with open(path, "w", encoding="utf-8", newline="\n") as f:
92 f.write(body)
93 digest = hashlib.sha256(body.encode("utf-8")).hexdigest()
94 with open(path + ".sha256", "w", encoding="utf-8", newline="\n") as f:
95 f.write(f"{digest} {kind}.tsv\n")
96 return digest
97
98
99def main(argv=None) -> int:
100 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
101 sub = ap.add_subparsers(dest="kind", required=True)
102 b = sub.add_parser("branches", help="manifest the old-pr/* branches")
103 b.add_argument("--remote", default="origin", help="remote that carries the old-pr/* refs (default: origin)")
104 i = sub.add_parser("issues", help="manifest the issue index from issue #18")
105 i.add_argument("--index", required=True, help="file holding the issue table (or - for stdin)")
106 for p in (b, i):
107 p.add_argument("--out", default="docs/history", help="output directory (default: docs/history)")
108 a = ap.parse_args(argv)
109
110 if a.kind == "branches":
111 rows = branches(a.remote)
112 digest = write_tsv(a.out, "old-pr", ("number", "tip", "author_date", "author", "subject"), rows)
113 print(f"{len(rows)} old pull request branches, sha256 {digest}")
114 else:
115 text = sys.stdin.read() if a.index == "-" else open(a.index, encoding="utf-8").read()
116 rows = issues(text)
117 digest = write_tsv(a.out, "issues", ("number", "title", "author", "labels"), rows)
118 print(f"{len(rows)} old issues, sha256 {digest}")
119 return 0
120
121
122if __name__ == "__main__":
123 sys.exit(main())
diff --git a/scripts/merge_check.py b/scripts/merge_check.py
index e270cbe00..5499da29c 100644
--- a/scripts/merge_check.py
+++ b/scripts/merge_check.py
@@ -41,13 +41,13 @@ class GitError(Exception):
41 pass 41 pass
42 42
43 43
44def git(repo, *args, check=True): 44def git(repo, *args, check=True, stdout_errors="replace"):
45 try: 45 try:
46 r = subprocess.run(["git", "-C", repo, *args], capture_output=True) 46 r = subprocess.run(["git", "-C", repo, *args], capture_output=True)
47 except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback 47 except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback
48 raise GitError(f"cannot run git: {e.strerror or e}") from None 48 raise GitError(f"cannot run git: {e.strerror or e}") from None
49 # Decode without universal-newline translation: a bare CR inside a Git line is content. 49 # Decode without universal-newline translation: a bare CR inside a Git line is content.
50 r.stdout = r.stdout.decode("utf-8", "replace") 50 r.stdout = r.stdout.decode("utf-8", stdout_errors)
51 r.stderr = r.stderr.decode("utf-8", "replace") 51 r.stderr = r.stderr.decode("utf-8", "replace")
52 if check and r.returncode != 0: 52 if check and r.returncode != 0:
53 raise GitError(f"git {' '.join(args)}: {r.stderr.strip() or r.returncode}") 53 raise GitError(f"git {' '.join(args)}: {r.stderr.strip() or r.returncode}")
@@ -132,7 +132,8 @@ def duplicates(repo, main, tree, min_length, block=3):
132 132
133 def windows(rev, path): 133 def windows(rev, path):
134 # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file. 134 # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file.
135 r = git(repo, "show", f"{rev}:{path}", "--") 135 # Keep undecodable bytes distinct while comparing lines from legacy-encoded documents.
136 r = git(repo, "show", f"{rev}:{path}", "--", stdout_errors="surrogateescape")
136 lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())] 137 lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())]
137 content = [text for _, text in lines] 138 content = [text for _, text in lines]
138 return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1)) 139 return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1))
@@ -153,7 +154,8 @@ def duplicates(repo, main, tree, min_length, block=3):
153 if before[run] and after[run] > before[run]: 154 if before[run] and after[run] > before[run]:
154 marked.update(number for number, _ in window) 155 marked.update(number for number, _ in window)
155 if marked: 156 if marked:
156 found[path] = [text for number, text in after_lines if number in marked] 157 found[path] = [text.encode("utf-8", "surrogateescape").decode("utf-8", "replace")
158 for number, text in after_lines if number in marked]
157 return found 159 return found
158 160
159 161
diff --git a/scripts/run_address_guard_gpu_test.py b/scripts/run_address_guard_gpu_test.py
index f7aa53366..c61b34704 100644
--- a/scripts/run_address_guard_gpu_test.py
+++ b/scripts/run_address_guard_gpu_test.py
@@ -68,15 +68,19 @@ def find_tool(build, name):
68def main(argv=None): 68def main(argv=None):
69 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) 69 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
70 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), help="folder with vk_compute_test") 70 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), help="folder with vk_compute_test")
71 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc")) 71 # No literal default: unset, mc_command() reads LLVM_MC and then finds llvm-mc on PATH or a versioned
72 # Debian/Ubuntu install (llvm-mc-21, /usr/lib/llvm-21/bin/llvm-mc), as run_gpu_tests.py does.
73 ap.add_argument("--llvm-mc", default=None)
72 ap.add_argument("--work", default=None, help="keep the intermediate files here") 74 ap.add_argument("--work", default=None, help="keep the intermediate files here")
73 a = ap.parse_args(argv) 75 a = ap.parse_args(argv)
74 vk_compute = find_tool(a.build, "vk_compute_test") 76 vk_compute = find_tool(a.build, "vk_compute_test")
75 if not vk_compute: 77 if not vk_compute:
76 print(f"SKIP: no vk_compute_test under {a.build}") 78 print(f"SKIP: no vk_compute_test under {a.build}")
77 return 77 79 return 77
78 if not shutil.which(a.llvm_mc.split()[0]): 80 import mc_command
79 print(f"SKIP: {a.llvm_mc} not found") 81 mc = mc_command.mc_command(a.llvm_mc)
82 if not shutil.which(mc[0]):
83 print(f"SKIP: {' '.join(mc)} not found")
80 return 77 84 return 77
81 sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) 85 sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders"))
82 sys.path.insert(0, os.path.join(ROOT, "scripts")) 86 sys.path.insert(0, os.path.join(ROOT, "scripts"))
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index 3ad731573..e0303951e 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -102,7 +102,7 @@ def make_ms_psv0(threads_x: int, maxv: int, maxp: int, topology: int = 2, group_
102TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here" 102TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here"
103 103
104 104
105def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: 105def assemble_to_s(llvm_mc: str | None, asm_path: str, s_path: str, name: str) -> None:
106 """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py.""" 106 """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py."""
107 with open(asm_path, encoding="utf-8") as source: 107 with open(asm_path, encoding="utf-8") as source:
108 raw = source.read() 108 raw = source.read()
@@ -334,7 +334,9 @@ def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *,
334 # gpu=False (the translator over the whole suite) runs without a limit. 334 # gpu=False (the translator over the whole suite) runs without a limit.
335 limit = gpu_test_timeout() if gpu else None 335 limit = gpu_test_timeout() if gpu else None
336 try: 336 try:
337 p = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=limit, cwd=cwd) 337 # Keep the exit status and the rest of the log if a tool emits bytes outside the host encoding.
338 p = subprocess.run(cmd, capture_output=True, text=True, errors="backslashreplace",
339 env=env, timeout=limit, cwd=cwd)
338 except subprocess.TimeoutExpired: 340 except subprocess.TimeoutExpired:
339 return 1, timed_out(cmd[0], limit) 341 return 1, timed_out(cmd[0], limit)
340 except OSError as e: # e.g. Smart App Control blocked a fresh build: fail this test, keep running the others 342 except OSError as e: # e.g. Smart App Control blocked a fresh build: fail this test, keep running the others
@@ -377,7 +379,9 @@ def _device_per_vertex():
377 try: 379 try:
378 r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], 380 r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")],
379 capture_output=True, text=True, timeout=60) 381 capture_output=True, text=True, timeout=60)
380 answer = json.loads(r.stdout.strip().splitlines()[-1]).get("per_vertex_inputs") 382 report = json.loads(r.stdout.strip().splitlines()[-1])
383 if isinstance(report, dict):
384 answer = report.get("per_vertex_inputs")
381 except (OSError, ValueError, IndexError, subprocess.SubprocessError): 385 except (OSError, ValueError, IndexError, subprocess.SubprocessError):
382 pass 386 pass
383 _PER_VERTEX.append(answer) 387 _PER_VERTEX.append(answer)
@@ -392,7 +396,9 @@ def _device_barycentric_fallback():
392 try: 396 try:
393 r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], 397 r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")],
394 capture_output=True, text=True, timeout=60) 398 capture_output=True, text=True, timeout=60)
395 answer = json.loads(r.stdout.strip().splitlines()[-1]).get("barycentric_fallback") 399 report = json.loads(r.stdout.strip().splitlines()[-1])
400 if isinstance(report, dict):
401 answer = report.get("barycentric_fallback")
396 except (OSError, ValueError, IndexError, subprocess.SubprocessError): 402 except (OSError, ValueError, IndexError, subprocess.SubprocessError):
397 pass 403 pass
398 _BARYCENTRIC_FALLBACK.append(answer) 404 _BARYCENTRIC_FALLBACK.append(answer)
@@ -774,8 +780,11 @@ def native_folder(path: str, ansi: str = "mbcs") -> str | None:
774 780
775def main() -> int: 781def main() -> int:
776 ap = argparse.ArgumentParser() 782 ap = argparse.ArgumentParser()
777 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), 783 # No literal default: unset, mc_command() reads LLVM_MC and then finds llvm-mc on PATH or a versioned
778 help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'") 784 # Debian/Ubuntu install (llvm-mc-21, /usr/lib/llvm-21/bin/llvm-mc), as the not-found message promises.
785 ap.add_argument("--llvm-mc", default=None,
786 help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' "
787 "(default: LLVM_MC, then llvm-mc on PATH, then the newest llvm-mc-<N>)")
779 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), 788 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"),
780 help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " 789 help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... "
781 "subfolder that has the test programs is found by itself") 790 "subfolder that has the test programs is found by itself")
@@ -1698,14 +1707,15 @@ def run_suite(a, work: str) -> int:
1698 ok, detail = check_flat(raw) 1707 ok, detail = check_flat(raw)
1699 results.append((name, ok, detail)) 1708 results.append((name, ok, detail))
1700 1709
1701 if a.filter and not results: # the filter matched only inputs/partners: say so rather than "0/0 passed" 1710 if (a.filter or disasm_src is not None) and not results:
1702 names = [os.path.splitext(f)[0] for f in asm_files] 1711 names = [os.path.splitext(f)[0] for f in asm_files]
1703 partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES) 1712 partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES)
1704 shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "") 1713 shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "")
1705 role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row" 1714 role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row"
1706 hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool" 1715 hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool"
1707 if all(n.startswith("cs_bench_") for n in names) else "") 1716 if all(n.startswith("cs_bench_") for n in names) else "")
1708 print(f"error: --filter {a.filter!r} selected {shown} but no runnable GPU test cases ({role}){hint}", 1717 selected_by = f"--filter {a.filter!r}" if a.filter else f"--disasm-dir {disasm_src!r}"
1718 print(f"error: {selected_by} selected {shown} but no runnable GPU test cases ({role}){hint}",
1709 file=sys.stderr) 1719 file=sys.stderr)
1710 return 2 1720 return 2
1711 1721
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py
index 514e78133..a25e363bb 100644
--- a/scripts/run_semantic_tests.py
+++ b/scripts/run_semantic_tests.py
@@ -15,10 +15,13 @@ error in serial and parallel runs.
15It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each in its own process from that folder, so a file sees the same import path as under discover. 15It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each in its own process from that folder, so a file sees the same import path as under discover.
16 16
17The files can run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1, 17The files can run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1,
18or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary 18or on a single core, it runs that discover command itself. Prints the output of every failing file, headed by its
19line, and exits 1 if a file fails, none is found, or no test ran. Standard library only. 19exit code (a POSIX signal by name, a known Windows NTSTATUS with its meaning, e.g. 0xC0000005 access violation,
20since a file that crashes prints nothing), and one summary line, and exits 1 if a file fails, none is found, or no
21test ran. Standard library only.
20 22
21The count of tests comes from unittest's own result object, not from its output: a module that writes a line shaped like unittest's summary to stderr - a nested runner, or an atexit handler that runs after unittest's own summary - cannot change it. 23The test count and verdict come from unittest's result, not from printed summaries. A child exiting with status 0
24without a completed result, or after unittest reported failure, fails the run.
22 25
23`--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with 26`--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with
24`-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. 27`-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits.
@@ -33,6 +36,7 @@ import locale
33import math 36import math
34import os 37import os
35import re 38import re
39import signal
36import subprocess 40import subprocess
37import sys 41import sys
38import tempfile 42import tempfile
@@ -59,7 +63,7 @@ def _unregister_process(proc):
59def _kill_process_tree(proc): 63def _kill_process_tree(proc):
60 if proc is None: 64 if proc is None:
61 return 65 return
62 if os.name == "nt": 66 if os.name == "nt" and proc.poll() is None:
63 try: 67 try:
64 subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], 68 subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)],
65 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 69 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
@@ -74,11 +78,13 @@ def _kill_process_tree(proc):
74def _terminate_active_processes(): 78def _terminate_active_processes():
75 with _processes_lock: 79 with _processes_lock:
76 procs = list(_active_processes) 80 procs = list(_active_processes)
77 for p in procs: 81 if os.name != "nt":
78 try: 82 for p in procs:
79 p.terminate() 83 try:
80 except OSError: 84 p.terminate()
81 pass 85 except OSError:
86 pass
87 # On Windows taskkill /T needs the root process alive to find its descendants.
82 for p in procs: 88 for p in procs:
83 _kill_process_tree(p) 89 _kill_process_tree(p)
84 try: 90 try:
@@ -94,13 +100,44 @@ CHILD_PROGRAM = (
94 "import json, os, sys, unittest\n" 100 "import json, os, sys, unittest\n"
95 "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" 101 "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n"
96 "result = program.result\n" 102 "result = program.result\n"
97 "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n" 103 "code = 1 if not result.wasSuccessful() else 5 if not result.testsRun and not result.skipped else 0\n"
98 " json.dump({'testsRun': result.testsRun}, handle)\n" 104 "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8', newline='\\n') as handle:\n"
99 "if not result.wasSuccessful():\n" 105 " json.dump({'testsRun': result.testsRun, 'exitCode': code}, handle)\n"
100 " sys.exit(1)\n" 106 "sys.exit(code)\n")
101 "elif result.testsRun == 0 and len(result.skipped) == 0:\n" 107
102 " sys.exit(5)\n" 108# Windows NTSTATUS codes python.exe exits with when it crashes. A file that dies this way prints nothing, so the code
103 "sys.exit(0)\n") 109# is the only clue there is (an access violation in a pure-Python test points at the machine, not at the test).
110NTSTATUS_CRASHES = {
111 0xC0000005: "access violation",
112 0xC000001D: "illegal instruction",
113 0xC0000017: "out of memory",
114 0xC00000FD: "stack overflow",
115 0xC0000374: "heap corruption",
116 0xC0000409: "fail fast / stack buffer overrun",
117}
118# Known statuses that end a process without it crashing.
119NTSTATUS_OTHER = {
120 0xC000013A: "interrupted with Ctrl+C",
121}
122
123
124def describe_exit(code):
125 """A failed module's exit code in words: `exit code 1`, `killed by SIGSEGV (-11)` for a POSIX signal, or for a
126 known Windows NTSTATUS its hexadecimal value and meaning (3221225477 -> 0xC0000005, access violation). Only the
127 statuses in NTSTATUS_CRASHES are called a crash: a process can also exit with any 32-bit value on purpose, so an
128 unknown one is reported as just its value."""
129 if code < 0:
130 try:
131 return f"killed by {signal.Signals(-code).name} ({code})"
132 except ValueError:
133 return f"killed by signal {-code} ({code})"
134 if code in NTSTATUS_CRASHES:
135 return f"exit code 0x{code:08X}, {NTSTATUS_CRASHES[code]} (the process crashed)"
136 if code in NTSTATUS_OTHER:
137 return f"exit code 0x{code:08X}, {NTSTATUS_OTHER[code]}"
138 if code > 0xFFFF: # an NTSTATUS-sized value reads better in hexadecimal
139 return f"exit code 0x{code:08X}"
140 return f"exit code {code}"
104 141
105 142
106def module_path(directory, module): 143def module_path(directory, module):
@@ -139,14 +176,64 @@ def positive_seconds(value):
139 return seconds 176 return seconds
140 177
141 178
142def read_count(path): 179def read_result(path, process_code):
143 """The number of tests the child ran, as unittest's own result object reported it.""" 180 """Return the effective exit code, completed test count, and any diagnostic."""
144 try: 181 try:
145 with open(path, encoding="utf-8") as handle: 182 with open(path, encoding="utf-8") as handle:
146 return int(json.load(handle)["testsRun"]) 183 result = json.load(handle)
184 count, test_code = result["testsRun"], result["exitCode"]
185 if type(count) is not int or count < 0 or type(test_code) is not int or test_code not in (0, 1, 5):
186 raise ValueError("invalid unittest result")
147 except (OSError, ValueError, KeyError, TypeError): 187 except (OSError, ValueError, KeyError, TypeError):
148 # The child wrote no result: it did not finish, so no test is known to have run. 188 if process_code == 0:
149 return 0 189 return 1, 0, "process exited without a unittest result"
190 return process_code, None, ""
191 if process_code in (0, 5) and process_code != test_code:
192 return 1, count, f"process exited with status {process_code} but unittest reported {test_code}"
193 return process_code, count, ""
194
195
196def result_environment(scratch):
197 result_path = os.path.join(scratch, "count.json")
198 return result_path, dict(os.environ, LEONIDA_TEST_COUNT=result_path)
199
200
201def run_discover(directory, pattern, verbose, timeout):
202 args = ["discover", "-s", directory, "-p", pattern, *(["-v"] if verbose else [])]
203 with tempfile.TemporaryDirectory() as scratch:
204 path, env = result_environment(scratch)
205 proc = subprocess.Popen([sys.executable, "-c", CHILD_PROGRAM, *args], env=env)
206 _register_process(proc)
207 start_time = time.monotonic()
208 try:
209 while True:
210 try:
211 code = proc.wait(timeout=0.2)
212 break
213 except subprocess.TimeoutExpired:
214 if timeout is not None and time.monotonic() - start_time >= timeout:
215 raise
216 except subprocess.TimeoutExpired:
217 _kill_process_tree(proc)
218 print(f"TIMED OUT after {timeout:g} s: unittest discover in {directory}", file=sys.stderr)
219 return 1
220 except KeyboardInterrupt:
221 _kill_process_tree(proc)
222 try:
223 proc.wait(timeout=0.5)
224 except (subprocess.TimeoutExpired, OSError):
225 pass
226 print("interrupted", file=sys.stderr)
227 return 130
228 except BaseException:
229 _kill_process_tree(proc)
230 raise
231 finally:
232 _unregister_process(proc)
233 code, _, diagnostic = read_result(path, code)
234 if diagnostic:
235 print(f"unittest discover in {directory}: {diagnostic}", file=sys.stderr)
236 return code
150 237
151 238
152def run_module(directory, module, verbose, timeout=None): 239def run_module(directory, module, verbose, timeout=None):
@@ -157,8 +244,7 @@ def run_module(directory, module, verbose, timeout=None):
157 target = module[:-len(".__init__")] if module.endswith(".__init__") else module 244 target = module[:-len(".__init__")] if module.endswith(".__init__") else module
158 cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] 245 cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target]
159 with tempfile.TemporaryDirectory() as scratch: 246 with tempfile.TemporaryDirectory() as scratch:
160 count_path = os.path.join(scratch, "count.json") 247 result_path, env = result_environment(scratch)
161 env = dict(os.environ, LEONIDA_TEST_COUNT=count_path)
162 proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, 248 proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
163 text=True, errors="replace") 249 text=True, errors="replace")
164 _register_process(proc) 250 _register_process(proc)
@@ -181,13 +267,14 @@ def run_module(directory, module, verbose, timeout=None):
181 raise 267 raise
182 finally: 268 finally:
183 _unregister_process(proc) 269 _unregister_process(proc)
184 count = read_count(count_path) 270 code, count, diagnostic = read_result(result_path, proc.returncode)
185 out = stdout + stderr 271 out = stdout + stderr
186 # Discover imports every package initializer, but an empty one has no tests to run. It is included in the 272 if diagnostic:
187 # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. 273 out += f"\n{diagnostic}\n"
188 if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr: 274 # A package initializer that completed with no tests isn't a failed module.
275 if code == 5 and count == 0 and module.endswith(".__init__"):
189 return 0, 0, out 276 return 0, 0, out
190 return proc.returncode, count, out 277 return code, count or 0, out
191 278
192 279
193def main(argv=None): 280def main(argv=None):
@@ -206,35 +293,7 @@ def main(argv=None):
206 print(f"no {a.pattern} files in {directory}") 293 print(f"no {a.pattern} files in {directory}")
207 return 1 294 return 1
208 if a.jobs <= 1: 295 if a.jobs <= 1:
209 cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory, 296 return run_discover(directory, a.pattern, a.verbose, a.timeout)
210 "-p", a.pattern, *(["-v"] if a.verbose else [])]
211 proc = subprocess.Popen(cmd)
212 _register_process(proc)
213 start_time = time.monotonic()
214 try:
215 while True:
216 try:
217 return proc.wait(timeout=0.2)
218 except subprocess.TimeoutExpired:
219 if a.timeout is not None and time.monotonic() - start_time >= a.timeout:
220 raise
221 except subprocess.TimeoutExpired:
222 _kill_process_tree(proc)
223 print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr)
224 return 1
225 except KeyboardInterrupt:
226 _kill_process_tree(proc)
227 try:
228 proc.wait(timeout=0.5)
229 except (subprocess.TimeoutExpired, OSError):
230 pass
231 print("interrupted", file=sys.stderr)
232 return 130
233 except BaseException:
234 _kill_process_tree(proc)
235 raise
236 finally:
237 _unregister_process(proc)
238 # Largest files first: they tend to run longest, and one started last would set the wall time alone. 297 # Largest files first: they tend to run longest, and one started last would set the wall time alone.
239 modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) 298 modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m)))
240 start, total, failed = time.monotonic(), 0, [] 299 start, total, failed = time.monotonic(), 0, []
@@ -252,7 +311,8 @@ def main(argv=None):
252 total += ran 311 total += ran
253 if code: 312 if code:
254 failed.append(jobs[job]) 313 failed.append(jobs[job])
255 print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) 314 silent = "" if out.strip() else "(no output: the process ended before printing anything)\n"
315 print(f"==== FAILED: {jobs[job]} ({describe_exit(code)})\n{silent}{out}", flush=True)
256 elif a.verbose: 316 elif a.verbose:
257 print(f"==== {jobs[job]}\n{out}", flush=True) 317 print(f"==== {jobs[job]}\n{out}", flush=True)
258 except KeyboardInterrupt: 318 except KeyboardInterrupt:
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py
index d36011430..393b17ce9 100644
--- a/scripts/run_wine_tests.py
+++ b/scripts/run_wine_tests.py
@@ -12,8 +12,8 @@ Some tests open files through absolute paths compiled into them (the GLSL test s
12runtime/build/generated). For those, the drive of --windows-root is pointed at --root in the Wine prefix for the run 12runtime/build/generated). For those, the drive of --windows-root is pointed at --root in the Wine prefix for the run
13($WINEPREFIX, else ~/.wine), unless that drive is already in use there. 13($WINEPREFIX, else ~/.wine), unless that drive is already in use there.
14 14
15Every test is reported. The exit code is 1 if a test named by --require fails or is missing, else 0: the 15Every test is reported. Each name given to --require must be listed and all of its tests must pass, or the
16others show what does and doesn't work under Wine yet without failing the job. 16exit code is 1. The other results show what does and doesn't work under Wine yet without failing the job.
17--timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test. 17--timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test.
18Relative executable paths in --wine or WINE are read from the directory where you start this runner. 18Relative executable paths in --wine or WINE are read from the directory where you start this runner.
19 19
@@ -515,7 +515,7 @@ def main() -> int:
515 ap.add_argument("--root", type=os.path.abspath, default=ROOT, help="the Linux checkout (default: this repository)") 515 ap.add_argument("--root", type=os.path.abspath, default=ROOT, help="the Linux checkout (default: this repository)")
516 ap.add_argument("--wine", type=wine_command, default=os.environ.get("WINE", "wine"), 516 ap.add_argument("--wine", type=wine_command, default=os.environ.get("WINE", "wine"),
517 help="Wine command (default: $WINE or wine)") 517 help="Wine command (default: $WINE or wine)")
518 ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)") 518 ap.add_argument("--require", action="append", default=[], help="a test name whose entries must all pass (repeatable)")
519 ap.add_argument("--timeout", type=positive_seconds, default=120.0, 519 ap.add_argument("--timeout", type=positive_seconds, default=120.0,
520 help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)") 520 help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)")
521 ap.add_argument("--jobs", type=positive_int, default=1, 521 ap.add_argument("--jobs", type=positive_int, default=1,
@@ -546,7 +546,6 @@ def main() -> int:
546 # Each test starts in its own CTest working directory. Keep bare commands on PATH. 546 # Each test starts in its own CTest working directory. Keep bare commands on PATH.
547 if os.path.dirname(wine[0]) and not os.path.isabs(wine[0]): 547 if os.path.dirname(wine[0]) and not os.path.isabs(wine[0]):
548 wine[0] = os.path.join(os.getcwd(), wine[0]) 548 wine[0] = os.path.join(os.getcwd(), wine[0])
549 results = {}
550 results_by_index: dict[int, str] = {} 549 results_by_index: dict[int, str] = {}
551 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") 550 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine")
552 outcomes: dict[int, tuple[str, str]] = {} 551 outcomes: dict[int, tuple[str, str]] = {}
@@ -557,7 +556,6 @@ def main() -> int:
557 556
558 def report(index: int) -> None: 557 def report(index: int) -> None:
559 status, detail = outcomes[index] 558 status, detail = outcomes[index]
560 results[names[index]] = status
561 print(f"[{status.upper()}] {names[index]}", flush=True) 559 print(f"[{status.upper()}] {names[index]}", flush=True)
562 if status != "pass": 560 if status != "pass":
563 for line in detail.rstrip().splitlines()[-40:]: 561 for line in detail.rstrip().splitlines()[-40:]:
@@ -574,11 +572,12 @@ def main() -> int:
574 else: 572 else:
575 run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report) 573 run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report)
576 574
577 missing = list(dict.fromkeys(n for n in args.require if n not in results)) 575 missing = list(dict.fromkeys(n for n in args.require if n not in indices))
578 failed_required = [n for n in args.require if results.get(n) != "pass"] 576 nonpassing_names = {names[index] for index, status in results_by_index.items() if status != "pass"}
579 counts = {s: sum(1 for v in results.values() if v == s) for s in ("pass", "fail", "skip")} 577 failed_required = [n for n in args.require if n not in indices or n in nonpassing_names]
578 counts = {s: sum(1 for v in results_by_index.values() if v == s) for s in ("pass", "fail", "skip")}
580 print(f"\n{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped under Wine " 579 print(f"\n{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped under Wine "
581 f"({len(results)} tests)") 580 f"({len(results_by_index)} tests)")
582 for n in missing: 581 for n in missing:
583 print(f"required test not listed by the Windows build: {n}") 582 print(f"required test not listed by the Windows build: {n}")
584 if failed_required: 583 if failed_required:
@@ -591,7 +590,8 @@ def main() -> int:
591 f.write(f"### Windows tests under {args.label or 'Wine'}\n\n") 590 f.write(f"### Windows tests under {args.label or 'Wine'}\n\n")
592 f.write(f"{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped.\n\n") 591 f.write(f"{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped.\n\n")
593 f.write("| Test | Result | Required |\n|---|---|---|\n") 592 f.write("| Test | Result | Required |\n|---|---|---|\n")
594 for name, status in results.items(): 593 for index in order:
594 name, status = names[index], results_by_index[index]
595 f.write(f"| `{name}` | {status} | {'yes' if name in args.require else ''} |\n") 595 f.write(f"| `{name}` | {status} | {'yes' if name in args.require else ''} |\n")
596 for name in missing: 596 for name in missing:
597 # The job fails on these, so the table must name them, not only the log. 597 # The job fails on these, so the table must name them, not only the log.
diff --git a/scripts/shader_stats.py b/scripts/shader_stats.py
index 34b61cd8a..85e408099 100644
--- a/scripts/shader_stats.py
+++ b/scripts/shader_stats.py
@@ -50,17 +50,27 @@ def original(path: str) -> tuple[int, int]:
50 if kind == "vgpr": 50 if kind == "vgpr":
51 top = max(top, operand["r"] + operand.get("n", 1)) 51 top = max(top, operand["r"] + operand.get("n", 1))
52 elif kind == "vlist": 52 elif kind == "vlist":
53 top = max(top, max(operand["r"]) + 1) 53 if operand["r"]:
54 top = max(top, max(operand["r"]) + 1)
54 return len(insns), top 55 return len(insns), top
55 56
56 57
57REQUIRED = ("name", "stage", "statistic", "value") 58REQUIRED = ("name", "stage", "statistic", "value")
58 59
59 60
61def _safe_shader_name(name):
62 """True when `name` is a single non-empty filename stem inside the disasm directory."""
63 if not name or name in (".", "..") or "\x00" in name:
64 return False
65 if "/" in name or "\\" in name or os.path.splitdrive(name)[0]:
66 return False
67 return os.path.basename(name) == name
68
69
60def load_stats(path): 70def load_stats(path):
61 """Read counters keyed by (shader, stage) from vk_pipeline_check --stats.""" 71 """Read counters keyed by (shader, stage) from vk_pipeline_check --stats."""
62 out = defaultdict(dict) 72 out = defaultdict(dict)
63 with open(path, newline="", encoding="utf-8") as f: 73 with open(path, newline="", encoding="utf-8-sig") as f:
64 reader = csv.DictReader(f, strict=True) 74 reader = csv.DictReader(f, strict=True)
65 header = reader.fieldnames or [] 75 header = reader.fieldnames or []
66 missing = [c for c in REQUIRED if c not in header] 76 missing = [c for c in REQUIRED if c not in header]
@@ -76,12 +86,16 @@ def load_stats(path):
76 absent = [c for c in REQUIRED if row[c] is None] 86 absent = [c for c in REQUIRED if row[c] is None]
77 if absent: 87 if absent:
78 raise ValueError(f"line {line}: row missing required column(s): {', '.join(absent)}") 88 raise ValueError(f"line {line}: row missing required column(s): {', '.join(absent)}")
89 if not _safe_shader_name(row["name"]):
90 raise ValueError(f"line {line}: invalid shader name {row['name']!r}")
79 out[row["name"], row["stage"]][row["statistic"]] = row["value"] 91 out[row["name"], row["stage"]][row["statistic"]] = row["value"]
80 return out 92 return out
81 93
82 94
83def number(raw): 95def number(raw):
84 """The exact int, or else the finite float, a raw value holds; None if it is missing or not such a number.""" 96 """The exact int, or else the finite float, a raw value holds; None if it is missing or not such a number."""
97 if isinstance(raw, bool):
98 return None
85 try: 99 try:
86 value = float(raw) 100 value = float(raw)
87 except (TypeError, ValueError, OverflowError): 101 except (TypeError, ValueError, OverflowError):
@@ -149,18 +163,18 @@ def median_clause(rs, key, label):
149USAGE = "usage: shader_stats.py <stats.csv> <disasm dir> [--details]" 163USAGE = "usage: shader_stats.py <stats.csv> <disasm dir> [--details]"
150 164
151 165
152def main(): 166def main(argv=None):
153 argv = sys.argv[1:] 167 argv = sys.argv[1:] if argv is None else list(argv)
154 if "-h" in argv or "--help" in argv: 168 if "-h" in argv or "--help" in argv:
155 print(__doc__) 169 print(__doc__)
156 return 0 170 return 0
157 # A misspelt option (--detail) used to be dropped, and the summary printed as if it had been asked for. 171 # A misspelt option (--detail, -d) used to be dropped or misparsed as a positional argument.
158 unknown = [a for a in argv if a.startswith("--") and a != "--details"] 172 unknown = [a for a in argv if a.startswith("-") and a != "--details"]
159 if unknown: 173 if unknown:
160 print(f"unknown option {unknown[0]}\n{USAGE}", file=sys.stderr) 174 print(f"unknown option {unknown[0]}\n{USAGE}", file=sys.stderr)
161 return 2 175 return 2
162 args = [a for a in argv if not a.startswith("--")] 176 args = [a for a in argv if not a.startswith("-")]
163 if len(args) != 2: 177 if len(args) != 2 or not args[0].strip() or not args[1].strip():
164 print(USAGE, file=sys.stderr) 178 print(USAGE, file=sys.stderr)
165 return 2 179 return 2
166 path = args[0] 180 path = args[0]
@@ -169,6 +183,8 @@ def main():
169 except (OSError, ValueError, csv.Error) as e: 183 except (OSError, ValueError, csv.Error) as e:
170 sys.exit(f"{path}: {e}") 184 sys.exit(f"{path}: {e}")
171 disasm = args[1] 185 disasm = args[1]
186 if not os.path.isdir(disasm):
187 sys.exit(f"{disasm}: not a directory")
172 rows = [] 188 rows = []
173 for (name, stage), st in sorted(stats.items()): 189 for (name, stage), st in sorted(stats.items()):
174 src = os.path.join(disasm, name + ".s") 190 src = os.path.join(disasm, name + ".s")
@@ -179,7 +195,7 @@ def main():
179 sys.exit(f"{src}: {e.strerror or e}") 195 sys.exit(f"{src}: {e.strerror or e}")
180 if not rows: 196 if not rows:
181 sys.exit("no shader is in both the statistics and the disasm folder") 197 sys.exit("no shader is in both the statistics and the disasm folder")
182 if "--details" in sys.argv: 198 if "--details" in argv:
183 print(f"{'shader':26} {'stage':5} " + " ".join(f"{head:>{width}}" for _, head, width, _ in COLUMNS)) 199 print(f"{'shader':26} {'stage':5} " + " ".join(f"{head:>{width}}" for _, head, width, _ in COLUMNS))
184 for r in rows: 200 for r in rows:
185 print(f"{r['name']:26} {r['stage']:5} " 201 print(f"{r['name']:26} {r['stage']:5} "
diff --git a/scripts/smoke.py b/scripts/smoke.py
new file mode 100644
index 000000000..131996be9
--- /dev/null
+++ b/scripts/smoke.py
@@ -0,0 +1,332 @@
1#!/usr/bin/env python3
2"""One-command synthetic source-only smoke suite for Leonida (DX-07).
3
4Validates prerequisites, compiles source trees, enforces clean-room boundaries,
5and executes fast synthetic smoke tests on Windows, Linux, and macOS without game files.
6"""
7
8from __future__ import annotations
9
10import argparse
11import compileall
12import contextlib
13import io
14import json
15import os
16from pathlib import Path
17import platform
18import shutil
19import subprocess
20import sys
21import time
22
23ROOT = Path(__file__).resolve().parents[1]
24MIN_PYTHON_VERSION = (3, 10)
25
26
27def check_prerequisites(require_toolchains: list[str] | None = None) -> tuple[dict, bool]:
28 """Check required environment and discover optional toolchains."""
29 py_ver = sys.version_info
30 py_ok = (py_ver.major, py_ver.minor) >= MIN_PYTHON_VERSION
31
32 prereqs = {
33 "python": {
34 "version": f"{py_ver.major}.{py_ver.minor}.{py_ver.micro}",
35 "satisfies": py_ok,
36 "required": f">={MIN_PYTHON_VERSION[0]}.{MIN_PYTHON_VERSION[1]}",
37 }
38 }
39
40 toolchains = {
41 "cmake": _detect_command("cmake", ["--version"]),
42 "ninja": _detect_command("ninja", ["--version"]),
43 "compiler_msvc": _detect_command("cl", []),
44 "compiler_gcc": _detect_command("gcc", ["--version"]),
45 "compiler_clang": _detect_command("clang", ["--version"]),
46 "vulkan_sdk": _detect_vulkan(),
47 "node": _detect_command("node", ["--version"]),
48 "dotnet": _detect_command("dotnet", ["--version"]),
49 }
50
51 all_ok = py_ok
52 if require_toolchains:
53 for req in require_toolchains:
54 found = False
55 if req == "compiler":
56 found = any(
57 toolchains[c]["available"]
58 for c in ("compiler_msvc", "compiler_gcc", "compiler_clang")
59 )
60 elif req in toolchains:
61 found = toolchains[req]["available"]
62 if not found:
63 all_ok = False
64
65 return {"prerequisites": prereqs, "toolchains": toolchains}, all_ok
66
67
68def _detect_command(command: str, version_args: list[str]) -> dict:
69 exe = shutil.which(command)
70 if not exe:
71 return {"available": False, "path": None, "version": None}
72
73 version_str = None
74 if version_args:
75 try:
76 res = subprocess.run(
77 [exe, *version_args],
78 capture_output=True,
79 text=True,
80 timeout=5,
81 )
82 if res.returncode == 0:
83 first_line = (res.stdout or res.stderr).strip().splitlines()
84 if first_line:
85 version_str = first_line[0]
86 except (OSError, subprocess.TimeoutExpired):
87 pass
88
89 return {"available": True, "path": exe, "version": version_str}
90
91
92def _detect_vulkan() -> dict:
93 sdk_dir = os.environ.get("VULKAN_SDK")
94 glslang = shutil.which("glslangValidator") or shutil.which("glslang")
95 available = bool(sdk_dir or glslang)
96 return {
97 "available": available,
98 "path": sdk_dir or (glslang if glslang else None),
99 "version": sdk_dir if sdk_dir else ("glslang found" if glslang else None),
100 }
101
102
103def run_checks(root: Path, quick: bool = False, verbose: bool = False) -> list[dict]:
104 """Execute synthetic source-only sanity checks."""
105 checks = []
106
107 # 1. Bytecode compilation of Python source trees
108 t0 = time.monotonic()
109 compile_ok = True
110 compile_err = None
111 compile_buf = io.StringIO()
112 try:
113 with contextlib.redirect_stdout(compile_buf):
114 if quick:
115 # Quick mode: verify core entry points compile
116 for p in (root / "make_game.py", root / "tools" / "rdna2spirv.py", root / "scripts" / "dev.py", root / "scripts" / "smoke.py"):
117 if p.is_file() and not compileall.compile_file(str(p), quiet=1, force=False):
118 compile_ok = False
119 compile_err = f"{p.name} failed bytecode compilation"
120 break
121 else:
122 # Full mode: verify all tools and scripts
123 res = compileall.compile_dir(str(root / "tools"), quiet=1, force=False)
124 res = compileall.compile_dir(str(root / "scripts"), quiet=1, force=False) and res
125 res = compileall.compile_file(str(root / "make_game.py"), quiet=1, force=False) and res
126 if not res:
127 compile_ok = False
128 compile_err = "One or more files failed bytecode compilation"
129 except Exception as exc: # noqa: BLE001
130 compile_ok = False
131 compile_err = str(exc)
132 if not compile_ok and compile_buf.getvalue().strip():
133 print(compile_buf.getvalue().rstrip(), file=sys.stderr)
134
135 checks.append({
136 "name": "python_compileall",
137 "status": "PASS" if compile_ok else "FAIL",
138 "duration_ms": int((time.monotonic() - t0) * 1000),
139 "details": compile_err or ("Core entry points compile cleanly" if quick else "tools/, scripts/, make_game.py compile cleanly"),
140 })
141
142 # 2. Clean-room validation (no game data)
143 t0 = time.monotonic()
144 check_no_game_script = root / "scripts" / "check_no_game_data.py"
145 if check_no_game_script.is_file():
146 cmd = [sys.executable, "-I", str(check_no_game_script), "make_game.py", "scripts/dev.py"]
147 proc = subprocess.run(cmd, cwd=root, capture_output=True, text=True)
148 no_game_ok = proc.returncode == 0
149 checks.append({
150 "name": "clean_room_no_game_data",
151 "status": "PASS" if no_game_ok else "FAIL",
152 "duration_ms": int((time.monotonic() - t0) * 1000),
153 "details": proc.stderr.strip() if not no_game_ok else "No game data or retail assets detected",
154 })
155 else:
156 checks.append({
157 "name": "clean_room_no_game_data",
158 "status": "SKIP",
159 "duration_ms": 0,
160 "details": "scripts/check_no_game_data.py not present",
161 })
162
163 # 3. Core CLI --help entry points
164 cli_targets = [
165 ("make_game.py", root / "make_game.py"),
166 ("tools/rdna2spirv.py", root / "tools" / "rdna2spirv.py"),
167 ("scripts/dev.py", root / "scripts" / "dev.py"),
168 ]
169 for label, script_path in cli_targets:
170 if not script_path.is_file():
171 checks.append({
172 "name": f"cli_help_{label}",
173 "status": "SKIP",
174 "duration_ms": 0,
175 "details": f"{label} not found",
176 })
177 continue
178
179 t0 = time.monotonic()
180 proc = subprocess.run(
181 [sys.executable, "-I", str(script_path), "--help"],
182 cwd=root,
183 capture_output=True,
184 text=True,
185 timeout=10,
186 )
187 ok = proc.returncode == 0 and bool(proc.stdout)
188 checks.append({
189 "name": f"cli_help_{label}",
190 "status": "PASS" if ok else "FAIL",
191 "duration_ms": int((time.monotonic() - t0) * 1000),
192 "details": f"Exit code {proc.returncode}" if not ok else f"{label} --help exited with 0",
193 })
194
195 # 4. Fast synthetic unit test smoke pass (unless --quick)
196 if not quick:
197 test_targets = [
198 "tests/test_dev_discovery.py",
199 "tests/test_shader_ir_parse.py",
200 ]
201 for rel_test in test_targets:
202 test_path = root / rel_test
203 if not test_path.is_file():
204 continue
205
206 t0 = time.monotonic()
207 proc = subprocess.run(
208 [sys.executable, "-I", str(test_path)],
209 cwd=root,
210 capture_output=True,
211 text=True,
212 timeout=30,
213 )
214 ok = proc.returncode == 0
215 checks.append({
216 "name": f"test_{Path(rel_test).stem}",
217 "status": "PASS" if ok else "FAIL",
218 "duration_ms": int((time.monotonic() - t0) * 1000),
219 "details": proc.stderr.strip() if not ok else "Test suite passed",
220 })
221
222 return checks
223
224
225def main(argv: list[str] | None = None) -> int:
226 parser = argparse.ArgumentParser(
227 prog="smoke.py",
228 description="One-command synthetic source-only smoke suite (DX-07).",
229 )
230 parser.add_argument(
231 "--quick",
232 action="store_true",
233 help="Run fast sanity compilation and CLI help checks only (< 1s)",
234 )
235 parser.add_argument(
236 "--prereqs-only",
237 action="store_true",
238 help="Discover toolchains and report prerequisite status without running checks",
239 )
240 parser.add_argument(
241 "--json",
242 action="store_true",
243 help="Print machine-readable JSON summary",
244 )
245 parser.add_argument(
246 "--require",
247 nargs="+",
248 metavar="TOOL",
249 help="Require specific toolchain(s) to be present (e.g. cmake, ninja, compiler)",
250 )
251 parser.add_argument(
252 "-v", "--verbose",
253 action="store_true",
254 help="Print detailed execution output",
255 )
256
257 args = parser.parse_args(argv)
258
259 diag, prereqs_ok = check_prerequisites(require_toolchains=args.require)
260
261 if not prereqs_ok:
262 if args.json:
263 print(json.dumps({
264 "schema_version": 1,
265 "platform": platform.platform(),
266 "verdict": "ERROR",
267 "error": "Required prerequisites or toolchains missing",
268 **diag,
269 }, indent=2))
270 else:
271 print("error: required environment prerequisites or toolchains missing:", file=sys.stderr)
272 for k, v in diag["prerequisites"].items():
273 if not v["satisfies"]:
274 print(f" - {k}: {v['version']} (requires {v['required']})", file=sys.stderr)
275 if args.require:
276 for req in args.require:
277 print(f" - required toolchain '{req}' was not found", file=sys.stderr)
278 return 2
279
280 if args.prereqs_only:
281 if args.json:
282 print(json.dumps({
283 "schema_version": 1,
284 "platform": platform.platform(),
285 "verdict": "PASS",
286 **diag,
287 }, indent=2))
288 else:
289 print(f"Leonida Smoke Suite — Environment Discovery ({platform.platform()})")
290 print("Prerequisites:")
291 for k, v in diag["prerequisites"].items():
292 status = "OK" if v["satisfies"] else "FAIL"
293 print(f" - {k}: {v['version']} [{status}]")
294 print("Toolchains (optional for synthetic tests):")
295 for k, v in diag["toolchains"].items():
296 status = "PRESENT" if v["available"] else "NOT FOUND"
297 detail = f" ({v['version']})" if v["version"] else ""
298 print(f" - {k}: {status}{detail}")
299 return 0
300
301 if args.json:
302 with contextlib.redirect_stdout(sys.stderr):
303 checks = run_checks(ROOT, quick=args.quick, verbose=args.verbose)
304 else:
305 checks = run_checks(ROOT, quick=args.quick, verbose=args.verbose)
306 all_passed = all(c["status"] in ("PASS", "SKIP") for c in checks)
307
308 if args.json:
309 report = {
310 "schema_version": 1,
311 "platform": platform.platform(),
312 "verdict": "PASS" if all_passed else "FAIL",
313 **diag,
314 "checks": checks,
315 }
316 print(json.dumps(report, indent=2))
317 else:
318 print(f"Leonida Smoke Suite — Source-Only Validation ({platform.platform()})")
319 for c in checks:
320 status_tag = f"[{c['status']}]"
321 print(f" {status_tag:<8} {c['name']:<30} ({c['duration_ms']} ms) — {c['details']}")
322 print("Verdict: " + ("PASS (All source-only checks succeeded)" if all_passed else "FAIL"))
323
324 return 0 if all_passed else 1
325
326
327if __name__ == "__main__":
328 try:
329 sys.stdout.reconfigure(errors="replace")
330 except (AttributeError, ValueError, OSError):
331 pass
332 raise SystemExit(main())