From 511958811c955d074cdd4bc1fa411e7c61bf67c9 Mon Sep 17 00:00:00 2001 From: Manuel Smith Lazarte Alcocer <168827963+smith-3@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:25:46 -0400 Subject: [PATCH] worker: add experimental persistent DXC --- docs/PROJECTSCARLETT.md | 25 ++++++++ project_tuxbox/persistent_dxc.py | 94 ++++++++++++++++++++++++++++++ project_tuxbox/runtime_shaders.py | 64 +++++++++++++++----- tests/test_persistent_dxc.py | 77 ++++++++++++++++++++++++ tests/test_runtime_shader_links.py | 47 +++++++++++++++ tools/benchmark_scarlett_worker.py | 8 ++- tools/dxc_worker.cpp | 49 ++++++++++++++++ 7 files changed, 347 insertions(+), 17 deletions(-) create mode 100644 project_tuxbox/persistent_dxc.py create mode 100644 tests/test_persistent_dxc.py create mode 100644 tools/dxc_worker.cpp diff --git a/docs/PROJECTSCARLETT.md b/docs/PROJECTSCARLETT.md index 016abe37..f8a885f1 100644 --- a/docs/PROJECTSCARLETT.md +++ b/docs/PROJECTSCARLETT.md @@ -155,6 +155,31 @@ matched across configurations. See `--help` for reproduction arguments and +### Experimental persistent DXC + +On Linux, build the helper against the same Microsoft DXC release used by +TuxBox. Set `DXC_ROOT` to the extracted release directory. + +```sh +mkdir -p build +c++ -std=c++17 -O2 -isystem "$DXC_ROOT/include" tools/dxc_worker.cpp \ + -L "$DXC_ROOT/lib" -ldxcompiler -o build/dxc-worker +export TUXBOX_PERSISTENT_DXC="$PWD/build/dxc-worker" +``` + +The live worker starts helpers on demand for optimized `cs_6_0` requests. +Each helper handles one request at a time and stays open for the session. +The worker retries once if a helper exits during compilation and falls +back to the CLI if the helper or validation fails. Each newly compiled +result still passes DXV before publication. The CLI handles other profiles +and slow requests. The experimental cache identity includes the helper +binary. Unset `TUXBOX_PERSISTENT_DXC` to use the default CLI. + +For a synthetic comparison, run the worker benchmark described above +with `--jobs 4` and add `--dxc-helper build/dxc-worker` for the experimental +variant. Give each run a fresh output path. Compare per-request SHA-256 +values and latency. + ## What to expect The game opens its Americas window, loads its archives and presents 3840×2160 frames. The recorded run reached the player selection prompt, with Account Picker, Screen Narration and TuxBox options. It stopped at a title breakpoint 97 seconds after launch. Intro video, input after player selection and gameplay aren't verified yet. [Current priorities](PROGRESS.md#current-priorities) diff --git a/project_tuxbox/persistent_dxc.py b/project_tuxbox/persistent_dxc.py new file mode 100644 index 00000000..69ba74aa --- /dev/null +++ b/project_tuxbox/persistent_dxc.py @@ -0,0 +1,94 @@ +"""Session-scoped pool for the experimental Linux DXC helper.""" + +import os +from pathlib import Path +from queue import Queue +import select +import subprocess +from time import monotonic + + +class CompilerExited(ConnectionError): + pass + + +class Compiler: + def __init__(self, helper, library): + env = dict(os.environ, LD_LIBRARY_PATH=str(library)) + self.process = subprocess.Popen( + [helper], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, bufsize=0, env=env, + ) + + def compile(self, hlsl, output, deadline): + request = b"\n".join(os.fsencode(path) for path in (hlsl, output)) + b"\n" + self.process.stdin.write(request) + response = b"" + while len(response) < 3: + if not select.select([self.process.stdout], [], [], max(0, deadline - monotonic()))[0]: + raise TimeoutError("persistent DXC timed out") + data = os.read(self.process.stdout.fileno(), 3 - len(response)) + if not data: + raise CompilerExited("persistent DXC exited") + response += data + if response != b"ok\n": + raise ValueError("invalid persistent DXC response") + + def close(self, *, kill=False): + if kill: + self.process.kill() + self.process.stdin.close() + try: + self.process.wait(timeout=2) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + finally: + self.process.stdout.close() + + +class PersistentDxc: + def __init__(self, helper, jobs, report): + self.helper = helper + self.report = report + self.slots = Queue(jobs) + for _ in range(jobs): + self.slots.put(None) + + def compile(self, dxc, hlsl, output, *, timeout=15): + # The helper uses newline-delimited ASCII paths and the same Linux + # library as the Microsoft DXC installation selected for this session. + dxc = Path(dxc).resolve() + library = dxc.parent.parent / "lib" + if not (library / "libdxcompiler.so").is_file() or any( + not str(path).isascii() or "\n" in str(path) for path in (hlsl, output) + ): + return False + deadline = monotonic() + timeout + compiler = self.slots.get() + try: + for attempt in range(2): + try: + if compiler is None: + compiler = Compiler(self.helper, library) + compiler.compile(hlsl, output, deadline) + return True + except (OSError, ValueError) as error: + if compiler is not None: + compiler.close(kill=True) + compiler = None + output.unlink(missing_ok=True) + if attempt or not isinstance(error, (CompilerExited, BrokenPipeError)) or monotonic() >= deadline: + self.report(f"Persistent DXC unavailable, using the CLI: {error}") + return False + finally: + self.slots.put(compiler) + + def __enter__(self): + return self + + def __exit__(self, *_): + for _ in range(self.slots.maxsize): + compiler = self.slots.get_nowait() + if compiler is not None: + compiler.close() diff --git a/project_tuxbox/runtime_shaders.py b/project_tuxbox/runtime_shaders.py index f221fc20..c1593075 100644 --- a/project_tuxbox/runtime_shaders.py +++ b/project_tuxbox/runtime_shaders.py @@ -1,5 +1,5 @@ """Compile Xbox shaders and link raster stages requested by a running Proton game.""" -from contextlib import contextmanager +from contextlib import contextmanager, nullcontext from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait as wait_futures import errno import hashlib @@ -16,6 +16,7 @@ from .dxil_store import DxilStore, write_identity from .inspect import digest +from .persistent_dxc import PersistentDxc from .shader_diagnostics import refusal_line from .shader_prep import SOURCE_CACHE, ToolFailure, compiler_tools, run_tool @@ -232,7 +233,15 @@ def compile_dxil(dxc, target, hlsl, output, store, request): run_tool(unoptimised, timeout=O0_TIMEOUT) -def compile_request(source, key, tools, cache, session, *, remember=None): +def validated_dxil(dxv, output, stage): + run_tool([dxv, output], timeout=10) + data = bounded_shader(output) + if portable_stage(data) != stage: + raise ValueError("compiler returned invalid DXIL or a different shader stage") + return data + + +def compile_request(source, key, tools, cache, session, *, remember=None, persistent=None): linked = source.suffix == ".link" xshader, dxc, dxv = tools with TemporaryDirectory(dir=cache) as tmp: @@ -331,11 +340,18 @@ def reuse(): data = bounded_shader(output) if store and store.fetch(content, output) else None if data is None or portable_stage(data) != target_stage: output.unlink(missing_ok=True) - compile_dxil(dxc, target, hlsl, output, store, key) - run_tool([dxv, output], timeout=10) - data = bounded_shader(output) - if portable_stage(data) != target_stage: - raise ValueError("compiler returned invalid DXIL or a different shader stage") + 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: + compile_dxil(dxc, target, hlsl, output, store, key) + data = validated_dxil(dxv, output, target_stage) if store: store.save(content, output) stamp = work / "sha256" @@ -356,11 +372,21 @@ def remove_request(path): path.unlink(missing_ok=True) -def serve(session, stop, report, archive=None, jobs=1): +def serve(session, stop, report, archive=None, jobs=1, *, dxc_helper=None): # Cargo can replace the release executable while another title is running. # Keep the executable we fingerprint private to this host worker. with TemporaryDirectory(prefix="tuxbox-xshader-") as tmp, request_notifications(session / "requests", stop) as wait: - _serve_requests(session, stop, report, Path(tmp) / "xshader", wait, archive, jobs) + pinned = None + if dxc_helper: + try: + helper = Path(tmp) / "dxc-worker" + shutil.copyfile(Path(dxc_helper).expanduser(), helper) + helper.chmod(0o700) + pinned = helper + except OSError as error: + report(f"Could not stage persistent DXC, using the CLI: {error}") + with PersistentDxc(pinned, jobs, report) if pinned else nullcontext() as persistent: + _serve_requests(session, stop, report, Path(tmp) / "xshader", wait, archive, jobs, persistent=persistent) @contextmanager @@ -394,13 +420,15 @@ def wait(): os.close(fd) -def snapshot_compiler_cache(xshader, cache_root): +def snapshot_compiler_cache(xshader, cache_root, *, dxc_helper=None): """Pin the executable used for all requests under this toolchain fingerprint.""" compiler, dxc, dxv = compiler_tools() shutil.copyfile(compiler, xshader) xshader.chmod(0o700) tools = (xshader, dxc, dxv) version = subprocess.check_output([dxc, "--version"], timeout=10) + if dxc_helper is not None: + version += b"\npersistent-dxc:" + digest(dxc_helper).encode("ascii") fingerprint = hashlib.sha256(version) for tool in tools: fingerprint.update(bytes.fromhex(digest(Path(tool)))) @@ -445,9 +473,10 @@ def ordered_requests(directory): return [source for _, _, source in sorted(entries)] -def _serve_requests(session, stop, report, xshader, wait, archive, jobs=1): +def _serve_requests(session, stop, report, xshader, wait, archive, jobs=1, *, persistent=None): def bind_cache(): - tools, cache = snapshot_compiler_cache(xshader, session.parent) + options = {"dxc_helper": persistent.helper} if persistent is not None else {} + tools, cache = snapshot_compiler_cache(xshader, session.parent, **options) # Publish only after the exact compiler used by this worker is pinned. pending = session / "compiler-id.tmp" pending.write_text(cache.name, encoding="ascii") @@ -478,9 +507,10 @@ def remember(source, inputs): def compile_one(source, key, bound_tools, bound_cache): # Only this job owns the source. Archive publication is separately # serialized; compiler temporary directories are private per request. - if record_requests: - return compile_request(source, key, bound_tools, bound_cache, session, remember=remember) - return compile_request(source, key, bound_tools, bound_cache, session) + options = {"remember": remember} if record_requests else {} + if persistent is not None: + options["persistent"] = persistent + return compile_request(source, key, bound_tools, bound_cache, session, **options) def complete(source, key, future=None, error=None): nonlocal refused, cached_refusals @@ -582,8 +612,10 @@ def shader_session(cache, env, report, *, archive=None): (session / "requests").mkdir() env["TUXBOX_SHADER_SESSION"] = session.name stop = Event() + helper = env.get("TUXBOX_PERSISTENT_DXC") + options = {"dxc_helper": helper} if helper else {} worker = Thread(target=serve, args=(session, stop, report, archive, runtime_jobs(env, report)), - name="shader-compiler", daemon=True) + kwargs=options, name="shader-compiler", daemon=True) worker.start() try: yield diff --git a/tests/test_persistent_dxc.py b/tests/test_persistent_dxc.py new file mode 100644 index 00000000..0c0471de --- /dev/null +++ b/tests/test_persistent_dxc.py @@ -0,0 +1,77 @@ +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +import unittest + +from project_tuxbox.persistent_dxc import PersistentDxc + + +@unittest.skipUnless(sys.platform == "linux", "The DXC helper uses Linux pipes") +class PersistentDxcTests(unittest.TestCase): + def setUp(self): + temporary = TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.dxc = self.root / "bin/dxc" + self.dxc.parent.mkdir() + self.dxc.touch() + library = self.root / "lib/libdxcompiler.so" + library.parent.mkdir() + library.touch() + self.source = self.root / "source.hlsl" + self.source.write_bytes(b"synthetic HLSL") + self.output = self.root / "out.cso" + self.report = [] + + def helper(self, body): + executable = self.root / "helper" + executable.write_text(f"#!{sys.executable}\n" + body) + executable.chmod(0o700) + return executable + + def test_replaces_crashed_helper_and_retries_before_reusing_it(self): + helper = self.helper( + """import os, sys +from pathlib import Path +for line in sys.stdin: + source = Path(line.strip()) + output = Path(sys.stdin.readline().strip()) + marker = source.with_suffix(".crashed") + if not marker.exists(): + marker.touch() + output.write_bytes(b"partial DXIL") + os._exit(3) + assert not output.exists() + output.write_bytes(f"{os.getpid()}:".encode() + source.read_bytes()) + print("ok", flush=True) +""" + ) + with PersistentDxc(helper, 1, self.report.append) as pool: + self.assertTrue(pool.compile(self.dxc, self.source, self.output)) + first = self.output.read_bytes() + pid = int(first.split(b":")[0]) + self.assertTrue(first.endswith(self.source.read_bytes())) + self.output.unlink() + self.assertTrue(pool.compile(self.dxc, self.source, self.output)) + self.assertEqual(self.output.read_bytes(), first) + self.assertFalse(Path(f"/proc/{pid}").exists()) + self.assertEqual(self.report, []) + + def test_repeated_crash_leaves_no_partial_dxil_for_cli(self): + helper = self.helper( + """import os, sys +from pathlib import Path +source = Path(sys.stdin.readline().strip()) +output = Path(sys.stdin.readline().strip()) +assert not output.exists() +with source.with_suffix(".attempts").open("ab") as log: + log.write(b"x") +output.write_bytes(b"partial DXIL") +os._exit(3) +""" + ) + with PersistentDxc(helper, 1, self.report.append) as pool: + self.assertFalse(pool.compile(self.dxc, self.source, self.output)) + self.assertFalse(self.output.exists()) + self.assertEqual(self.source.with_suffix(".attempts").read_bytes(), b"xx") + self.assertEqual(len(self.report), 1) diff --git a/tests/test_runtime_shader_links.py b/tests/test_runtime_shader_links.py index 6b01dcc2..c7491bd1 100644 --- a/tests/test_runtime_shader_links.py +++ b/tests/test_runtime_shader_links.py @@ -36,6 +36,36 @@ def setUp(self): self.cache.mkdir() self.tools = ("xshader", "dxc", "dxv") + def test_invalid_persistent_dxil_falls_back_to_cli_before_publication(self): + data = b"synthetic compute shader" + key = hashlib.sha256(data).hexdigest() + source = self.requests / (key + ".dxbc") + source.write_bytes(data) + expected = portable_program(5, b"cli") + messages = [] + calls = [] + + def persistent_compile(dxc, hlsl, output): + output.write_bytes(portable_program(0, b"wrong stage")) + return True + + def tool(args, *, timeout): + calls.append(args[0]) + if args[0] == "xshader": + args[args.index("--hlsl-out") + 1].write_text("void main() {}") + args[args.index("--profile-out") + 1].write_text("cs_6_0") + elif args[0] == "dxc": + output = args[args.index("-Fo") + 1] + self.assertFalse(output.exists()) + output.write_bytes(expected) + + persistent = SimpleNamespace(compile=persistent_compile, report=messages.append) + with patch("project_tuxbox.runtime_shaders.run_tool", side_effect=tool): + self.assertTrue(compile_request(source, key, self.tools, self.cache, self.session, persistent=persistent)) + self.assertEqual(calls, ["xshader", "dxv", "dxc", "dxv"]) + self.assertEqual((self.session / (key + ".cso")).read_bytes(), expected) + self.assertIn("using the CLI", messages[0]) + def request(self, pixel_order, pixel=b"Xbox pixel shader"): inputs = {"producer.dxbc": b"Xbox geometry shader", "pixel.dxbc": pixel, "pixel.cso": pixel_order} key = "_".join(hashlib.sha256(data).hexdigest() for data in inputs.values()) @@ -231,6 +261,23 @@ def test_rejects_native_code_non_pixel_dxil_and_non_regular_input(self): with self.assertRaises(OSError): compile_request(source, key, self.tools, self.cache, self.session) + def test_persistent_helper_has_separate_request_and_hlsl_caches(self): + release, dxc, snapshot, helper = ( + self.cache / name for name in ("release", "dxc", "snapshot", "helper") + ) + release.write_bytes(b"xshader") + dxc.write_text("#!/bin/sh\necho version\n") + dxc.chmod(0o700) + helper.write_bytes(b"helper A") + with patch("project_tuxbox.runtime_shaders.compiler_tools", return_value=(release, dxc, dxc)): + _, cli = snapshot_compiler_cache(snapshot, self.cache) + _, experimental = snapshot_compiler_cache(snapshot, self.cache, dxc_helper=helper) + helper.write_bytes(b"helper B") + _, replacement = snapshot_compiler_cache(snapshot, self.cache, dxc_helper=helper) + self.assertEqual(len({cli, experimental, replacement}), 3) + self.assertEqual(len({(cache / "dxil-identity").read_bytes() + for cache in (cli, experimental, replacement)}), 3) + def test_refusal_requires_exact_inputs_and_compiler_build(self): release, dxc, snapshot = (self.cache / name for name in ("release", "dxc", "snapshot")) dxc.write_text("#!/bin/sh\necho version\n") diff --git a/tools/benchmark_scarlett_worker.py b/tools/benchmark_scarlett_worker.py index 2598b832..d8a7dc44 100644 --- a/tools/benchmark_scarlett_worker.py +++ b/tools/benchmark_scarlett_worker.py @@ -25,6 +25,7 @@ parser.add_argument("--rounds", type=int, default=1) parser.add_argument("--count", type=int, default=64) parser.add_argument("--arrival-ms", type=float, default=0) +parser.add_argument("--dxc-helper", type=Path, help="opt-in persistent DXC helper") args = parser.parse_args() sys.path.insert(0, str(args.repo.resolve())) from project_tuxbox import runtime_shaders as worker @@ -38,7 +39,10 @@ assert has_jobs or args.jobs == 1 def hashes(): - return {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in tools} + fingerprints = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in tools} + if args.dxc_helper: + fingerprints["dxc_helper"] = hashlib.sha256(args.dxc_helper.read_bytes()).hexdigest() + return fingerprints def memory_available(): return int(next(line.split()[1] for line in Path("/proc/meminfo").read_text().splitlines() @@ -82,6 +86,8 @@ def run(cache, phase): def target(): try: kwargs = {"jobs": args.jobs} if has_jobs else {} + if args.dxc_helper: + kwargs["dxc_helper"] = args.dxc_helper.resolve() worker.serve(session, stop, logs.append, **kwargs) except BaseException as exc: errors.append(repr(exc)) diff --git a/tools/dxc_worker.cpp b/tools/dxc_worker.cpp new file mode 100644 index 00000000..a4518788 --- /dev/null +++ b/tools/dxc_worker.cpp @@ -0,0 +1,49 @@ +#include + +#include +#include +#include +#include +#include + +static void check(HRESULT status, const char *operation) { + if (FAILED(status)) throw std::runtime_error(operation); +} + +static void compile(IDxcCompiler3 *compiler, const std::string &source_path, + const std::string &output_path) { + std::ifstream input(source_path, std::ios::binary); + if (!input) throw std::runtime_error("open HLSL input"); + const std::string source{std::istreambuf_iterator{input}, {}}; + const std::wstring wide_name(source_path.begin(), source_path.end()); + LPCWSTR arguments[] = {wide_name.c_str(), L"-T", L"cs_6_0", L"-E", L"main"}; + const DxcBuffer buffer{source.data(), source.size(), DXC_CP_UTF8}; + CComPtr result; + check(compiler->Compile(&buffer, arguments, 5, nullptr, IID_PPV_ARGS(&result)), "compile call"); + HRESULT status{}; + check(result->GetStatus(&status), "read compile status"); + check(status, "compile failed"); + CComPtr bytecode; + check(result->GetOutput(DXC_OUT_OBJECT, IID_PPV_ARGS(&bytecode), nullptr), "get DXIL"); + std::ofstream output(output_path, std::ios::binary); + output.write(static_cast(bytecode->GetBufferPointer()), bytecode->GetBufferSize()); + output.close(); + if (!output) throw std::runtime_error("write DXIL"); +} + +int main() { + try { + CComPtr compiler; + check(DxcCreateInstance(CLSID_DxcCompiler, IID_PPV_ARGS(&compiler)), "create compiler"); + std::string source, output; + while (std::getline(std::cin, source)) { + if (!std::getline(std::cin, output)) throw std::runtime_error("missing output path"); + compile(compiler, source, output); + std::cout << "ok\n" << std::flush; + } + if (!std::cin.eof()) throw std::runtime_error("read compiler request"); + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 1; + } +}