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
40 changes: 40 additions & 0 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -1119,6 +1119,46 @@ print the same results and write the same failures as one, an unexpected transla
`startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it together
with a child process.

### Native graphics interface catalog in runs

The native graphics translator uses the catalog to look up reflected stage interfaces for
matching raw shader requests. A request that needs a reflected vertex and pixel interface
must match both stages.

To build a corpus from your own local package, pass its shader archive to the extractor.
Replace `<archive>` with the archive path and `<dir>` with the local output directory.

```text
python -B tools/extract_shaders.py "<archive>" --format dxbc --stage vertex pixel mesh --output-dir "<dir>"
```

The extractor writes `.dxbc` containers under `<dir>`. Review the output and rename the
compatible guest containers from `.dxbc` to `.cdxil`, the only extension the indexer reads.
The corpus and seeded cache contain copies of your own shader data and must stay local without
ever being committed, attached, or uploaded. See [CONTRIBUTING.md](../CONTRIBUTING.md).

With `-Render`, pass `-InterfaceCorpus 'D:\reviewed-interfaces'` to `run.ps1`. Under Wine, pass
`--render --interface-corpus /path/to/reviewed-interfaces` to `run.sh`. Both launchers index
the corpus into the selected shader cache after any fresh-cache rotation and before the
watcher or debugger starts. An install failure stops the run. The shared preset can also
install the corpus in native shader mode.

```powershell
python -B tools/startup/run_preset.py --package 'D:\package' --console x --gpu nvidia `
--set translate=false --set 'interface_corpus=D:\reviewed-interfaces'
```

Add `--print` to see the generated launcher command. The launchers use `compile_dxil.exe`
from the selected build directory. To install the same catalog manually, pass the cache
directory that the run will use:

```powershell
.\out\build\release\compile_dxil.exe --index-graphics-interfaces 'D:\reviewed-interfaces' 'out\startup\shader_cache'
```

Check the install command's output for `indexed_graphics_containers=<count>` and the
selected cache for `interfaces/library/catalog` and its `.index` and `.stage` files.

### Translating compute programs in the stand-in

