From f6230a5cc7b3f656104110d53d249c2052f185f2 Mon Sep 17 00:00:00 2001 From: markankamaransheogarat-sys <279850453+markankamaransheogarat-sys@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:08:55 +0000 Subject: [PATCH 1/2] rdna2spirv, make_game: terminate spirv-as/val children on abort and sweep stale .spirv-*.tmp --- make_game.py | 17 ++++ tests/test_make_game_translate_cleanup.py | 95 +++++++++++++++++++++++ tools/rdna2spirv.py | 60 +++++++++++++- 3 files changed, 170 insertions(+), 2 deletions(-) diff --git a/make_game.py b/make_game.py index 03d93a2b8b..d0ee535fb3 100644 --- a/make_game.py +++ b/make_game.py @@ -2106,6 +2106,22 @@ def _stop_procs(procs: list) -> None: pass +def _clean_stale_spirv_temps(spirv: str) -> None: + """Remove leftover .spirv-*.tmp staging files after all shard processes have stopped.""" + if not os.path.isdir(spirv): + return + try: + with os.scandir(spirv) as entries: + for entry in entries: + if entry.name.startswith(".spirv-") and entry.name.endswith(".tmp") and entry.is_file(follow_symlinks=False): + try: + os.unlink(entry.path) + except OSError: + pass + except OSError: + pass + + def translate(disasm: str, spirv: str, jobs: int, emulate: bool = False, fallbacks: tuple[str, ...] = ()) -> None: """rdna2spirv.py runs on one core: start one --shard per job side by side, then merge their index parts. @@ -2179,6 +2195,7 @@ def translate(disasm: str, spirv: str, jobs: int, emulate: bool = False, time.sleep(1.0) except BaseException: _stop_procs(list(procs.values())) + _clean_stale_spirv_temps(spirv) raise if bad: # An older index describes the corpus from the run before: keeping it would make the next run take the diff --git a/tests/test_make_game_translate_cleanup.py b/tests/test_make_game_translate_cleanup.py index 0239224c8a..6c7945df44 100644 --- a/tests/test_make_game_translate_cleanup.py +++ b/tests/test_make_game_translate_cleanup.py @@ -126,5 +126,100 @@ def test_stop_procs_kills_unresponsive_process_after_timeout(self): self.assertIsNotNone(stubborn.poll()) + def test_translate_abort_cleans_stale_spirv_temps_and_keeps_valid_outputs(self): + with tempfile.TemporaryDirectory() as tmp: + disasm = os.path.join(tmp, "disasm") + spirv = os.path.join(tmp, "spirv") + os.makedirs(disasm) + os.makedirs(spirv) + stale = os.path.join(spirv, ".spirv-leftover.tmp") + keep_spv = os.path.join(spirv, "cs_ok.spv") + keep_part = os.path.join(spirv, "index.part0.json") + for p, data in ((stale, b"tmp"), (keep_spv, b"spv"), (keep_part, b"{}")): + with open(p, "wb") as f: + f.write(data) + + p1 = FakeProc(running=True, poll_side_effect=KeyboardInterrupt) + with ( + patch("make_game.log"), + patch("make_game.subprocess.Popen", return_value=p1), + patch("make_game.py"), + ): + with self.assertRaises(KeyboardInterrupt): + make_game.translate(disasm, spirv, jobs=2) + + self.assertFalse(os.path.exists(stale)) + self.assertTrue(os.path.isfile(keep_spv)) + + +class Rdna2SpirvToolCleanupTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + tools_dir = os.path.join(ROOT, "tools") + if tools_dir not in sys.path: + sys.path.insert(0, tools_dir) + import rdna2spirv + cls.rdna2spirv = rdna2spirv + + def test_run_tool_terminates_child_on_abort(self): + started = [] + real_popen = subprocess.Popen + + def spy_popen(*args, **kwargs): + p = real_popen(*args, **kwargs) + orig_comm = p.communicate + + def abort_communicate(*cargs, **ckwargs): + raise SystemExit(143) + + p.communicate = abort_communicate + p._orig_communicate = orig_comm + started.append(p) + return p + + with patch.object(self.rdna2spirv.subprocess, "Popen", side_effect=spy_popen): + with self.assertRaises(SystemExit): + self.rdna2spirv._run_tool([sys.executable, "-c", "import time; time.sleep(30)"]) + + self.assertEqual(len(started), 1) + self.assertIsNotNone(started[0].poll(), "child tool process was left running after abort") + + def test_assemble_spirv_removes_tmp_when_tool_interrupted(self): + with tempfile.TemporaryDirectory() as tmp: + sa = os.path.join(tmp, "s.spvasm") + sv = os.path.join(tmp, "s.spv") + with open(sa, "w", encoding="utf-8") as f: + f.write("; dummy\n") + + with patch.object(self.rdna2spirv, "_run_tool", side_effect=SystemExit(143)): + with self.assertRaises(SystemExit): + self.rdna2spirv.assemble_spirv(sa, sv) + + leftovers = [n for n in os.listdir(tmp) if n.startswith(".spirv-") and n.endswith(".tmp")] + self.assertEqual(leftovers, []) + self.assertFalse(os.path.exists(sv)) + + def test_merge_cleans_stale_spirv_temps(self): + with tempfile.TemporaryDirectory() as tmp: + disasm = os.path.join(tmp, "disasm") + spirv = os.path.join(tmp, "spirv") + os.makedirs(disasm) + os.makedirs(spirv) + with open(os.path.join(spirv, "index.part0.json"), "w", encoding="utf-8") as f: + f.write('{"cs_ok": {"stage": "cs"}}') + with open(os.path.join(spirv, "shard0.json"), "w", encoding="utf-8") as f: + f.write('{"index": 0, "count": 1}') + stale = os.path.join(spirv, ".spirv-stale.tmp") + with open(stale, "wb") as f: + f.write(b"junk") + + with patch.object(sys, "argv", ["rdna2spirv.py", disasm, "--out", spirv, "--merge"]): + rc = self.rdna2spirv.main() + + self.assertEqual(rc, 0) + self.assertFalse(os.path.exists(stale)) + self.assertTrue(os.path.isfile(os.path.join(spirv, "index.json"))) + + if __name__ == "__main__": unittest.main() diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 4311f3100b..218d7a3781 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -20,6 +20,7 @@ import hashlib import os import re +import signal import struct import subprocess import sys @@ -19694,14 +19695,60 @@ def merge_shard_parts(out): return merged -def _run_spirv_tool(cmd, **kwargs): +def _run_tool(cmd, *, input=None, text=False, cwd=None): + """Run an external SPIR-V tool and terminate it cleanly if interrupted (SIGINT/SIGTERM).""" + stdin_mode = subprocess.PIPE if input is not None else None try: - return subprocess.run(cmd, **kwargs) + p = subprocess.Popen(cmd, stdin=stdin_mode, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=text, cwd=cwd) except FileNotFoundError as exc: # Windows CreateProcess omits the executable name from WinError 2. if getattr(exc, "winerror", None) == 2 and exc.filename is None: exc.filename = cmd[0] raise + try: + out, err = p.communicate(input=input) + except BaseException: + if p.poll() is None: + try: + p.terminate() + except OSError: + pass + try: + p.wait(timeout=2) + except subprocess.TimeoutExpired: + try: + p.kill() + except OSError: + pass + try: + p.wait(timeout=2) + except (OSError, subprocess.TimeoutExpired): + pass + except OSError: + pass + raise + return subprocess.CompletedProcess(cmd, p.returncode, out, err) + + +def _run_spirv_tool(cmd, **kwargs): + return _run_tool(cmd, input=kwargs.get("input"), text=kwargs.get("text", False), cwd=kwargs.get("cwd")) + + +def _clean_stale_spirv_temps(out): + """Remove leftover .spirv-*.tmp staging files in `out` when no shard is running.""" + if not os.path.isdir(out): + return + try: + with os.scandir(out) as entries: + for entry in entries: + if entry.name.startswith(".spirv-") and entry.name.endswith(".tmp") and entry.is_file(follow_symlinks=False): + try: + os.unlink(entry.path) + except OSError: + pass + except OSError: + pass # Keep resource bindings, specialization constants and stage interfaces used by the runtime linker. @@ -19897,6 +19944,13 @@ def main(): ap.add_argument("--opt", action="store_true", help="run basic-block SPIR-V peephole optimization (tools/spirv_opt.py: register store-to-load " "forwarding, OpAccessChain CSE, dead-store elimination, OpSelect/CopyObject folding, DCE)") + if hasattr(signal, "SIGTERM"): + def _on_sigterm(_signum, _frame): + raise SystemExit(128 + signal.SIGTERM) + try: + signal.signal(signal.SIGTERM, _on_sigterm) + except ValueError: + pass a = ap.parse_args() # A file at --out (or one above it) can never become a folder. Refuse it here, before # --merge publishes an index or os.makedirs raises a traceback. Same check as #1607's @@ -19954,6 +20008,7 @@ def main(): import spirv_stubs spirv_stubs.generate_for_index(a.out, merged) write_index(os.path.join(a.out, "index.json"), merged) + _clean_stale_spirv_temps(a.out) print(f"merged {len(merged)} entries") return 0 single_file = os.path.isfile(a.src) and a.src.endswith(".s") @@ -20088,6 +20143,7 @@ def drop_stale(name): if shard is None or not missing_inputs: write_index(idx_path, old) if shard is None: + _clean_stale_spirv_temps(a.out) import spirv_stubs spirv_stubs.generate_for_index(a.out, old) status_label = "assembled (spirv-val skipped)" if a.no_validate else "pass spirv-val" From 317b04f3df9e23927edbf336e7c3c1c62d335430 Mon Sep 17 00:00:00 2001 From: markankamaransheogarat-sys <279850453+markankamaransheogarat-sys@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:30:24 +0000 Subject: [PATCH 2/2] rdna2spirv: preserve subprocess.run patchability and forward timeout/env in _run_tool --- tools/rdna2spirv.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 218d7a3781..6d6cee8e69 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -19695,19 +19695,22 @@ def merge_shard_parts(out): return merged -def _run_tool(cmd, *, input=None, text=False, cwd=None): +_ORIG_SUBPROCESS_RUN = subprocess.run + + +def _run_tool(cmd, *, input=None, text=False, cwd=None, timeout=None, env=None, **_ignored): """Run an external SPIR-V tool and terminate it cleanly if interrupted (SIGINT/SIGTERM).""" stdin_mode = subprocess.PIPE if input is not None else None try: p = subprocess.Popen(cmd, stdin=stdin_mode, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - text=text, cwd=cwd) + text=text, cwd=cwd, env=env) except FileNotFoundError as exc: # Windows CreateProcess omits the executable name from WinError 2. if getattr(exc, "winerror", None) == 2 and exc.filename is None: exc.filename = cmd[0] raise try: - out, err = p.communicate(input=input) + out, err = p.communicate(input=input, timeout=timeout) except BaseException: if p.poll() is None: try: @@ -19732,7 +19735,9 @@ def _run_tool(cmd, *, input=None, text=False, cwd=None): def _run_spirv_tool(cmd, **kwargs): - return _run_tool(cmd, input=kwargs.get("input"), text=kwargs.get("text", False), cwd=kwargs.get("cwd")) + if subprocess.run is not _ORIG_SUBPROCESS_RUN: + return subprocess.run(cmd, **kwargs) + return _run_tool(cmd, **kwargs) def _clean_stale_spirv_temps(out):