From 615189afda1cd558f820c900d5ce8e82dad9cf43 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 19:05:19 +0100 Subject: [PATCH 1/6] startup: write shader requests from the shader archive before a run Translation requests were only written when the title created a pipeline, so every new pipeline cost a run before it could be drawn. A traced startup run showed the native programs come from 64-byte aligned zlib streams in the shader archive, byte for byte. tools/startup/archive_requests.py inflates those streams, joins a stream with the one that starts on the next 64-byte boundary, carves programs (36-byte header, s_inst_prefetch, 64-byte blocks on 256-byte steps) and pairs each pixel program with a directly following vertex program. Root signatures are not in the archive, so they come from earlier req_*.root files and every pair is written once per distinct root, with the runtime's key. gfx2hlsl.py --pending then translates them. Measured locally: 4,982 programs, 1,258 pairs, 3,774 requests in 22 s. Eight of the eleven pipelines of a cold run were among them with identical keys and byte-identical translations. Test: startup_archive_requests on a synthetic archive, with controls for unpaired programs, a pair cut off at the end of a stream, a stream off the 64-byte grid, a pair split across two consecutive streams, missing roots and a second run. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 4 + docs/startup-runtime.md | 45 +++++++ tests/startup_archive_requests_check.py | 120 +++++++++++++++++++ tools/startup/archive_requests.py | 153 ++++++++++++++++++++++++ 6 files changed, 324 insertions(+) create mode 100644 tests/startup_archive_requests_check.py create mode 100644 tools/startup/archive_requests.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 7817ba0896..75371a3a64 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -173,6 +173,7 @@ jobs: tests/startup_image_2d_array_check.py \ tests/startup_host_cpu_check.py \ tests/startup_gfx2hlsl_capture_check.py \ + tests/startup_archive_requests_check.py \ tests/startup_translator_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ tests/startup_triage_run_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 0e942257fa..3b6cba1e16 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -148,6 +148,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_host_cpu_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_capture_check.py +./out/pe-env/bin/python -B tests/startup_archive_requests_check.py ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py ./out/pe-env/bin/python -B tests/startup_flat_param_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index f53e8843ea..110e1ac8b9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1640,6 +1640,10 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_capture COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_capture_check.py") set_tests_properties(startup_gfx2hlsl_capture PROPERTIES TIMEOUT 120) + # archive_requests.py writes runtime-keyed shader requests from a synthetic archive. + add_test(NAME startup_archive_requests COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_archive_requests_check.py") + set_tests_properties(startup_archive_requests PROPERTIES TIMEOUT 120) # gfx2hlsl refuses a binary32 or integer vector operation with a source too few or too many. add_test(NAME startup_gfx2hlsl_operand_count COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_operand_count_check.py") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 7d736f480c..0fd36ecbca 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -277,6 +277,51 @@ It writes: | `/stderr.txt` | the stand-ins' logs (`x2w-d3d12`, `x2w-dstorage`, `x2w-xmem`, `x2w-runtime`, ...) | | `/files.txt` | every file the process opened | +### Shader requests from the archive, before a run + +`tools/startup/archive_requests.py [--roots ...]` writes +requests without starting the title, then `gfx2hlsl.py --pending ` translates them: + +```powershell +python -B tools/startup/archive_requests.py \shaders.rpf out/startup/shader_cache +python -B tools/startup/gfx2hlsl.py --pending out/startup/shader_cache +``` + +A startup run that traced every DirectStorage read showed where the native programs come from: +zlib streams in the shader archive that start on 64-byte boundaries and inflate to 64 KiB. Inflated +offline, those streams hold the exact bytes the runtime later records. Each program has a 36-byte +header followed by `s_inst_prefetch`, is padded in 64-byte blocks and starts on a 256-byte step, +and in every measured pipeline the vertex program directly follows the pixel program. The tool +carves every complete program, pairs each pixel program with a directly following vertex program +and writes `req_.{a,b,root}` with the runtime's key. + +What it cannot take from the archive: + +- **Root signatures.** None of the recorded root signatures occurs in the archive or the + executable; the title appears to serialize them at run time. The tool reads `req_*.root` files + from earlier runs (by default those in the cache) and writes each pair once per distinct root. + A key is only used when the title binds that pair with that root, so the extra requests cost + translation time and nothing else. +- **Pipelines the title builds from other sources.** Programs embedded in the executable as DXBC + containers are not in the archive. +- **Other pairings.** A program shared by several pipelines, or a pair that is not adjacent, is + only found by a run (`run.ps1 -Translate`). +- **Programs cut off at the end of a stream.** A zlib stream that starts on the 64-byte boundary + right after the previous one continues it, and the two are carved as one, so a program split + between them is kept. A program that reaches the end of such a joined run is skipped. + +In one local measurement the tool joined 1,079 zlib streams into 800 runs, carved 4,982 programs +(2,730 pixel, 2,115 vertex, 137 other) and wrote 3,774 requests for 1,258 pairs and three recorded +root signatures in 22 s. Eight of the eleven pipelines that a cold run recorded were among them with +identical keys, and their translations (`.txt`, both `.hlsl` files and both `.cso` files) were +byte-identical to those from the run. The other three were two pipelines whose programs are DXBC +containers in the executable and one pipeline whose programs were not carved. Check with `python3 -B tests/startup_archive_requests_check.py` +(ctest `startup_archive_requests`): on a synthetic archive each adjacent pixel/vertex pair becomes one +request per root with the runtime's key; a pixel program followed by a pixel program, a vertex +program without a pixel program before it, a pair that reaches the end of its stream, a pair in a +stream off the 64-byte grid and a run without root signatures write nothing, a pair split between +two consecutive zlib streams is carved whole, and a second run writes nothing new. + `run.ps1` prints the first five lines of `.out` and exits with the debugger's exit code: 2 when the process could not be created, 0 when the debugger finished its report, whatever the process did. Check with `python3 -B tests/startup_run_ps1_check.py` (ctest `startup_run_ps1`): on Windows it diff --git a/tests/startup_archive_requests_check.py b/tests/startup_archive_requests_check.py new file mode 100644 index 0000000000..5bb6790e49 --- /dev/null +++ b/tests/startup_archive_requests_check.py @@ -0,0 +1,120 @@ +"""archive_requests.py on a synthetic archive (pure Python, no Windows, no GPU, no title files). + +Programs follow the measured layout: a 36-byte header, s_inst_prefetch, code, s_code_end padding to +64 bytes, each on a 256-byte step of a zlib stream that starts on a 64-byte boundary. Each pixel +program directly followed by a vertex program must become one request per root, keyed exactly as +the runtime keys it. Controls: a pixel program followed by another pixel program, a vertex program +with no pixel program before it, a program that runs to the end of its stream, a valid pair in a +stream that is not on a 64-byte boundary, and a run with no root signature must write nothing. A +pair split between two consecutive zlib streams must be carved whole. A second run must write +nothing new. +""" +import os +import struct +import subprocess +import sys +import tempfile +import zlib +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +TOOL = ROOT / 'tools' / 'startup' / 'archive_requests.py' +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +import gfx2hlsl # noqa: E402 + +CODE_END = bytes.fromhex('00009fbf') +failures = [] + + +def expect(label, got, want): + if got != want: + failures.append('%s: got %r, want %r' % (label, got, want)) + + +def program(stage, serial, blocks=1): + target = {'vs': 12, 'ps': 0}[stage] # exp pos0 / exp mrt0, then s_endpgm + header = b'\x00\x00\x80\xd5' + struct.pack(' [--roots ...] + +The archive stores native programs in zlib streams that start on 64-byte boundaries. Each program +begins with a 36-byte header followed by s_inst_prefetch and is padded in 64-byte blocks. In the +measured archive a pipeline's vertex program directly follows its pixel program, so each pixel +program followed by a vertex program in the same stream becomes one request (a = pixel, b = vertex, +the order the runtime records). Root signatures were not found in the archive; they are read from +existing req_*.root files (by default those already in the cache), and every pair is written once +per distinct root, so each key matches what the runtime would compute for that combination. +Translate the result with gfx2hlsl.py --pending . +""" +import argparse +import glob +import mmap +import os +import sys +import zlib + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl # noqa: E402 + +HEADER = 0x24 # bytes before s_inst_prefetch +HEADER_TAG = b'\x80\xd5' # bytes 2..3 of the first header word in every measured program +BLOCK = 0x40 +STEP = 0x100 # programs start on 256-byte steps of the stream +WINDOW = 0x20000 # compressed bytes offered to one stream; a 64 KiB stream needs far less + + +def is_program(data, at): + return (at >= 0 and data[at + 2:at + 4] == HEADER_TAG + and data[at + HEADER:at + HEADER + 4] == gfx2hlsl.PREFETCH) + + +def carve(data): + """Yield (offset, program) in stream order; a program that runs past the stream is skipped.""" + hit = data.find(gfx2hlsl.PREFETCH) + while hit >= 0: + at = hit - HEADER + if at % 4 == 0 and is_program(data, at): + end = at + BLOCK + # 64-byte blocks until an all-zero block or the next program on a 256-byte step + while end + BLOCK <= len(data) and any(data[end:end + BLOCK]) and not ( + (end - at) % STEP == 0 and is_program(data, end)): + end += BLOCK + # a program that reaches the end of the joined stream may be cut off, so it is skipped + if end + BLOCK <= len(data): + yield at, data[at:end] + hit = data.find(gfx2hlsl.PREFETCH, hit + 4) + + +def chunks(view): + """Yield (archive offset, end offset, inflated bytes) for each complete zlib stream on a 64-byte boundary.""" + at = 0 + while at < len(view) - 1: + cmf, flg = view[at], view[at + 1] + if cmf == 0x78 and (cmf << 8 | flg) % 31 == 0: + inflater = zlib.decompressobj() + window = view[at:at + WINDOW] + try: + data = inflater.decompress(window) + except zlib.error: + data = b'' + if inflater.eof and data: + end = at + len(window) - len(inflater.unused_data) + yield at, end, data + at = (end + 63) & ~63 + continue + at += 64 + + +def streams(archive): + """Yield (archive offset, inflated bytes); a zlib stream that starts on the 64-byte boundary right + after the previous one continues it, so a program split between the two is carved whole.""" + with open(archive, 'rb') as file: + if os.fstat(file.fileno()).st_size == 0: + return + view = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) + start, joined, expected = None, [], None + for at, end, data in chunks(view): + if at != expected and joined: + yield start, b''.join(joined) + joined = [] + if not joined: + start = at + joined.append(data) + expected = (end + 63) & ~63 + if joined: + yield start, b''.join(joined) + + +def read_roots(paths): + roots = [] + for path in paths: + if not os.path.exists(path): + sys.exit('root signature path not found: %s' % path) + files = sorted(glob.glob(os.path.join(path, 'req_*.root'))) if os.path.isdir(path) else [path] + for name in files: + blob = open(name, 'rb').read() + if blob and blob not in roots: + roots.append(blob) + return roots + + +def write_request(cache, key, a, b, root): + """Writes .b and .root, then .a last: the scanner treats .a as the ready marker.""" + name = os.path.join(cache, 'req_%016x' % key) + if os.path.exists(name + '.a'): + return False + for ext, blob in (('.b', b), ('.root', root), ('.a', a)): + temporary = '%s%s.%d.tmp' % (name, ext, os.getpid()) + with open(temporary, 'wb') as out: + out.write(blob) + os.replace(temporary, name + ext) + return True + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('archive') + parser.add_argument('cache') + parser.add_argument('--roots', nargs='+', help='req_*.root files or directories (default: the cache)') + args = parser.parse_args() + roots = read_roots(args.roots or [args.cache]) + if not roots: + sys.exit('no root signature found: run the title once with a shader cache, or pass --roots') + os.makedirs(args.cache, exist_ok=True) + # streams counts joined runs of consecutive zlib streams + counts = dict(streams=0, programs=0, ps=0, vs=0, other=0, undecodable=0, pairs=0, written=0, existing=0) + for _, data in streams(args.archive): + counts['streams'] += 1 + previous = None + for _, program in carve(data): + counts['programs'] += 1 + try: + stage = gfx2hlsl.classify(program) + except gfx2hlsl.Unsupported: + stage = 'undecodable' + counts[stage] += 1 + if stage == 'vs' and previous and previous[0] == 'ps': + counts['pairs'] += 1 + for root in roots: + key = gfx2hlsl.pipeline_key(previous[1], program, root) + counts['written' if write_request(args.cache, key, previous[1], program, root) else 'existing'] += 1 + previous = (stage, program) + counts['roots'] = len(roots) + print(' '.join('%s=%d' % item for item in counts.items())) + + +if __name__ == '__main__': + main() From c357c8d3c77a7f992db3ca5b8aeacdb54b9d048a Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 19:28:40 +0100 Subject: [PATCH 2/6] startup: address review findings in the archive request writer - "Directly following" is now enforced: a vertex program pairs only when it starts on the 256-byte step right after the pixel program. Before, any vertex program after a pixel program paired, whatever the gap. - A carved program must contain s_endpgm; one cut short by an all-zero block is counted as incomplete and never paired. - The memory map is closed, and the docs use a neutral placeholder. On the local archive both rules leave the result unchanged (1,258 pairs, 0 incomplete, 8 of 11 recorded keys), so every measured pair was already adjacent. The test adds a gap pair and a program without s_endpgm as controls, and a mutation of each rule is detected. Co-Authored-By: Claude Opus 5.5 --- docs/startup-runtime.md | 8 ++-- tests/startup_archive_requests_check.py | 15 +++++-- tools/startup/archive_requests.py | 53 ++++++++++++++++--------- 3 files changed, 52 insertions(+), 24 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 0fd36ecbca..abcf7d2a99 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -283,7 +283,7 @@ It writes: requests without starting the title, then `gfx2hlsl.py --pending ` translates them: ```powershell -python -B tools/startup/archive_requests.py \shaders.rpf out/startup/shader_cache +python -B tools/startup/archive_requests.py out/startup/shader_cache python -B tools/startup/gfx2hlsl.py --pending out/startup/shader_cache ``` @@ -292,7 +292,8 @@ zlib streams in the shader archive that start on 64-byte boundaries and inflate offline, those streams hold the exact bytes the runtime later records. Each program has a 36-byte header followed by `s_inst_prefetch`, is padded in 64-byte blocks and starts on a 256-byte step, and in every measured pipeline the vertex program directly follows the pixel program. The tool -carves every complete program, pairs each pixel program with a directly following vertex program +carves every program that ends in `s_endpgm` (an all-zero block inside a program would cut it +short), pairs each pixel program with a vertex program that starts on the next 256-byte step and writes `req_.{a,b,root}` with the runtime's key. What it cannot take from the archive: @@ -318,7 +319,8 @@ byte-identical to those from the run. The other three were two pipelines whose p containers in the executable and one pipeline whose programs were not carved. Check with `python3 -B tests/startup_archive_requests_check.py` (ctest `startup_archive_requests`): on a synthetic archive each adjacent pixel/vertex pair becomes one request per root with the runtime's key; a pixel program followed by a pixel program, a vertex -program without a pixel program before it, a pair that reaches the end of its stream, a pair in a +program without a pixel program before it, a vertex program one empty step after its pixel program, +a pixel program without `s_endpgm`, a pair that reaches the end of its stream, a pair in a stream off the 64-byte grid and a run without root signatures write nothing, a pair split between two consecutive zlib streams is carved whole, and a second run writes nothing new. diff --git a/tests/startup_archive_requests_check.py b/tests/startup_archive_requests_check.py index 5bb6790e49..e1d49d64b4 100644 --- a/tests/startup_archive_requests_check.py +++ b/tests/startup_archive_requests_check.py @@ -4,7 +4,8 @@ 64 bytes, each on a 256-byte step of a zlib stream that starts on a 64-byte boundary. Each pixel program directly followed by a vertex program must become one request per root, keyed exactly as the runtime keys it. Controls: a pixel program followed by another pixel program, a vertex program -with no pixel program before it, a program that runs to the end of its stream, a valid pair in a +with no pixel program before it, a vertex program one empty 256-byte step after a pixel program, a +pixel program without s_endpgm, a program that runs to the end of its stream, a valid pair in a stream that is not on a 64-byte boundary, and a run with no root signature must write nothing. A pair split between two consecutive zlib streams must be carved whole. A second run must write nothing new. @@ -63,8 +64,15 @@ def stream(layout, length=0x1000): PS8, VS8 = program('ps', 13), program('vs', 14, blocks=2) split = stream([(0x02c, PS8), (0x12c, VS8)], length=0x300) +# Controls that must not pair: a vertex program one empty 256-byte step after its pixel program, and +# a vertex program after a pixel program that has no s_endpgm (cut short by an all-zero block). +PS9, VS9 = program('ps', 15), program('vs', 16) +cut = program('ps', 17).replace(struct.pack(' Date: Tue, 24 Nov 2026 19:38:14 +0100 Subject: [PATCH 3/6] startup: bound archive inflation and harden the archive request tests Review follow-up. - A zlib stream that would inflate past 1 MiB (a measured one inflates to 64 KiB) is counted as oversized and skipped without inflating it in full, and a joined run of consecutive streams stops growing at 64 MiB. Before, a small crafted archive could make the tool allocate gigabytes. - A part that cannot be written leaves no .a and no temporary file and the run exits with an error; an archive without any pair also fails. Root files are read with a context manager. - The test computes the expected keys with its own copy of the runtime's FNV-1a (start value 1469598103934665603, as in d3d12_draw.inl) instead of gfx2hlsl.pipeline_key, parses the summary, and adds controls for an untagged program, a pair at offsets not a multiple of 4, an empty root file, an oversized stream, a blocked .root write and an archive without pairs. All nine mutants (step size, write order, tag check, alignment check, empty roots, inflate limit, temporary file cleanup, and both failure exits) are detected. The local archive gives the same 1,258 pairs and 8 of 11 recorded keys, with 0 oversized streams. Co-Authored-By: Claude Opus 5.5 --- docs/startup-runtime.md | 28 ++++-- tests/startup_archive_requests_check.py | 127 +++++++++++++++++------- tools/startup/archive_requests.py | 62 ++++++++---- 3 files changed, 155 insertions(+), 62 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index abcf7d2a99..7f689ce9ed 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -311,18 +311,32 @@ What it cannot take from the archive: right after the previous one continues it, and the two are carved as one, so a program split between them is kept. A program that reaches the end of such a joined run is skipped. +A stream that would inflate past 1 MiB is counted as `oversized` and skipped without inflating it in +full, and a joined run stops growing at 64 MiB. A request is written as `.b`, `.root`, then `.a`; +if one part cannot be written, no `.a` and no temporary file are left and the run exits with an +error, as it does when the archive yields no pair at all. + In one local measurement the tool joined 1,079 zlib streams into 800 runs, carved 4,982 programs (2,730 pixel, 2,115 vertex, 137 other) and wrote 3,774 requests for 1,258 pairs and three recorded root signatures in 22 s. Eight of the eleven pipelines that a cold run recorded were among them with identical keys, and their translations (`.txt`, both `.hlsl` files and both `.cso` files) were byte-identical to those from the run. The other three were two pipelines whose programs are DXBC -containers in the executable and one pipeline whose programs were not carved. Check with `python3 -B tests/startup_archive_requests_check.py` -(ctest `startup_archive_requests`): on a synthetic archive each adjacent pixel/vertex pair becomes one -request per root with the runtime's key; a pixel program followed by a pixel program, a vertex -program without a pixel program before it, a vertex program one empty step after its pixel program, -a pixel program without `s_endpgm`, a pair that reaches the end of its stream, a pair in a -stream off the 64-byte grid and a run without root signatures write nothing, a pair split between -two consecutive zlib streams is carved whole, and a second run writes nothing new. +containers in the executable and one pipeline whose programs were not carved. + +Check with `python3 -B tests/startup_archive_requests_check.py` (ctest `startup_archive_requests`). +On a synthetic archive built from documented instruction words, each adjacent pixel/vertex pair +becomes one request per root, and the test computes the expected keys with its own copy of the +runtime's hash. Controls that write nothing: + +- a pixel program followed by a pixel program, or a vertex program without a pixel program before it; +- a vertex program one empty step after its pixel program, or after a pixel program without `s_endpgm`; +- a program without the header tag, or a pair at offsets that are not a multiple of 4; +- a pair that reaches the end of its stream, or a pair in a stream off the 64-byte grid; +- an empty or duplicate root file, an oversized stream, or a run without root signatures. + +A pair split between two consecutive zlib streams is carved whole. A blocked `.root` write leaves no +`.a` and no temporary file and fails the run, as does an archive without pairs. A second run writes +nothing new. `run.ps1` prints the first five lines of `.out` and exits with the debugger's exit code: 2 when the process could not be created, 0 when the debugger finished its report, whatever the process diff --git a/tests/startup_archive_requests_check.py b/tests/startup_archive_requests_check.py index e1d49d64b4..9a2e51747d 100644 --- a/tests/startup_archive_requests_check.py +++ b/tests/startup_archive_requests_check.py @@ -3,14 +3,18 @@ Programs follow the measured layout: a 36-byte header, s_inst_prefetch, code, s_code_end padding to 64 bytes, each on a 256-byte step of a zlib stream that starts on a 64-byte boundary. Each pixel program directly followed by a vertex program must become one request per root, keyed exactly as -the runtime keys it. Controls: a pixel program followed by another pixel program, a vertex program -with no pixel program before it, a vertex program one empty 256-byte step after a pixel program, a -pixel program without s_endpgm, a program that runs to the end of its stream, a valid pair in a -stream that is not on a 64-byte boundary, and a run with no root signature must write nothing. A -pair split between two consecutive zlib streams must be carved whole. A second run must write -nothing new. +the runtime keys it; the expected keys are computed here with an independent FNV-1a, not with the +translator's function. + +Controls that must write nothing: a pixel program followed by another pixel program, a vertex +program with no pixel program before it, a vertex program one empty 256-byte step after a pixel +program, a pixel program without s_endpgm, a program without the header tag, a pair at an offset +that is not a multiple of 4, a program that runs to the end of its stream, a valid pair in a stream +that is not on a 64-byte boundary, an empty or duplicate root file, a stream that inflates past the +limit, and a run with no root signature. A pair split between two consecutive zlib streams must be +carved whole. A request whose .root cannot be written must leave no .a and no temporary file and make +the run fail. An archive without any pair must make the run fail. A second run must write nothing new. """ -import os import struct import subprocess import sys @@ -20,10 +24,10 @@ ROOT = Path(__file__).resolve().parent.parent TOOL = ROOT / 'tools' / 'startup' / 'archive_requests.py' -sys.path.insert(0, str(ROOT / 'tools' / 'startup')) -import gfx2hlsl # noqa: E402 +PREFETCH = bytes.fromhex('0300a0bf') # s_inst_prefetch 0x3 CODE_END = bytes.fromhex('00009fbf') +ENDPGM = struct.pack(' MAX_JOINED): yield start, b''.join(joined) - joined = [] + joined, size = [], 0 if not joined: start = at joined.append(data) + size += len(data) expected = (end + 63) & ~63 if joined: yield start, b''.join(joined) @@ -109,23 +117,31 @@ def read_roots(paths): sys.exit('root signature path not found: %s' % path) files = sorted(glob.glob(os.path.join(path, 'req_*.root'))) if os.path.isdir(path) else [path] for name in files: - blob = open(name, 'rb').read() + with open(name, 'rb') as file: + blob = file.read() if blob and blob not in roots: roots.append(blob) return roots def write_request(cache, key, a, b, root): - """Writes .b and .root, then .a last: the scanner treats .a as the ready marker.""" + """Writes .b and .root, then .a last: the scanner treats .a as the ready marker. Returns 'written', + 'existing' or 'failed'; a failed write leaves no temporary file and no .a.""" name = os.path.join(cache, 'req_%016x' % key) if os.path.exists(name + '.a'): - return False + return 'existing' for ext, blob in (('.b', b), ('.root', root), ('.a', a)): temporary = '%s%s.%d.tmp' % (name, ext, os.getpid()) - with open(temporary, 'wb') as out: - out.write(blob) - os.replace(temporary, name + ext) - return True + try: + with open(temporary, 'wb') as out: + out.write(blob) + os.replace(temporary, name + ext) + except OSError as error: + print('req_%016x%s: %s' % (key, ext, error), file=sys.stderr) + if os.path.exists(temporary): + os.remove(temporary) + return 'failed' + return 'written' def main(): @@ -139,9 +155,9 @@ def main(): sys.exit('no root signature found: run the title once with a shader cache, or pass --roots') os.makedirs(args.cache, exist_ok=True) # streams counts joined runs of consecutive zlib streams - counts = dict(streams=0, programs=0, incomplete=0, ps=0, vs=0, other=0, undecodable=0, pairs=0, - written=0, existing=0) - for _, data in streams(args.archive): + counts = dict(streams=0, oversized=0, programs=0, incomplete=0, ps=0, vs=0, other=0, undecodable=0, + pairs=0, written=0, existing=0, failed=0) + for _, data in streams(args.archive, counts): counts['streams'] += 1 previous = None # (stage, offset, program) of the program carved just before for at, program in carve(data): @@ -159,11 +175,17 @@ def main(): if stage == 'vs' and previous and previous[0] == 'ps' and at == next_step(previous[1], previous[2]): counts['pairs'] += 1 for root in roots: + # The runtime hashes its first recorded blob (the pixel program here) first. + # pipeline_key names its parameters vs_code, ps_code; only the order matters. key = gfx2hlsl.pipeline_key(previous[2], program, root) - counts['written' if write_request(args.cache, key, previous[2], program, root) else 'existing'] += 1 + counts[write_request(args.cache, key, previous[2], program, root)] += 1 previous = (stage, at, program) counts['roots'] = len(roots) print(' '.join('%s=%d' % item for item in counts.items())) + if counts['failed']: + sys.exit('%d request(s) could not be written' % counts['failed']) + if not counts['pairs']: + sys.exit('no program pair found in %s' % args.archive) if __name__ == '__main__': From 92f8c6cd6c434fcebc91a8c4167f3f9dfc8facb1 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 19:59:34 +0100 Subject: [PATCH 4/6] startup: classify carved programs from export targets, not translator support main now refuses some forms inside gfx2hlsl.decode (v_cndmask_b32_e64 with NEG on an immediate), and gfx2hlsl.classify goes through decode, so 289 carved programs became "undecodable" and 143 pairs were lost. Which programs pair must not depend on whether they can be translated. stage_of() applies the same export-target rule as classify but reads the disassembler directly. The local archive is back to 1,258 pairs with 0 undecodable programs, and 8 of the 11 recorded pipelines, re-keyed with the current revision, are among the offline requests. The test reads the key revision from src/startup_stubs/d3d12_draw.inl (main bumped it to x2w-startup-shader-4) instead of hard-coding it, and one vertex program now contains that refused v_cndmask form; going back to classify() loses the pair and is detected. Co-Authored-By: Claude Opus 5.5 --- tests/startup_archive_requests_check.py | 18 +++++++++++++----- tools/startup/archive_requests.py | 24 ++++++++++++++++++++---- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/tests/startup_archive_requests_check.py b/tests/startup_archive_requests_check.py index 9a2e51747d..5ea37a1b56 100644 --- a/tests/startup_archive_requests_check.py +++ b/tests/startup_archive_requests_check.py @@ -15,6 +15,7 @@ carved whole. A request whose .root cannot be written must leave no .a and no temporary file and make the run fail. An archive without any pair must make the run fail. A second run must write nothing new. """ +import re import struct import subprocess import sys @@ -25,6 +26,8 @@ ROOT = Path(__file__).resolve().parent.parent TOOL = ROOT / 'tools' / 'startup' / 'archive_requests.py' +REVISION = re.search(rb'constexpr char revision\[\] = "([^"]+)";', + (ROOT / 'src' / 'startup_stubs' / 'd3d12_draw.inl').read_bytes()).group(1) PREFETCH = bytes.fromhex('0300a0bf') # s_inst_prefetch 0x3 CODE_END = bytes.fromhex('00009fbf') ENDPGM = struct.pack(' Date: Tue, 24 Nov 2026 20:01:46 +0100 Subject: [PATCH 5/6] startup: list the archive check apart from the watch check #1749 adds its check right after startup_gfx2hlsl_capture_check.py in AGENTS.md and the workflow, as this PR did, so whichever merged second conflicted. This entry now sits two lines further down, so the two PRs merge in either order. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/windows.yml | 2 +- AGENTS.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 140e347b73..821297deb6 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -174,9 +174,9 @@ jobs: tests/startup_image_2d_array_check.py \ tests/startup_host_cpu_check.py \ tests/startup_gfx2hlsl_capture_check.py \ - tests/startup_archive_requests_check.py \ tests/startup_translator_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ + tests/startup_archive_requests_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ tests/startup_flat_param_check.py \ diff --git a/AGENTS.md b/AGENTS.md index d9dd68202e..c567f98bb9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,9 +149,9 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_host_cpu_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_capture_check.py -./out/pe-env/bin/python -B tests/startup_archive_requests_check.py ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py +./out/pe-env/bin/python -B tests/startup_archive_requests_check.py ./out/pe-env/bin/python -B tests/startup_flat_param_check.py ./out/pe-env/bin/python -B tests/startup_inline_sampler_check.py ./out/pe-env/bin/python -B tests/compute_entry_layout_check.py From 3543b489371a795622ed11cbf5e526f5b57c3108 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 21:08:08 +0100 Subject: [PATCH 6/6] startup: test the 64 MiB cap on joined archive streams 130 consecutive 512 KiB zlib streams (65 MiB inflated, a few KB on disk) must come out as two joined runs. Before, removing the cap still passed the test. Co-Authored-By: Claude Opus 5.5 --- tests/startup_archive_requests_check.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/startup_archive_requests_check.py b/tests/startup_archive_requests_check.py index 5ea37a1b56..dc0109e7f1 100644 --- a/tests/startup_archive_requests_check.py +++ b/tests/startup_archive_requests_check.py @@ -13,7 +13,8 @@ that is not on a 64-byte boundary, an empty or duplicate root file, a stream that inflates past the limit, and a run with no root signature. A pair split between two consecutive zlib streams must be carved whole. A request whose .root cannot be written must leave no .a and no temporary file and make -the run fail. An archive without any pair must make the run fail. A second run must write nothing new. +the run fail. An archive without any pair must make the run fail. 65 MiB of consecutive streams +must be split into two joined runs. A second run must write nothing new. """ import re import struct @@ -184,6 +185,17 @@ def run(cache_dir, *extra, archive_name='archive.bin'): none = run(tmp / 'none', '--roots', str(rootdir), archive_name='nopairs.bin') expect('no pairs: run fails', none.returncode != 0 and 'no program pair' in none.stderr, True) + + # 130 consecutive 512 KiB streams (65 MiB inflated, a few KB on disk) would join into one run; + # the 64 MiB cap must split them into two. + piece = zlib.compress(bytes(0x80000), 9) + joined = bytearray() + for _ in range(130): + aligned(joined) + joined += piece + (tmp / 'joined.bin').write_bytes(joined) + capped = run(tmp / 'capped', '--roots', str(rootdir), archive_name='joined.bin') + expect('joined run capped at 64 MiB', summary(capped.stdout).get('streams'), '2') if failures: print(out.stdout, out.stderr, again.stdout, jam.stdout, jam.stderr, sep='\n')