With `X2W_NATIVE_SHADERS=<directory of dxcompiler.dll and dxil.dll>` (`run.ps1 -Render -NativeShaders <dir>`),
Expand Down
14 changes: 13 additions & 1 deletion tests/native_graphics_interface_library_check.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""Index source-built native containers and replay their raw runtime form."""
import pathlib
import shutil
import subprocess
import sys
import tempfile

from native_direct_container_check import patched_pixel, publish, vertex, words
from startup_run_ps1_check import OLDER_CACHE, RUN_PS1, run_case


def main(compiler, sdk):
Expand All @@ -18,7 +20,7 @@ def run(*args, expected=None):

with tempfile.TemporaryDirectory() as tmp:
base = pathlib.Path(tmp)
library, cache, requests = (base / s for s in ("library", "cache", "requests"))
library, cache, requests = (base / s for s in ("reviewed interfaces", "cache", "requests"))
library.mkdir()
# The old raw reader has no PS state for this scalar branch. Exact
# native programs recover the full stage ABI from the catalog.
Expand All @@ -39,6 +41,13 @@ def batch(folder, output, **kwargs):
batch(requests, base / "bare", expected="verified stage interface")
install = ("--index-graphics-interfaces", library, cache)
run(*install)
shell = shutil.which("powershell") or shutil.which("pwsh")
if sys.platform == "win32" and shell:
launcher = RUN_PS1.read_text(encoding="utf-8")
launch_options = dict(work=base, translate=True, switches=["-FakeUser"], absolute_build=True,
cache_files=OLDER_CACHE, interface_corpus=library, interface_compiler=compiler)
problems = run_case(shell, launcher, 7, **launch_options)
assert not problems, problems
for name, hit in (("cold",0), ("warm",1)):
assert f"frontend_cache_hit={hit}" in batch(requests, base / name)
run(sdk,cache,"gfx1013-container-pair",vertex_file,base/"vertex.cso",pixel_file,base/"pixel.cso")
Expand Down Expand Up @@ -67,6 +76,9 @@ def tree(folder):
(library/"broken.cdxil").write_bytes(b"bad")
assert subprocess.run([compiler,*install],capture_output=True).returncode
assert subprocess.run([compiler,*install,"--jobs","3"],capture_output=True).returncode
if sys.platform == "win32" and shell:
problems = run_case(shell, launcher, 0, expect_catalog_error=True, **launch_options)
assert not problems, problems
batch(requests,base/"retained")

# Two reflected parameter rows. The fixed PS uses P1/P2 for x
Expand Down
16 changes: 16 additions & 0 deletions tests/startup_run_preset_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import itertools
import json
import re
import subprocess
import sys
import tempfile
from pathlib import Path
Expand Down Expand Up @@ -78,6 +79,8 @@ def arg_after(cmd, flag):
check(s["env"].get("X2W_HIDE_TITLE_WINDOW") == "1", f"{where}: the title's own window is hidden")
host = "linux" if os_name == "linux" else "windows"
cmd = rp.build_command(host, s, pkg / "stage" / "t.exe", pkg, pkg / "log", pkg / "storage")
corpus_flag = "--interface-corpus" if host == "linux" else "-InterfaceCorpus"
check("interface_corpus" not in s["run"] and corpus_flag not in cmd, f"{where}: no shared interface corpus")
if host == "linux":
check(cmd[1].endswith("run.sh") and "--render" in cmd, f"{where}: run.sh command")
check(s["env"].get("X2W_XMEM_SHARED_VIEWS") == "1", f"{where}: shared views on Linux")
Expand Down Expand Up @@ -258,6 +261,19 @@ def no_link(*_a):
and "X2W_PRESET_CHECK_CALLER=1 (from the caller's shell)" in printed, "--print output")
check(not (Path(tmp) / "runs").exists(), "--print creates nothing")

for host, flag in (("win11", "-InterfaceCorpus"), ("linux", "--interface-corpus")):
args = ["--package", str(package), "--console", "s", "--gpu", "amd", "--os", host, "--print",
"--runs", str(Path(tmp) / "runs")]
corpus = str(Path(tmp) / "reviewed interfaces")
for value in ("", corpus):
out = io.StringIO()
with contextlib.redirect_stdout(out):
code = rp.main([*args, "--set", f"interface_corpus={value}"])
command = next((line for line in out.getvalue().splitlines() if line.startswith(" command: ")), "")
passed = subprocess.list2cmdline([flag, value]) in command if value else flag not in command
check(code == 0 and command and passed, f"{host}: --print interface corpus {value!r}")
check(not (Path(tmp) / "runs").exists(), f"{host}: --print with an interface corpus creates nothing")

# A run with the child start replaced: the environment it gets and what settings.json records.
mini_path = Path(tmp) / "mini.json"
mini_path.write_text(json.dumps(mini), encoding="utf-8")
Expand Down
71 changes: 69 additions & 2 deletions tests/startup_run_ps1_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@
os.environ.get("X2W_TITLE_ID"), os.environ.get("X2W_STORAGE_MB"),
os.environ.get("X2W_NATIVE_SHADERS_ONLY"), os.environ.get("X2W_XAPU_TYPED_COMPLETIONS")]
Path(__file__).with_name("debugger.json").write_text(json.dumps(record), encoding="utf-8")
cache = os.environ.get("X2W_SHADER_CACHE")
if cache and (Path(cache) / "interfaces" / "library" / "catalog").is_file():
Path(__file__).with_name("catalog-at-debugger.flag").touch()
# Under -Translate, wait until the watcher stub has started so run.ps1 cannot stop it before then.
watch = Path(__file__).with_name("watch.json")
deadline = time.monotonic() + 30
Expand Down Expand Up @@ -71,6 +74,8 @@

child = None if {early_exit} else subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])
record = Path(__file__).with_name("watch.json")
if (Path(sys.argv[2]) / "interfaces" / "library" / "catalog").is_file():
record.with_name("catalog-at-watch.flag").touch()
temp = record.with_suffix(".tmp")
temp.write_text(json.dumps([os.getpid(), child.pid if child else None] + sys.argv[1:]), encoding="utf-8")
temp.replace(record)
Expand Down Expand Up @@ -151,13 +156,15 @@ def alive(pid):

def run_case(shell, script, code, work, translate=False, switches=(), passed=(), fake_user_env=False,
early_exit=False, trace_api_env=None, absolute_build=False, missing_build=False, emit_stderr=False,
missing_python=False, real_log_error=False, native=False, manifest="absent", cache_files=None):
missing_python=False, real_log_error=False, native=False, manifest="absent", cache_files=None,
interface_corpus=None, interface_compiler=None, expect_catalog_error=False):
"""Run one copy of the script on a stub that exits with `code`; return what is wrong.

