Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ jobs:
tests/startup_gfx2hlsl_cvt_alu_check.py \
tests/startup_gfx2hlsl_int_med3_check.py \
tests/startup_gfx2hlsl_capture_check.py \
tests/startup_gfx2hlsl_watch_check.py \
tests/startup_translator_check.py \
tests/startup_gfx2hlsl_smem_offset_check.py \
tests/startup_gfx2hlsl_refusals_check.py \
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ python3 -m venv out/pe-env
./out/pe-env/bin/python -B tests/startup_host_cpu_check.py
./out/pe-env/bin/python -B tests/startup_live_telemetry_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_capture_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_watch_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_gfx2hlsl_refusals_check.py
Expand Down
4 changes: 4 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2216,6 +2216,10 @@ if(EXISTS "${INTAKE_PYTHON}")
# gfx2hlsl lowers s_bitcmp1_b32 and s_bitcmp0_b32 (SOPC): CPU evaluation of the translated SCC test.
add_test(NAME startup_gfx2hlsl_s_bitcmp COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp_check.py")
# gfx2hlsl.py --watch consumes only ready requests and does not retry an unchanged failure.
add_test(NAME startup_gfx2hlsl_watch COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_watch_check.py")
set_tests_properties(startup_gfx2hlsl_watch PROPERTIES TIMEOUT 120)
add_test(NAME startup_gfx2hlsl_handler_arity COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_handler_arity_check.py")
# VOP1/VOP2 sub-dword addressing (SDWA) in the translator (#1141), checked against the pixel AOT
Expand Down
34 changes: 32 additions & 2 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ Then:

```powershell
.\tools\startup\run.ps1 -Exe <folder>\<title>.exe -DataDir <package root> -LogDir out\startup\run1 `
-Seconds 180 -Render -FakeUser -GpuMirror -ContinueAsserts 1000 -InputScript "4@70"
-Seconds 180 -Render -Translate -FakeUser -GpuMirror -ContinueAsserts 1000 -InputScript "4@70"
```

`run.ps1` copies the stand-ins next to the executable and starts `tools/startup/debug_launch.py`.
Expand Down Expand Up @@ -447,6 +447,36 @@ It writes:
| `<log>/events.txt` | module loads and every exception with its time |
| `<log>/stderr.txt` | the stand-ins' logs (`x2w-d3d12`, `x2w-dstorage`, `x2w-xmem`, `x2w-runtime`, ...) |
| `<log>/files.txt` | every file the process opened |
| `<log>/translate.txt` | with `-Translate`: one line per shader request translated during the run |

### Translating shaders during a run

With `-Render -Translate`, `run.ps1` starts `tools/startup/gfx2hlsl.py --watch <shader cache>` beside
the debugger and stops it, with its worker processes, when the debugger returns (`-Translate`
without `-Render` is ignored with a warning). The watcher repeats the `--pending` scan every
2 seconds (`--watch <dir> <seconds>` sets another interval), so a pipeline the title creates during
the run is translated within seconds, and the runtime picks it up on a later draw instead of on the
next run. The cache persists: a later run reads every published `<key>.txt` and translates only new
requests. The watcher's first pass retries every earlier failure once, so a translator update reaches
requests that failed in an earlier run; after that, a request whose `<key>.fail` is newer than its
ready marker is not retried during the run (the runtime writes each request once and never rewrites
it). The one-shot `--pending` scan retries every failure. An unexpected translator error is written
to `<key>.fail` as `translator error: ...` instead of stopping the scan. A worker killed from outside
(for example out of memory) ends that watcher pass only; its requests are retried on the next pass.
FXC is located as described for `X2W_SHADER_CACHE` under [Switches](#switches). A scan with more than
one pending request translates them in parallel processes, one per logical processor (at most 61 on
Windows, the `ProcessPoolExecutor` limit) unless `X2W_TRANSLATE_JOBS` sets the count; each request
writes only its own files. On a 16-thread host,
3,513 requests (132 translated, 3,381 refused) took 56.9 s with one process and 7.8 s in parallel,
with byte-identical results.

Check with `python3 -B tests/startup_gfx2hlsl_watch_check.py` (ctest `startup_gfx2hlsl_watch`): a
request without its ready marker is not consumed, the watcher retries an earlier failure once and
then leaves failures alone, it translates a request written while it runs, four parallel workers
print the same results and write the same failures as one, an unexpected translator error becomes
`<key>.fail`, and an invalid `X2W_TRANSLATE_JOBS` falls back to the processor count.
`startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it together
with a child process.

`run.ps1` prints the first five lines of `<log>.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
Expand Down Expand Up @@ -731,7 +761,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=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}` and, when needed, RTV variants `req_<key>.rtv`. Run `tools/startup/gfx2hlsl.py --pending <dir>` 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\<version>\x64`, else `PATH`. When none exists it writes `<key>.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_SHADER_CACHE=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}` and, when needed, RTV variants `req_<key>.rtv`. Run `tools/startup/gfx2hlsl.py --pending <dir>` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). 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\<version>\x64`, else `PATH`. When none exists it writes `<key>.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_PRESENT_SIGNATURE_EVERY=<n>` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) |
| `X2W_D3D12_DUMP_SURFACE=<bmp>` | writes the last presented surface |
Expand Down
177 changes: 177 additions & 0 deletions tests/startup_gfx2hlsl_watch_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
"""gfx2hlsl.py pending scan and --watch on synthetic request files (pure Python, no Windows, no GPU).

A request is consumed only once its ready marker (.a or .rtv) exists and it is not finished: a
published .txt with both .cso files (or a .txt under X2W_FXC='') is done; a .txt without bytecode
is resumed. After the watcher's first pass, a request whose .fail is newer than its marker is not
retried; the first pass and the one-shot --pending scan retry it. The --watch process must retry an
earlier failure once, translate a new request while it runs and not rewrite a failure on later
passes. A --pending scan with four parallel workers must print the same results and write the same
failures as one worker, an unexpected translator error must become <key>.fail, a broken process
pool must end one watcher pass and not the watcher, and an invalid X2W_TRANSLATE_JOBS must fall
back to the processor count.
"""
import os
import re
import subprocess
import sys
import tempfile
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / 'tools' / 'startup'))
import gfx2hlsl # noqa: E402

