From b87a99a3f14b04a2f60c3149f93c3fa4bc2d9db3 Mon Sep 17 00:00:00 2001 From: avt0m4t Date: Wed, 25 Nov 2026 01:57:35 +0300 Subject: [PATCH] tooling: resume startup shader compilation after manifest-only runs --- docs/experiments.md | 9 ++++ docs/startup-runtime.md | 2 +- tests/startup_translator_check.py | 86 ++++++++++++++++++++++++++++++- tools/startup/gfx2hlsl.py | 65 +++++++++++++++++------ 4 files changed, 143 insertions(+), 19 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 1aea0e778..54af4c467 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12,6 +12,15 @@ arguments. Identifying both masks for the affected pipeline remains open. [Refs Run commands from the repository root. Start with the [project overview](../README.md) and [contribution guide](../CONTRIBUTING.md). Package-specific observations below used local inputs. Community regression tests use fixtures built from this repository. +## Resuming startup shader compilation + +Run `python3 -B tests/startup_translator_check.py`. The check runs `--pending` in +manifest-only mode, then enables a synthetic FXC invocation and verifies that it +compiles both stages. A pixel compile failure leaves the request pending. A later +run publishes both bytecode files and clears the failure report. The next run +skips the completed request. Restart the runtime if it already read the manifest +before the bytecode was available. + ## One-dimensional texture sampling in startup draws The startup translator accepts ordinary 1D image sampling with a single coordinate and a diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 055167225..ac97b9d25 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -610,7 +610,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_XMEM_GPU_MIRROR=1` | pairs a no-access graphics reservation with the read-write reservation of the same size made just before it, and maps every physical page into both (same section) | | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | -| `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}` and, when needed, RTV variants `req_.rtv`. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running. Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` and no manifest; `X2W_FXC=` (empty) skips compilation and publishes the manifest alone. | +| `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}` and, when needed, RTV variants `req_.rtv`. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running. Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_D3D12_DUMP_SURFACE=` | writes the last presented surface | | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | diff --git a/tests/startup_translator_check.py b/tests/startup_translator_check.py index f953f8af4..818133e63 100644 --- a/tests/startup_translator_check.py +++ b/tests/startup_translator_check.py @@ -8,9 +8,13 @@ naming X2W_FXC and no manifest; with the empty X2W_FXC or check=False it publishes the manifest alone. """ import contextlib +import io import os +from pathlib import Path +import subprocess import sys import tempfile +from unittest import mock sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) import gfx2hlsl # noqa: E402 @@ -186,11 +190,91 @@ def check_negative_discovery(failures): failures.append('negative control: a Windows Kits tree with fxc.exe was not found') +def check_pending_manifest_upgrade(failures): + with tempfile.TemporaryDirectory() as work: + out = Path(work) + key = '0000000000001234' + (out / ('req_%s.a' % key)).touch() + manifest = out / (key + '.txt') + failure = out / (key + '.fail') + vs, ps = (out / (key + '.' + stage + '.cso') for stage in ('vs', 'ps')) + runs = [] + fail_pixel = True + + def compile_shader(command, **kwargs): + profile = command[command.index('/T') + 1] + runs.append(profile) + Path(command[command.index('/Fo') + 1]).write_bytes(profile.encode('ascii')) + if fail_pixel and profile == 'ps_5_1': + return subprocess.CompletedProcess(command, 1, '', 'synthetic compiler failure') + return subprocess.CompletedProcess(command, 0, '', '') + + def pending(configured): + request = ({'vs': b'', 'ps': b''}, b'', (), '', None, {}) + with fxc_environment(work, configured, os.path.join(work, 'none')), \ + mock.patch.object(sys, 'argv', ['gfx2hlsl.py', '--pending', work]), \ + mock.patch.object(gfx2hlsl, 'load_request', return_value=request), \ + mock.patch.object(subprocess, 'run', side_effect=compile_shader), \ + contextlib.redirect_stdout(io.StringIO()) as output: + gfx2hlsl.main() + return output.getvalue() + + if pending('') != '%s: ok\n' % key or not manifest.is_file() or vs.exists() or ps.exists(): + failures.append('pending manifest-only pass did not publish just the manifest and HLSL') + if pending('') or runs: + failures.append('pending manifest-only pass did not skip an existing manifest') + + fxc = out / 'fxc.exe' + fxc.touch() + if 'fxc ps failed' not in pending(str(fxc)) or runs != ['vs_5_1', 'ps_5_1']: + failures.append('pending did not compile an existing manifest when FXC became available') + if vs.exists() or ps.exists(): + failures.append('a failed compilation published partial shader bytecode') + if not failure.is_file(): + failures.append('a failed compilation did not write a failure report') + + fail_pixel = False + if pending(str(fxc)) != '%s: ok\n' % key or not all(path.is_file() for path in (vs, ps)): + failures.append('pending did not retry and publish both shader stages') + return + if (vs.read_bytes(), ps.read_bytes()) != (b'vs_5_1', b'ps_5_1'): + failures.append('pending did not publish the expected bytecode for both stages') + if failure.exists(): + failures.append('pending left a stale failure report after successful compilation') + runs.clear() + if pending(str(fxc)) or runs: + failures.append('pending recompiled an already complete translation') + ps.write_bytes(b'') + if pending(str(fxc)) != '%s: ok\n' % key or ps.read_bytes() != b'ps_5_1': + failures.append('pending did not repair an empty shader bytecode file') + + replace = os.replace + + def reject_manifest_publish(source, destination): + if Path(destination) == manifest: + raise PermissionError('synthetic manifest publication failure') + replace(source, destination) + + ps.unlink() + with mock.patch.object(StubPipeline, 'manifest', return_value='updated bindings\n'): + with mock.patch.object(os, 'replace', side_effect=reject_manifest_publish): + try: + pending(str(fxc)) + except PermissionError: + pass + else: + failures.append('pending did not attempt to publish the changed manifest') + if manifest.exists(): + failures.append('failed publication left an old manifest beside the new bytecode') + if pending(str(fxc)) != '%s: ok\n' % key or manifest.read_text() != 'updated bindings\n': + failures.append('pending did not retry an interrupted manifest publication') + + def main(): failures = [] for check in (check_wide_load, check_offset_load, check_root_descriptor, check_numeric_symbol_refusal, check_negative_control, check_missing_fxc, - check_fxc_discovery, check_negative_discovery): + check_fxc_discovery, check_negative_discovery, check_pending_manifest_upgrade): check(failures) for line in failures: print('FAIL', line) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 5df469afa..731a36fcd 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5,10 +5,12 @@ values (tables, vertex-buffer table, root buffers) turn into HLSL resources instead of arithmetic. The output is HLSL for both stages plus a manifest that tells the runtime what to bind where. """ +from contextlib import suppress import os import re import struct import sys +import tempfile sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) import disasm_rdna2 as D # noqa: E402 @@ -2004,6 +2006,13 @@ def find_fxc(): return shutil.which('fxc.exe') +def has_bytecode(path): + try: + return os.path.isfile(path) and os.path.getsize(path) > 0 + except OSError: + return False + + def translate_to(out_dir, key, vs_code, ps_code, root_blob, check=True, rtv_formats=(), rtv_request='', vs_fetch=None): """Writes .vs.hlsl, .ps.hlsl and .txt (last), or .fail with the reason. @@ -2025,18 +2034,41 @@ def translate_to(out_dir, key, vs_code, ps_code, root_blob, check=True, rtv_form message = 'fxc.exe not found (X2W_FXC=%s): set X2W_FXC to its path or install the Windows SDK' % os.environ.get('X2W_FXC', '') open(name + '.fail', 'w').write(message + '\n') return message + manifest_path = name + '.txt' + write_manifest = True if fxc: import subprocess - for stage, profile in (('vs', 'vs_5_1'), ('ps', 'ps_5_1')): - r = subprocess.run([fxc, '/nologo', '/T', profile, '/E', 'main', '/Fo', name + '.%s.cso' % stage, name + '.%s.hlsl' % stage], - capture_output=True, text=True) - if r.returncode: - open(name + '.fail', 'w').write('fxc %s: %s\n' % (stage, r.stderr[-2000:])) - return 'fxc %s failed: %s' % (stage, r.stderr.strip().splitlines()[-1] if r.stderr.strip() else '?') - temporary = '%s.txt.%d.tmp' % (name, os.getpid()) - with open(temporary, 'w') as result: - result.write(manifest) - os.replace(temporary, name + '.txt') + # An existing manifest can already point at these paths. Publish only bytecode from a successful pair. + with tempfile.TemporaryDirectory(prefix='.fxc-', dir=out_dir) as staging: + for stage, profile in (('vs', 'vs_5_1'), ('ps', 'ps_5_1')): + bytecode = os.path.join(staging, stage + '.cso') + r = subprocess.run([fxc, '/nologo', '/T', profile, '/E', 'main', '/Fo', bytecode, name + '.%s.hlsl' % stage], + capture_output=True, text=True) + if r.returncode or not has_bytecode(bytecode): + detail = r.stderr.strip() or ('?' if r.returncode else 'no bytecode produced') + open(name + '.fail', 'w').write('fxc %s: %s\n' % (stage, detail[-2000:])) + return 'fxc %s failed: %s' % (stage, detail.splitlines()[-1]) + with suppress(FileNotFoundError, UnicodeError): + with open(manifest_path) as existing: + write_manifest = existing.read() != manifest + # If the bindings changed, withdraw the old manifest before publishing new bytecode. + if write_manifest: + with suppress(FileNotFoundError): + os.remove(manifest_path) + for stage in ('vs', 'ps'): + os.replace(os.path.join(staging, stage + '.cso'), name + '.%s.cso' % stage) + if write_manifest: + temporary = '%s.%d.tmp' % (manifest_path, os.getpid()) + try: + with open(temporary, 'w') as result: + result.write(manifest) + os.replace(temporary, manifest_path) + finally: + with suppress(FileNotFoundError): + os.remove(temporary) + if fxc: + with suppress(FileNotFoundError): + os.remove(name + '.fail') return 'ok' @@ -2302,13 +2334,12 @@ def main(): for ext, blob in (('.a', a), ('.b', b), ('.root', root)): open(os.path.join(out_dir, 'req_%016x%s' % (key, ext)), 'wb').write(blob) print('pso %x -> request %016x' % (w & 0xffffff, key)) - # translate every request that has no result yet - for name in sorted(os.listdir(out_dir)): - m = re.fullmatch(r'req_([0-9a-f]{16})\.(?:a|rtv)', name) - if not m: - continue - key = int(m.group(1), 16) - if os.path.exists(os.path.join(out_dir, '%016x.txt' % key)): + manifest_only = os.environ.get('X2W_FXC') == '' + for key in request_keys(out_dir): + name = os.path.join(out_dir, '%016x' % key) + if os.path.isfile(name + '.txt') and ( + manifest_only or (has_bytecode(name + '.vs.cso') and has_bytecode(name + '.ps.cso')) + ): continue print('%016x: %s' % (key, translate_request(out_dir, key)))