diff --git a/docs/experiments/native-compile-dxil-rekey.md b/docs/experiments/native-compile-dxil-rekey.md new file mode 100644 index 0000000000..0a886e986c --- /dev/null +++ b/docs/experiments/native-compile-dxil-rekey.md @@ -0,0 +1,44 @@ +# Native cache re-keying (`compile_dxil --rekey`) + +Added `--rekey` to `tools/startup/compile_dxil.cpp` as the native C++ equivalent of +`tools/startup/shader_cache_rekey.py` (`Refs #2935`). + +## Usage + +```powershell +compile_dxil --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N] +``` + +This mode runs without `SDK_DIRECTORY` or DXC: + +- Scans `OLD_CACHE_DIR` (non-recursively) for `req_<16-hex>` markers (`.a`, `.c67`, + `.m57`, `.rtv`), counts `.m86` markers, and ignores result/diagnostic files + (`.txt`, `.fail`, `.cso`, `.psdep`). +- Validates and recomputes keys in parallel using the current output revision + strings (`x2w-startup-shader-29`, `x2w-startup-shader-29cs`, + `x2w-startup-mesh-57-3` via shared helpers in `src/shader_compute_request.cpp`), + while the readers retain `x2w-startup-shader-28` and `x2w-startup-shader-28cs` + input compatibility. +- Rewrites `.psin` and `.rtv` payloads under their updated keys while leaving all + shader bytecode/root/layout parts intact. +- Fails with exit code `1` before creating or writing `NEW_REQUEST_DIR` if any + request is incomplete, unreadable, or malformed; exits `2` on invalid CLI usage + or when `OLD_CACHE_DIR` and `NEW_REQUEST_DIR` refer to the same directory. +- Publishes files atomically (ready markers `.a`, `.c67`, `.m57` written last) + and preserves already-present files in `NEW_REQUEST_DIR`. + +## Verification + +Build `compile_dxil` and run the native rekey parity and control check: + +```powershell +.\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target compile_dxil +ctest --preset release --no-tests=error -V -R '^native_compile_dxil_rekey$' +``` + +Expected: `native_compile_dxil_rekey` exits `0` and verifies byte-for-byte parity +with `tools/startup/shader_cache_rekey.py`, `gfx2hlsl.pending_keys` compatibility, +idempotency, read-only preservation of `OLD_CACHE_DIR`, and all incomplete-request +and CLI negative controls. diff --git a/src/shader_compute_request.cpp b/src/shader_compute_request.cpp index bd9e785b1b..7f3d956b9e 100644 --- a/src/shader_compute_request.cpp +++ b/src/shader_compute_request.cpp @@ -53,17 +53,16 @@ uint64_t parse_request_stem(std::string_view stem, const char *error_message) { throw std::runtime_error(error_message); return expected; } -void parse_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, Bytes &description) { - fs::path path = marker; - path.replace_extension(".psin"); - std::ifstream file(path, std::ios::binary | std::ios::ate); - const auto size = file.tellg(); - if (size < 0 || size > 128) - throw std::runtime_error("invalid pixel input description"); - Bytes raw(static_cast(size), 0); - file.seekg(0); - if (size && !file.read(raw.data(), size)) - throw std::runtime_error("short read"); +} // namespace + +std::string x2w::format_pixel_input_description(uint64_t key, uint32_t ena, uint32_t addr) { + char text[64]; + std::snprintf(text, sizeof(text), "psin1 %016llx ena=0x%04x addr=0x%04x\n", + static_cast(key), ena, addr); + return text; +} + +x2w::PixelInputDescription x2w::parse_pixel_input_description(std::string_view raw, uint64_t expected) { std::string_view line = raw; if (!line.empty() && line.back() == '\n') line.remove_suffix(1); @@ -114,30 +113,20 @@ void parse_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, throw std::runtime_error("pixel input address mask missing from the stream description"); if (ena & ~addr) throw std::runtime_error("contradictory pixel input enable/address masks"); - entry.assign("psin1", 5); + PixelInputDescription parsed; + parsed.ena = ena; + parsed.addr = addr; + parsed.entry.assign("psin1", 5); const uint32_t words[2]{ena, addr}; - entry.append(reinterpret_cast(words), sizeof(words)); - char text[64]; - std::snprintf(text, sizeof(text), "psin1 %016llx ena=0x%04x addr=0x%04x\n", - static_cast(expected), ena, addr); - description = text; + parsed.entry.append(reinterpret_cast(words), sizeof(words)); + parsed.canonical_text = format_pixel_input_description(expected, ena, addr); + return parsed; } -// tools/startup/gfx2hlsl.py request_source: at most 256 bytes of "rtv1 ..." in decimal with one to -// eight formats and nothing else, whose FNV-1a hash is the key in the file name. The variant is translated from its -// base request's parts, which are read and checked against the base key like any base request. -x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { - const auto stem = marker.stem().string(); - if (stem.size() != 20 || stem.compare(0, 4, "req_")) - throw std::runtime_error("expected req_<16 hex digits>.rtv"); - const uint64_t expected = parse_request_stem(stem, "invalid RTV variant request key"); - Bytes text; - try { - text = part(marker, ".rtv", 256); - } catch (const std::runtime_error &) { + +x2w::RtvVariantDescription x2w::parse_rtv_variant_text(std::string_view text, uint64_t expected) { + if (text.size() > 256) throw std::runtime_error("invalid RTV variant request"); - } - uint64_t key = 1469598103934665603ull; - hash_bytes(key, text.data(), text.size()); + const uint64_t key = fnv1a_64(text); std::vector tokens; std::string_view rest = text; bool valid = rest.substr(0, 5) == "rtv1 "; @@ -153,18 +142,102 @@ x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { } if (!valid || tokens.size() < 2 || tokens.size() > 9 || key != expected) throw std::runtime_error("invalid RTV variant request"); - uint64_t base = 0; - std::vector formats; + RtvVariantDescription result; for (size_t i = 0; i < tokens.size(); ++i) { uint64_t value = 0; const auto parsed = std::from_chars(tokens[i].data(), tokens[i].data() + tokens[i].size(), value); if (parsed.ec != std::errc{} || (i && value > 0xffffffffull)) throw std::runtime_error("invalid RTV variant values"); - if (!i) base = value; - else formats.push_back(static_cast(value)); + if (!i) result.base_key = value; + else result.formats.push_back(static_cast(value)); + } + return result; +} + +std::string x2w::format_rtv_variant_text(uint64_t base_key, const std::vector &formats) { + std::string out = "rtv1 " + std::to_string(base_key); + for (unsigned format : formats) { + out.push_back(' '); + out += std::to_string(format); + } + return out; +} + +uint64_t x2w::fnv1a_64(std::string_view bytes) { + uint64_t key = 1469598103934665603ull; + hash_bytes(key, bytes.data(), bytes.size()); + return key; +} + +uint64_t x2w::graphics_request_key(std::string_view a, std::string_view b, std::string_view root, + std::string_view input_layout, std::string_view pixel_entry, + std::string_view revision_override) { + constexpr char revision[] = "x2w-startup-shader-29"; + uint64_t key = fnv1a_64(revision_override.empty() ? std::string_view(revision, sizeof(revision) - 1) + : revision_override); + for (const auto part_view : {a, b, root, input_layout, pixel_entry}) + hash_bytes(key, part_view.data(), part_view.size()); + return key; +} + +uint64_t x2w::compute_request_key(std::string_view code, std::string_view data, std::string_view root, + std::string_view description, std::string_view sa, std::string_view sb, + std::string_view revision_override) { + constexpr char revision[] = "x2w-startup-shader-29cs"; + uint64_t key = fnv1a_64(revision_override.empty() ? std::string_view(revision, sizeof(revision) - 1) + : revision_override); + for (const auto part_view : {code, data, root, description, sa, sb}) { + const uint64_t size = part_view.size(); + hash_bytes(key, &size, sizeof(size)); + hash_bytes(key, part_view.data(), part_view.size()); } + return key; +} + +uint64_t x2w::mesh57_request_key(std::string_view code, std::string_view ps57, std::string_view root) { + constexpr char revision[] = "x2w-startup-mesh-57-3"; + uint64_t key = fnv1a_64(std::string_view(revision, sizeof(revision) - 1)); + for (const auto part_view : {code, ps57, root}) { + const uint64_t size = part_view.size(); + hash_bytes(key, &size, sizeof(size)); + hash_bytes(key, part_view.data(), part_view.size()); + } + return key; +} + +namespace { +void parse_pixel_inputs(const fs::path &marker, uint64_t expected, Bytes &entry, Bytes &description) { + fs::path path = marker; + path.replace_extension(".psin"); + std::ifstream file(path, std::ios::binary | std::ios::ate); + const auto size = file.tellg(); + if (size < 0 || size > 128) + throw std::runtime_error("invalid pixel input description"); + Bytes raw(static_cast(size), 0); + file.seekg(0); + if (size && !file.read(raw.data(), size)) + throw std::runtime_error("short read"); + auto parsed = x2w::parse_pixel_input_description(raw, expected); + entry = std::move(parsed.entry); + description = std::move(parsed.canonical_text); +} +// tools/startup/gfx2hlsl.py request_source: at most 256 bytes of "rtv1 ..." in decimal with one to +// eight formats and nothing else, whose FNV-1a hash is the key in the file name. The variant is translated from its +// base request's parts, which are read and checked against the base key like any base request. +x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { + const auto stem = marker.stem().string(); + if (stem.size() != 20 || stem.compare(0, 4, "req_")) + throw std::runtime_error("expected req_<16 hex digits>.rtv"); + const uint64_t expected = parse_request_stem(stem, "invalid RTV variant request key"); + Bytes text; + try { + text = part(marker, ".rtv", 256); + } catch (const std::runtime_error &) { + throw std::runtime_error("invalid RTV variant request"); + } + auto parsed = x2w::parse_rtv_variant_text(text, expected); char name[32]; - std::snprintf(name, sizeof(name), "req_%016llx.a", static_cast(base)); + std::snprintf(name, sizeof(name), "req_%016llx.a", static_cast(parsed.base_key)); x2w::GraphicsRequest request; try { request = x2w::read_graphics_request(marker.parent_path() / name); @@ -173,7 +246,7 @@ x2w::GraphicsRequest read_rtv_variant(const fs::path &marker) { } request.key = expected; request.rtv_request = std::move(text); - request.rtv_formats = std::move(formats); + request.rtv_formats = std::move(parsed.formats); return request; } } // namespace @@ -190,18 +263,13 @@ x2w::GraphicsRequest x2w::read_graphics_request(const fs::path &marker) { request.input_layout = part(marker, ".ia", 1 << 20); if (fs::exists(fs::path(marker).replace_extension(".psin"))) parse_pixel_inputs(marker, expected, request.pixel_entry, request.pixel_input_description); - const auto request_key = [&](std::string_view revision) { - uint64_t key = 1469598103934665603ull; - hash_bytes(key, revision.data(), revision.size()); - for (const auto *p : {&request.a, &request.b, &request.root, &request.input_layout, &request.pixel_entry}) - hash_bytes(key, p->data(), p->size()); - return key; - }; if (request.root.empty()) throw std::runtime_error("graphics request key mismatch or missing root"); // Match new runtime captures and keep revision-28 archives replayable. - constexpr char revision[] = "x2w-startup-shader-29"; - if (request_key(revision) != expected && request_key("x2w-startup-shader-28") != expected) { + if (x2w::graphics_request_key(request.a, request.b, request.root, request.input_layout, request.pixel_entry) != + expected && + x2w::graphics_request_key(request.a, request.b, request.root, request.input_layout, request.pixel_entry, + "x2w-startup-shader-28") != expected) { if (!request.pixel_entry.empty()) throw std::runtime_error("stale pixel input description: graphics request key mismatch"); throw std::runtime_error("graphics request key mismatch or missing root"); @@ -220,18 +288,8 @@ x2w::ComputeRequest x2w::read_compute_request(const fs::path &marker) { if (desc.size() != 96 || read(desc, 48) != code.size() || read(desc, 64) != data.size() || read(desc, 16) != sa.size() || read(desc, 32) != sb.size()) throw std::runtime_error("inconsistent compute request"); - const auto request_key = [&](std::string_view revision) { - uint64_t key = 1469598103934665603ull; - hash_bytes(key, revision.data(), revision.size()); - for (const auto *p : {&code, &data, &root, &desc, &sa, &sb}) { - uint64_t size = p->size(); - hash_bytes(key, &size, sizeof(size)); - hash_bytes(key, p->data(), p->size()); - } - return key; - }; - constexpr char revision[] = "x2w-startup-shader-29cs"; - if (request_key(revision) != expected && request_key("x2w-startup-shader-28cs") != expected) + if (x2w::compute_request_key(code, data, root, desc, sa, sb) != expected && + x2w::compute_request_key(code, data, root, desc, sa, sb, "x2w-startup-shader-28cs") != expected) throw std::runtime_error("compute request key mismatch"); if (root.empty() || sa.size() != 28 || code.empty() || data.empty() || code.size() % 4) throw std::runtime_error(sa.size() != 28 ? "compute state block A is not 28 bytes" diff --git a/src/shader_compute_request.h b/src/shader_compute_request.h index 1e1cd39dd8..10ea8328a3 100644 --- a/src/shader_compute_request.h +++ b/src/shader_compute_request.h @@ -2,9 +2,35 @@ #include #include #include +#include #include namespace x2w { +uint64_t fnv1a_64(std::string_view bytes); +uint64_t graphics_request_key(std::string_view a, std::string_view b, std::string_view root, + std::string_view input_layout = {}, std::string_view pixel_entry = {}, + std::string_view revision = {}); +uint64_t compute_request_key(std::string_view code, std::string_view data, std::string_view root, + std::string_view description, std::string_view sa, std::string_view sb, + std::string_view revision = {}); +uint64_t mesh57_request_key(std::string_view code, std::string_view ps57, std::string_view root); + +struct PixelInputDescription { + uint32_t ena{}; + uint32_t addr{}; + std::string entry; + std::string canonical_text; +}; +PixelInputDescription parse_pixel_input_description(std::string_view text, uint64_t expected_key); +std::string format_pixel_input_description(uint64_t key, uint32_t ena, uint32_t addr); + +struct RtvVariantDescription { + uint64_t base_key{}; + std::vector formats; +}; +RtvVariantDescription parse_rtv_variant_text(std::string_view text, uint64_t expected_key); +std::string format_rtv_variant_text(uint64_t base_key, const std::vector &formats); + struct ComputeRequest { std::string code, data, root, description, sa, sb; uint64_t key; diff --git a/tests/cmake/native_compile_dxil_rekey.cmake b/tests/cmake/native_compile_dxil_rekey.cmake new file mode 100644 index 0000000000..25559ea344 --- /dev/null +++ b/tests/cmake/native_compile_dxil_rekey.cmake @@ -0,0 +1,7 @@ +# Native cache re-keying (--rekey) in compile_dxil (#2935). +if(TARGET compile_dxil) + add_test(NAME native_compile_dxil_rekey COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compile_dxil_rekey_check.py" + "$") + set_tests_properties(native_compile_dxil_rekey PROPERTIES TIMEOUT 60) +endif() diff --git a/tests/native_compile_dxil_rekey_check.py b/tests/native_compile_dxil_rekey_check.py new file mode 100644 index 0000000000..390540d99d --- /dev/null +++ b/tests/native_compile_dxil_rekey_check.py @@ -0,0 +1,262 @@ +"""Tests for `compile_dxil --rekey` parity with `tools/startup/shader_cache_rekey.py`.""" +import hashlib +import importlib.util +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +STARTUP = ROOT / 'tools' / 'startup' +REKEY_PY = STARTUP / 'shader_cache_rekey.py' +sys.path.insert(0, str(STARTUP)) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(name, ok, detail=''): + print('%s: %s%s' % ('ok' if ok else 'FAIL', name, (' (%s)' % detail) if detail and not ok else '')) + if not ok: + failures.append(name) + + +def older_revision_module(): + text = (STARTUP / 'gfx2hlsl.py').read_text(encoding='utf-8') + literal = re.compile(r"b'x2w-startup-shader-([0-9]+)(cs)?'") + found = literal.findall(text) + assert sorted(suffix for _, suffix in found) == ['', 'cs'] and len({n for n, _ in found}) == 1 + number = int(found[0][0]) - 1 + module = importlib.util.module_from_spec(importlib.util.spec_from_loader('gfx2hlsl_%d' % number, loader=None)) + module.__file__ = str(STARTUP / 'gfx2hlsl.py') + exec(compile(literal.sub(lambda m: "b'x2w-startup-shader-%d%s'" % (number, m.group(2) or ''), text), + module.__file__, 'exec'), module.__dict__) + return module + + +def graphics(index, layout=b''): + vs = struct.pack('<4I', 0x7e000280 + index, 0x01020304, index, 0xbf810000) + ps = struct.pack('<3I', 0x7e020281, index * 7, 0xbf810000) + parts = {'.b': ps, '.root': b'RTS0 synthetic root %d' % index, '.a': vs} + if layout: + parts['.ia'] = layout + return parts + + +def gkey(module, parts, ps_inputs=None): + return module.pipeline_key(parts['.a'], parts['.b'], parts['.root'], parts.get('.ia', b''), ps_inputs) + + +COMPUTE = {'.desc': struct.pack('<12Q', *range(12)), '.sa': struct.pack('<7I', *range(7)), '.sb': b'\x05' * 20, + '.data': struct.pack('<2Q', 0x1122334455667788, 0x99), '.root': b'RTS0 synthetic compute root', + '.c67': struct.pack('<2I', 0x7e020280, 0xbf810000)} +MESH_OLD = {'.ps57': b'', '.root': b'RTS0 synthetic mesh root', '.m57': b'synthetic mesh'} +MESH_CURRENT = {'.ps57': b'synthetic pixel stage', '.root': b'RTS0 synthetic mesh root', + '.m57': b'another synthetic mesh'} + + +def write_request(directory, key, parts): + for ext, data in parts.items(): + (directory / ('req_%016x%s' % (key, ext))).write_bytes(data) + + +def write_rtv(directory, base): + text = ('rtv1 %d 28 87' % base).encode('ascii') + key = G.fnv(text) + (directory / ('req_%016x.rtv' % key)).write_bytes(text) + return key + + +def snapshot(directory): + return {p.name: (hashlib.sha256(p.read_bytes()).hexdigest(), p.stat().st_mtime_ns) + for p in sorted(directory.iterdir())} + + +def contents(directory): + return {p.name: p.read_bytes() for p in sorted(directory.iterdir())} + + +def run_cpp(exe, *args): + return subprocess.run([str(exe), '--rekey', *[str(a) for a in args]], + capture_output=True, text=True, timeout=60) + + +def check_revision_strings(): + cpp_req = (ROOT / 'src' / 'shader_compute_request.cpp').read_text(encoding='utf-8') + draw_inl = (ROOT / 'src' / 'startup_stubs' / 'd3d12_draw.inl').read_text(encoding='utf-8') + py_text = (STARTUP / 'gfx2hlsl.py').read_text(encoding='utf-8') + for token in ('x2w-startup-shader-29', 'x2w-startup-shader-29cs', 'x2w-startup-mesh-57-3'): + ok = (token in cpp_req) and (token in draw_inl) and (token in py_text) + check('revision string %s matches across C++ and Python' % token, ok) + + +def main(): + if len(sys.argv) != 2: + print('usage: native_compile_dxil_rekey_check.py ', file=sys.stderr) + return 2 + exe = Path(sys.argv[1]) + check('compile_dxil executable exists', exe.is_file(), str(exe)) + check_revision_strings() + + older = older_revision_module() + g1 = graphics(1) + g2 = graphics(2, b'synthetic layout POSITION 0 R32G32B32_FLOAT') + g3 = graphics(3) + psin_masks = (0x0003, 0x000f) + + with tempfile.TemporaryDirectory(prefix='x2w-native-rekey-') as tmp: + tmp = Path(tmp) + src = tmp / 'old_cache' + src.mkdir() + + k1_old = gkey(older, g1) + k2_old = gkey(older, g2) + k3_old = gkey(older, g3, psin_masks) + k1_cur = gkey(G, g1) + k2_cur = gkey(G, g2) + k3_cur = gkey(G, g3, psin_masks) + c_old = older.compute_key(COMPUTE['.c67'], COMPUTE['.data'], COMPUTE['.root'], + COMPUTE['.desc'], COMPUTE['.sa'], COMPUTE['.sb']) + c_cur = G.compute_key(COMPUTE['.c67'], COMPUTE['.data'], COMPUTE['.root'], + COMPUTE['.desc'], COMPUTE['.sa'], COMPUTE['.sb']) + m_old_key = G.mesh57_key(MESH_OLD['.m57'], MESH_OLD['.ps57'], MESH_OLD['.root']) ^ 1 + m_old_cur = G.mesh57_key(MESH_OLD['.m57'], MESH_OLD['.ps57'], MESH_OLD['.root']) + m_cur_key = G.mesh57_key(MESH_CURRENT['.m57'], MESH_CURRENT['.ps57'], MESH_CURRENT['.root']) + + write_request(src, k1_old, g1) + write_request(src, k2_old, g2) + g3_old_parts = dict(g3) + g3_old_parts['.psin'] = ('psin1 %016x ena=0x%04x addr=0x%04x\n' % (k3_old, *psin_masks)).encode('ascii') + write_request(src, k3_old, g3_old_parts) + write_request(src, k1_cur, g1) # duplicate current copy of g1 + write_request(src, c_old, COMPUTE) + write_request(src, m_old_key, MESH_OLD) + write_request(src, m_cur_key, MESH_CURRENT) + old_rtv = write_rtv(src, k1_old) + write_request(src, 0x123456789abcdef0, {'.m86': b'synthetic slot 86'}) + + # Non-request outputs and diagnostics that must never be copied. + (src / ('%016x.txt' % k1_old)).write_bytes(b'synthetic manifest\n') + (src / ('%016x.fail' % k2_old)).write_bytes(b'synthetic refusal\n') + (src / ('%016x.vs.cso' % k1_old)).write_bytes(b'DXBC...') + (src / ('%016x.psdep' % k3_old)).write_bytes(b'psin1 ...\n') + + before_src = snapshot(src) + + dst_cpp = tmp / 'dst_cpp' + dst_py = tmp / 'dst_py' + res_cpp = run_cpp(exe, src, dst_cpp, '--jobs', '2') + res_py = subprocess.run([sys.executable, '-B', str(REKEY_PY), str(src), str(dst_py)], + capture_output=True, text=True, timeout=60) + + check('compile_dxil --rekey exits 0', res_cpp.returncode == 0, res_cpp.stdout + res_cpp.stderr) + check('shader_cache_rekey.py exits 0', res_py.returncode == 0, res_py.stdout + res_py.stderr) + check('byte-for-byte parity with shader_cache_rekey.py', + dst_cpp.is_dir() and contents(dst_cpp) == contents(dst_py)) + check('only req_* files copied (no .txt/.fail/.cso/.psdep)', + all(name.startswith('req_') for name in contents(dst_cpp))) + + rtv_cur = G.fnv(('rtv1 %d 28 87' % k1_cur).encode('ascii')) + check('rewritten .psin names new key with preserved masks', + (dst_cpp / ('req_%016x.psin' % k3_cur)).read_bytes() == + ('psin1 %016x ena=0x%04x addr=0x%04x\n' % (k3_cur, *psin_masks)).encode('ascii')) + check('rewritten .rtv names new base key', + rtv_cur != old_rtv and + (dst_cpp / ('req_%016x.rtv' % rtv_cur)).read_bytes() == ('rtv1 %d 28 87' % k1_cur).encode('ascii')) + + check('summary graphics line', + 'graphics: 4 requests, 1 already current -> 3 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary compute line', + 'compute: 1 requests, 0 already current -> 1 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary m57 line', + 'm57: 2 requests, 1 already current -> 2 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary rtv line', + 'rtv variants: 1 requests -> 1 keys' in res_cpp.stdout, res_cpp.stdout) + check('summary m86 line', + 'not re-keyed (own key strings): m86 1' in res_cpp.stdout, res_cpp.stdout) + + expected_pending = sorted({k1_cur, k2_cur, k3_cur, c_cur, m_old_cur, m_cur_key, rtv_cur}) + check('gfx2hlsl.pending_keys recognizes re-keyed cache', + G.pending_keys(str(dst_cpp), False) == expected_pending, + str(G.pending_keys(str(dst_cpp), False))) + + # --jobs 1 matches --jobs 2 + dst_j1 = tmp / 'dst_j1' + res_j1 = run_cpp(exe, src, dst_j1, '--jobs', '1') + check('--jobs 1 produces identical contents to --jobs 2', + res_j1.returncode == 0 and contents(dst_j1) == contents(dst_cpp), res_j1.stderr) + + # Idempotency (second run writes 0 files and touches nothing) + snap_dst = snapshot(dst_cpp) + second = run_cpp(exe, src, dst_cpp) + total_files = len(snap_dst) + check('second run is idempotent (0 written)', + second.returncode == 0 and ('files: 0 written, %d already present' % total_files) in second.stdout, + second.stdout + second.stderr) + check('second run leaves mtimes and contents unchanged', snapshot(dst_cpp) == snap_dst) + + # Re-keying an already current cache preserves every name and reports all current + dst_again = tmp / 'dst_again' + third = run_cpp(exe, dst_cpp, dst_again) + check('re-keying current cache preserves names and reports all current', + third.returncode == 0 and contents(dst_again) == contents(dst_cpp) + and 'graphics: 3 requests, 3 already current -> 3 keys' in third.stdout + and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout + and 'm57: 2 requests, 2 already current -> 2 keys' in third.stdout, + third.stdout + third.stderr) + + # Incomplete/malformed negative controls (exit 1, write nothing, dst not created) + bad_cases = [ + ('graphics missing .root', 8, lambda d: (d / ('req_%016x.root' % k2_old)).unlink()), + ('graphics psin wrong key', 8, + lambda d: (d / ('req_%016x.psin' % k3_old)).write_bytes( + ('psin1 %016x ena=0x0003 addr=0x000f\n' % (k3_old ^ 1)).encode('ascii'))), + ('graphics psin contradictory masks', 8, + lambda d: (d / ('req_%016x.psin' % k3_old)).write_bytes( + ('psin1 %016x ena=0x0010 addr=0x0001\n' % k3_old).encode('ascii'))), + ('compute missing .sa', 8, lambda d: (d / ('req_%016x.sa' % c_old)).unlink()), + ('mesh57 missing .ps57', 8, lambda d: (d / ('req_%016x.ps57' % m_old_key)).unlink()), + ('truncated .rtv', 8, + lambda d: (d / ('req_%016x.rtv' % old_rtv)).write_bytes(b'rtv1 123')), + ('missing .rtv base', 7, lambda d: (d / ('req_%016x.a' % k1_old)).unlink()), + ] + for label, expected_total, damage in bad_cases: + bad_src = tmp / ('bad_' + label.replace(' ', '_').replace('.', '')) + bad_dst = tmp / ('out_' + label.replace(' ', '_').replace('.', '')) + shutil.copytree(src, bad_src) + damage(bad_src) + res = run_cpp(exe, bad_src, bad_dst) + check('%s exits 1' % label, res.returncode == 1, '%d %s' % (res.returncode, res.stderr)) + check('%s reports failure count without writing' % label, + ('error: 1 of %d requests are incomplete or unreadable; nothing written' % expected_total) in res.stderr + and not bad_dst.exists(), + res.stderr) + + # CLI negative controls (exit 2) + reg_file = tmp / 'regular_file.txt' + reg_file.write_bytes(b'not a dir') + cli_cases = [ + ('src == dst', [src, src]), + ('missing args', [src]), + ('extra args', [src, tmp / 'x', tmp / 'y']), + ('unknown flag', [src, tmp / 'x', '--bogus']), + ('missing src dir', [tmp / 'does_not_exist', tmp / 'x']), + ('dst is regular file', [src, reg_file]), + ('jobs 0', [src, tmp / 'x', '--jobs', '0']), + ('jobs 65', [src, tmp / 'x', '--jobs', '65']), + ] + for label, cli_args in cli_cases: + res = run_cpp(exe, *cli_args) + check('CLI %s exits 2' % label, res.returncode == 2, '%d %s' % (res.returncode, res.stderr)) + + check('old cache completely unchanged', snapshot(src) == before_src) + + print('%d failed' % len(failures) if failures else 'all checks passed') + return 1 if failures else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/startup/compile_dxil.cpp b/tools/startup/compile_dxil.cpp index 94ee24896c..e642d227b8 100644 --- a/tools/startup/compile_dxil.cpp +++ b/tools/startup/compile_dxil.cpp @@ -1,6 +1,7 @@ #include "shader_dxil_compiler.h" #include "direct_compute_cache.h" #include "native_compute_output.h" +#include "shader_compute_request.h" #include "gfx1013_pixel.h" #include "gfx1013_sampled_pixel.h" #include "gfx1013_vertex_id.h" @@ -892,7 +893,390 @@ static int run_watch(int argc, wchar_t** argv) { } } +static std::string format_key16(uint64_t key) { + char buf[20]; + std::snprintf(buf, sizeof(buf), "%016llx", static_cast(key)); + return std::string(buf); +} + +static fs::path rekey_request_path(const fs::path& dir, const std::string& hex16, const char* ext) { + return dir / ("req_" + hex16 + ext); +} + +static bool read_rekey_bytes(const fs::path& path, size_t max_bytes, std::string& out, std::string& error) { + std::error_code ec; + if (!fs::is_regular_file(path, ec)) { + error = "unreadable " + path.filename().string() + ": not a regular file"; + return false; + } + const auto file_bytes = fs::file_size(path, ec); + if (ec || file_bytes > max_bytes) { + error = "unreadable " + path.filename().string() + ": " + (ec ? ec.message() : "oversized file"); + return false; + } + std::ifstream file(path, std::ios::binary); + if (!file) { + error = "unreadable " + path.filename().string() + ": cannot open"; + return false; + } + out.assign(static_cast(file_bytes), '\0'); + if (file_bytes && !file.read(out.data(), static_cast(file_bytes))) { + error = "unreadable " + path.filename().string() + ": short read"; + return false; + } + return true; +} + +static void publish_rekey_file(const fs::path& dst_file, const void* data, size_t size, + size_t& written, size_t& kept) { + std::error_code ec; + if (fs::exists(dst_file, ec)) { + ++kept; + return; + } + if (ec) + throw fs::filesystem_error("cannot inspect destination file", dst_file, ec); + publish_atomic(dst_file, data, size); + ++written; +} + +static int run_rekey(int argc, wchar_t** argv) { + fs::path src_dir, dst_dir; + int positional = 0; + unsigned hw_threads = std::thread::hardware_concurrency(); + int jobs = static_cast((std::min)(64u, (std::max)(1u, hw_threads))); + auto usage = []() { + std::cerr << "usage: compile_dxil --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N]\n"; + return 2; + }; + for (int i = 2; i < argc; ++i) { + const std::wstring_view arg = argv[i]; + if (arg == L"--jobs") { + if (i + 1 >= argc) + return usage(); + try { + jobs = parse_jobs_count(argv[++i]); + } catch (const std::exception& error) { + std::cerr << "error: " << error.what() << '\n'; + return 2; + } + } else if (!arg.empty() && arg.front() == L'-') { + return usage(); + } else { + if (positional == 0) src_dir = fs::path(arg); + else if (positional == 1) dst_dir = fs::path(arg); + else return usage(); + ++positional; + } + } + if (positional != 2) + return usage(); + + std::error_code ec; + if (!fs::is_directory(src_dir, ec)) { + std::cerr << "error: " << src_dir.string() << " is not a directory\n"; + return 2; + } + if (fs::exists(dst_dir, ec)) { + if (!fs::is_directory(dst_dir, ec)) { + std::cerr << "error: " << dst_dir.string() << " is not a directory\n"; + return 2; + } + if (fs::equivalent(src_dir, dst_dir, ec)) { + std::cerr << "error: the new request dir must not be the old cache\n"; + return 2; + } + } else if (ec) { + std::cerr << "error: cannot inspect " << dst_dir.string() << ": " << ec.message() << '\n'; + return 2; + } + + enum class Kind { graphics, compute, m57 }; + struct Marker { + Kind kind; + uint64_t old_key = 0; + std::string old_hex; + }; + struct RtvMarker { + uint64_t old_key = 0; + std::string old_hex; + }; + + std::vector graphics_markers, compute_markers, m57_markers; + std::vector rtv_markers; + size_t m86_count = 0; + + try { + for (const auto& entry : fs::directory_iterator(src_dir)) { + if (!entry.is_regular_file(ec)) { + ec.clear(); + continue; + } + const fs::path path = entry.path(); + const std::wstring wname = path.filename().wstring(); + if (wname.size() < 22 || wname.rfind(L"req_", 0) != 0) + continue; + const std::wstring wstem = path.stem().wstring(); + if (wstem.size() != 20) + continue; + const std::wstring_view whex = std::wstring_view(wstem).substr(4); + if (!is_lower_hex16(whex)) + continue; + std::string hex16; + hex16.reserve(16); + for (wchar_t ch : whex) + hex16.push_back(static_cast(ch)); + uint64_t old_key = 0; + const auto parsed = std::from_chars(hex16.data(), hex16.data() + hex16.size(), old_key, 16); + if (parsed.ec != std::errc{} || parsed.ptr != hex16.data() + hex16.size()) + continue; + const std::wstring ext = path.extension().wstring(); + if (ext == L".a") + graphics_markers.push_back({Kind::graphics, old_key, std::move(hex16)}); + else if (ext == L".c67") + compute_markers.push_back({Kind::compute, old_key, std::move(hex16)}); + else if (ext == L".m57") + m57_markers.push_back({Kind::m57, old_key, std::move(hex16)}); + else if (ext == L".rtv") + rtv_markers.push_back({old_key, std::move(hex16)}); + else if (ext == L".m86") + ++m86_count; + } + } catch (const fs::filesystem_error& error) { + std::cerr << "error: cannot list " << src_dir.string() << ": " << error.what() << '\n'; + return 1; + } + + auto by_old_key = [](const auto& a, const auto& b) { return a.old_key < b.old_key; }; + std::sort(graphics_markers.begin(), graphics_markers.end(), by_old_key); + std::sort(compute_markers.begin(), compute_markers.end(), by_old_key); + std::sort(m57_markers.begin(), m57_markers.end(), by_old_key); + std::sort(rtv_markers.begin(), rtv_markers.end(), by_old_key); + + std::vector work; + work.reserve(graphics_markers.size() + compute_markers.size() + m57_markers.size()); + work.insert(work.end(), graphics_markers.begin(), graphics_markers.end()); + work.insert(work.end(), compute_markers.begin(), compute_markers.end()); + work.insert(work.end(), m57_markers.begin(), m57_markers.end()); + + struct WorkResult { + uint64_t new_key = 0; + bool has_ia = false; + bool has_psin = false; + std::string rewritten_psin; + std::string error; + }; + std::vector results(work.size()); + + auto hash_item = [&](size_t idx) { + const Marker& m = work[idx]; + WorkResult& res = results[idx]; + std::string err; + try { + if (m.kind == Kind::graphics) { + std::string a, b, root, ia, psin_raw; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".b"), 64ull << 20, b, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".root"), 16ull << 20, root, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".a"), 64ull << 20, a, err)) { + res.error = std::move(err); + return; + } + const fs::path ia_path = rekey_request_path(src_dir, m.old_hex, ".ia"); + std::error_code file_ec; + if (fs::is_regular_file(ia_path, file_ec)) { + if (!read_rekey_bytes(ia_path, 1ull << 20, ia, err)) { + res.error = std::move(err); + return; + } + res.has_ia = true; + } + const fs::path psin_path = rekey_request_path(src_dir, m.old_hex, ".psin"); + std::string psin_entry; + if (fs::is_regular_file(psin_path, file_ec)) { + if (!read_rekey_bytes(psin_path, 128, psin_raw, err)) { + res.error = std::move(err); + return; + } + auto parsed_psin = x2w::parse_pixel_input_description(psin_raw, m.old_key); + psin_entry = std::move(parsed_psin.entry); + res.has_psin = true; + res.new_key = x2w::graphics_request_key(a, b, root, ia, psin_entry); + res.rewritten_psin = x2w::format_pixel_input_description(res.new_key, parsed_psin.ena, parsed_psin.addr); + } else { + res.new_key = x2w::graphics_request_key(a, b, root, ia); + } + } else if (m.kind == Kind::compute) { + std::string desc, sa, sb, data, root, c67; + constexpr size_t limit = 64ull << 20; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".desc"), limit, desc, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".sa"), limit, sa, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".sb"), limit, sb, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".data"), limit, data, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".root"), limit, root, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".c67"), limit, c67, err)) { + res.error = std::move(err); + return; + } + res.new_key = x2w::compute_request_key(c67, data, root, desc, sa, sb); + } else { + std::string ps57, root, m57; + constexpr size_t limit = 64ull << 20; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".ps57"), limit, ps57, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".root"), limit, root, err) || + !read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ".m57"), limit, m57, err)) { + res.error = std::move(err); + return; + } + res.new_key = x2w::mesh57_request_key(m57, ps57, root); + } + } catch (const std::exception& ex) { + res.error = ex.what(); + } + }; + + if (!work.empty()) { + const int worker_count = (std::min)(jobs, static_cast(work.size())); + if (worker_count <= 1) { + for (size_t i = 0; i < work.size(); ++i) + hash_item(i); + } else { + std::atomic next{}; + std::vector> workers; + workers.reserve(worker_count); + for (int w = 0; w < worker_count; ++w) { + workers.emplace_back(std::async(std::launch::async, [&]() { + for (size_t i = next++; i < work.size(); i = next++) + hash_item(i); + })); + } + for (auto& w : workers) + w.get(); + } + } + + std::vector bad; + std::map new_graphics_map; + for (size_t i = 0; i < work.size(); ++i) { + if (!results[i].error.empty()) { + bad.push_back("req_" + work[i].old_hex + ": " + results[i].error); + } else if (work[i].kind == Kind::graphics) { + new_graphics_map[work[i].old_key] = results[i].new_key; + } + } + + std::map rtv_rewritten; + for (const auto& rm : rtv_markers) { + std::string raw, err; + if (!read_rekey_bytes(rekey_request_path(src_dir, rm.old_hex, ".rtv"), 256, raw, err)) { + bad.push_back("req_" + rm.old_hex + ".rtv: " + err); + continue; + } + try { + const auto parsed = x2w::parse_rtv_variant_text(raw, rm.old_key); + const auto it = new_graphics_map.find(parsed.base_key); + if (it == new_graphics_map.end()) { + bad.push_back("req_" + rm.old_hex + ".rtv: .rtv base request " + format_key16(parsed.base_key) + + " is not a complete graphics request"); + continue; + } + std::string rewritten = x2w::format_rtv_variant_text(it->second, parsed.formats); + const uint64_t new_rtv_key = x2w::fnv1a_64(rewritten); + rtv_rewritten.try_emplace(new_rtv_key, std::move(rewritten)); + } catch (const std::exception& ex) { + bad.push_back("req_" + rm.old_hex + ".rtv: " + ex.what()); + } + } + + if (!bad.empty()) { + std::cerr << "error: " << bad.size() << " of " << (work.size() + rtv_markers.size()) + << " requests are incomplete or unreadable; nothing written\n"; + const size_t limit = (std::min)(bad.size(), size_t{10}); + for (size_t i = 0; i < limit; ++i) + std::cerr << " " << bad[i] << '\n'; + return 1; + } + + try { + fs::create_directories(dst_dir); + size_t written = 0, kept = 0; + + const size_t gfx_end = graphics_markers.size(); + const size_t cmp_end = gfx_end + compute_markers.size(); + const size_t m57_end = cmp_end + m57_markers.size(); + + auto publish_group = [&](size_t begin, size_t end, const char* label) { + std::set done_keys; + size_t already_current = 0; + for (size_t i = begin; i < end; ++i) { + const Marker& m = work[i]; + const WorkResult& res = results[i]; + if (m.old_key == res.new_key) + ++already_current; + if (!done_keys.insert(res.new_key).second) + continue; + const std::string new_hex = format_key16(res.new_key); + auto copy_part = [&](const char* ext, size_t max_bytes) { + const fs::path dst_file = rekey_request_path(dst_dir, new_hex, ext); + std::error_code file_ec; + if (fs::exists(dst_file, file_ec)) { + ++kept; + return; + } + if (file_ec) + throw fs::filesystem_error("cannot inspect destination file", dst_file, file_ec); + std::string bytes, err; + if (!read_rekey_bytes(rekey_request_path(src_dir, m.old_hex, ext), max_bytes, bytes, err)) + throw std::runtime_error(err); + publish_atomic(dst_file, bytes.data(), bytes.size()); + ++written; + }; + if (m.kind == Kind::graphics) { + copy_part(".b", 64ull << 20); + copy_part(".root", 16ull << 20); + if (res.has_ia) + copy_part(".ia", 1ull << 20); + if (res.has_psin) + publish_rekey_file(rekey_request_path(dst_dir, new_hex, ".psin"), + res.rewritten_psin.data(), res.rewritten_psin.size(), written, kept); + copy_part(".a", 64ull << 20); + } else if (m.kind == Kind::compute) { + constexpr size_t limit = 64ull << 20; + copy_part(".desc", limit); + copy_part(".sa", limit); + copy_part(".sb", limit); + copy_part(".data", limit); + copy_part(".root", limit); + copy_part(".c67", limit); + } else { + constexpr size_t limit = 64ull << 20; + copy_part(".ps57", limit); + copy_part(".root", limit); + copy_part(".m57", limit); + } + } + std::cout << label << ": " << (end - begin) << " requests, " << already_current + << " already current -> " << done_keys.size() << " keys\n"; + }; + + publish_group(0, gfx_end, "graphics"); + publish_group(gfx_end, cmp_end, "compute"); + publish_group(cmp_end, m57_end, "m57"); + for (const auto& [new_key, text] : rtv_rewritten) + publish_rekey_file(rekey_request_path(dst_dir, format_key16(new_key), ".rtv"), + text.data(), text.size(), written, kept); + std::cout << "rtv variants: " << rtv_markers.size() << " requests -> " << rtv_rewritten.size() << " keys\n"; + std::cout << "not re-keyed (own key strings): m86 " << m86_count << '\n'; + std::cout << "files: " << written << " written, " << kept << " already present in " << dst_dir.string() << '\n'; + return 0; + } catch (const std::exception& error) { + std::cerr << "error: failed writing " << dst_dir.string() << ": " << error.what() << '\n'; + return 1; + } +} + int wmain(int argc, wchar_t** argv) { + if (argc >= 2 && std::wstring_view(argv[1]) == L"--rekey") + return run_rekey(argc, argv); if (argc >= 2 && std::wstring_view(argv[1]) == L"--watch") return run_watch(argc, argv); if (argc >= 2 && std::wstring_view(argv[1]) == L"--refusals") @@ -925,6 +1309,7 @@ int wmain(int argc, wchar_t** argv) { "gfx1013-container-rect also emits the rectangle geometry stage.\n" "Use --refusals REQUEST_DIRECTORY [--jobs N] [--json] for a read-only refusal summary.\n" "Use --watch SDK_DIRECTORY CACHE_DIRECTORY REQUEST_DIRECTORY [--jobs N] [--interval MS] [--once] to translate pending requests.\n" + "Use --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N] to copy requests under the current cache revision keys.\n" "Use --index-graphics-interfaces REVIEWED_DIRECTORY CACHE_DIRECTORY to index native graphics interfaces.\n"; return 2; }