From e91eedad647f60f906209fa9d6e284c3e25ea859 Mon Sep 17 00:00:00 2001 From: Valdi320 <61891540+Valdi320@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:20:49 +0100 Subject: [PATCH 1/5] launcher: deduplicate concurrent DXIL compilation by HLSL content --- docs/ENVIRONMENT.md | 10 +++ project_tuxbox/runtime_shaders.py | 45 +++++++---- tests/test_dxil_store.py | 124 +++++++++++++++++++++++++++++ tests/test_runtime_shader_links.py | 4 +- 4 files changed, 167 insertions(+), 16 deletions(-) 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/runtime_shaders.py b/project_tuxbox/runtime_shaders.py index a6a6f710..50ecedb5 100644 --- a/project_tuxbox/runtime_shaders.py +++ b/project_tuxbox/runtime_shaders.py @@ -394,22 +394,37 @@ def reuse(): # 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: + def reuse_content(): + data = bounded_shader(output) if store and store.fetch(content, output) 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, output) stamp = work / "sha256" stamp.write_text(hashlib.sha256(data).hexdigest()) if session is not None: diff --git a/tests/test_dxil_store.py b/tests/test_dxil_store.py index 44f9ff17..0c76775e 100644 --- a/tests/test_dxil_store.py +++ b/tests/test_dxil_store.py @@ -1,8 +1,11 @@ +from concurrent.futures import ThreadPoolExecutor import hashlib +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 @@ -73,6 +76,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): + # Force both initial lookups to miss before either can publish. + result = original_fetch(store, key, output) + 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() { }" diff --git a/tests/test_runtime_shader_links.py b/tests/test_runtime_shader_links.py index b72041ef..3c926c78 100644 --- a/tests/test_runtime_shader_links.py +++ b/tests/test_runtime_shader_links.py @@ -364,7 +364,9 @@ 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.key.return_value = "c" * 64 + store.root = self.cache / "content" + store.root.mkdir() store.fetch.return_value = False store.is_slow.return_value = True From 2057645f6bb60475c467df612a3af175d57f2557 Mon Sep 17 00:00:00 2001 From: Valdi320 <61891540+Valdi320@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:23:49 +0100 Subject: [PATCH 2/5] launcher: reuse one bounded verified DXIL snapshot --- project_tuxbox/dxil_store.py | 32 +++++++++++-------- project_tuxbox/runtime_shaders.py | 33 ++----------------- project_tuxbox/shader_blob.py | 39 +++++++++++++++++++++++ tests/test_dxil_store.py | 51 ++++++++++++++++++++++++++++++ tests/test_runtime_shader_links.py | 2 +- 5 files changed, 112 insertions(+), 45 deletions(-) create mode 100644 project_tuxbox/shader_blob.py diff --git a/project_tuxbox/dxil_store.py b/project_tuxbox/dxil_store.py index 46bb7f9c..1ff2bed7 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,42 @@ 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): tag = f"{target} {VARIANTS[target]}" if target in VARIANTS else target - return hashlib.sha256(f"{tag}\n".encode("ascii") + hlsl).hexdigest() + digest = hashlib.sha256(f"{tag}\n".encode("ascii")) + digest.update(hlsl) + return digest.hexdigest() def fetch(self, key, output): - """Copy the stored DXIL to `output` if its bytes still match their stamp.""" + """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): + 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..8351a51b 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) @@ -394,7 +367,7 @@ def reuse(): # 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 + data = store.fetch(content, output) if store else None if data is None or portable_stage(data) != target_stage: output.unlink(missing_ok=True) data = None @@ -409,7 +382,7 @@ def reuse(): if data is None: data = compile_dxil(dxc, dxv, target, hlsl, output, store, key, target_stage) if store: - store.save(content, output) + 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..a33ea3c5 100644 --- a/tests/test_dxil_store.py +++ b/tests/test_dxil_store.py @@ -1,4 +1,5 @@ import hashlib +import os from pathlib import Path import struct import subprocess @@ -97,6 +98,56 @@ 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_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..6825b252 100644 --- a/tests/test_runtime_shader_links.py +++ b/tests/test_runtime_shader_links.py @@ -365,7 +365,7 @@ def test_large_pixel_candidate_precedes_slow_marker_and_validates_once(self): dxil = portable_program(0, b"pixel") store = Mock() store.key.return_value = "content" - store.fetch.return_value = False + store.fetch.return_value = None store.is_slow.return_value = True def run(args, *, timeout): From 2fb96ad7f1c7fd16086ed35068977dbb506c1e48 Mon Sep 17 00:00:00 2001 From: Valdi320 <61891540+Valdi320@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:22:37 +0100 Subject: [PATCH 3/5] launcher: hash generated shader content incrementally --- project_tuxbox/dxil_store.py | 19 +++++++++++++++++-- project_tuxbox/runtime_shaders.py | 2 +- tests/test_dxil_store.py | 9 +++++++++ tests/test_runtime_shader_links.py | 2 +- 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/project_tuxbox/dxil_store.py b/project_tuxbox/dxil_store.py index 46bb7f9c..2e4b233e 100644 --- a/project_tuxbox/dxil_store.py +++ b/project_tuxbox/dxil_store.py @@ -75,9 +75,24 @@ def for_cache(cls, cache): 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")) + + @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): """Copy the stored DXIL to `output` if its bytes still match their stamp.""" diff --git a/project_tuxbox/runtime_shaders.py b/project_tuxbox/runtime_shaders.py index 50ecedb5..a2c75f8f 100644 --- a/project_tuxbox/runtime_shaders.py +++ b/project_tuxbox/runtime_shaders.py @@ -393,7 +393,7 @@ 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 + content = store.key_file(hlsl, target) if store else None def reuse_content(): data = bounded_shader(output) if store and store.fetch(content, output) else None if data is not None and portable_stage(data) == target_stage: diff --git a/tests/test_dxil_store.py b/tests/test_dxil_store.py index 0c76775e..0e7dc04e 100644 --- a/tests/test_dxil_store.py +++ b/tests/test_dxil_store.py @@ -68,6 +68,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")) diff --git a/tests/test_runtime_shader_links.py b/tests/test_runtime_shader_links.py index 3c926c78..bc94c265 100644 --- a/tests/test_runtime_shader_links.py +++ b/tests/test_runtime_shader_links.py @@ -364,7 +364,7 @@ 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 = "c" * 64 + store.key_file.return_value = "c" * 64 store.root = self.cache / "content" store.root.mkdir() store.fetch.return_value = False From ce7edf2bf214630773db750c4597918d91e36556 Mon Sep 17 00:00:00 2001 From: Valdi320 <61891540+Valdi320@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:22:40 +0100 Subject: [PATCH 4/5] launcher: reject wrong-stage snapshots before counting reuse --- project_tuxbox/dxil_store.py | 5 +++-- project_tuxbox/runtime_shaders.py | 2 +- tests/test_dxil_store.py | 16 ++++++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/project_tuxbox/dxil_store.py b/project_tuxbox/dxil_store.py index 1ff2bed7..7fa15eee 100644 --- a/project_tuxbox/dxil_store.py +++ b/project_tuxbox/dxil_store.py @@ -81,12 +81,13 @@ def key(hlsl, target): digest.update(hlsl) return digest.hexdigest() - def fetch(self, key, output): + def fetch(self, key, output, *, accept=None): """Return and stage one bounded, verified snapshot of stored DXIL.""" try: 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): + 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 data diff --git a/project_tuxbox/runtime_shaders.py b/project_tuxbox/runtime_shaders.py index 8351a51b..fa294ac2 100644 --- a/project_tuxbox/runtime_shaders.py +++ b/project_tuxbox/runtime_shaders.py @@ -367,7 +367,7 @@ def reuse(): # 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 = store.fetch(content, output) if store else None + data = store.fetch(content, output, accept=lambda blob: portable_stage(blob) == target_stage) if store else None if data is None or portable_stage(data) != target_stage: output.unlink(missing_ok=True) data = None diff --git a/tests/test_dxil_store.py b/tests/test_dxil_store.py index a33ea3c5..ccbf7545 100644 --- a/tests/test_dxil_store.py +++ b/tests/test_dxil_store.py @@ -107,6 +107,22 @@ def test_fetch_returns_the_verified_snapshot(self): 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 From b460d1ced7c1efbc89c39760b7b550f46d5f0e57 Mon Sep 17 00:00:00 2001 From: Valdi320 <61891540+Valdi320@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:18:32 +0100 Subject: [PATCH 5/5] test: preserve snapshot validator in concurrent cache control --- tests/test_dxil_store.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_dxil_store.py b/tests/test_dxil_store.py index fff1d242..a09fcc35 100644 --- a/tests/test_dxil_store.py +++ b/tests/test_dxil_store.py @@ -106,9 +106,9 @@ def run(args, *, timeout): if args[0].name == "xshader": translated.wait(5) - def fetch(store, key, output): + def fetch(store, key, output, **kwargs): # Force both initial lookups to miss before either can publish. - result = original_fetch(store, key, output) + result = original_fetch(store, key, output, **kwargs) with guard: first = output not in fetched fetched.add(output)