`switches` are extra run.ps1 switches and `passed` the debugger arguments they must add.
`translate` exercises -Render -Translate and requires the watcher to stop with its child.
With `early_exit` the watcher has no child and exits before the debugger finishes.
`native` passes -Render -NativeShaders <dir>: the stand-in gets the directory and no watcher starts.
The native interface library fixture supplies a compiler and synthetic corpus for a fresh-cache install.
This checks the log head and debugger exit code. The live watcher case checks worker cleanup.
"""
root = Path(tempfile.mkdtemp(dir=work)).resolve()
Expand Down Expand Up @@ -205,6 +212,7 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(),
env.pop("X2W_FAKE_USER", None)
env.pop("X2W_NATIVE_SHADERS", None)
env.pop("X2W_NATIVE_SHADERS_ONLY", None)
env.pop("X2W_SHADER_CACHE", None)
env.pop("X2W_XAPU_TYPED_COMPLETIONS", None)
if trace_api_env is None:
env.pop("X2W_TRACE_API", None)
Expand Down Expand Up @@ -235,6 +243,9 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(),
if translate:
command += ["-Render", "-Translate", "-ShaderCache", "cache"]
(startup / "translate.flag").write_bytes(b"")
if interface_corpus is not None:
shutil.copyfile(interface_compiler, build / "compile_dxil.exe")
command += ["-InterfaceCorpus", str(interface_corpus), "-FreshShaderCache"]
# A surviving watcher can keep a capture pipe open after PowerShell exits.
# Capture to files so we can check the watcher's PID as soon as the shell exits.
with (tempfile.TemporaryFile(mode="w+", errors="replace", dir=root) as stdout,
Expand All @@ -247,6 +258,13 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(),
stderr.seek(0)
printed = [line.strip() for line in stdout if line.strip()]
error_text = stderr.read().strip()
if expect_catalog_error:
found = []
if out.returncode == 0 or (startup / "debugger.json").exists() or (startup / "watch.json").exists():
found.append("an invalid interface corpus did not stop the run")
if "Native graphics interface catalog install failed" not in error_text:
found.append(f"missing catalog install failure message (stderr: {error_text!r})")
return found
if missing_python:
return (["missing Python returned success"] if out.returncode == 0 else []) + (
["missing Python launched debugger"] if (startup / "debugger.json").exists() else [])
Expand All @@ -264,7 +282,19 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(),
summary = Path(str(log) + ".out")
summary_lines = [line.strip() for line in decode(summary.read_bytes()).splitlines() if line.strip()] if summary.is_file() else []
want_output = summary_lines[:HEAD_LINES] if emit_stderr else STUB_LINES[:HEAD_LINES]
if cache_files is not None:
if interface_corpus is not None:
library = root / "cache" / "interfaces" / "library"
if not ((library / "catalog").is_file() and list(library.glob("*.index")) and list(library.glob("*.stage"))):
found.append("the catalog was not installed in the selected cache")
moved = list(root.glob("cache.old-*"))
if len(moved) != 1 or not (moved[0] / "revision.txt").is_file() or (root / "cache" / "revision.txt").exists():
found.append("the old cache was not rotated before installing the catalog")
if not all((startup / f"catalog-at-{name}.flag").exists() for name in ("watch", "debugger")):
found.append("the catalog was missing when the watcher or debugger started")
if "indexed_graphics_containers=2" not in printed:
found.append("the indexer did not report the two installed containers")
printed = [line for line in printed if line in STUB_LINES]
elif cache_files is not None:
# One warning with both revisions and the fixes; PowerShell may wrap it, so compare without whitespace.
flat = re.sub(r"\s", "", " ".join(printed))
missing = [phrase for phrase in REVISION_PHRASES if re.sub(r"\s", "", phrase) not in flat]
Expand Down Expand Up @@ -389,6 +419,23 @@ def text_problems(script):
found.append("missing -TraceApi environment opt-in before launch")
if not re.search(r"\$env:X2W_NATIVE_SHADERS\s*=", before):
found.append("missing -NativeShaders directory hand-over before launch")
install = re.search(
r'^if \(\$InterfaceCorpus\) \{\n\$indexer = Join-Path \$buildRoot "compile_dxil\.exe"\ntry \{\n'
r'& \$indexer --index-graphics-interfaces \$InterfaceCorpus \$env:X2W_SHADER_CACHE\n'
r'if \(\$LASTEXITCODE -ne 0\) \{ throw [^\n]+ \}\n\} catch \{\n'
r'throw "Native graphics interface catalog install failed:', before, re.M)
if not re.search(r'^\[string\]\s*\$InterfaceCorpus\s*=\s*""', before, re.M) or not install:
found.append("missing opt-in catalog install into the selected cache or failure handling")
else:
fresh = before.find('$cachePath --fresh |')
selected = before.find('$env:X2W_SHADER_CACHE =')
watcher = before.find('Start-Process -FilePath $python')
if not 0 <= fresh < selected < install.start() < watcher:
found.append("the catalog install must follow fresh-cache handling and precede the watcher and debugger")
if 'if ($InterfaceCorpus -and -not $Render) { throw ' not in before:
found.append("an explicit catalog install must require rendering")
if 'if ($InterfaceCorpus -and $LASTEXITCODE -ne 0) { throw ' not in before:
found.append("a failed fresh-cache rotation must stop an explicit catalog install")
if not WATCH_CLEANUP.search("\n".join(after)):
found.append("tree cleanup lacks taskkill /T, the live-watcher guard or the local Continue scope")
return found
Expand Down Expand Up @@ -455,6 +502,26 @@ def shell_failures(shell, script, tmp):
for removed in (' -and -not $translator.HasExited', '$ErrorActionPreference = "Continue"', '/T '):
if not text_problems(script.replace(removed, '')):
failures.append(f"text: removing {removed.strip()} escaped the cleanup check")
install_at = script.index(" if ($InterfaceCorpus) {")
install_end = script.index(" if (-not $Translate) {", install_at)
install = script[install_at:install_end]
before_fresh = script.replace(install, "").replace(" if ($FreshShaderCache) {", install + " if ($FreshShaderCache) {")
catalog_mutants = {
"interface corpus defaults to a path": script.replace('$InterfaceCorpus = ""', '$InterfaceCorpus = "local"'),
"no catalog install": script.replace(install, ""),
"unconditional catalog install": script.replace("if ($InterfaceCorpus) {", "if ($Render) {"),
"catalog install before fresh cache": before_fresh,
"catalog cache argument changed": script.replace("$InterfaceCorpus $env:X2W_SHADER_CACHE",
"$InterfaceCorpus $ShaderCache"),
"catalog failure ignored": script.replace(
'if ($LASTEXITCODE -ne 0) { throw "compile_dxil.exe exited with code $LASTEXITCODE." }', ""),
"catalog without render allowed": script.replace("if ($InterfaceCorpus -and -not $Render) {", "if ($false) {"),
"catalog after a failed cache rotation": script.replace("if ($InterfaceCorpus -and $LASTEXITCODE -ne 0) {",
"if ($false) {"),
}
for label, mutant in catalog_mutants.items():
if mutant == script or not text_problems(mutant):
failures.append(f"text: mutant '{label}' was not detected")
return failures


Expand Down
Loading
Loading