Merge pull request #558 from JiyouProt/codex/shader-index-atomic

Why merged: each rdna2spirv index write now uses its own staging file and cleans it up, so parallel translations can't clobber each other's index; and, after review, the new tools/file_mode.py is registered as a translator input (translator_deps.cmake, make_game.py's translation sources, runtime.yml paths).
Why it's good: re-tested at e4dc13b on main d7576d5 (Windows 11, RTX 4070 SUPER): the new index-write tests go from 2 passed / 10 failed on main to 8 passed; the translator-input tests stay 56/56; the full repo-consistency set is 565 passed / 0 failed; compileall clean. Thanks @JiyouProt for the quick fix.

AI-assisted (Claude Code, Claude Opus 5.5).
This commit is contained in:
QemmHD
2026-11-24 04:50:35 -05:00
committed by GitHub
5 changed files with 155 additions and 7 deletions

View File

@ -25,6 +25,7 @@ on:
- "tools/cfg_structure.py"
- "tools/cpu_ref.py"
- "tools/f32_fuzz.py"
- "tools/file_mode.py"
- "tools/first_light.py"
- "tools/fspx_unpack.py"
- "tools/fssm_header.py"
@ -66,6 +67,7 @@ on:
- "tools/cfg_structure.py"
- "tools/cpu_ref.py"
- "tools/f32_fuzz.py"
- "tools/file_mode.py"
- "tools/first_light.py"
- "tools/fspx_unpack.py"
- "tools/fssm_header.py"

View File

@ -1806,7 +1806,7 @@ def runtime_gpu_max_push_constants():
# Source and data files that produce the translated modules, metadata and partner stubs.
TRANSLATION_SOURCES = ("rdna2spirv.py", "shader_ir.py", "cfg_structure.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py",
TRANSLATION_SOURCES = ("rdna2spirv.py", "shader_ir.py", "cfg_structure.py", "file_mode.py", "fssm_header.py", "lane_masks.py", "wave64_halves.py",
"wave64_emulate_opt.py", "shader_meta.py", "spirv_stubs.py", "spirv_asm.py", "spirv_asm_tables.py",
"spirv_opt.py", "report_paths.py", "replace_retry.py", "fssm_unpack.py", "shader_stage_manifest.py",
"rdna2_decode.py", "rdna2_isa_tables.py", "gfx10_formats.json")

View File

@ -10,6 +10,7 @@ set(LEONIDA_TRANSLATOR_DEPS
${_leonida_repo}/runtime/test/shaders/compute_fixture.py
${_leonida_repo}/tools/bary_fallback_gs.py
${_leonida_repo}/tools/cfg_structure.py
${_leonida_repo}/tools/file_mode.py
${_leonida_repo}/tools/fssm_header.py
${_leonida_repo}/tools/fssm_unpack.py
${_leonida_repo}/tools/gfx10_formats.json

View File

@ -0,0 +1,129 @@
"""Synthetic checks for durable, isolated shader-index publication.
python -I tests/test_rdna2spirv_index_write.py
"""
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools"))
import rdna2spirv as R # noqa: E402
class WriteIndexTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.out = Path(self.tmp.name)
self.path = self.out / "index.part0.json"
self.previous = b'{"previous": {}}\n'
self.path.write_bytes(self.previous)
self.index = {"z": {"synthetic": True}, "a": {}}
def assert_previous_only(self):
self.assertEqual(self.path.read_bytes(), self.previous)
self.assertEqual(list(self.out.iterdir()), [self.path])
def test_existing_tmp_file_is_not_overwritten_or_removed(self):
neighbor = Path(str(self.path) + ".tmp")
neighbor.write_bytes(b"unrelated input")
R.write_index(str(self.path), self.index)
self.assertEqual(neighbor.read_bytes(), b"unrelated input")
self.assertEqual(self.path.read_bytes(),
json.dumps(self.index, indent=0, sort_keys=True).encode("utf-8"))
self.assertEqual(set(self.out.iterdir()), {self.path, neighbor})
def test_stale_tmp_directory_does_not_block_publication(self):
neighbor = Path(str(self.path) + ".tmp")
neighbor.mkdir()
R.write_index(str(self.path), self.index)
self.assertEqual(json.loads(self.path.read_text(encoding="utf-8")), self.index)
self.assertTrue(neighbor.is_dir())
self.assertEqual(set(self.out.iterdir()), {self.path, neighbor})
def test_serialization_error_preserves_index_and_removes_staging(self):
with self.assertRaises(TypeError):
R.write_index(str(self.path), {"not_json": object()})
self.assert_previous_only()
def test_sync_error_preserves_index_and_removes_staging(self):
with patch.object(R.os, "fsync", side_effect=OSError("sync failed")), \
patch.object(R, "replace_retry") as publish:
with self.assertRaisesRegex(OSError, "sync failed"):
R.write_index(str(self.path), self.index)
publish.assert_not_called()
self.assert_previous_only()
def test_replace_error_or_interruption_removes_staging(self):
for error in (PermissionError("replace failed"), KeyboardInterrupt()):
with self.subTest(error=type(error).__name__):
with patch.object(R, "replace_retry", side_effect=error):
with self.assertRaises(type(error)):
R.write_index(str(self.path), self.index)
self.assert_previous_only()
def test_overlapping_writers_stage_separately_outside_merge_glob(self):
real_replace = R.replace_retry
staged = []
inner = {"other": {}}
def interleave(source, destination):
staged.append(source)
self.assertEqual(list(self.out.glob("index.part*.json")), [self.path])
self.assertFalse(str(source).endswith(".json"))
if len(staged) == 1:
self.assertEqual(self.path.read_bytes(), self.previous)
R.write_index(str(self.path), inner)
self.assertEqual(json.loads(self.path.read_text(encoding="utf-8")), inner)
real_replace(source, destination)
with patch.object(R, "replace_retry", side_effect=interleave):
R.write_index(str(self.path), self.index)
self.assertEqual(len(set(staged)), 2)
self.assertEqual(json.loads(self.path.read_text(encoding="utf-8")), self.index)
self.assertEqual(list(self.out.iterdir()), [self.path])
def test_posix_mode_is_applied_before_publication(self):
real_replace = R.replace_retry
def publish(source, destination):
mode.assert_called_once_with(str(self.path))
chmod.assert_called_once_with(source, 0o640)
real_replace(source, destination)
with patch.object(R.os, "name", "posix"), \
patch.object(R, "published_mode", return_value=0o640, create=True) as mode, \
patch.object(R.os, "chmod") as chmod, \
patch.object(R, "replace_retry", side_effect=publish):
R.write_index(str(self.path), self.index)
self.assertEqual(json.loads(self.path.read_text(encoding="utf-8")), self.index)
def test_mode_error_preserves_index_and_removes_staging(self):
for operation in ("mode", "chmod"):
with self.subTest(operation=operation):
with patch.object(R.os, "name", "posix"), \
patch.object(R, "published_mode", return_value=0o640, create=True) as mode, \
patch.object(R.os, "chmod") as chmod:
(mode if operation == "mode" else chmod).side_effect = OSError("mode failed")
with self.assertRaisesRegex(OSError, "mode failed"):
R.write_index(str(self.path), self.index)
self.assert_previous_only()
@unittest.skipUnless(os.name == "posix", "POSIX permission bits")
def test_permissions_of_existing_and_new_indexes(self):
os.chmod(self.path, 0o640)
R.write_index(str(self.path), self.index)
self.assertEqual(self.path.stat().st_mode & 0o777, 0o640)
self.path.unlink()
probe = self.out / "ordinary-file"
probe.write_bytes(b"")
R.write_index(str(self.path), self.index)
self.assertEqual(self.path.stat().st_mode & 0o777, probe.stat().st_mode & 0o777)
if __name__ == "__main__":
unittest.main()

View File

@ -33,6 +33,7 @@ sys.path.insert(0, os.path.dirname(__file__))
from report_paths import path_key, same_report_path # noqa: E402
from shader_ir import HDR, parse_file # noqa: E402
from replace_retry import replace as replace_retry # noqa: E402
from file_mode import published_mode # noqa: E402
import cfg_structure # noqa: E402
import fssm_header # noqa: E402
import fssm_unpack # noqa: E402
@ -18662,12 +18663,27 @@ def shader_meta(g, asm, src_path=None, fssm_path=None):
def write_index(path, index):
"""Write an index under another name and rename it into place, so a run stopped part-way never leaves half of
one: make_game.py takes these files as proof that a shard, or the whole translation, finished."""
tmp = path + ".tmp" # must not end in .json: --merge globs index.part*.json
with open(tmp, "w", encoding="utf-8", newline="\n") as f:
_json.dump(index, f, indent=0, sort_keys=True)
f.flush()
os.fsync(f.fileno()) # on disk before the rename, or a power cut could leave the name with no data
replace_retry(tmp, path) # a scanner or sync client on Windows may hold the new file open for a moment
tmp = None
try:
# Unique per writer, and not a .json file: --merge globs index.part*.json.
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", newline="\n", dir=os.path.dirname(os.path.abspath(path)),
prefix=".index-", suffix=".tmp", delete=False,
) as f:
tmp = f.name
_json.dump(index, f, indent=0, sort_keys=True)
f.flush()
os.fsync(f.fileno()) # on disk before the rename, or a power cut could leave the name with no data
if os.name != "nt":
os.chmod(tmp, published_mode(path)) # do not publish NamedTemporaryFile's private 0600 mode
replace_retry(tmp, path) # a scanner or sync client on Windows may hold the new file open for a moment
except BaseException:
if tmp is not None:
try:
os.unlink(tmp)
except OSError:
pass
raise
class ShardSetError(Exception):