diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index 53d81bdf..382e3e66 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -93,3 +93,13 @@ All are off by default. Capture variables write the game's data to disk, so don' ## Build and test tools `TUXBOX_XSHADER` selects the shader compiler for launcher preparation and `DXC` selects the DirectX Shader Compiler. `TUXBOX_BLESS_PROFILES`, `TUXBOX_ORACLE_*`, `TUXBOX_TEST_*` and the probe and replay variables in `tools/` belong to individual checks. `TUXBOX_PROVIDER`, `TUXBOX_SHADER_SESSION` and `TUXBOX_WINE_*` are internal; don't set them. + + +Cold shader requests that translate to identical HLSL and the same target +profile share a single DXC compilation across launcher processes using the +same toolchain cache. Exact source cache hits still bypass compilation and +locking. Different HLSL or target profiles compile independently. A failed +compile does not publish an unsupported marker for another source; the next +request can retry. Content locks are retained as empty files to avoid races +with other processes. The wait is bounded by the maximum compiler fallback +budget plus validation and scheduling margin. diff --git a/project_tuxbox/dxil_store.py b/project_tuxbox/dxil_store.py index 46bb7f9c..e562932e 100644 --- a/project_tuxbox/dxil_store.py +++ b/project_tuxbox/dxil_store.py @@ -10,11 +10,11 @@ import os from pathlib import Path import re -import shutil from tempfile import mkstemp from .inspect import digest from .shader_prep import has_dxil_container +from .shader_blob import MAX_SHADER_BYTES, bounded_shader, exact_marker, bounded_regular # Bump when a policy change can make cached DXIL unacceptable under validation. @@ -64,38 +64,56 @@ def __init__(self, root): def for_cache(cls, cache): """The store behind `cache`, or None when reuse is not enabled for it.""" try: - identity = (cache / IDENTITY_FILE).read_text(encoding="ascii") + identity = bounded_regular(cache / IDENTITY_FILE, 64).decode("ascii") if not re.fullmatch(r"[a-f0-9]{64}", identity): return None # /runtime/ -> /dxil/ root = cache.parent.parent / "dxil" / identity root.mkdir(parents=True, exist_ok=True) - except (OSError, UnicodeError): + except (OSError, UnicodeError, ValueError): return None return cls(root) @staticmethod - def key(hlsl, target): + def _key_hasher(target): tag = f"{target} {VARIANTS[target]}" if target in VARIANTS else target - return hashlib.sha256(f"{tag}\n".encode("ascii") + hlsl).hexdigest() + return hashlib.sha256(f"{tag}\n".encode("ascii")) - def fetch(self, key, output): - """Copy the stored DXIL to `output` if its bytes still match their stamp.""" + @staticmethod + def key(hlsl, target): + digest = DxilStore._key_hasher(target) + digest.update(hlsl) + return digest.hexdigest() + + @staticmethod + def key_file(hlsl, target): + """Hash private generated HLSL with bounded memory and unchanged keys.""" + digest = DxilStore._key_hasher(target) + with hlsl.open("rb") as stream: + for chunk in iter(lambda: stream.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + def fetch(self, key, output, *, accept=None): + """Return and stage one bounded, verified snapshot of stored DXIL.""" try: - expected = (self.root / f"{key}.sha256").read_text(encoding="ascii") - shutil.copyfile(self.root / f"{key}.cso", output) - if digest(output) == expected and has_dxil_container(output.read_bytes()): + data = bounded_shader(self.root / f"{key}.cso") + checksum = hashlib.sha256(data).hexdigest().encode("ascii") + if (exact_marker(self.root / f"{key}.sha256", checksum) and has_dxil_container(data) + and (accept is None or accept(data))): + output.write_bytes(data) reused["dxil"] += 1 - return True - except (OSError, UnicodeError): + return data + except (OSError, ValueError): pass output.unlink(missing_ok=True) - return False + return None - def save(self, key, output): - """Keep validated DXIL. A failure only costs a later recompile.""" + def save(self, key, data): + """Keep already-validated DXIL bytes. Failure only costs a later compile.""" + if len(data) > MAX_SHADER_BYTES: + return try: - data = output.read_bytes() _publish(self.root / f"{key}.cso", data) _publish(self.root / f"{key}.sha256", hashlib.sha256(data).hexdigest().encode("ascii")) except OSError: diff --git a/project_tuxbox/runtime_shaders.py b/project_tuxbox/runtime_shaders.py index a6a6f710..9d49d4dd 100644 --- a/project_tuxbox/runtime_shaders.py +++ b/project_tuxbox/runtime_shaders.py @@ -18,10 +18,10 @@ from .inspect import digest from .persistent_dxc import PersistentDxc from .shader_diagnostics import refusal_line +from .shader_blob import MAX_SHADER_BYTES, bounded_shader, exact_marker from .shader_prep import SOURCE_CACHE, ToolFailure, compiler_tools, run_tool -MAX_SHADER_BYTES = 64 << 20 XSHADER_UNSUPPORTED_HLSL = 65 # The emitter's one-line refusal reason kept beside an .unsupported marker. REASON_BYTES = 512 @@ -46,21 +46,6 @@ def reason_known(self): return not self.cached or self.remembered -def bounded_shader(path): - """Snapshot a regular file without following links or blocking on FIFOs.""" - flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) - with os.fdopen(os.open(path, flags), "rb") as stream: - info = os.fstat(stream.fileno()) - if not stat.S_ISREG(info.st_mode): - raise ValueError(f"{path.name} is not a regular shader file") - if info.st_size > MAX_SHADER_BYTES: - raise ValueError("shader exceeds the 64 MiB runtime limit") - data = stream.read(MAX_SHADER_BYTES + 1) - if len(data) > MAX_SHADER_BYTES: - raise ValueError("shader exceeds the 64 MiB runtime limit") - return data - - def verified_input(path, expected): data = bounded_shader(path) if hashlib.sha256(data).hexdigest() != expected: @@ -116,18 +101,6 @@ def portable_stage(data): return container_stage(data, portable=True) -def exact_marker(path, expected): - """Read a tiny regular marker, without following links or blocking.""" - flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) - try: - with os.fdopen(os.open(path, flags), "rb") as stream: - info = os.fstat(stream.fileno()) - return (stat.S_ISREG(info.st_mode) and info.st_size == len(expected) - and stream.read(len(expected) + 1) == expected) - except OSError: - return False - - def remembered_reason(path): """The refusal reason saved with a marker, or None for caches that predate it.""" flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) @@ -393,23 +366,38 @@ def reuse(): # validated equivalent output, including the candidate and -O0 paths; # compiler policy changes deliberately leave warm cache entries valid. store = DxilStore.for_cache(cache) - content = store.key(hlsl.read_bytes(), target) if store else None - data = bounded_shader(output) if store and store.fetch(content, output) else None - if data is None or portable_stage(data) != target_stage: + content = store.key_file(hlsl, target) if store else None + def reuse_content(): + data = store.fetch(content, output, accept=lambda blob: portable_stage(blob) == target_stage) if store else None + if data is not None and portable_stage(data) == target_stage: + return data output.unlink(missing_ok=True) - data = None - if (persistent is not None and target == "cs_6_0" - and not (store and store.is_slow(key, target)) - and persistent.compile(dxc, hlsl, output)): - try: - data = validated_dxil(dxv, output, target_stage) - except (OSError, ValueError, subprocess.SubprocessError) as error: - persistent.report(f"Persistent DXC output rejected, using the CLI: {error}") - output.unlink(missing_ok=True) - if data is None: - data = compile_dxil(dxc, dxv, target, hlsl, output, store, key, target_stage) - if store: - store.save(content, output) + return None + + data = reuse_content() + if data is None: + # The exact-source lock above cannot deduplicate different + # requests (or translator builds) that emit identical HLSL. + # Acquire the shared toolchain/content lock only after a miss. + # Always acquire source before content; never the reverse. + # Allow time for the optimised attempt, fallback and validation. + lock = (compile_lock(store.root, content, timeout=O0_TIMEOUT_MAX + COMPUTE_TIMEOUT + 60) + if store else nullcontext()) + with lock: + data = reuse_content() if store else None + if data is None: + if (persistent is not None and target == "cs_6_0" + and not (store and store.is_slow(key, target)) + and persistent.compile(dxc, hlsl, output)): + try: + data = validated_dxil(dxv, output, target_stage) + except (OSError, ValueError, subprocess.SubprocessError) as error: + persistent.report(f"Persistent DXC output rejected, using the CLI: {error}") + output.unlink(missing_ok=True) + if data is None: + data = compile_dxil(dxc, dxv, target, hlsl, output, store, key, target_stage) + if store: + store.save(content, data) stamp = work / "sha256" stamp.write_text(hashlib.sha256(data).hexdigest()) if session is not None: diff --git a/project_tuxbox/shader_blob.py b/project_tuxbox/shader_blob.py new file mode 100644 index 00000000..57ef6ae8 --- /dev/null +++ b/project_tuxbox/shader_blob.py @@ -0,0 +1,39 @@ +"""Bounded snapshots of local shader cache files.""" +import os +import stat + + +MAX_SHADER_BYTES = 64 << 20 + + +def bounded_regular(path, limit): + """Snapshot a regular file, without following links or blocking on FIFOs.""" + flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) + with os.fdopen(os.open(path, flags), "rb") as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode): + raise ValueError(f"{path.name} is not a regular shader file") + if info.st_size > limit: + raise ValueError("shader exceeds the 64 MiB runtime limit" if limit == MAX_SHADER_BYTES + else "file exceeds the cache snapshot limit") + data = stream.read(info.st_size + 1) + if len(data) != info.st_size: + raise ValueError("file size changed during cache snapshot") + return data + + +def bounded_shader(path): + """Snapshot a regular shader under the provider's 64 MiB limit.""" + return bounded_regular(path, MAX_SHADER_BYTES) + + +def exact_marker(path, expected): + """Read a tiny regular marker, without following links or blocking.""" + flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) + try: + with os.fdopen(os.open(path, flags), "rb") as stream: + info = os.fstat(stream.fileno()) + return (stat.S_ISREG(info.st_mode) and info.st_size == len(expected) + and stream.read(len(expected) + 1) == expected) + except OSError: + return False diff --git a/tests/test_dxil_store.py b/tests/test_dxil_store.py index 44f9ff17..a09fcc35 100644 --- a/tests/test_dxil_store.py +++ b/tests/test_dxil_store.py @@ -1,8 +1,12 @@ +from concurrent.futures import ThreadPoolExecutor import hashlib +import os +from threading import Barrier, Lock from pathlib import Path import struct import subprocess import sys +from time import monotonic, sleep from tempfile import TemporaryDirectory import unittest from unittest.mock import patch @@ -65,6 +69,15 @@ def test_output_built_with_other_compute_flags_is_not_reused(self): # Other targets keep their key, so their cached output stays usable. self.assertEqual(DxilStore.key(b"shader", "ps_6_0"), hashlib.sha256(b"ps_6_0\nshader").hexdigest()) + def test_streamed_content_key_matches_existing_cache_keys(self): + path = self.root / "large.hlsl" + data = bytes(range(256)) * 12289 + path.write_bytes(data) + for target in ("ps_6_0", "cs_6_6", "ms_6_5"): + self.assertEqual(DxilStore.key_file(path, target), DxilStore.key(data, target)) + path.write_bytes(b"") + self.assertEqual(DxilStore.key_file(path, "ps_6_0"), DxilStore.key(b"", "ps_6_0")) + def test_new_translator_with_same_hlsl_skips_dxc(self): first = self.compile(self.cache("a")) second = self.compile(self.cache("b")) @@ -73,6 +86,127 @@ def test_new_translator_with_same_hlsl_skips_dxc(self): self.assertEqual((self.root / "runtime/b" / (hashlib.sha256(b"shader").hexdigest() + ".sha256")).read_text(), hashlib.sha256(second).hexdigest()) + def test_parallel_distinct_sources_share_identical_cold_hlsl(self): + caches = [self.cache("a"), self.cache("b")] + sources = [] + for i in range(2): + data = f"distinct source {i}".encode() + key = hashlib.sha256(data).hexdigest() + source = self.root / (key + ".dxbc") + source.write_bytes(data) + sources.append((source, key)) + translated = Barrier(2) + misses = Barrier(2) + guard = Lock() + original_fetch = DxilStore.fetch + fetched = set() + + def run(args, *, timeout): + self.run_tool(args, timeout=timeout) + if args[0].name == "xshader": + translated.wait(5) + + def fetch(store, key, output, **kwargs): + # Force both initial lookups to miss before either can publish. + result = original_fetch(store, key, output, **kwargs) + with guard: + first = output not in fetched + fetched.add(output) + if first: + misses.wait(5) + return result + + with patch("project_tuxbox.runtime_shaders.run_tool", side_effect=run), \ + patch.object(DxilStore, "fetch", fetch), ThreadPoolExecutor(max_workers=2) as pool: + jobs = [pool.submit(compile_request, source, key, self.tools, cache, None) + for (source, key), cache in zip(sources, caches)] + self.assertTrue(all(job.result(timeout=10) for job in jobs)) + self.assertEqual(len(self.calls), 1) + self.assertEqual(*( (cache / (key + ".cso")).read_bytes() + for (_, key), cache in zip(sources, caches))) + + def test_content_lock_releases_after_failed_compile_and_never_caches_failure(self): + cache = self.cache("a") + original = self.run_tool + def fail(args, *, timeout): + if args[0].name == "dxc": + raise OSError("transient compile failure") + original(args, timeout=timeout) + data = b"failed source" + key = hashlib.sha256(data).hexdigest() + source = self.root / (key + ".dxbc") + source.write_bytes(data) + with patch("project_tuxbox.runtime_shaders.run_tool", side_effect=fail): + with self.assertRaisesRegex(OSError, "transient"): + compile_request(source, key, self.tools, cache, None) + self.assertFalse((cache / (key + ".unsupported")).exists()) + self.assertEqual(self.compile(self.cache("b"), b"new source"), container(b"void")) + self.assertEqual(self.compile(cache, data), container(b"void")) + self.assertEqual(len(self.calls), 1) + + def test_different_content_locks_do_not_serialize_unrelated_shaders(self): + caches = [self.cache("a"), self.cache("b")] + ready = Barrier(2) + active = Barrier(2) + def run(args, *, timeout): + if args[0].name == "xshader": + args[args.index("--hlsl-out") + 1].write_bytes(args[1].read_bytes()) + args[args.index("--profile-out") + 1].write_text("ps_6_0") + ready.wait(5) + elif args[0].name == "dxc": + active.wait(5) # Both independent content keys must proceed. + self.run_tool(args, timeout=timeout) + sources = [] + for i in range(2): + data = f"distinct source {i}".encode() + key = hashlib.sha256(data).hexdigest() + source = self.root / (key + ".dxbc") + source.write_bytes(data) + sources.append((source, key)) + with patch("project_tuxbox.runtime_shaders.run_tool", side_effect=run), ThreadPoolExecutor(max_workers=2) as pool: + jobs = [pool.submit(compile_request, source, key, self.tools, cache, None) + for (source, key), cache in zip(sources, caches)] + self.assertTrue(all(job.result(timeout=10) for job in jobs)) + self.assertEqual(len(self.calls), 2) + + def test_content_lock_coordinates_independent_processes(self): + from project_tuxbox.runtime_shaders import compile_lock + store = DxilStore.for_cache(self.cache("a")) + key = "a" * 64 + entered = self.root / "entered" + attempted = self.root / "attempted" + program = ( + "from pathlib import Path; import sys; " + "from project_tuxbox.runtime_shaders import compile_lock; " + "Path(sys.argv[3]).touch(); " + "lock = compile_lock(Path(sys.argv[1]), sys.argv[2], timeout=5); " + "lock.__enter__(); Path(sys.argv[4]).touch(); lock.__exit__(None, None, None)" + ) + with compile_lock(store.root, key): + child = subprocess.Popen([sys.executable, "-c", program, str(store.root), key, + str(attempted), str(entered)], + cwd=Path(__file__).resolve().parents[1], + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + try: + deadline = monotonic() + 3 + while not attempted.exists() and monotonic() < deadline: + sleep(.005) + self.assertTrue(attempted.exists()) + sleep(.1) + self.assertFalse(entered.exists()) + except BaseException: + child.kill() + child.communicate() + raise + try: + _, stderr = child.communicate(timeout=5) + self.assertEqual(child.returncode, 0, stderr) + self.assertTrue(entered.exists()) + finally: + if child.poll() is None: + child.kill() + child.communicate() + def test_changed_hlsl_profile_or_toolchain_recompiles(self): self.compile(self.cache("a")) self.hlsl = "void main() { }" @@ -97,6 +231,72 @@ def test_damaged_entry_is_recompiled(self): self.compile(self.cache("c")) self.assertEqual(len(self.calls), 2, "the recompile replaced the damaged entry") + def test_fetch_returns_the_verified_snapshot(self): + cache = self.cache("a") + data = self.compile(cache) + store = DxilStore.for_cache(cache) + key = store.key(self.hlsl.encode(), self.profile) + output = self.root / "output.cso" + self.assertEqual(store.fetch(key, output), data) + self.assertEqual(output.read_bytes(), data) + + def test_rejected_stage_is_not_staged_or_counted_as_reuse(self): + from project_tuxbox.dxil_store import reused + from project_tuxbox.runtime_shaders import portable_stage + cache = self.cache("a") + data = self.compile(cache) + store = DxilStore.for_cache(cache) + key = store.key(self.hlsl.encode(), self.profile) + output = self.root / "output.cso" + before = reused["dxil"] + self.assertEqual(portable_stage(data), 0) + self.assertIsNone(store.fetch(key, output, accept=lambda blob: portable_stage(blob) == 5)) + self.assertFalse(output.exists()) + self.assertEqual(reused["dxil"], before) + self.assertEqual(store.fetch(key, output, accept=lambda blob: portable_stage(blob) == 0), data) + self.assertEqual(reused["dxil"], before + 1) + + def test_fetch_rejects_oversized_entries_before_copy(self): + store = DxilStore.for_cache(self.cache("a")) + key = "a" * 64 + output = self.root / "output.cso" + with (store.root / f"{key}.cso").open("wb") as stream: + stream.truncate((64 << 20) + 1) + (store.root / f"{key}.sha256").write_text("0" * 64) + self.assertIsNone(store.fetch(key, output)) + self.assertFalse(output.exists()) + + def test_fetch_rejects_linked_payloads_and_markers(self): + store = DxilStore.for_cache(self.cache("a")) + key = "a" * 64 + output = self.root / "output.cso" + data = container(b"void") + payload = self.root / "payload" + marker = self.root / "marker" + payload.write_bytes(data) + marker.write_text(hashlib.sha256(data).hexdigest()) + (store.root / f"{key}.cso").symlink_to(payload) + (store.root / f"{key}.sha256").write_bytes(marker.read_bytes()) + self.assertIsNone(store.fetch(key, output)) + (store.root / f"{key}.cso").unlink() + (store.root / f"{key}.cso").write_bytes(data) + (store.root / f"{key}.sha256").unlink() + (store.root / f"{key}.sha256").symlink_to(marker) + self.assertIsNone(store.fetch(key, output)) + self.assertFalse(output.exists()) + + def test_fifo_payload_and_identity_are_rejected_without_blocking(self): + cache = self.cache("a") + store = DxilStore.for_cache(cache) + key = "a" * 64 + output = self.root / "output.cso" + os.mkfifo(store.root / f"{key}.cso") + (store.root / f"{key}.sha256").write_text("0" * 64) + self.assertIsNone(store.fetch(key, output)) + (cache / "dxil-identity").unlink() + os.mkfifo(cache / "dxil-identity") + self.assertIsNone(DxilStore.for_cache(cache)) + def test_timed_out_request_goes_straight_to_o0_afterwards(self): self.timeouts = 1 self.compile(self.cache("a")) diff --git a/tests/test_runtime_shader_links.py b/tests/test_runtime_shader_links.py index b72041ef..bdc89ac9 100644 --- a/tests/test_runtime_shader_links.py +++ b/tests/test_runtime_shader_links.py @@ -364,8 +364,10 @@ def test_large_pixel_candidate_precedes_slow_marker_and_validates_once(self): source.write_bytes(program) dxil = portable_program(0, b"pixel") store = Mock() - store.key.return_value = "content" - store.fetch.return_value = False + store.key_file.return_value = "c" * 64 + store.root = self.cache / "content" + store.root.mkdir() + store.fetch.return_value = None store.is_slow.return_value = True def run(args, *, timeout):