failures = []


def expect(label, got, want):
if got != want:
failures.append('%s: got %s, want %s' % (label, got, want))


def touch(path, data=b'', mtime=None):
path.write_bytes(data)
if mtime is not None:
os.utime(path, (mtime, mtime))


def scan(directory, skip_failed):
return gfx2hlsl.pending_keys(str(directory), skip_failed)


def pending_run(directory, jobs):
env = dict(os.environ, X2W_TRANSLATE_JOBS=str(jobs))
out = subprocess.run([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'), '--pending', str(directory)],
capture_output=True, text=True, timeout=120, env=env)
def local(text): # the temporary directory differs between runs; keep the file name only
return re.sub(r"'[^']*?(req_[0-9a-f]{16}\.\w+)'", r"'\1'", text)
fails = {p.name: local(p.read_text()) for p in Path(directory).glob('*.fail')}
return out.returncode, sorted(local(line) for line in out.stdout.splitlines()), fails


with tempfile.TemporaryDirectory() as tmp:
d = Path(tmp)
now = time.time()
# 1: complete request; 2: already published with bytecode; 3: no ready marker yet (negative
# control); 4: failed after its marker was written; 5: marker rewritten after the failure;
# 6: RTV variant; 9: manifest-only publication that still needs bytecode (#2008 resume).
for key in (1, 2, 4, 5, 9):
for ext in ('.b', '.root'):
touch(d / ('req_%016x%s' % (key, ext)))
touch(d / ('req_%016x.a' % 1))
touch(d / ('req_%016x.a' % 2))
touch(d / ('%016x.txt' % 2))
touch(d / ('%016x.vs.cso' % 2), b'DXBC')
touch(d / ('%016x.ps.cso' % 2), b'DXBC')
touch(d / ('req_%016x.b' % 3))
touch(d / ('req_%016x.root' % 3))
touch(d / ('req_%016x.a' % 4), mtime=now - 10)
touch(d / ('%016x.fail' % 4), mtime=now - 5)
touch(d / ('%016x.fail' % 5), mtime=now - 10)
touch(d / ('req_%016x.a' % 5), mtime=now - 5)
touch(d / ('req_%016x.rtv' % 6))
touch(d / ('req_%016x.a' % 9))
touch(d / ('%016x.txt' % 9))
expect('watch pass', scan(d, True), [1, 5, 6, 9])
expect('one-shot pass', scan(d, False), [1, 4, 5, 6, 9])

# Parallel --pending must give the same results as one worker. Sixteen RTV variants each name a
# different missing base request, so each failure names its own base and a result reported against
# the wrong key is visible. With four workers each batch holds one request.
bases = {}
with tempfile.TemporaryDirectory() as one, tempfile.TemporaryDirectory() as many:
for n in range(16):
request = b'rtv1 %d 28' % (0x7000 + n)
bases[gfx2hlsl.fnv(request)] = 0x7000 + n
for d in (one, many):
touch(Path(d) / ('req_%016x.rtv' % gfx2hlsl.fnv(request)), request)
serial, parallel = pending_run(one, 1), pending_run(many, 4)
expect('parallel --pending output and failures', parallel, serial)
expect('every request answered', len(serial[1]), 16)
for line in parallel[1]:
key = int(line[:16], 16)
expect('result for %016x names its own base' % key, 'req_%016x.a' % bases.get(key, -1) in line, True)

# An unexpected translator error becomes <key>.fail instead of ending the scan.
with tempfile.TemporaryDirectory() as tmp:
d = Path(tmp)
touch(d / ('req_%016x.rtv' % 9))
real = gfx2hlsl.translate_request
gfx2hlsl.translate_request = lambda out_dir, key: 1 / 0
try:
gfx2hlsl.translate_pending(str(d), jobs=1)
except ZeroDivisionError:
failures.append('a translator error escaped translate_pending')
finally:
gfx2hlsl.translate_request = real
fail = d / ('%016x.fail' % 9)
expect('translator error recorded', fail.read_text().startswith('translator error: ZeroDivisionError') if fail.exists() else None, True)

# A broken process pool (a worker killed from outside) ends one pass, not the watcher.
from concurrent.futures.process import BrokenProcessPool # noqa: E402


def broken(out_dir, skip_failed=False):
raise BrokenProcessPool('a worker was terminated abruptly')


real = gfx2hlsl.translate_pending
gfx2hlsl.translate_pending = broken
try:
expect('broken pool: pass reported as incomplete', gfx2hlsl.watch_pass('.', True), False)
except BrokenProcessPool:
failures.append('a broken process pool escaped watch_pass')
finally:
gfx2hlsl.translate_pending = real
with tempfile.TemporaryDirectory() as tmp:
expect('normal pass reported as complete', gfx2hlsl.watch_pass(tmp, True), True)

# An invalid job count falls back to the processor count instead of raising.
saved = os.environ.get('X2W_TRANSLATE_JOBS')
for value in ('', 'abc', '-3'):
os.environ['X2W_TRANSLATE_JOBS'] = value
expect('X2W_TRANSLATE_JOBS=%r' % value, gfx2hlsl.translation_jobs() >= 1, True)
os.environ['X2W_TRANSLATE_JOBS'] = '2'
expect('X2W_TRANSLATE_JOBS=2', gfx2hlsl.translation_jobs(), 2)
if saved is None:
del os.environ['X2W_TRANSLATE_JOBS']
else:
os.environ['X2W_TRANSLATE_JOBS'] = saved

with tempfile.TemporaryDirectory() as tmp:
d = Path(tmp)
# A failure from an earlier run, newer than its marker: the watcher's first pass retries it once.
now = time.time()
touch(d / ('req_%016x.rtv' % 8), b'not an rtv request either', mtime=now - 20)
touch(d / ('%016x.fail' % 8), b'stale reason\n', mtime=now - 10)
watch = subprocess.Popen([sys.executable, '-B', str(ROOT / 'tools' / 'startup' / 'gfx2hlsl.py'),
'--watch', str(d), '0.1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
time.sleep(0.5)
# Written while the watcher runs; an invalid RTV request fails without a GPU or compiler.
touch(d / ('req_%016x.rtv' % 7), b'not an rtv request')
fail = d / ('%016x.fail' % 7)
deadline = time.time() + 20
while not fail.exists() and time.time() < deadline and watch.poll() is None:
time.sleep(0.1)
expect('watcher wrote a failure for the new request', fail.exists(), True)
first = fail.stat().st_mtime_ns if fail.exists() else None
time.sleep(1.0)
expect('failure left unchanged by later passes', fail.stat().st_mtime_ns if fail.exists() else None, first)
old = (d / ('%016x.fail' % 8)).read_text().strip()
expect('earlier failure retried once at start', old, 'invalid RTV variant request')
expect('watcher still running', watch.poll(), None)
finally:
watch.kill()
out, err = watch.communicate(timeout=20)
lines = sorted(line for line in out.splitlines() if line.strip())
expect('watcher output (each request translated once)', [line[:16] for line in lines], ['%016x' % 7, '%016x' % 8])
if err.strip():
failures.append('watcher stderr: %r' % err.strip()[-500:])

for item in failures:
print('FAIL', item)
if failures:
sys.exit(1)
print('startup_gfx2hlsl_watch_check passed')
Loading
Loading