Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions make_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -2158,6 +2158,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 translation_plan(jobs: int, emulate: bool, fallbacks: tuple[str, ...]) -> dict:
return {"jobs": jobs, "wave64_emulate": bool(emulate), "fallbacks": list(fallbacks),
"translator": translator_digest()}
Expand Down Expand Up @@ -2240,6 +2256,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
Expand Down
98 changes: 98 additions & 0 deletions tests/test_make_game_translate_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""

import os
import signal
import subprocess
import sys
import tempfile
Expand Down Expand Up @@ -126,5 +127,102 @@ 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_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_spirv_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")))

@unittest.skipUnless(hasattr(signal, "SIGTERM"), "SIGTERM not available on this platform")
def test_main_registers_sigterm_handler_that_exits(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}')

orig_handler = signal.getsignal(signal.SIGTERM)
try:
with patch.object(sys, "argv", ["rdna2spirv.py", disasm, "--out", spirv, "--merge"]):
rc = self.rdna2spirv.main()
self.assertEqual(rc, 0)
installed = signal.getsignal(signal.SIGTERM)
self.assertIsNot(installed, orig_handler)
with self.assertRaises(SystemExit) as ctx:
installed(signal.SIGTERM, None)
self.assertEqual(ctx.exception.code, 128 + signal.SIGTERM)
finally:
signal.signal(signal.SIGTERM, orig_handler)


if __name__ == "__main__":
unittest.main()
26 changes: 26 additions & 0 deletions tools/rdna2spirv.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import math
import os
import re
import signal
import struct
import subprocess
import sys
Expand Down Expand Up @@ -20407,6 +20408,22 @@ def _run_spirv_tool(cmd, **kwargs):
raise


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.
# Avoid the generic -O/-Os pipelines: they inline the shared typed-buffer and descriptor helpers.
COMPACT_PASSES = ("--preserve-interface", "--preserve-bindings", "--preserve-spec-constants",
Expand Down Expand Up @@ -20608,6 +20625,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
Expand Down Expand Up @@ -20668,6 +20692,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")
Expand Down Expand Up @@ -20802,6 +20827,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"
Expand Down
Loading