From bce4d52f04e31e2ac092d71436cfa9d03084b8e8 Mon Sep 17 00:00:00 2001 From: ArnabSaga Date: Wed, 25 Nov 2026 04:44:06 +0600 Subject: [PATCH] shader: add offline native compute translation and cache Add a bounded offline translation pipeline and revision-2 cache for two source-built gfx1013 compute programs. - Reuse pixel_aot and compute_store_aot for native instruction decoding and lowering. - Compile generated HLSL into validated and signed desktop DXIL. - Add canonical records, deterministic cache keys and SHA-256 artifact verification. - Enforce dependency identity, root-signature compatibility and backend PSO evidence. - Implement ownership-aware publication, request quarantine and cache refusal handling. - Add source-built fixtures, negative controls and reproducible Windows/WSL documentation. Verification: - Native machine-code preflight: PASS. - Offline native cache: 156/156 checks passed. - WARP and Intel Iris Xe root/PSO creation: PASS. - Selected upstream regression tests: 9/9 passed. - Fresh native code, records, HLSL and CSOs match the previously accepted vectors. - Stale validated manifests are rejected. - Documentation, bidi and diff checks passed. Tested against upstream commit 3682b34f. This contribution is offline-only. It introduces no slot 62 loader, C++ runtime integration, production slot 67 parsing, Dispatch or ExecuteIndirect implementation. The verification scripts are manually invoked and are not registered in CTest. Refs #1412 Related to #1954. --- docs/experiments.md | 174 ++++ tests/compute_native_cache_check.py | 877 ++++++++++++++++ tests/compute_native_check.py | 824 +++++++++++++++ tools/startup/compute_native.py | 1459 +++++++++++++++++++++++++++ 4 files changed, 3334 insertions(+) create mode 100644 tests/compute_native_cache_check.py create mode 100644 tests/compute_native_check.py create mode 100644 tools/startup/compute_native.py diff --git a/docs/experiments.md b/docs/experiments.md index 307424f717..147cafab6b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -11663,3 +11663,177 @@ Command-list slot 34 no longer sets a title root signature flagged `CBV_SRV_UAV_ cmake --build --preset dev --target startup_stream_consumer startup_heap_indexed_root_check ctest --preset dev --no-tests=error -R "^startup_(heap_indexed_root.*|root_heap_(warp|hardware))$" -V ``` + +## Source-built native compute translation and offline cache + +`tools/startup/compute_native.py` turns a bounded set of gfx1013 compute machine +code into a validated, signed desktop compute container and records it in a +revision-scoped cache. The machine code is assembled from source by LLVM 15 +(`llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013`), decoded by `pixel_aot.disassemble`, +lowered by the existing `compute_store_aot.lower`, compiled by DXC as `cs_6_0 -E main`, +validated and signed through `probe_roots`/`dxil_retarget`, and probed with +`CreateRootSignature` and `CreateComputePipelineState`. It is an offline +translator and cache producer. It does not execute anything through the startup +stand-in, does not load a slot 62 pipeline, does not parse slot 67, and does not +change the shim. + +### Fixture profiles + +Two source-built programs are supported. Both read two descriptor words through +the table pointer, apply a lane guard, and store to a `RWTexture2D`: + +| Profile | Group | Dispatch | Output | +|---|---|---|---| +| `1d` | 32x1x1 | 6x1x1 | 192 words, one column per dispatch | +| `2d` | 8x4x1 | 3x2x1 | 24 columns by 8 rows, 96-byte row stride | + +The 2-D store uses the translator's proven two-axis layout. The guard is the +column bound, the only lane guard the translator verifies, and the load is a +column broadcast because the accepted load form has no row term. Other group +shapes, other descriptors, LDS, missing source bindings, a wrong table register +and a linear-index guard are refused with a named reason. + +### Record and cache protocol + +A record is a canonical little-endian structure with a fixed magic, the scalar +contract fields, the root parameter list, a SHA-256 of the code and the code +bytes. The supported contract is `version 1`, `stage 5` (compute), `isa gfx1013`, +`guest_wave 32`, translator revision 1, decoder identity 1, `cs_6_0`, and no +interpreted `COMPUTE_PGM_RSRC2`: `rsrc2_interpretation` must be 0 and +`recorded_rsrc2` must be 0. A nonzero field, another guest wave or another +profile is refused rather than defaulted. + +The cache uses revision `x2w-startup-compute-native-2`. For each record: + +| File | Contents | +|---|---| +| `req_.csn` | the canonical record | +| `.csn.src` | the request manifest (`status request`) | +| `.csn.hlsl` | the accepted HLSL | +| `.csn.cso` | the signed desktop container | +| `.csn.manifest` | `x2w-native-compute 2` manifest with the status and evidence | + +`` is FNV-1a 64 over the revision string and the canonical record digest, +formatted as 16 lowercase hex digits. The manifest repeats the key, revision, +record digest, code size and digest, group, HLSL digest, output size and digest, +the dependency identity, the two validation HRESULTs, the `RTS0` contract, the +intrinsic-gate verdict, the signing state, and one `pso-` line per +probed adapter. Publication writes the artifacts first and the manifest last; a +reader accepts only a manifest whose digests, identity and backend evidence all +match, and an interrupted publication therefore never reads as a hit. A refusal +is written as `status refused` with its reason before any obsolete success +artifact is removed, and it is permanent for that revision. Refusal manifests +carry no dependency identity, so a translator change does not expire them; a +cache produced under another translator must be regenerated rather than reused. + +### Dependency identity and toolchain pins + +Every validated manifest declares eight identity fields. Three of them hash the +working-tree content of the repository tools used to produce the artifact: +`translator` (`compute_store_aot.py`), `decoder` (`pixel_aot.py`) and `pipeline` +(all of `compute_store_aot.py`, `pixel_aot.py`, `resource_inventory.py`, +`dxil_retarget.py`, `probe_roots.py`, `xbox_intrinsic_gate.py` and +`compute_native.py`). The other five are the pinned toolchain: + +| Field | Pinned value | +|---|---| +| `llvm` | `de2e35a4f9b3f6a06d2a8a3342b3f62a3842b1923b8dfc2a6ce48e0cc2d1e85d` (LLVM 15.0.7 `libLLVM-15.so.1`) | +| `compiler` | `495033935c058fc6d318ac257afdfa910795bf41b7e5ba905a0e7191dc8bd4fa` (`dxcompiler.dll`, Windows SDK 10.0.26100) | +| `validator` | `db108ffef7bcecb984bdccf2b4725719d65b2ce7f1ebc40019dbe6c5a7016e09` (`dxil.dll`) | +| `target` | `dxil-ms-dx` | +| `dxc_flags` | `cs_6_0 -E main` | + +The three content identities hash the bytes on disk, so the same tools checked +out with `core.autocrlf=true` and with LF line endings produce different +`translator`, `decoder` and `pipeline` values. A cache is therefore +machine-local: it is valid for the checkout that produced it, and a manifest +from another checkout is refused as stale rather than silently accepted. The +toolchain pins are file hashes and do not depend on line endings. + +### Reproduction + +Requirements: x64 Windows with the Visual Studio C++ tools and the Windows SDK, +CMake/Ninja, Python 3.11 or newer, WSL with LLVM 15 for the assemble and +translate stages, `root_probe.exe`/`root_device_probe.exe` built from this +repository, and a physical D3D12 adapter for the full cache suite because both +backends are required; the preflight alone can be limited with `--warp-only`. + +```powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target root_probe root_device_probe + +$py = 'out\pe-env\Scripts\python.exe' +$dxc = 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\dxc.exe' + +# Machine-code preflight: translate, refusals, reference, assemble, disassemble, +# compile, validate, probe. +& $py -B tests\compute_native_check.py --out out\native-compute\preflight ` + --wsl-distro Ubuntu-22.04 --dxc $dxc ` + --root-probe out\build\dev\root_probe.exe --device-probe out\build\dev\root_device_probe.exe + +# Full offline cache suite: 156 checks over requests, translation, publication, +# acceptance, identity, locking, refusals, cache hits and stale entries. +& $py -B tests\compute_native_cache_check.py --out out\native-compute\fresh ` + --wsl-distro Ubuntu-22.04 --dxc $dxc ` + --probe out\build\dev\root_probe.exe --pso-probe out\build\dev\root_device_probe.exe +``` + +`--linux-worker` is the internal entry point that the Windows orchestrator runs +inside WSL; it is not the command to start on Windows. The stages can also be +split by hand with `compute_native.py --pending --stage request`, +`--stage translate --llvm ` and `--stage compile --dxc --probe + --pso-probe `. + +### Measured results + +On Windows 11 build 26300.9974 with LLVM 15.0.7 in WSL Ubuntu-22.04, Windows SDK +10.0.26100 DXC, WARP and an Intel Iris Xe (`8086:9a49`, driver 31.0.101.5333): + +| Item | `1d` | `2d` | +|---|---|---| +| Machine code | 124 bytes, SHA-256 `57f31991…` | 128 bytes, SHA-256 `8374d7b3…` | +| Record | 336 bytes, SHA-256 `420b4d31…` | 340 bytes, SHA-256 `15c4cc21…` | +| Cache key | `d55528b6b2cfa1f8` | `95c4c65e03a8b336` | +| HLSL | 466 bytes, SHA-256 `6b6e8250…` | 482 bytes, SHA-256 `6836ef38…` | +| Signed container | 3640 bytes, SHA-256 `92d6a012…` | 3660 bytes, SHA-256 `6be3003e…` | + +Both manifest identities were `translator compute_store_aot/d47dacfb7be907f9`, +`decoder pixel_aot/419cde0d50268c70` and `pipeline a6002e220219d61b` on the +checkout that produced them. Validation returned `0x00000000` for the container +and the module through `dxil.dll`, the root-signature contract `RTS0` was +present, the intrinsic gate returned `ALLOW`, and signing left a nonzero +container digest. `CreateRootSignature` and `CreateComputePipelineState` returned +`0x00000000` on WARP and on the physical adapter at shader model `0x65`. + +The preflight passed its translate, refusal, reference, assemble, disassemble, +compile, validate and probe stages, with 9 text refusals and 9 byte refusals. The +refusals include a `COMPUTE_PGM_RSRC2` combined with explicit group registers +(`COMPUTE_PGM_RSRC2 places the group IDs; do not also give group registers`) and +`TG_SIZE_EN` (`COMPUTE_PGM_RSRC2 TG_SIZE_EN is not supported`); the adapter does +not interpret that field. The cache suite passed all 156 checks, including a +second compile that translated and compiled nothing and reported both keys as +`hit`, every identity and evidence mutation as non-accepted, artifact/digest +mismatches, interrupted publication, lock contention, and a published refusal +that removes the obsolete artifacts only after the refusal itself is visible. + +A manifest rewritten to a different identity is refused, not revalidated: +`translator 'compute_store_aot/036cdd081f7f709a' is not the pinned +'compute_store_aot/d47dacfb7be907f9'`, and likewise for `decoder` and +`pipeline`. The cache is trusted only as far as the local filesystem and the +toolchain pins: every accepted entry is re-hashed on read, and nothing verifies +who wrote it. + +### Scope and registration + +Not covered here: native runtime execution, GPU readback through the startup +stand-in, a slot 62 loader, production slot 67 parsing, ExecuteIndirect, any new +instruction lowering, profiles other than the two above, interpreted +`COMPUTE_PGM_RSRC2`, `TG_SIZE_EN`, and guest waves other than 32. + +The two Python checks are not registered in `CMakeLists.txt`: they need a WSL +distribution name, an explicitly selected DXC, both probe executables and +optionally a physical adapter, none of which the build system currently names. +They are run manually with the commands above. Registering them would need the +WSL distribution and toolchain paths exposed as cache variables, and a decision +about whether a missing adapter is a skip (77) or a failure. diff --git a/tests/compute_native_cache_check.py b/tests/compute_native_cache_check.py new file mode 100644 index 0000000000..f8de52c7b8 --- /dev/null +++ b/tests/compute_native_cache_check.py @@ -0,0 +1,877 @@ +"""Stage 4B.2 checks: the hardened native compute adapter and cache (#1412). + +Runs the real split toolchain: assembly and translation in WSL (LLVM 15), compilation, validation and +PSO probes in Windows (DXC, dxil.dll, WARP and the physical adapter). Infrastructure failure controls +call the real functions with clearly labelled stub tools; every other control exercises the real +acceptance, publication and locking code against a clone of the published cache. + + out\\pe-env\\Scripts\\python.exe -B tests\\compute_native_cache_check.py ` + --out out\\native-compute\\cache-suite --wsl-distro Ubuntu-22.04 ` + --dxc --validator --probe root_probe.exe --pso-probe root_device_probe.exe + +Exit codes: 0 all checks passed, 1 a failure. +""" +import argparse +import hashlib +import json +import os +import shutil +import struct +import subprocess +import sys +import time +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tools" / "startup")) + +import compute_native as native # noqa: E402 + +LLVM15_LIB = "/usr/lib/llvm-15/lib/libLLVM-15.so.1" +REQUIRED = ("warp", "hardware") +IDENTITY_MUTATIONS = ("translator", "decoder", "pipeline", "llvm", "compiler", "validator", "target", + "dxc_flags") +EVIDENCE_MUTATIONS = ("validation", "rts0", "gate", "signed") + + +def run(command, **kwargs): + return subprocess.run(command, capture_output=True, text=True, **kwargs) + + +def to_wsl(path): + resolved = Path(path).resolve() + return "/mnt/" + resolved.drive.rstrip(":").lower() + resolved.as_posix()[len(resolved.drive):] + + +def sha_bytes(data): + return hashlib.sha256(data).hexdigest() + + +def sha_file(path): + return sha_bytes(Path(path).read_bytes()) + + +def part_offset(blob, tag): + count = struct.unpack_from(" translate (WSL) -> compile (Windows) --------------------------------- + requested = native.stage_request(cache, [record_1d, record_2d], REQUIRED, evidence_writer) + check("request stage writes both requests", + all(outcome in ("requested", "hit") for _, outcome, _ in requested), requested) + + translate = run(["wsl", "-d", args.wsl_distro, "-u", "root", "--", "python3", + to_wsl(ROOT / "tools" / "startup" / "compute_native.py"), "--pending", to_wsl(cache), + "--stage", "translate", "--llvm", args.llvm, + "--require-backend", "warp", "--require-backend", "hardware"]) + (evidence / "translate.log").write_text( + f"$ {' '.join(translate.args)}\nexit={translate.returncode}\n{translate.stdout}\n{translate.stderr}\n", + encoding="utf-8") + check("translate stage in WSL", translate.returncode == 0, + (translate.stdout + translate.stderr).strip()[-200:]) + for name in ("1d", "2d"): + receipt = native.parse_manifest( + native.cache_paths(cache, keys[name])["request_manifest"].read_text(encoding="utf-8")) + evidence_writer(keys[name], "translation", receipt) + + compiled = native.stage_compile(cache, args.dxc, args.probe, args.pso_probe, REQUIRED, + validator=args.validator, evidence=evidence_writer) + check("compile stage validates and publishes", + all(outcome in ("validated", "revalidated", "hit") for _, outcome, _ in compiled), compiled) + + for name in ("1d", "2d"): + paths = native.cache_paths(cache, keys[name]) + finding = native.inspect_entry(cache, keys[name], REQUIRED) + check(f"{name}: authoritative acceptance is a hit", finding["state"] == "hit", + f'state={finding["state"]} {finding["detail"]}') + manifest = native.parse_manifest(paths["manifest"].read_text(encoding="utf-8")) + missing = sorted(set(native.MANIFEST_VALIDATED) - set(manifest)) + check(f"{name}: manifest declares every mandatory field", not missing, missing) + check(f"{name}: manifest identity is the pinned identity", + all(manifest[field] == identity[field] for field in native.MANIFEST_IDENTITY)) + check(f"{name}: manifest evidence is green", + manifest["validation"] == native.VALIDATION_OK and manifest["rts0"] == "present" + and manifest["gate"] == "ALLOW" and manifest["signed"] == native.SIGNED_OK) + check(f"{name}: manifest digests match the files", + manifest["record_sha256"] == native.record_digest(record_by_name[name]).hex() + and manifest["output_sha256"] == sha_file(paths["output"]) + and manifest["hlsl_sha256"] == sha_file(paths["hlsl"])) + check(f"{name}: published HLSL is the accepted translation", + paths["hlsl"].read_bytes() == (golden_1d if name == "1d" else golden_2d)) + verdict = native.verify_entry(cache, keys[name], REQUIRED) + check(f"{name}: consumer verification returns the verified bytes", + verdict["accepted"] and verdict["output"] == paths["output"].read_bytes() + and verdict["hlsl"] == paths["hlsl"].read_bytes(), verdict["problems"]) + check(f"{name}: embedded root matches the supported contract", + native.verify_rts0_from_container(paths["output"].read_bytes(), record_by_name[name]) + == {"version": 2, "samplers": 0, "flags": 0, "parameters": [ + {"type": 3, "visibility": 0, "register": 0, "space": 0, "count": None, "flags": 0}, + {"type": 4, "visibility": 0, "register": 0, "space": 0, "count": None, "flags": 0}, + {"type": 1, "visibility": 0, "register": 0, "space": 0, "count": 16, "flags": None}]}) + validation = json.loads((evidence / "validation" / f"{native.key_text(keys[name])}.json") + .read_text(encoding="utf-8")) + check(f"{name}: raw validator report is green", + validation["container"]["status"] == "0x00000000" + and validation["module"]["status"] == "0x00000000" + and validation["ir"]["target_triple"] == "dxil-ms-dx" + and not validation["ir"]["xbox_call_sites"]) + pso = json.loads((evidence / "pso" / f"{native.key_text(keys[name])}.json") + .read_text(encoding="utf-8")) + check(f"{name}: raw PSO probe reports both backends", + pso["warp"]["warp_root"] == "0x00000000" and pso["warp"]["warp_pso"] == "0x00000000" + and pso["both"]["adapter_id"] == manifest["pso-hardware"].split()[0].split("=")[1] + and pso["both"]["hardware_root"] == "0x00000000" + and pso["both"]["hardware_pso"] == "0x00000000") + + # -- cache hit must not translate or compile again ------------------------------------ + before = {name: (sha_file(native.cache_paths(cache, keys[name])["hlsl"]), + sha_file(native.cache_paths(cache, keys[name])["output"])) for name in keys} + again = run(["wsl", "-d", args.wsl_distro, "-u", "root", "--", "python3", + to_wsl(ROOT / "tools" / "startup" / "compute_native.py"), "--pending", to_wsl(cache), + "--stage", "translate", "--llvm", args.llvm]) + recompiled = native.stage_compile(cache, args.dxc, args.probe, args.pso_probe, REQUIRED, + validator=args.validator) + after = {name: (sha_file(native.cache_paths(cache, keys[name])["hlsl"]), + sha_file(native.cache_paths(cache, keys[name])["output"])) for name in keys} + check("cache hit skips translation", again.returncode == 0 and "translated" not in again.stdout, + again.stdout.strip()[:160]) + check("cache hit skips compilation", before == after + and all(outcome == "hit" for _, outcome, _ in recompiled), recompiled) + + # ------------------------------------------------------------------ control helpers + def fresh(name): + directory = scratch / name + if directory.exists(): + shutil.rmtree(directory) + directory.mkdir(parents=True) + return directory + + def clone(name): + target = scratch / name + if target.exists(): + shutil.rmtree(target) + shutil.copytree(cache, target) + return target + + def clone_of(source, name): + target = scratch / name + if target.exists(): + shutil.rmtree(target) + shutil.copytree(source, target) + return target + + def manifest_of(directory, key): + return native.parse_manifest(native.cache_paths(directory, key)["manifest"].read_text(encoding="utf-8")) + + def rewrite_manifest(directory, key, fields): + native.cache_paths(directory, key)["manifest"].write_bytes( + native.manifest_text(sorted(fields.items())).encode("ascii")) + + def state(name, condition, detail=""): + checks.append({"check": name, "ok": bool(condition), "detail": str(detail)[:300]}) + if not condition: + failures.append((name, str(detail)[:300])) + print(f"B2 {'PASS' if condition else 'FAIL'} {name}" + (f" {detail}" if detail else "")) + return bool(condition) + + stubs = write_stub_tools(out / "mocks", sys.executable) + validation_2d = json.loads((evidence / "validation" / f"{native.key_text(keys['2d'])}.json") + .read_text(encoding="utf-8")) + inventory = validation_2d["ir"]["xbox_intrinsics"] + gate = {"verdict": "ALLOW"} + verified_cache = native.verify_entry(cache, keys["2d"], REQUIRED) + blob = native.cache_paths(cache, keys["2d"])["output"].read_bytes() + hlsl = native.cache_paths(cache, keys["2d"])["hlsl"].read_bytes() + + # ------------------------------------------------------------------ real-byte refusals + def translate_refusal(name, code, record, message, directory): + mutated = variant(record, code) + native.validate(mutated) + key = native.cache_key(mutated) + native.stage_request(directory, [mutated], REQUIRED) + result = run(["wsl", "-d", args.wsl_distro, "-u", "root", "--", "python3", + to_wsl(ROOT / "tools" / "startup" / "compute_native.py"), "--pending", + to_wsl(directory), "--stage", "translate", "--llvm", args.llvm, + "--require-backend", "warp", "--require-backend", "hardware"]) + manifest = native.cache_paths(directory, key)["manifest"] + fields = native.parse_manifest(manifest.read_text(encoding="utf-8")) if manifest.exists() else {} + reason = fields.get("reason", (result.stdout + result.stderr).strip()) + state(name, result.returncode == 1 and fields.get("status") == "refused" and message in reason, + reason[:200]) + + translate_refusal("bytes: invalid encoding refused", b"\xff\xff\xff\xff" + code_2d[4:], record_2d, + "Unknown instruction at byte 0", fresh("bytes-invalid")) + translate_refusal("bytes: branch target outside the program refused", code_2d[:-4], record_2d, + "not an instruction boundary", fresh("bytes-branch")) + translate_refusal("bytes: missing final exit refused", code_2d[:4], record_2d, + "Missing final program exit", fresh("bytes-exit")) + translate_refusal("bytes: unsupported opcode refused", (llvm_dir / "control_lds.bin").read_bytes(), + record_2d, "Unverified private LDS read", fresh("bytes-lds")) + translate_refusal("bytes: computed-index guard refused", + (llvm_dir / "control_linear.bin").read_bytes(), record_2d, + "Unverified lane guard compare", fresh("bytes-linear")) + + # ------------------------------------------------------------------ H4 strict metadata + def expect_record_error(name, record, message): + try: + native.validate(record) + except native.RecordError as error: + state(name, message in str(error), str(error)) + else: + state(name, False, "accepted") + + for value in (0x984, 1, 0xFFFFFFFF): + expect_record_error(f"record: recorded_rsrc2 0x{value:x} is refused", + dict(record_2d, recorded_rsrc2=value), "recorded COMPUTE_PGM_RSRC2") + expect_record_error("record: unsupported interpretation mode", + dict(record_2d, rsrc2_interpretation=1), "recorded, not interpreted") + expect_record_error("record: unsupported guest wave", dict(record_2d, guest_wave=64), + "Unsupported guest wave contract") + expect_record_error("record: unsupported version", dict(record_2d, version=2), + "Unsupported record version") + expect_record_error("record: invalid stage", dict(record_2d, stage=4), "Unsupported shader stage") + expect_record_error("record: invalid ISA", dict(record_2d, isa=2), "Unsupported ISA") + expect_record_error("record: unsupported profile", dict(record_2d, profile=3), + "Unsupported native compute profile") + expect_record_error("record: stale translator revision", dict(record_2d, translator_revision=2), + "Unsupported translator revision") + expect_record_error("record: missing binding metadata", dict(record_2d, source_descriptor=0), + "share a table offset") + expect_record_error("record: invalid group dimension", dict(record_2d, group_x=48), + "not a power of two") + expect_record_error("record: incorrect root contract", dict(record_2d, root_parameters=((2, 0, 1),)), + "not the approved fixture contract") + expect_record_error("record: code digest mismatch", dict(record_2d, code_sha256=bytes(32)), + "digest does not match its bytes") + + def expect_parse_error(name, blob, message): + try: + native.parse(blob) + except native.RecordError as error: + state(name, message in str(error), str(error)) + else: + state(name, False, "accepted") + + expect_parse_error("record: truncated", serialized["2d"][:-4], "length does not match") + expect_parse_error("record: oversized", b"X2WN" + bytes(native.MAX_RECORD), "larger than") + expect_parse_error("record: bad magic", b"ZZZZ" + serialized["2d"][4:], "magic is not X2WN") + + # JSON intake + payload = native.record_to_json(record_2d) + for label, mutation, message in ( + ("unknown field", dict(payload, bogus=1), "Unknown record field"), + ("missing field", {k: v for k, v in payload.items() if k != "profile"}, "Missing record field"), + ("derived field", dict(payload, record_sha256="00"), "Unknown record field"), + ("fixed field", dict(payload, version=2), "is fixed at 1")): + try: + native.record_from_json(mutation) + except native.RecordError as error: + state(f"json: {label} is a named error", message is None or message in str(error), str(error)) + else: + state(f"json: {label} is a named error", False, "accepted") + try: + native.validate(native.record_from_json(dict(payload, group=[8, 4, 2]))) + except native.RecordError as error: + state("json: a semantically invalid group is refused", "Profile 2d" in str(error), str(error)) + else: + state("json: a semantically invalid group is refused", False, "accepted") + try: + native._no_duplicate_keys([("version", 1), ("version", 1)]) + except native.RecordError as error: + state("json: duplicate field is a named error", "Duplicate" in str(error), str(error)) + else: + state("json: duplicate field is a named error", False, "accepted") + + # ------------------------------------------------------------------ H1 manifest acceptance + base = clone("acceptance") + paths = native.cache_paths(base, keys["2d"]) + for field in native.MANIFEST_VALIDATED: + target = clone_of(base, f"drop-{field}") + fields = manifest_of(target, keys["2d"]) + fields.pop(field) + rewrite_manifest(target, keys["2d"], fields) + finding = native.inspect_entry(target, keys["2d"], REQUIRED) + state(f"manifest: missing {field} is not a hit", finding["state"] == "corrupt", + f'state={finding["state"]} {finding["detail"]}') + + for field in IDENTITY_MUTATIONS: + target = clone_of(base, f"identity-{field}") + fields = manifest_of(target, keys["2d"]) + fields[field] = "foreign/0000000000000000" + rewrite_manifest(target, keys["2d"], fields) + state(f"manifest: foreign {field} is stale", + native.entry_state(target, keys["2d"], REQUIRED)[0] == "stale") + + for field, bad in (("record_version", "9"), ("validation", "container=0x80004005 module=0x00000000"), + ("rts0", "a test marker"), ("gate", "DENY"), ("signed", "unsigned"), + ("output_bytes", "1"), ("code_sha256", "00")): + target = clone_of(base, f"evidence-{field}") + fields = manifest_of(target, keys["2d"]) + fields[field] = bad + rewrite_manifest(target, keys["2d"], fields) + finding = native.inspect_entry(target, keys["2d"], REQUIRED) + state(f"manifest: invalid {field} is not a hit", finding["state"] == "corrupt", + f'state={finding["state"]} {finding["detail"]}') + + target = clone_of(base, "manifest-key") + fields = manifest_of(target, keys["2d"]) + fields["key"] = native.key_text(keys["2d"] ^ 1) + rewrite_manifest(target, keys["2d"], fields) + state("manifest: a foreign cache key is stale", + native.entry_state(target, keys["2d"], REQUIRED)[0] == "stale") + + target = clone_of(base, "failed-hresult") + fields = manifest_of(target, keys["2d"]) + fields["pso-warp"] = fields["pso-warp"].replace("root=0x00000000", "root=0x80004005") + rewrite_manifest(target, keys["2d"], fields) + state("manifest: a failed HRESULT is not a hit", + native.entry_state(target, keys["2d"], REQUIRED)[0] == "backend-missing") + + target = clone_of(base, "missing-cso") + native.cache_paths(target, keys["2d"])["output"].unlink() + state("manifest: missing CSO is corrupt", + native.entry_state(target, keys["2d"], REQUIRED)[0] == "corrupt") + target = clone_of(base, "missing-hlsl") + native.cache_paths(target, keys["2d"])["hlsl"].unlink() + state("manifest: missing HLSL is corrupt", + native.entry_state(target, keys["2d"], REQUIRED)[0] == "corrupt") + target = clone_of(base, "missing-request") + native.cache_paths(target, keys["2d"])["request"].unlink() + state("manifest: missing request is corrupt", + native.entry_state(target, keys["2d"], REQUIRED)[0] == "corrupt") + + target = clone_of(base, "tampered-cso") + tampered_blob = bytearray(native.cache_paths(target, keys["2d"])["output"].read_bytes()) + tampered_blob[-1] ^= 0xFF + native.cache_paths(target, keys["2d"])["output"].write_bytes(bytes(tampered_blob)) + state("manifest: tampered CSO is corrupt", + native.entry_state(target, keys["2d"], REQUIRED)[0] == "corrupt") + target = clone_of(base, "tampered-hlsl") + tampered_hlsl = bytearray(native.cache_paths(target, keys["2d"])["hlsl"].read_bytes()) + tampered_hlsl[-1] ^= 0xFF + native.cache_paths(target, keys["2d"])["hlsl"].write_bytes(bytes(tampered_hlsl)) + state("manifest: tampered HLSL is corrupt", + native.entry_state(target, keys["2d"], REQUIRED)[0] == "corrupt") + + target = clone_of(base, "unsigned") + signed = bytearray(native.cache_paths(target, keys["2d"])["output"].read_bytes()) + signed[4:20] = bytes(16) + native.cache_paths(target, keys["2d"])["output"].write_bytes(bytes(signed)) + fields = manifest_of(target, keys["2d"]) + fields["output_sha256"] = sha_bytes(bytes(signed)) + fields["output_bytes"] = str(len(signed)) + rewrite_manifest(target, keys["2d"], fields) + finding = native.inspect_entry(target, keys["2d"], REQUIRED) + state("manifest: zeroed signing digest is not a hit", finding["state"] == "corrupt", + finding["detail"]) + + target = clone_of(base, "root-contract") + root_blob = bytearray(native.cache_paths(target, keys["2d"])["output"].read_bytes()) + offset = part_offset(bytes(root_blob), b"RTS0") + 8 + struct.pack_into(" --program both + +The Windows stages compile, validate and probe the same HLSL: + + out\\pe-env\\Scripts\\python.exe -B tests/compute_native_check.py --out out\\native-compute\\preflight ` + --wsl-distro Ubuntu-22.04 --dxc --root-probe root_probe.exe --device-probe root_device_probe.exe + +Stages: translate, controls, reference, assemble, disassemble, compile, validate, probe. +Exit codes: 0 all requested stages passed, 77 a capability skip, 1 a failure. +""" +import argparse +import json +import hashlib +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) + +import compute_store_aot as aot # noqa: E402 +from pixel_aot import disassemble # noqa: E402 +from resource_inventory import parts # noqa: E402 + +SKIP = 77 +LLVM15_MC = "/usr/lib/llvm-15/bin/llvm-mc" +LLVM15_OBJCOPY = "/usr/lib/llvm-15/bin/llvm-objcopy" +LLVM15_LIB = "/usr/lib/llvm-15/lib/libLLVM-15.so.1" + +# Stage 3J's proposed program, kept verbatim as the control that the local translator refuses: the +# lane guard compares against a linear index that v_mad_u32_u24 computed, and a guard operand must be +# a dispatch-thread word, not an ALU result. +STAGE3J_LINEAR = [ + "s_mov_b32 s1, 0", + "s_load_dwordx4 s[4:7], s[0:1], 0x20", + "v_lshl_add_u32 v0, s2, 3, v0", + "v_lshl_add_u32 v1, s3, 2, v1", + "v_mad_u32_u24 v0, v1, 24, v0", + "s_waitcnt lgkmcnt(0)", + "s_buffer_load_dword s16, s[4:7], 0x0", + "s_buffer_load_dword s17, s[4:7], 0x4", + "s_waitcnt lgkmcnt(0)", + "s_load_dwordx8 s[8:15], s[0:1], 0x0", + "v_cmp_gt_u32_e32 vcc_lo, s16, v0", + "s_and_saveexec_b32 s2, vcc_lo", + "s_cbranch_execz .LBB0_2", + "v_lshlrev_b32_e32 v2, 2, v0", + "s_waitcnt lgkmcnt(0)", + "buffer_load_dword v1, v2, s[12:15], 0 offen", + "s_waitcnt vmcnt(0)", + "v_and_b32_e32 v3, 0xffff, v1", + "v_lshrrev_b32_e32 v1, 16, v1", + "v_mad_u32_u24 v1, v3, v1, v0", + "v_min_u32_e32 v1, s17, v1", + "buffer_store_dword v1, v0, s[8:11], 0 idxen", + ".LBB0_2:", + "s_endpgm", +] + +# The corrected two-dimensional program. The store uses the translator's proven two-axis layout +# (idxen = row, offen = column bytes), so the linear index the refused program computed is not needed. +# The guard is the column bound, which is the only kind of lane guard the translator verifies. +PROGRAM_2D = [ + "s_mov_b32 s1, 0", + "s_load_dwordx4 s[4:7], s[0:1], 0x20", + "v_lshl_add_u32 v0, s2, 3, v0", + "v_lshl_add_u32 v1, s3, 2, v1", + "s_waitcnt lgkmcnt(0)", + "s_buffer_load_dword s16, s[4:7], 0x0", + "s_buffer_load_dword s17, s[4:7], 0x4", + "s_waitcnt lgkmcnt(0)", + "s_load_dwordx8 s[8:15], s[0:1], 0x0", + "v_lshlrev_b32_e32 v2, 2, v0", + "v_cmp_gt_u32_e32 vcc_lo, s16, v0", + "s_and_saveexec_b32 s2, vcc_lo", + "s_cbranch_execz .LBB0_2", + "s_waitcnt lgkmcnt(0)", + "buffer_load_dword v3, v2, s[12:15], 0 offen", + "s_waitcnt vmcnt(0)", + "v_and_b32_e32 v4, 0xffff, v3", + "v_lshrrev_b32_e32 v3, 16, v3", + "v_mad_u32_u24 v3, v4, v3, v0", + "v_min_u32_e32 v3, s17, v3", + "buffer_store_dword v3, v[1:2], s[8:11], 0 idxen offen", + ".LBB0_2:", + "s_endpgm", +] + +GROUP_2D = (8, 4, 1) +DISPATCH_2D = (3, 2, 1) +STRIDE_2D = 96 # 24 words per row of the 24x8 dispatch +BIND_2D = dict(table_reg=0, descriptor_offset=0, constant_descriptor=32, source_descriptor=16, + stride=STRIDE_2D, group_reg=2, group_reg_y=3) + +GROUP_1D = (32, 1, 1) +DISPATCH_1D = (6, 1, 1) +CONSTANTS = 16 # RootConstants(num32BitConstants=16,b0) +CAP = 100000 +SENTINEL = 0xC5C5C5C5 +WORDS = 320 # UAV size; the kernel writes at most words 0..191 + +ROOT_SIGNATURE = 'SRV(t0),UAV(u0),RootConstants(num32BitConstants=16,b0)' + + +def read_compute_1d(): + """The frozen fixture's guarded read-compute-write program and binding, imported, not copied.""" + sys.path.insert(0, str(ROOT / "tests")) + import compute_store_check as frozen + + return frozen.READ_COMPUTE, frozen.READ_BINDING + + +def source_word(index): + """The fixture's input: a 16-bit low half and a small high half, so the product never wraps.""" + return ((0x1234 + 0x101 * index) & 0xFFFF) | ((1 + index % 7) << 16) + + +def reference_1d(active, cap=CAP): + """Words for the 1-D program: out[i] = min(cap, (low * high + i) mod 2^32).""" + words = [SENTINEL] * WORDS + for i in range(active): + value = source_word(i) + product = (value & 0xFFFF) * (value >> 16) + words[i] = min(cap, (product + i) & 0xFFFFFFFF) + return words + + +def row_index(row, column): + return row * 24 + column + + +def reference_2d(columns, cap=CAP): + """Words for the 2-D program: out[row*24 + col] = min(cap, low(col) * high(col) + col). + + The read is a column broadcast: the translator's load has no row term, so every row reads the + same 24 source words. That is the documented limitation of this fixture. + """ + words = [SENTINEL] * WORDS + for row in range(DISPATCH_2D[1] * GROUP_2D[1]): + for col in range(DISPATCH_2D[0] * GROUP_2D[0]): + if col >= columns: + continue + value = source_word(col) + product = (value & 0xFFFF) * (value >> 16) + words[row * 24 + col] = min(cap, (product + col) & 0xFFFFFFFF) + return words + + +def page(text): + return text if text.endswith("\n") else text + "\n" + + +def write(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(page(text), encoding="ascii") + return path + + +def run(command, **kwargs): + return subprocess.run(command, capture_output=True, text=True, **kwargs) + + +def translate_text(out): + """Stage: lower both programs from authored text and check the emitted contract.""" + result = {} + source = aot.lower(PROGRAM_2D, GROUP_2D, **BIND_2D) + write(out / "native_tile_2d.hlsl", source) + write(out / "native_tile_2d.s", "\n".join(PROGRAM_2D)) + (out / "native_tile_2d.json").write_text(json.dumps({ + "program": "native_tile_2d", + "assembled_from": "source-built gfx1013 assembly (tools/compute_store_aot.py lower())", + "group": list(GROUP_2D), + "dispatch": list(DISPATCH_2D), + "threads": DISPATCH_2D[0] * DISPATCH_2D[1] * GROUP_2D[0] * GROUP_2D[1], + "binding": BIND_2D, + "constants": CONSTANTS, + "root_signature": ROOT_SIGNATURE, + "text_sha256": hashlib.sha256("\n".join(PROGRAM_2D).encode("ascii")).hexdigest(), + "hlsl_sha256": hashlib.sha256(source.encode("ascii")).hexdigest(), + "hlsl_lines": len(source.splitlines()), + }, indent=2, sort_keys=True) + "\n", encoding="ascii") + + required = [ + "cbuffer Constants : register(b0) { uint4 params[4]; };", + "ByteAddressBuffer inputData : register(t0);", + "RWByteAddressBuffer outputData : register(u0);", + "[numthreads(8,4,1)]", + "void main(uint3 tid : SV_DispatchThreadID)", + "if (params[0].x > tid.x) {", + "outputData.Store(tid.y * 96u + (tid.x << 2u) + 0u,", + "inputData.Load((tid.x << 2u) + 0u)", + "min(params[0].y,", + "(0x00000010u & 31u)", + "& 0xffffffu", # v_mad_u32_u24 keeps its 24-bit operand masks + ] + missing = [fragment for fragment in required if fragment not in source] + if missing: + raise AssertionError(f"generated HLSL is missing {missing}:\n{source}") + result["2d"] = source + + one, binding = read_compute_1d() + fallback = aot.lower(one, GROUP_1D[0], **binding) + write(out / "native_tile_1d.hlsl", fallback) + if "[numthreads(32,1,1)]" not in fallback or "outputData.Store" not in fallback: + raise AssertionError(f"1-D fallback did not lower as expected:\n{fallback}") + result["1d"] = fallback + return result + + +def controls(): + """Refusals must be explicit and must name the reason, not fall back to a dummy output.""" + cases = [ + ("stage3j linear index", STAGE3J_LINEAR, GROUP_2D, BIND_2D, "Unverified lane guard compare"), + ("truncated stream", PROGRAM_2D[:-1], GROUP_2D, BIND_2D, "Missing final program exit"), + ("LDS opcode", [line.replace("v_min_u32_e32 v3, s17, v3", "ds_read_b32 v3, v0") + for line in PROGRAM_2D], GROUP_2D, BIND_2D, "Unverified private LDS read"), + ("missing source binding", PROGRAM_2D, GROUP_2D, + dict(BIND_2D, source_descriptor=None), "Unresolved compute descriptor load"), + ("wrong table register", PROGRAM_2D, GROUP_2D, + dict(BIND_2D, table_reg=6), "Unresolved compute descriptor load"), + ("group too large", PROGRAM_2D, (64, 32, 1), BIND_2D, "Unsupported thread group"), + ("group not a power of two", PROGRAM_2D, (6, 4, 1), BIND_2D, "Unverified dispatch index"), + ] + results = [] + for label, program, group, binding, message in cases: + try: + aot.lower(program, group, **binding) + except ValueError as error: + if message not in str(error): + raise AssertionError(f"{label}: expected {message!r}, got {error!r}") from error + results.append((label, message, str(error))) + else: + raise AssertionError(f"{label}: the translator accepted an unsupported program") + # The translator now accepts COMPUTE_PGM_RSRC2, but this adapter records the field without + # interpreting it: the profile below names its group registers explicitly. Both upstream + # refusals that keep that contract reachable are checked, because neither the record schema + # nor a group dimension may silently come from the field. + rsrc2_cases = [ + ("rsrc2 with explicit group registers", dict(BIND_2D, rsrc2=0x984), + "COMPUTE_PGM_RSRC2 places the group IDs"), + ("rsrc2 TG_SIZE_EN", dict(BIND_2D, rsrc2=0x400, group_reg=None, group_reg_y=None), + "COMPUTE_PGM_RSRC2 TG_SIZE_EN is not supported"), + ] + for label, binding, message in rsrc2_cases: + try: + aot.lower(PROGRAM_2D, GROUP_2D, **binding) + except ValueError as error: + if message not in str(error): + raise AssertionError(f"{label}: expected {message!r}, got {error!r}") from error + results.append((label, message, str(error))) + else: + raise AssertionError(f"{label}: the translator accepted the unsupported binding") + return results + + +# ---------------------------------------------------------------- Linux (LLVM) worker + +def llvm_version(mc): + result = run([mc, "--version"]) + return result.stdout.splitlines()[0].strip() if result.returncode == 0 else "unknown" + + +def assemble(program, mc, objcopy, stem): + """Source-built machine code through llvm-mc, exactly as the repository's fixtures do.""" + source, obj, raw = stem.with_suffix(".s"), stem.with_suffix(".o"), stem.with_suffix(".bin") + source.write_text("\n".join(program) + "\n", encoding="ascii") + subprocess.run([mc, "-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-filetype=obj", + str(source), "-o", str(obj)], check=True, capture_output=True, text=True) + subprocess.run([objcopy, "-O", "binary", "--only-section=.text", str(obj), str(raw)], + check=True, capture_output=True, text=True) + return raw.read_bytes() + + +def decode(code, library): + """Machine bytes to (offset, text) pairs, rejecting an unknown encoding.""" + return disassemble(code, library, offsets=True, cpu=b"gfx1013") + + +def boundary_check(code, decoded): + """Every instruction is 4-byte aligned with a 4- or 8-byte encoding, and covers all bytes.""" + if not decoded or decoded[0][0] != 0: + raise AssertionError("decoding does not start at byte 0") + offsets = [where for where, _ in decoded] + sizes = [later - earlier for earlier, later in zip(offsets, offsets[1:])] + sizes.append(len(code) - offsets[-1]) + for where, size in zip(offsets, sizes): + if where % 4 or size not in (4, 8): + raise AssertionError(f"instruction at byte {where} has encoding size {size}") + if sum(sizes) != len(code): + raise AssertionError(f"decoded {sum(sizes)} bytes of {len(code)}") + return sizes + + +def branch_check(decoded): + """The single conditional branch must target the final s_endpgm offset.""" + branch = [(where, text) for where, text in decoded if text.startswith("s_cbranch_execz")] + if len(branch) != 1: + raise AssertionError(f"expected one s_cbranch_execz, found {len(branch)}") + where, text = branch[0] + operand = text.split()[-1] + try: + # gfx10 prints the target as a signed dword offset from the next instruction. + target = where + 4 + 4 * int(operand, 0) + except ValueError as error: + raise AssertionError(f"branch operand is not a relative offset: {text!r}") from error + end = [at for at, line in decoded if line == "s_endpgm"] + if not end: + raise AssertionError("no s_endpgm in the decoded program") + if target <= where or target != end[-1]: + raise AssertionError(f"branch target {target} is not the forward exit at {end[-1]}") + return {"at": where, "operand": int(operand, 0), "target": target, "exit": end[-1]} + + +def worker_program(out, name, program, group, binding, mc, objcopy, library): + stem = out / f"native_{name}" + code = assemble(program, mc, objcopy, stem) + (out / f"native_{name}.sha256").write_text(hashlib.sha256(code).hexdigest() + "\n", encoding="ascii") + decoded = decode(code, library) + sizes = boundary_check(code, decoded) + branch = branch_check(decoded) + (out / f"native_{name}.disasm.txt").write_text( + "\n".join(f"{where:08x}: {text}" for where, text in decoded) + "\n", encoding="ascii") + text_hlsl = aot.lower(program, group, **binding) + decoded_hlsl = aot.lower(aot.labelled(decoded), group, **binding) + (out / f"native_{name}.text.hlsl").write_text(text_hlsl, encoding="ascii") + (out / f"native_{name}.decoded.hlsl").write_text(decoded_hlsl, encoding="ascii") + if text_hlsl != decoded_hlsl: + raise AssertionError(f"{name}: the decoded program lowers to different HLSL") + return { + "bytes": len(code), + "sha256": hashlib.sha256(code).hexdigest(), + "words": len(code) // 4, + "instructions": len(decoded), + "encodings": {"4-byte": sizes.count(4), "8-byte": sizes.count(8)}, + "termination": decoded[-1][1], + "branch": branch, + "text_hlsl_sha256": hashlib.sha256(text_hlsl.encode("ascii")).hexdigest(), + "decoded_hlsl_sha256": hashlib.sha256(decoded_hlsl.encode("ascii")).hexdigest(), + "hlsl_identical": True, + } + + +def worker_controls(out, mc, objcopy, library): + """Byte-level refusals: the same decode -> lower path the accepted program takes.""" + stem = out / "control" + results = [] + + def attempt(label, code, group, binding, message): + try: + decoded = decode(code, library) + except ValueError as error: + actual = f"{type(error).__name__}: {error}" + else: + try: + aot.lower(aot.labelled(decoded), group, **binding) + except ValueError as error: + actual = f"{type(error).__name__}: {error}" + else: + actual = "ACCEPTED" + ok = message in actual + results.append({"control": label, "expected": message, "actual": actual, "ok": ok}) + if not ok: + raise AssertionError(f"{label}: expected {message!r}, got {actual!r}") + + good = assemble(PROGRAM_2D, mc, objcopy, stem.with_name("control_good")) + attempt("truncated stream (exit removed)", good[:-4], GROUP_2D, BIND_2D, + "Branch outside decoded instruction boundaries") + attempt("truncated stream (partial instruction)", good[:-2], GROUP_2D, BIND_2D, + "Unknown instruction at byte") + attempt("invalid instruction encoding", bytes.fromhex("ffffffff") + good[4:], GROUP_2D, BIND_2D, + "Unknown instruction at byte 0") + lds = assemble([line.replace("v_min_u32_e32 v3, s17, v3", "ds_read_b32 v3, v0") + for line in PROGRAM_2D], mc, objcopy, stem.with_name("control_lds")) + attempt("unsupported opcode", lds, GROUP_2D, BIND_2D, "Unverified private LDS read") + no_exit = assemble(PROGRAM_2D[:-1], mc, objcopy, stem.with_name("control_noexit")) + attempt("missing final exit", no_exit, GROUP_2D, BIND_2D, + "Branch outside decoded instruction boundaries") + linear = assemble(STAGE3J_LINEAR, mc, objcopy, stem.with_name("control_linear")) + attempt("computed-index guard", linear, GROUP_2D, BIND_2D, "Unverified lane guard compare") + + # Binding and group refusals against the *decoded* text, not the authored text. + decoded_good = aot.labelled(decode(good, library)) + for label, group, binding, message in ( + ("decoded: wrong table register", GROUP_2D, dict(BIND_2D, table_reg=6), + "Unresolved compute descriptor load"), + ("decoded: missing source binding", GROUP_2D, dict(BIND_2D, source_descriptor=None), + "Unresolved compute descriptor load"), + ("decoded: group too large", (64, 32, 1), BIND_2D, "Unsupported thread group")): + try: + aot.lower(decoded_good, group, **binding) + except ValueError as error: + actual = f"{type(error).__name__}: {error}" + else: + actual = "ACCEPTED" + ok = message in actual + results.append({"control": label, "expected": message, "actual": actual, "ok": ok}) + if not ok: + raise AssertionError(f"{label}: expected {message!r}, got {actual!r}") + return results + + +def linux_worker(argv): + parser = argparse.ArgumentParser(prog="compute_native_check.py --linux-worker") + parser.add_argument("--linux-worker", action="store_true", required=True) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--program", choices=("2d", "1d", "both"), default="both") + parser.add_argument("--llvm-mc", default=LLVM15_MC) + parser.add_argument("--objcopy", default=LLVM15_OBJCOPY) + parser.add_argument("--llvm", default=LLVM15_LIB) + args = parser.parse_args(argv) + + out = args.out + out.mkdir(parents=True, exist_ok=True) + report = { + "llvm": {"llvm_mc": args.llvm_mc, "objcopy": args.objcopy, "libLLVM": args.llvm, + "version": llvm_version(args.llvm_mc), "target": "amdgcn--amdpal", "cpu": "gfx1013"}, + "python": sys.version.split()[0], + } + if args.program in ("both", "2d"): + report["2d"] = worker_program(out, "2d", PROGRAM_2D, GROUP_2D, BIND_2D, + args.llvm_mc, args.objcopy, args.llvm) + if args.program in ("both", "1d"): + one, binding = read_compute_1d() + report["1d"] = worker_program(out, "1d", one, GROUP_1D, binding, + args.llvm_mc, args.objcopy, args.llvm) + report["controls"] = worker_controls(out, args.llvm_mc, args.objcopy, args.llvm) + (out / "machine.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", + encoding="ascii") + print(f"linux worker: {report['llvm']['version']}, " + f"2d={report.get('2d', {}).get('bytes', 0)} B, 1d={report.get('1d', {}).get('bytes', 0)} B, " + f"{len(report['controls'])} byte controls") + return 0 + + +# ---------------------------------------------------------------- Windows stages + +def to_wsl_path(path): + resolved = Path(path).resolve() + drive = resolved.drive.rstrip(":").lower() + return f"/mnt/{drive}" + resolved.as_posix()[len(resolved.drive):] + + +def check_container(blob): + if blob[:4] != b"DXBC": + raise AssertionError(f"DXC output is not a DXBC container: {blob[:4]!r}") + tags = [tag.decode("ascii", "replace") for tag in parts(blob)] + if "DXIL" not in tags: + raise AssertionError(f"DXC output has no DXIL part: {tags}") + return tags + + +def compile_hlsl(dxc, source, output, directory, *, root): + """Compile one HLSL file; with root=True, add the fixture root signature attribute.""" + path = directory / output.replace(".cso", ".hlsl") + text = source + if root: + index = text.index("[numthreads(") + text = text[:index] + f'[RootSignature("{ROOT_SIGNATURE}")]\n' + text[index:] + path.write_text(text, encoding="ascii") + result = run([str(dxc), "-T", "cs_6_0", "-E", "main", "-Fo", str(directory / output), str(path)]) + if result.returncode: + raise AssertionError(f"dxc failed for {output}:\n{result.stdout}\n{result.stderr}") + return (directory / output).read_bytes(), result.returncode + + +def compare_hlsl(out, machine_dir): + """Decoded-code HLSL against the accepted text-mode HLSL; a newline difference must be the only one.""" + result = {} + for name in ("2d", "1d"): + text_path = out / f"native_tile_{name}.hlsl" + decoded_path = machine_dir / f"native_{name}.decoded.hlsl" + if not (text_path.exists() and decoded_path.exists()): + continue + text_bytes, decoded_bytes = text_path.read_bytes(), decoded_path.read_bytes() + normalized_text = text_bytes.replace(b"\r\n", b"\n") + normalized_decoded = decoded_bytes.replace(b"\r\n", b"\n") + result[name] = { + "text_bytes": len(text_bytes), + "decoded_bytes": len(decoded_bytes), + "text_sha256": hashlib.sha256(text_bytes).hexdigest(), + "decoded_sha256": hashlib.sha256(decoded_bytes).hexdigest(), + "byte_identical": text_bytes == decoded_bytes, + "line_endings_only": normalized_text == normalized_decoded and text_bytes != decoded_bytes, + "normalized_sha256": hashlib.sha256(normalized_text).hexdigest(), + } + if not (text_bytes == decoded_bytes or normalized_text == normalized_decoded): + raise AssertionError(f"{name}: the decoded program lowers to different HLSL") + (out / "hlsl-comparison.json").write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", + encoding="ascii") + return result + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--out", type=Path, default=ROOT / "out" / "native-compute" / "preflight") + parser.add_argument("--linux-worker", action="store_true", help="run the LLVM stages in Linux") + parser.add_argument("--program", choices=("2d", "1d", "both"), default="both") + parser.add_argument("--wsl-distro", help="run the LLVM worker through this WSL distribution") + parser.add_argument("--llvm-mc") + parser.add_argument("--objcopy") + parser.add_argument("--llvm") + parser.add_argument("--dxc") + parser.add_argument("--root-probe") + parser.add_argument("--device-probe") + parser.add_argument("--warp-only", action="store_true") + args = parser.parse_args(argv) + + if args.linux_worker: + return linux_worker(argv) + + out = args.out.resolve() + out.mkdir(parents=True, exist_ok=True) + (out / "command.txt").write_text( + "python -B tests/compute_native_check.py " + " ".join(sys.argv[1:]) + "\n", encoding="ascii") + skips, failures = [], [] + summary = [] + + def record(stage, outcome, detail): + summary.append((stage, outcome, detail)) + print(f"N0 stage={stage:<12} {outcome:<6} {detail}") + + # -- translate (authored text) + translated = None + try: + translated = translate_text(out) + record("translate", "PASS", f"2-D {len(translated['2d'].splitlines())} HLSL lines, " + f"1-D {len(translated['1d'].splitlines())} HLSL lines") + except Exception as error: # noqa: BLE001 - the report names the failure + failures.append(("translate", str(error))) + record("translate", "FAIL", str(error)) + + # -- controls (authored text) + text_controls = [] + try: + text_controls = controls() + write(out / "controls.txt", "\n".join( + f"{label}: {expected}\n {actual}" for label, expected, actual in text_controls)) + record("controls", "PASS", f"{len(text_controls)} refusals, all named") + except Exception as error: # noqa: BLE001 + failures.append(("controls", str(error))) + record("controls", "FAIL", str(error)) + + # -- reference + try: + cases = [ + ("1d-n192", reference_1d(192), 192, 0), + ("1d-n173", reference_1d(173), 173, 19), + ("1d-n0", reference_1d(0), 0, 192), + ("2d-n24", reference_2d(24), 192, 0), + ("2d-n13", reference_2d(13), 104, 88), + ("2d-n0", reference_2d(0), 0, 192), + ] + payload = {} + for name, words, active, inactive in cases: + if len(words) != WORDS: + raise AssertionError(f"{name}: {len(words)} words") + payload[name] = {"active": active, "inactive": inactive, "words": words} + assert payload["1d-n192"]["words"][0] == 0x1234, payload["1d-n192"]["words"][0] + assert payload["1d-n192"]["words"][1] == 0x266B, payload["1d-n192"]["words"][1] + assert payload["1d-n192"]["words"][191] == CAP, payload["1d-n192"]["words"][191] + assert payload["1d-n173"]["words"][173] == SENTINEL + assert payload["2d-n13"]["words"][row_index(0, 12)] != SENTINEL, "column 12 must be written" + assert payload["2d-n13"]["words"][row_index(0, 13)] == SENTINEL, "column 13 must stay untouched" + assert payload["2d-n13"]["words"][row_index(1, 13)] == SENTINEL + # The 2-D read is a column broadcast: every row's active prefix is identical. + for row in range(1, 8): + assert payload["2d-n24"]["words"][row_index(row, 5)] == payload["2d-n24"]["words"][row_index(0, 5)] + (out / "reference.json").write_text(json.dumps(payload, indent=2) + "\n", encoding="ascii") + + # Lower-cap case: the cap binds for every active element. + low_cap = 4000 + for name, words, active in (("1d", reference_1d(192, cap=low_cap), 192), + ("2d", reference_2d(24, cap=low_cap), 192)): + if any(word != low_cap for word in words[:active]): + raise AssertionError(f"{name}: a lower cap did not bind on every active element") + if any(word != SENTINEL for word in words[active:]): + raise AssertionError(f"{name}: a lower cap changed an inactive word") + + # Row-stride sensitivity: a record with the wrong stride changes the address map, so the + # reference built for 96 bytes cannot describe it. + wrong = aot.lower(PROGRAM_2D, GROUP_2D, **dict(BIND_2D, stride=92)) + if wrong == translated["2d"]: + raise AssertionError("a wrong row stride produced identical HLSL") + accepted_row1 = STRIDE_2D // 4 + wrong_row1 = 92 // 4 + if accepted_row1 == wrong_row1: + raise AssertionError("the stride control does not separate row 1") + (out / "sensitivity.json").write_text(json.dumps({ + "lower_cap": {"cap": low_cap, "active_elements": 192, + "every_active_word": low_cap, "inactive_words": "sentinel"}, + "wrong_row_stride": {"accepted": STRIDE_2D, "wrong": 92, + "row1_col0_word_accepted": accepted_row1, + "row1_col0_word_wrong": wrong_row1, + "hlsl_differs": True}, + "row_broadcast": {"rows_identical": True, + "reason": "the load has no row term; only the store separates rows"}, + }, indent=2, sort_keys=True) + "\n", encoding="ascii") + record("reference", "PASS", "192/173/0 active (1-D), 24/13/0 columns (2-D), cap and stride controls") + except Exception as error: # noqa: BLE001 + failures.append(("reference", str(error))) + record("reference", "FAIL", str(error)) + + # -- assemble + disassemble (Linux worker, or a native LLVM if one is supplied) + machine = None + machine_dir = out / "llvm" + if args.wsl_distro: + try: + machine_dir.mkdir(parents=True, exist_ok=True) + command = ["wsl", "-d", args.wsl_distro, "-u", "root", "--", "python3", + to_wsl_path(ROOT / "tests" / "compute_native_check.py"), + "--linux-worker", "--out", to_wsl_path(machine_dir), "--program", "both"] + result = run(command) + (machine_dir / "linux-worker.log").write_text( + f"$ {' '.join(command)}\nexit={result.returncode}\n{result.stdout}\n{result.stderr}\n", + encoding="ascii") + if result.returncode: + raise AssertionError(f"linux worker failed:\n{result.stdout}\n{result.stderr}") + machine = json.loads((machine_dir / "machine.json").read_text(encoding="ascii")) + comparison = compare_hlsl(out, machine_dir) + record("assemble", "PASS", + f"2d {machine['2d']['bytes']} B sha256 {machine['2d']['sha256'][:16]}..., " + f"1d {machine['1d']['bytes']} B sha256 {machine['1d']['sha256'][:16]}...") + record("disassemble", "PASS", + f"2d {machine['2d']['instructions']} instructions, branch " + f"{machine['2d']['branch']['at']}->{machine['2d']['branch']['target']}, " + f"1d {machine['1d']['instructions']} instructions, HLSL " + + ", ".join(f"{name}:{'identical' if entry['byte_identical'] else 'newlines-only'}" + for name, entry in comparison.items())) + byte_controls = machine["controls"] + (machine_dir / "byte-controls.json").write_text( + json.dumps(byte_controls, indent=2) + "\n", encoding="ascii") + with (out / "controls.txt").open("a", encoding="ascii") as handle: + for entry in byte_controls: + handle.write(f"bytes: {entry['control']}: {entry['expected']}\n {entry['actual']}\n") + record("controls", "PASS", + f"{len(text_controls)} text refusals + {len(byte_controls)} byte refusals") + except Exception as error: # noqa: BLE001 + failures.append(("assemble", str(error))) + record("assemble", "FAIL", str(error)) + elif args.llvm_mc and args.objcopy: + try: + machine_dir.mkdir(parents=True, exist_ok=True) + # A native LLVM: assemble here, no worker process. + machine = {} + one, one_binding = read_compute_1d() + for name, program, group, binding in ( + ("2d", PROGRAM_2D, GROUP_2D, BIND_2D), + ("1d", one, GROUP_1D, one_binding)): + machine[name] = worker_program(machine_dir, name, program, group, binding, + args.llvm_mc, args.objcopy, args.llvm) + machine["controls"] = worker_controls(machine_dir, args.llvm_mc, args.objcopy, args.llvm) + (machine_dir / "machine.json").write_text(json.dumps(machine, indent=2, sort_keys=True) + "\n", + encoding="ascii") + record("assemble", "PASS", "native llvm-mc/objcopy") + record("disassemble", "PASS", "native libLLVM, HLSL identical") + except Exception as error: # noqa: BLE001 + failures.append(("assemble", str(error))) + record("assemble", "FAIL", str(error)) + else: + skips.append(("assemble", "no --wsl-distro and no --llvm-mc/--objcopy")) + record("assemble", "SKIP", "no LLVM toolchain was available") + skips.append(("disassemble", "no libLLVM")) + record("disassemble", "SKIP", "no libLLVM was available") + + # -- compile: the HLSL generated from the decoded machine code when it exists + programs = {} + if translated is not None: + programs["2d"] = translated["2d"] + programs["1d"] = translated["1d"] + if machine: + for name in ("2d", "1d"): + path = machine_dir / f"native_{name}.decoded.hlsl" + if path.exists(): + programs[name] = path.read_text(encoding="ascii") + containers = {} + if args.dxc and programs: + try: + for name, source in programs.items(): + plain, _ = compile_hlsl(args.dxc, source, f"native_{name}.cso", out, root=False) + rooted, _ = compile_hlsl(args.dxc, source, f"native_{name}.root.cso", out, root=True) + tags_plain, tags_root = check_container(plain), check_container(rooted) + if b"xbox." in plain: + raise AssertionError(f"{name}: the compiled module names an xbox intrinsic") + if "RTS0" not in tags_root: + raise AssertionError(f"{name}: the root variant carries no RTS0 part") + containers[name] = {"plain": plain, "root": rooted, + "tags_plain": tags_plain, "tags_root": tags_root} + (out / "containers.json").write_text(json.dumps({ + name: { + "source": "decoded machine code" if machine else "authored text", + "plain": {"parts": entry["tags_plain"], "bytes": len(entry["plain"]), + "sha256": hashlib.sha256(entry["plain"]).hexdigest()}, + "root": {"parts": entry["tags_root"], "bytes": len(entry["root"]), + "sha256": hashlib.sha256(entry["root"]).hexdigest()}, + } for name, entry in containers.items() + }, indent=2) + "\n", encoding="ascii") + record("compile", "PASS", "; ".join( + f"{name} {len(entry['plain'])}/{len(entry['root'])} B" for name, entry in containers.items())) + except Exception as error: # noqa: BLE001 + failures.append(("compile", str(error))) + record("compile", "FAIL", str(error)) + else: + skips.append(("compile", "no --dxc")) + record("compile", "SKIP", "dxc was not supplied") + + # -- validate + checks = {} + if args.root_probe and containers and not failures: + try: + import dxil_retarget as rt + from probe_roots import validate_shader + + evidence = {} + for name, entry in containers.items(): + for variant in ("plain", "root"): + blob = entry[variant] + key = f"{name}.{variant}" + checks[key] = validate_shader(Path(args.root_probe), blob, parts(blob)[b"DXIL"]) + status = checks[key]["container"]["status"] + module_status = checks[key]["module"]["status"] + if status != "0x00000000" or module_status != "0x00000000": + raise AssertionError(f"{key}: validation {status} / {module_status}") + if checks[key]["ir"]["xbox_call_sites"]: + raise AssertionError(f"{key}: xbox calls {checks[key]['ir']['xbox_call_sites']}") + signed = rt.sign_container(Path(args.root_probe), blob) + check_container(signed) + try: + rt.sign_container(Path(args.root_probe), blob[:-4]) + except Exception: # noqa: BLE001 - any refusal is the expected outcome + tamper = "rejected" + else: + raise AssertionError(f"{key}: the signer accepted a truncated container") + evidence[key] = { + "validation": checks[key], + "signed_bytes": len(signed), + "signed_sha256": hashlib.sha256(signed).hexdigest(), + "signed_digest_nonzero": signed[4:20] != bytes(16), + "signer_identical_to_dxc_output": signed == blob, + "truncated_container": tamper, + } + (out / f"native_{name}.{variant}.signed.cso").write_bytes(signed) + (out / "validation.json").write_text(json.dumps(evidence, indent=2, sort_keys=True) + "\n", + encoding="ascii") + record("validate", "PASS", "dxil.dll 0x00000000 for container and module, signed, both variants") + except Exception as error: # noqa: BLE001 + failures.append(("validate", str(error))) + record("validate", "FAIL", str(error)) + else: + skips.append(("validate", "no --root-probe")) + record("validate", "SKIP", "root_probe was not supplied") + + # -- probe + if args.device_probe and checks and not failures: + try: + import dxil_retarget as rt + + results = {} + for name in containers: + blob = containers[name]["root"] + inventory = checks[f"{name}.root"]["ir"]["xbox_intrinsics"] + warp = rt.check_compute_pso(Path(args.device_probe), blob, warp_only=True, + intrinsics=inventory) + both = rt.check_compute_pso(Path(args.device_probe), blob, warp_only=False, + intrinsics=inventory) + results[name] = {"warp": warp, "both": both} + (out / f"native_{name}.pso.json").write_text( + json.dumps(both, indent=2, sort_keys=True) + "\n", encoding="ascii") + (out / "pso.json").write_text(json.dumps(results, indent=2, sort_keys=True) + "\n", + encoding="ascii") + plain = rt.check_compute_pso(Path(args.device_probe), containers["2d"]["plain"], + warp_only=True, + intrinsics=checks["2d.root"]["ir"]["xbox_intrinsics"]) + (out / "pso-plain-container.json").write_text( + json.dumps({"embedded_root_missing": plain}, indent=2, sort_keys=True) + "\n", + encoding="ascii") + record("probe", "PASS", "; ".join( + f"{name} warp={results[name]['warp'].get('warp_pso')} " + f"hw={results[name]['both'].get('hardware_pso')}" for name in results)) + except subprocess.CalledProcessError as error: + detail = (error.stderr or b"").decode("utf-8", "replace").strip() or f"exit {error.returncode}" + if error.returncode == 5: + skips.append(("probe", detail)) + record("probe", "SKIP", detail) + else: + failures.append(("probe", detail)) + record("probe", "FAIL", detail) + except Exception as error: # noqa: BLE001 + failures.append(("probe", str(error))) + record("probe", "FAIL", str(error)) + else: + skips.append(("probe", "no --device-probe or no validated container")) + record("probe", "SKIP", "root_device_probe was not supplied") + + (out / "summary.json").write_text(json.dumps({ + "stages": [{"stage": s, "outcome": o, "detail": d} for s, o, d in summary], + "failures": failures, "skips": skips, + "machine_code": {name: {key: machine[name][key] for key in + ("bytes", "sha256", "instructions", "hlsl_identical")} + for name in ("2d", "1d")} if machine else None, + }, indent=2) + "\n", encoding="ascii") + + if failures: + print(f"N0 result: FAIL ({len(failures)} stage(s))") + return 1 + if skips: + print(f"N0 result: PARTIAL ({len(skips)} capability skip(s))") + return SKIP if len(skips) == len(summary) - 1 else 0 + print("N0 result: PASS") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/compute_native.py b/tools/startup/compute_native.py new file mode 100644 index 0000000000..e32fae34b5 --- /dev/null +++ b/tools/startup/compute_native.py @@ -0,0 +1,1459 @@ +"""Offline native gfx1013 compute adapter and cache (#1412, Stage 4B.2). + +Fixture-only toolchain: it consumes a bounded native compute record, translates the machine code +through the existing translator, compiles and validates desktop DXIL, probes the PSO and publishes an +integrity-checked cache entry. It does not touch the runtime, the slot 67 table or the slot 62 slice. + +Stages, so a machine with LLVM and a machine with DXC can split the work: + + --stage request write req_.csn and .csn.src from record JSON files + --stage translate --llvm LIB machine code -> HLSL (needs LLVM 15 + gfx1013) + --stage compile --dxc ... --probe ... --pso-probe ... HLSL -> validated signed DXIL + +Cache family: x2w-startup-compute-native-2 + req_.csn canonical record bytes + .csn.src request manifest + .csn.hlsl translated source (an intermediate, not a validated entry) + .csn.cso signed desktop DXIL + .csn.manifest response manifest, published last + .csn.error retryable infrastructure failure + .csn.corrupt quarantined malformed request + .csn.lock single-writer lock with an ownership token + +Single writer: a lock is acquired with O_EXCL and holds a random ownership token. It is never +reclaimed because of age; every cache mutation asserts the token first and release only removes a +lock that still holds this writer's token. An abandoned lock is a manual-repair condition: the +operator must establish that the original writer has stopped before deleting it. + +Exit codes: 0 published, revalidated or a cache hit; 1 a permanent program refusal; 2 retryable, +busy or a toolchain mismatch; 3 a record or usage error; 4 a quarantined corrupt request. +""" +import argparse +import contextlib +import hashlib +import json +import os +import re +import secrets +import struct +import subprocess +import sys +import time +from functools import lru_cache +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "tools")) + +MAGIC = b"X2WN" +VERSION = 1 +STAGE_COMPUTE = 5 +ISA_GFX1013 = 1 +GUEST_WAVE32 = 32 +REVISION = "x2w-startup-compute-native-2" +TRANSLATOR_NAME = "compute_store_aot" +DECODER_NAME = "pixel_aot" +TARGET = "dxil-ms-dx" +DXC_PROFILE = "cs_6_0" +DXC_FLAGS = "cs_6_0 -E main" +MAX_CODE = 64 * 1024 +MAX_RECORD = MAX_CODE + 4096 +MAX_MANIFEST = 1 << 16 +MAX_OUTPUT = 1 << 20 +MAX_HLSL = MAX_CODE * 4 +MAX_ROOT_PARAMETERS = 8 +NO_REGISTER = 0xFFFFFFFF + +D3D12_32BIT_CONSTANTS = 1 +D3D12_SRV = 3 +D3D12_UAV = 4 +SHADER_VISIBILITY_ALL = 0 +ROOT_DESCRIPTOR_FLAG_MASK_SUPPORTED = 0 + +PROFILE_1D = 1 +PROFILE_2D = 2 + +ROOT_FIXTURE = ( + (D3D12_SRV, 0, 1), + (D3D12_UAV, 0, 1), + (D3D12_32BIT_CONSTANTS, 0, 16), +) +ROOT_SIGNATURE = 'SRV(t0),UAV(u0),RootConstants(num32BitConstants=16,b0)' +ROOT_CONSTANTS = 16 + +# Deliberately pinned, content-addressed toolchain identities. The translate stage hashes the +# libLLVM file it is given and refuses a different one; the compile stage hashes dxcompiler.dll and +# dxil.dll next to the dxc it is given. A toolchain change is an explicit edit here and invalidates +# every entry through the manifest identity, never silently through a stale acceptance. +PINNED_LLVM = "de2e35a4f9b3f6a06d2a8a3342b3f62a3842b1923b8dfc2a6ce48e0cc2d1e85d" +PINNED_COMPILER = "495033935c058fc6d318ac257afdfa910795bf41b7e5ba905a0e7191dc8bd4fa" +PINNED_VALIDATOR = "db108ffef7bcecb984bdccf2b4725719d65b2ce7f1ebc40019dbe6c5a7016e09" + +# Repository tools whose content is part of the produced artifact's identity. Names only: no +# absolute path ever enters a record or a manifest. +PIPELINE_TOOLS = ( + ("compute_store_aot", "tools/compute_store_aot.py"), + ("pixel_aot", "tools/pixel_aot.py"), + ("resource_inventory", "tools/resource_inventory.py"), + ("dxil_retarget", "tools/dxil_retarget.py"), + ("probe_roots", "tools/probe_roots.py"), + ("xbox_intrinsic_gate", "tools/xbox_intrinsic_gate.py"), + ("compute_native", "tools/startup/compute_native.py"), +) + +# Exactly the fields of serialize(), in serialization order. The magic precedes them; the root +# parameter list, the code digest and the code bytes follow them. +SCALARS = ( + "version", "stage", "isa", "profile", "guest_wave", + "group_x", "group_y", "group_z", + "dispatch_x", "dispatch_y", "dispatch_z", + "user_sgpr_count", "table_reg", "group_reg", "group_reg_y", + "descriptor_offset", "constant_descriptor", "source_descriptor", + "source_stride", "u0_stride", + "address_layout", "column_shift", "element_bytes", + "guard_axis", "guard_op", "bound_constant", "cap_constant", + "translator_revision", "decoder_id", "dxc_profile", "dxc_flags", + "rsrc2_interpretation", "recorded_rsrc2", "code_length", +) + +GUARD_OPS = {1: "gt"} +FIXED_JSON_FIELDS = ("version", "stage", "isa", "guest_wave", "translator_revision", "decoder_id", + "dxc_profile", "dxc_flags", "rsrc2_interpretation", "guard_op") +BUILD_FIELDS = ("profile", "user_sgpr_count", "table_reg", "group_reg", "group_reg_y", + "descriptor_offset", "constant_descriptor", "source_descriptor", "source_stride", + "u0_stride", "address_layout", "column_shift", "element_bytes", "guard_axis", + "bound_constant", "cap_constant", "recorded_rsrc2") +JSON_FIELDS = frozenset(BUILD_FIELDS + FIXED_JSON_FIELDS + + ("group", "dispatch", "root_parameters", "code_hex")) + +MANIFEST_HEADER = "x2w-native-compute 2" +MANIFEST_COMMON = ("key", "revision", "status", "record_version", "record_sha256") +MANIFEST_REQUEST = MANIFEST_COMMON + ("code_bytes", "code_sha256") +MANIFEST_REFUSED = MANIFEST_COMMON + ("code_bytes", "code_sha256", "reason") +MANIFEST_VALIDATED = MANIFEST_COMMON + ( + "code_bytes", "code_sha256", "group", "hlsl_sha256", "output_bytes", "output_sha256", + "translator", "decoder", "pipeline", "llvm", "compiler", "validator", "target", "dxc_flags", + "validation", "rts0", "gate", "signed", +) +MANIFEST_TRANSLATED = MANIFEST_COMMON + ( + "code_bytes", "code_sha256", "hlsl_sha256", "translator", "decoder", "pipeline", "llvm", +) +MANIFEST_IDENTITY = ("translator", "decoder", "pipeline", "llvm", "compiler", "validator", "target", + "dxc_flags") +MANIFEST_EVIDENCE = ("validation", "rts0", "gate", "signed") +MANIFEST_KNOWN = frozenset(MANIFEST_VALIDATED + ("reason",)) + +VALIDATION_OK = "container=0x00000000 module=0x00000000" +SIGNED_OK = "dxil-digest-nonzero" + + +class RecordError(ValueError): + """The record is malformed or outside the supported schema.""" + + +class Refusal(Exception): + """The program is unsupported. Publishing this is permanent.""" + + +class Retryable(Exception): + """Infrastructure could not complete the job. The request stays queued.""" + + +class ToolchainMismatch(Exception): + """The local toolchain is not the pinned, verified one. Nothing is mutated.""" + + +def fnv_bytes(data, current=1469598103934665603): + for byte in data: + current = ((current ^ byte) * 1099511628211) & 0xFFFFFFFFFFFFFFFF + return current + + +def digest_hex(data): + return hashlib.sha256(data).hexdigest() + + +def file_sha256(path): + return digest_hex(Path(path).read_bytes()) + + +# ---------------------------------------------------------------- identity + +@lru_cache(maxsize=1) +def expected_identity(): + """The pinned identity every validated manifest must declare exactly.""" + digests = [] + for name, relative in PIPELINE_TOOLS: + path = ROOT / relative + try: + digest = file_sha256(path) + except OSError as error: + raise ToolchainMismatch(f"cannot read dependency {relative}: {error}") from error + digests.append(f"{name}={digest}\n") + pipeline = digest_hex("".join(sorted(digests)).encode("ascii"))[:16] + translator = f"{TRANSLATOR_NAME}/{file_sha256(ROOT / 'tools' / 'compute_store_aot.py')[:16]}" + decoder = f"{DECODER_NAME}/{file_sha256(ROOT / 'tools' / 'pixel_aot.py')[:16]}" + return { + "translator": translator, + "decoder": decoder, + "pipeline": pipeline, + "llvm": PINNED_LLVM, + "compiler": PINNED_COMPILER, + "validator": PINNED_VALIDATOR, + "target": TARGET, + "dxc_flags": DXC_FLAGS, + } + + +def verify_translate_toolchain(library): + """Refuse a different libLLVM before any cache mutation.""" + try: + observed = file_sha256(library) + except OSError as error: + raise ToolchainMismatch(f"cannot read {library}: {error}") from error + if observed != PINNED_LLVM: + raise ToolchainMismatch(f"libLLVM identity {observed[:16]} is not the pinned " + f"{PINNED_LLVM[:16]}") + + +def verify_compile_toolchain(dxc, validator=None): + """Refuse a different compiler or validator before any cache mutation.""" + dxc = Path(dxc) + compiler = dxc.parent / "dxcompiler.dll" + validator_path = Path(validator) if validator else dxc.parent / "dxil.dll" + for label, path, pin in (("dxcompiler.dll", compiler, PINNED_COMPILER), + ("dxil.dll", validator_path, PINNED_VALIDATOR)): + try: + observed = file_sha256(path) + except OSError as error: + raise ToolchainMismatch(f"cannot read {label} next to dxc: {error}") from error + if observed != pin: + raise ToolchainMismatch(f"{label} identity {observed[:16]} is not the pinned {pin[:16]}") + + +# ---------------------------------------------------------------- record + +def build_record(*, profile, code, group, dispatch, user_sgpr_count, table_reg, group_reg, + group_reg_y, descriptor_offset, constant_descriptor, source_descriptor, + source_stride, u0_stride, address_layout, column_shift, element_bytes, + guard_axis, bound_constant, cap_constant, recorded_rsrc2=0, + root_parameters=ROOT_FIXTURE): + """Build a record; the two approved fixture profiles are the only ones validate() accepts.""" + return { + "version": VERSION, + "stage": STAGE_COMPUTE, + "isa": ISA_GFX1013, + "profile": profile, + "guest_wave": GUEST_WAVE32, + "group_x": group[0], "group_y": group[1], "group_z": group[2], + "dispatch_x": dispatch[0], "dispatch_y": dispatch[1], "dispatch_z": dispatch[2], + "user_sgpr_count": user_sgpr_count, + "table_reg": table_reg, + "group_reg": group_reg, + "group_reg_y": group_reg_y, + "descriptor_offset": descriptor_offset, + "constant_descriptor": constant_descriptor, + "source_descriptor": source_descriptor, + "source_stride": source_stride, + "u0_stride": u0_stride, + "address_layout": address_layout, + "column_shift": column_shift, + "element_bytes": element_bytes, + "guard_axis": guard_axis, + "guard_op": 1, + "bound_constant": bound_constant, + "cap_constant": cap_constant, + "translator_revision": 1, + "decoder_id": 1, + "dxc_profile": 0, + "dxc_flags": 0, + "rsrc2_interpretation": 0, + "recorded_rsrc2": recorded_rsrc2, + "code_length": len(code), + "root_parameters": tuple(tuple(parameter) for parameter in root_parameters), + "code_sha256": hashlib.sha256(code).digest(), + "code": code, + } + + +def serialize(record): + """Canonical bytes: magic, the scalar block, the root list, the code digest, the code.""" + out = bytearray(MAGIC) + for name in SCALARS: + value = record[name] + if not isinstance(value, int) or isinstance(value, bool) or not 0 <= value <= 0xFFFFFFFF: + raise RecordError(f"Record field {name} is not a u32") + out += struct.pack(" MAX_RECORD: + raise RecordError(f"Record is larger than {MAX_RECORD} bytes") + if len(blob) < 4 + 4 * len(SCALARS) + 4 + 32: + raise RecordError("Record is truncated") + if blob[:4] != MAGIC: + raise RecordError("Record magic is not X2WN") + record = {} + offset = 4 + for name in SCALARS: + record[name], = struct.unpack_from(" MAX_ROOT_PARAMETERS: + raise RecordError(f"Record declares {count} root parameters") + if len(blob) < offset + 12 * count + 32: + raise RecordError("Record is truncated inside the root parameter list") + parameters = [] + for _ in range(count): + kind, register, size = struct.unpack_from(" MAX_CODE: + raise RecordError(f"Record declares {record['code_length']} code bytes") + if len(blob) != offset + record["code_length"]: + raise RecordError("Record length does not match its code length") + record["code"] = blob[offset:] + return record + + +def record_digest(record): + return hashlib.sha256(serialize(record)).digest() + + +def cache_key(record): + """FNV-1a 64 over the revision and the canonical record digest, as the repository does.""" + return fnv_bytes(record_digest(record), fnv_bytes(REVISION.encode("ascii"))) + + +def key_text(key): + return f"{key:016x}" + + +def validate(record): + """Every rejection names its cause. No field is defaulted or guessed.""" + if record["version"] != VERSION: + raise RecordError(f"Unsupported record version {record['version']}") + if record["stage"] != STAGE_COMPUTE: + raise RecordError(f"Unsupported shader stage {record['stage']}") + if record["isa"] != ISA_GFX1013: + raise RecordError(f"Unsupported ISA {record['isa']}") + if record["profile"] not in (PROFILE_1D, PROFILE_2D): + raise RecordError(f"Unsupported native compute profile {record['profile']}") + if record["guest_wave"] != GUEST_WAVE32: + raise RecordError(f"Unsupported guest wave contract {record['guest_wave']}") + if record["translator_revision"] != 1: + raise RecordError(f"Unsupported translator revision {record['translator_revision']}") + if record["decoder_id"] != 1: + raise RecordError(f"Unsupported decoder identity {record['decoder_id']}") + if record["dxc_profile"] != 0: + raise RecordError(f"Unsupported DXC profile {record['dxc_profile']}") + if record["dxc_flags"] != 0: + raise RecordError(f"Unsupported DXC flags {record['dxc_flags']}") + if record["rsrc2_interpretation"] != 0: + raise RecordError("COMPUTE_PGM_RSRC2 is recorded, not interpreted: TG_SIZE_EN stays unsupported") + if record["recorded_rsrc2"] != 0: + raise RecordError(f"recorded COMPUTE_PGM_RSRC2 0x{record['recorded_rsrc2']:08x} is not " + "supported: the local translator cannot interpret it") + + group = (record["group_x"], record["group_y"], record["group_z"]) + dispatch = (record["dispatch_x"], record["dispatch_y"], record["dispatch_z"]) + for axis, size in zip("xyz", group): + if not 1 <= size <= (64 if axis == "z" else 1024): + raise RecordError(f"Unsupported thread group axis {axis}={size}") + if size & (size - 1): + raise RecordError(f"Thread group axis {axis}={size} is not a power of two") + if group[0] * group[1] * group[2] > 1024: + raise RecordError(f"Unsupported thread group product {group[0] * group[1] * group[2]}") + if not all(1 <= size <= 0xFFFF for size in dispatch): + raise RecordError("Unsupported dispatch dimensions") + + user = record["user_sgpr_count"] + if not 2 <= user <= 16: + raise RecordError(f"Unsupported user SGPR count {user}") + if not 0 <= record["table_reg"] <= 105 or record["table_reg"] + 1 >= user: + raise RecordError("The table pointer does not fit the user SGPRs") + if not 0 <= record["group_reg"] < user or record["group_reg"] == record["table_reg"]: + raise RecordError("The group X register is outside the user SGPRs") + if record["group_reg_y"] != NO_REGISTER: + if not 0 <= record["group_reg_y"] < user: + raise RecordError("The group Y register is outside the user SGPRs") + if record["group_reg_y"] in (record["table_reg"], record["group_reg"]): + raise RecordError("The group Y register collides with another entry register") + + for name in ("descriptor_offset", "constant_descriptor", "source_descriptor"): + value = record[name] + if value % 4 or value >= 0x1000: + raise RecordError(f"{name} {value} is not a bounded DWORD table offset") + offsets = (record["descriptor_offset"], record["constant_descriptor"], record["source_descriptor"]) + if len(set(offsets)) != 3: + raise RecordError("The bound descriptors share a table offset") + if record["source_stride"] and (record["source_stride"] % 4 or record["source_stride"] >= 0x1000): + raise RecordError(f"source_stride {record['source_stride']} is not a bounded DWORD stride") + + if record["address_layout"] not in (1, 2): + raise RecordError(f"Unsupported address layout {record['address_layout']}") + if record["element_bytes"] != 4: + raise RecordError(f"Unsupported element width {record['element_bytes']}") + if record["column_shift"] != 2: + raise RecordError(f"Unsupported column shift {record['column_shift']}") + if record["address_layout"] == 1: + if record["u0_stride"] != 4: + raise RecordError("The index layout requires a four-byte u0 stride") + if group[1] != 1 or group[2] != 1: + raise RecordError("The index layout requires a one-dimensional group") + if record["group_reg_y"] != NO_REGISTER: + raise RecordError("The index layout does not use a group Y register") + else: + if record["u0_stride"] < group[0] << record["column_shift"] or record["u0_stride"] % 4: + raise RecordError("The row stride does not hold one group row") + if record["group_reg_y"] == NO_REGISTER: + raise RecordError("The index-offset layout requires a group Y register") + + if record["guard_axis"] not in (0, 1): + raise RecordError(f"Unsupported guard axis {record['guard_axis']}") + if record["guard_op"] not in GUARD_OPS: + raise RecordError(f"Unsupported guard compare {record['guard_op']}") + for name in ("bound_constant", "cap_constant"): + if record[name] >= 16: + raise RecordError(f"{name} {record[name]} is outside the 16-DWORD constant contract") + + parameters = record["root_parameters"] + if len(parameters) != len(ROOT_FIXTURE) or tuple(parameters) != ROOT_FIXTURE: + raise RecordError("The root signature contract is not the approved fixture contract") + + profile = record["profile"] + if profile == PROFILE_1D and (group != (32, 1, 1) or record["address_layout"] != 1): + raise RecordError("Profile 1d requires group (32,1,1) and the index layout") + if profile == PROFILE_2D and (group != (8, 4, 1) or record["address_layout"] != 2 + or record["u0_stride"] != 96): + raise RecordError("Profile 2d requires group (8,4,1), the index-offset layout and stride 96") + if profile == PROFILE_2D and dispatch[0] * group[0] > (record["u0_stride"] // 4): + raise RecordError("The dispatch row overruns the declared stride") + + code = record["code"] + if len(code) % 4: + raise RecordError("The native code is not a whole number of words") + if not 4 <= len(code) <= MAX_CODE: + raise RecordError(f"Unsupported native code length {len(code)}") + if record["code_length"] != len(code): + raise RecordError("code_length does not match the native code") + if hashlib.sha256(code).digest() != record["code_sha256"]: + raise RecordError("The native code digest does not match its bytes") + return record + + +def record_to_json(record): + """The accepted JSON form: constructor fields plus the fixed scalars, nothing derived.""" + payload = {name: record[name] for name in BUILD_FIELDS} + payload.update({name: record[name] for name in FIXED_JSON_FIELDS}) + payload["group"] = [record["group_x"], record["group_y"], record["group_z"]] + payload["dispatch"] = [record["dispatch_x"], record["dispatch_y"], record["dispatch_z"]] + payload["root_parameters"] = [list(parameter) for parameter in record["root_parameters"]] + payload["code_hex"] = record["code"].hex() + return payload + + +def record_from_json(payload): + """Strict JSON intake: unknown, duplicate, missing and contradictory fields are named errors.""" + if not isinstance(payload, dict): + raise RecordError("A record description must be a JSON object") + unknown = sorted(set(payload) - JSON_FIELDS) + if unknown: + raise RecordError(f"Unknown record field {unknown[0]!r}") + required = set(BUILD_FIELDS) | set(FIXED_JSON_FIELDS) | {"group", "dispatch", "root_parameters", "code_hex"} + missing = sorted(required - set(payload)) + if missing: + raise RecordError(f"Missing record field {missing[0]!r}") + fields = dict(payload) + code_hex = fields.pop("code_hex") + if not isinstance(code_hex, str): + raise RecordError("code_hex must be a string") + try: + code = bytes.fromhex(code_hex) + except ValueError as error: + raise RecordError("code_hex is not hexadecimal") from error + group = fields["group"] + dispatch = fields["dispatch"] + for name, value in (("group", group), ("dispatch", dispatch)): + if not isinstance(value, list) or len(value) != 3: + raise RecordError(f"{name} must be a three-element list") + if any(not isinstance(item, int) or isinstance(item, bool) for item in value): + raise RecordError(f"{name} must contain integers") + parameters = fields["root_parameters"] + if not isinstance(parameters, list) or any( + not isinstance(parameter, list) or len(parameter) != 3 for parameter in parameters): + raise RecordError("root_parameters must be a list of three-element lists") + record = build_record(code=code, group=tuple(group), dispatch=tuple(dispatch), + root_parameters=tuple(tuple(parameter) for parameter in parameters), + **{name: fields[name] for name in BUILD_FIELDS}) + if tuple(tuple(parameter) for parameter in parameters) != record["root_parameters"]: + raise RecordError("root_parameters does not round-trip") + for name in FIXED_JSON_FIELDS: + if fields[name] != record[name]: + raise RecordError(f"Record field {name} is fixed at {record[name]}") + return record + + +# ---------------------------------------------------------------- translation + +def boundary_check(code, decoded): + """4-byte aligned 4- or 8-byte encodings covering every byte, starting at zero.""" + if not decoded or decoded[0][0] != 0: + raise Refusal("Decoding does not start at byte 0") + offsets = [where for where, _ in decoded] + sizes = [later - earlier for earlier, later in zip(offsets, offsets[1:])] + sizes.append(len(code) - offsets[-1]) + for where, size in zip(offsets, sizes): + if where % 4 or size not in (4, 8): + raise Refusal(f"Invalid instruction boundary at byte {where}") + if sum(sizes) != len(code): + raise Refusal(f"Decoded {sum(sizes)} bytes of {len(code)}") + + +def branch_check(decoded): + """Branches must target a decoded boundary, forward, and the program must end in s_endpgm.""" + starts = {where for where, _ in decoded} + for where, text in decoded: + if not text.startswith("s_cbranch_execz"): + continue + operand = text.split()[-1] + try: + target = where + 4 + 4 * int(operand, 0) + except ValueError as error: + raise Refusal(f"Unreadable branch target {operand!r}") from error + if target <= where: + raise Refusal(f"Backward branch at byte {where}") + if target not in starts: + raise Refusal(f"Branch target {target} is not an instruction boundary") + if not decoded or decoded[-1][1] != "s_endpgm": + raise Refusal("Missing final program exit") + + +def translation_kwargs(record): + return dict(table_reg=record["table_reg"], + descriptor_offset=record["descriptor_offset"], + constant_descriptor=record["constant_descriptor"], + source_descriptor=record["source_descriptor"], + stride=record["u0_stride"], + source_stride=record["source_stride"] or None, + group_reg=record["group_reg"], + group_reg_y=None if record["group_reg_y"] == NO_REGISTER else record["group_reg_y"], + cpu="gfx1013") + + +def translate(record, library): + """Native bytes -> decoded instructions -> HLSL, with no assembly-text fallback anywhere.""" + import compute_store_aot as aot + from pixel_aot import disassemble + + validate(record) + try: + decoded = disassemble(record["code"], library, offsets=True, cpu=b"gfx1013") + except ValueError as error: + raise Refusal(f"Undecodable native code: {error}") from error + boundary_check(record["code"], decoded) + branch_check(decoded) + group = (record["group_x"], record["group_y"], record["group_z"]) + try: + return aot.lower(aot.labelled(decoded), group, **translation_kwargs(record)) + except ValueError as error: + raise Refusal(f"Unsupported program: {error}") from error + + +# ---------------------------------------------------------------- compilation and probing + +def embed_root(hlsl): + """Insert the approved fixture root signature before the entry attribute; nothing else changes.""" + marker = b"[numthreads(" + if marker not in hlsl: + raise Refusal("The translated source has no [numthreads] entry") + index = hlsl.index(marker) + return hlsl[:index] + f'[RootSignature("{ROOT_SIGNATURE}")]\n'.encode("ascii") + hlsl[index:] + + +def compile_dxil(hlsl, dxc, work): + """Normal DXC path, cs_6_0 -E main; output must be DXBC carrying DXIL and the embedded root.""" + source = work / "shader.root.hlsl" + output = work / "shader.cso" + source.write_bytes(embed_root(hlsl)) + result = subprocess.run([str(dxc), "-T", DXC_PROFILE, "-E", "main", "-Fo", str(output), str(source)], + capture_output=True, text=True) + if result.returncode: + raise Retryable(f"dxc failed ({result.returncode}): {result.stderr.strip()[:200]}") + blob = output.read_bytes() + from resource_inventory import parts + + if blob[:4] != b"DXBC": + raise Retryable("DXC output is not a DXBC container") + tags = [tag.decode("ascii", "replace") for tag in parts(blob)] + if "DXIL" not in tags: + raise Retryable(f"DXC output has no DXIL part: {tags}") + if "RTS0" not in tags: + raise Retryable("DXC output carries no embedded root signature") + return blob, tags + + +def validate_and_sign(blob, probe): + """dxil.dll container and module validation, the intrinsic gate, then the repository signer.""" + import dxil_retarget as rt + from probe_roots import validate_shader + from resource_inventory import parts + from xbox_intrinsic_gate import decide + + checks = validate_shader(Path(probe), blob, parts(blob)[b"DXIL"]) + container, module = checks["container"], checks["module"] + if container["status"] != "0x00000000" or module["status"] != "0x00000000": + raise Retryable(f"Validation failed: {container['status']} / {module['status']}") + if checks["ir"]["target_triple"] != TARGET: + raise Retryable(f"Unexpected target triple {checks['ir']['target_triple']}") + if checks["ir"]["xbox_call_sites"]: + raise Refusal(f"Executable Xbox intrinsics remain: {sorted(checks['ir']['xbox_call_sites'])}") + gate = decide(checks["ir"]["xbox_intrinsics"]) + if gate["verdict"] != "ALLOW": + raise Refusal(gate["message"]) + signed = rt.sign_container(Path(probe), blob) + if signed[4:20] == bytes(16): + raise Retryable("The signer left the container digest zeroed") + return checks, signed, gate + + +def collect_backends(blob, inventory, pso_probe, required): + """Every required backend must report a root and a PSO HRESULT; a missing key is not a pass.""" + import dxil_retarget as rt + + def run(warp_only): + try: + result = rt.check_compute_pso(Path(pso_probe), blob, warp_only=warp_only, + intrinsics=inventory) + except subprocess.CalledProcessError as error: + raise Retryable(f"PSO probe failed: exit {error.returncode}") from error + except ValueError as error: + raise Retryable(f"PSO probe output is not JSON: {error}") from error + if not isinstance(result, dict): + raise Retryable("PSO probe returned malformed JSON") + if result.get("gate", {}).get("submitted") is not True: + raise Retryable("PSO probe did not submit the module") + return result + + warp = run(True) + backends = {"warp": {"root": warp.get("warp_root"), "pso": warp.get("warp_pso"), + "adapter": "warp", "shader_model": warp.get("warp_shader_model")}} + both = None + if "hardware" in required: + both = run(False) + backends["hardware"] = {"root": both.get("hardware_root"), "pso": both.get("hardware_pso"), + "adapter": both.get("adapter_id", ""), + "shader_model": both.get("hardware_shader_model")} + for name, entry in backends.items(): + if entry["root"] != "0x00000000": + raise Retryable(f"{name}: root signature creation {entry['root']}") + if entry["pso"] != "0x00000000": + raise Retryable(f"{name}: compute PSO creation {entry['pso']}") + if not entry["adapter"] or not entry["shader_model"]: + raise Retryable(f"{name}: probe did not identify the adapter and shader model") + if name == "warp" and entry["adapter"] != "warp": + raise Retryable(f"warp: probe reported adapter {entry['adapter']!r}") + if name == "hardware" and entry["adapter"] == "warp": + raise Retryable("hardware: the probe ran WARP, not a physical adapter") + return {"backends": backends, "raw": {"warp": warp, "both": both}} + + +# ---------------------------------------------------------------- root signature + +def parse_rts0(payload): + """Read the DXC-serialized versioned root signature (version 1.1 layout).""" + if len(payload) < 24: + raise RecordError("The embedded RTS0 part is truncated") + version, count, parameter_offset, samplers, sampler_offset, flags = struct.unpack_from("<6I", payload, 0) + if version != 2: + raise RecordError(f"Unsupported embedded root signature version {version}") + if count > MAX_ROOT_PARAMETERS: + raise RecordError(f"The embedded root signature declares {count} parameters") + if samplers > 8: + raise RecordError(f"The embedded root signature declares {samplers} static samplers") + if sampler_offset > len(payload): + raise RecordError("The embedded sampler table is outside the part") + parameters = [] + for index in range(count): + at = parameter_offset + 12 * index + if at + 12 > len(payload): + raise RecordError("A root parameter entry is truncated") + kind, visibility, offset = struct.unpack_from("<3I", payload, at) + if kind == D3D12_32BIT_CONSTANTS: + if offset + 12 > len(payload): + raise RecordError("A root constants entry is truncated") + register, space, count_values = struct.unpack_from("<3I", payload, offset) + parameters.append({"type": kind, "visibility": visibility, "register": register, + "space": space, "count": count_values, "flags": None}) + elif kind in (D3D12_SRV, D3D12_UAV): + if offset + 12 > len(payload): + raise RecordError("A root descriptor entry is truncated") + register, space, descriptor_flags = struct.unpack_from("<3I", payload, offset) + parameters.append({"type": kind, "visibility": visibility, "register": register, + "space": space, "count": None, "flags": descriptor_flags}) + else: + raise RecordError(f"Unsupported embedded root parameter type {kind}") + return {"version": version, "parameters": parameters, "samplers": samplers, "flags": flags} + + +def verify_rts0(payload, record): + """The embedded signature must be exactly the supported fixture contract.""" + parsed = parse_rts0(payload) + if parsed["samplers"] != 0: + raise RecordError("The supported root signature has no static samplers") + if parsed["flags"] != 0: + raise RecordError(f"The supported root signature has flags 0x{parsed['flags']:x}") + expected = record["root_parameters"] + if len(parsed["parameters"]) != len(expected): + raise RecordError("The embedded root signature parameter count differs from the record") + for index, (parameter, (kind, register, count)) in enumerate(zip(parsed["parameters"], expected)): + if parameter["type"] != kind or parameter["register"] != register: + raise RecordError(f"Root parameter {index} differs from the record contract") + if parameter["visibility"] != SHADER_VISIBILITY_ALL: + raise RecordError(f"Root parameter {index} is not visible to all stages") + if parameter["space"] != 0: + raise RecordError(f"Root parameter {index} uses register space {parameter['space']}") + if kind == D3D12_32BIT_CONSTANTS: + if parameter["count"] != count or count != ROOT_CONSTANTS: + raise RecordError(f"Root constants parameter {index} has {parameter['count']} values") + else: + if parameter["flags"] != ROOT_DESCRIPTOR_FLAG_MASK_SUPPORTED: + raise RecordError(f"Root descriptor {index} has flags 0x{parameter['flags']:x}") + return parsed + + +# ---------------------------------------------------------------- cache files + +def cache_paths(directory, key): + stem = key_text(key) + return {name: directory / f"{prefix}{stem}{suffix}" for name, prefix, suffix in ( + ("request", "req_", ".csn"), + ("request_manifest", "", ".csn.src"), + ("hlsl", "", ".csn.hlsl"), + ("output", "", ".csn.cso"), + ("manifest", "", ".csn.manifest"), + ("error", "", ".csn.error"), + ("corrupt", "", ".csn.corrupt"), + ("lock", "", ".csn.lock"), + )} + + +def write_atomic(path, data): + temporary = path.with_name(f"{path.name}.{os.getpid()}.{time.monotonic_ns()}.tmp") + try: + with open(temporary, "wb") as handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + for attempt in range(4): + try: + os.replace(temporary, path) + return + except PermissionError: + # A file published by the other side of the split toolchain can still be briefly + # held across the /mnt boundary. + if attempt == 3: + raise + time.sleep(0.05) + finally: + temporary.unlink(missing_ok=True) + + +class Writer: + """A lock handle. Every mutation asserts that this token is still the one on disk.""" + + def __init__(self, path, token): + self.path = path + self.token = token + + def assert_owner(self): + try: + current = self.path.read_text(encoding="ascii").strip() + except FileNotFoundError as error: + raise Retryable("the writer lock disappeared; no mutation was made") from error + except OSError as error: + raise Retryable(f"the writer lock is unreadable: {error}") from error + if current != self.token: + raise Retryable("the writer lock is held by another writer; no mutation was made") + + +def release_lock(path, token): + """Remove the lock only when it still holds this writer's token.""" + try: + current = path.read_text(encoding="ascii").strip() + except OSError: + return + if current != token: + return + try: + path.unlink() + except OSError: + pass + + +@contextlib.contextmanager +def writer_lock(directory, key): + """Exclusive acquisition with an ownership token. A held lock is never reclaimed by age.""" + path = cache_paths(directory, key)["lock"] + token = f"{os.getpid():d}-{secrets.token_hex(16)}" + try: + handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError as error: + raise Retryable("another writer holds the lock; an abandoned lock is a manual-repair " + "condition") from error + try: + os.write(handle, (token + "\n").encode("ascii")) + finally: + os.close(handle) + writer = Writer(path, token) + try: + yield writer + finally: + release_lock(path, token) + + +def read_bounded(path, limit): + if path.stat().st_size > limit: + raise RecordError(f"{path.name} is larger than {limit} bytes") + return path.read_bytes() + + +def manifest_text(fields): + return "\n".join([MANIFEST_HEADER] + [f"{name} {value}" for name, value in fields]) + "\n" + + +def parse_manifest(text): + """Strict manifest parsing: known names only, no duplicates, no control characters.""" + lines = text.splitlines() + if not lines or lines[0].strip() != MANIFEST_HEADER: + raise RecordError("Not a native compute manifest") + fields = {} + for line in lines[1:]: + if not line.strip(): + continue + name, separator, value = line.strip().partition(" ") + if not separator or not value: + raise RecordError(f"Manifest line {line.strip()!r} has no value") + if not re.fullmatch(r"[a-z][a-z0-9_-]*", name): + raise RecordError(f"Manifest field name {name!r} is not supported") + if name in fields: + raise RecordError(f"Contradictory or repeated manifest field {name!r}") + if any(ord(character) < 0x20 or ord(character) > 0x7E for character in value): + raise RecordError(f"Manifest field {name!r} has a non-printable value") + if name.startswith("pso-"): + if name[len("pso-"):] not in ("warp", "hardware"): + raise RecordError(f"Unsupported probe backend {name!r}") + elif name not in MANIFEST_KNOWN: + raise RecordError(f"Unsupported manifest field {name!r}") + fields[name] = value + return fields + + +def verified_backends(fields): + """The backends a manifest actually proves, from its own lines.""" + found = {} + for name, value in fields.items(): + if not name.startswith("pso-"): + continue + backend = name[len("pso-"):] + parts = dict(piece.split("=", 1) for piece in value.split() if "=" in piece) + if not {"root", "pso", "adapter", "shader_model"} <= set(parts): + continue + if not parts["root"].startswith("0x") or not parts["pso"].startswith("0x"): + continue + if parts["root"] != "0x00000000" or parts["pso"] != "0x00000000": + continue + if backend == "warp" and parts["adapter"] != "warp": + continue + if backend == "hardware" and (parts["adapter"] == "warp" or ":" not in parts["adapter"]): + continue + found[backend] = parts + return found + + +def _problems_add(problems, name, detail): + problems.append(f"{name}: {detail}") + + +def inspect_entry(directory, key, required=(), *, expected=None, want_artifacts=True): + """The one authoritative acceptance decision. + + Returns {state, detail, problems, fields, record, output, hlsl} and never raises for malformed + cache content. States: hit, backend-missing, refused, error, corrupt-request, corrupt, stale, + missing. + """ + result = {"state": "missing", "detail": "", "problems": [], "fields": None, "record": None, + "output": None, "hlsl": None} + paths = cache_paths(directory, key) + if expected is None: + try: + expected = expected_identity() + except ToolchainMismatch as error: + result.update(state="error", detail=str(error)) + return result + if paths["corrupt"].exists(): + try: + detail = read_bounded(paths["corrupt"], 4096).decode("ascii", "replace").strip() + except OSError as error: + detail = str(error) + result.update(state="corrupt-request", detail=detail) + return result + if paths["error"].exists(): + try: + detail = read_bounded(paths["error"], 4096).decode("ascii", "replace").strip() + except OSError as error: + detail = str(error) + result.update(state="error", detail=detail) + return result + if not paths["manifest"].exists(): + return result + try: + fields = parse_manifest(read_bounded(paths["manifest"], MAX_MANIFEST).decode("utf-8", "replace")) + except (RecordError, OSError) as error: + result.update(state="corrupt", detail=str(error)) + return result + result["fields"] = fields + problems = result["problems"] + for name in MANIFEST_COMMON: + if name not in fields: + _problems_add(problems, "missing", name) + if problems: + result.update(state="corrupt", detail="; ".join(problems)) + return result + if fields["key"] != key_text(key): + result.update(state="stale", detail="manifest key does not match the filename") + return result + if fields["revision"] != REVISION: + result.update(state="stale", detail=f"manifest revision {fields['revision']!r} is not supported") + return result + if fields["status"] == "refused": + try: + record = _load_record(paths, key) + except (RecordError, OSError) as error: + result.update(state="corrupt", detail=f"refusal record: {error}") + return result + result["record"] = record + if fields.get("record_sha256") != record_digest(record).hex(): + result.update(state="corrupt", detail="refusal record digest does not match") + return result + if fields.get("record_version") != str(record["version"]): + result.update(state="corrupt", detail="refusal record version does not match") + return result + if fields.get("code_bytes") != str(len(record["code"])) or \ + fields.get("code_sha256") != digest_hex(record["code"]): + result.update(state="corrupt", detail="refusal record code identity does not match") + return result + result.update(state="refused", detail=fields.get("reason", "")) + return result + if fields["status"] != "validated": + result.update(state="corrupt", detail=f"unknown manifest status {fields['status']!r}") + return result + + for name in MANIFEST_VALIDATED: + if name not in fields: + _problems_add(problems, "missing", name) + for name in MANIFEST_IDENTITY: + if name in fields and fields[name] != expected[name]: + result.update(state="stale", detail=f"manifest {name} {fields[name]!r} is not the " + f"pinned {expected[name]!r}") + return result + for name in MANIFEST_EVIDENCE: + if name not in fields: + continue + valid = {"validation": VALIDATION_OK, "rts0": "present", "gate": "ALLOW", + "signed": SIGNED_OK}[name] + if fields[name] != valid: + _problems_add(problems, name, f"{fields[name]!r} is not {valid!r}") + if problems: + result.update(state="corrupt", detail="; ".join(problems)) + return result + + try: + record = _load_record(paths, key) + except (RecordError, OSError) as error: + result.update(state="corrupt", detail=f"record: {error}") + return result + result["record"] = record + if fields["record_version"] != str(record["version"]): + _problems_add(problems, "record_version", "does not match the record") + if fields["record_sha256"] != record_digest(record).hex(): + _problems_add(problems, "record_sha256", "does not match the record") + if fields["code_bytes"] != str(len(record["code"])): + _problems_add(problems, "code_bytes", "does not match the record") + if fields["code_sha256"] != digest_hex(record["code"]): + _problems_add(problems, "code_sha256", "does not match the record") + expected_group = f'{record["group_x"]}x{record["group_y"]}x{record["group_z"]}' + if fields["group"] != expected_group: + _problems_add(problems, "group", "does not match the record") + if problems: + result.update(state="corrupt", detail="; ".join(problems)) + return result + + try: + hlsl = read_bounded(paths["hlsl"], MAX_HLSL) + except OSError as error: + result.update(state="corrupt", detail=f"hlsl: {error}") + return result + if fields["hlsl_sha256"] != digest_hex(hlsl): + result.update(state="corrupt", detail="hlsl digest does not match") + return result + result["hlsl"] = hlsl + try: + output = read_bounded(paths["output"], MAX_OUTPUT) + except OSError as error: + result.update(state="corrupt", detail=f"output: {error}") + return result + if fields["output_bytes"] != str(len(output)): + result.update(state="corrupt", detail="output size does not match") + return result + if fields["output_sha256"] != digest_hex(output): + result.update(state="corrupt", detail="output digest does not match") + return result + if output[:4] != b"DXBC": + result.update(state="corrupt", detail="output is not a DXBC container") + return result + try: + from resource_inventory import parts + + sections = parts(output) + except ValueError as error: + result.update(state="corrupt", detail=f"output container: {error}") + return result + if b"DXIL" not in sections: + result.update(state="corrupt", detail="output carries no DXIL part") + return result + if b"RTS0" not in sections: + result.update(state="corrupt", detail="output carries no embedded root signature") + return result + if output[4:20] == bytes(16): + result.update(state="corrupt", detail="output container digest is zero (unsigned)") + return result + try: + verify_rts0(sections[b"RTS0"], record) + except RecordError as error: + result.update(state="corrupt", detail=f"root contract: {error}") + return result + result["output"] = output + backends = verified_backends(fields) + missing = [backend for backend in required if backend not in backends] + if missing: + result.update(state="backend-missing", detail="missing required backend " + ",".join(missing)) + return result + result.update(state="hit", detail="") + return result + + +def _load_record(paths, key): + if not paths["request"].exists(): + raise RecordError("the request record is missing") + record = parse(read_bounded(paths["request"], MAX_RECORD)) + validate(record) + if cache_key(record) != key: + raise RecordError("the request bytes do not hash to the request key") + return record + + +def entry_state(directory, key, required=()): + result = inspect_entry(directory, key, required) + return result["state"], result["detail"] + + +def verify_entry(directory, key, required): + """Consumer-side acceptance. The returned bytes are exactly the bytes that were verified.""" + result = inspect_entry(directory, key, required) + return {"accepted": result["state"] == "hit", "state": result["state"], + "detail": result["detail"], "problems": result["problems"], + "fields": result["fields"], "record": result["record"], + "output": result["output"], "hlsl": result["hlsl"]} + + +# ---------------------------------------------------------------- publication + +def publish_error(writer, directory, key, reason): + writer.assert_owner() + write_atomic(cache_paths(directory, key)["error"], + ((" ".join(reason.split())[:300]) + "\n").encode("ascii")) + + +def publish_corrupt(writer, directory, key, reason): + writer.assert_owner() + write_atomic(cache_paths(directory, key)["corrupt"], + ((" ".join(reason.split())[:300]) + "\n").encode("ascii")) + cache_paths(directory, key)["error"].unlink(missing_ok=True) + + +def publish_refusal(writer, directory, key, record, reason): + """Publish the permanent refusal before removing obsolete successful artifacts.""" + paths = cache_paths(directory, key) + writer.assert_owner() + fields = [ + ("key", key_text(key)), ("revision", REVISION), ("status", "refused"), + ("record_version", record["version"]), ("record_sha256", record_digest(record).hex()), + ("code_bytes", len(record["code"])), ("code_sha256", digest_hex(record["code"])), + ("reason", " ".join(reason.split())[:300]), + ] + paths["error"].unlink(missing_ok=True) + paths["corrupt"].unlink(missing_ok=True) + write_atomic(paths["manifest"], manifest_text(fields).encode("ascii")) + for name in ("hlsl", "output"): + try: + paths[name].unlink(missing_ok=True) + except OSError: + # The refusal is already authoritative; leftover artifacts are ignored by acceptance. + pass + + +def publish_validated(writer, directory, key, record, hlsl, output, checks, gate, backends, expected): + """Write artifacts first, clear obsolete markers, publish the manifest last.""" + paths = cache_paths(directory, key) + verify_rts0_from_container(output, record) + fields = [ + ("key", key_text(key)), ("revision", REVISION), ("status", "validated"), + ("record_version", record["version"]), ("record_sha256", record_digest(record).hex()), + ("code_bytes", len(record["code"])), ("code_sha256", digest_hex(record["code"])), + ("group", f'{record["group_x"]}x{record["group_y"]}x{record["group_z"]}'), + ("hlsl_sha256", digest_hex(hlsl)), + ("output_bytes", len(output)), ("output_sha256", digest_hex(output)), + ] + fields += [(name, expected[name]) for name in MANIFEST_IDENTITY] + fields += [ + ("validation", f'container={checks["container"]["status"]} module={checks["module"]["status"]}'), + ("rts0", "present"), ("gate", gate["verdict"]), ("signed", SIGNED_OK), + ] + for backend, entry in sorted(backends.items()): + fields.append((f"pso-{backend}", + f'adapter={entry["adapter"]} root={entry["root"]} pso={entry["pso"]} ' + f'shader_model={entry["shader_model"]}')) + writer.assert_owner() + write_atomic(paths["hlsl"], hlsl) + writer.assert_owner() + write_atomic(paths["output"], output) + paths["error"].unlink(missing_ok=True) + paths["corrupt"].unlink(missing_ok=True) + writer.assert_owner() + write_atomic(paths["manifest"], manifest_text(fields).encode("ascii")) + + +def verify_rts0_from_container(output, record): + from resource_inventory import parts + + return verify_rts0(parts(output)[b"RTS0"], record) + + +def verify_translation_receipt(directory, key, record, hlsl, expected): + """The split stages agree: the HLSL being compiled is the one the translate stage produced.""" + paths = cache_paths(directory, key) + try: + receipt = parse_manifest(read_bounded(paths["request_manifest"], MAX_MANIFEST) + .decode("utf-8", "replace")) + except (RecordError, OSError) as error: + raise Retryable(f"translation receipt is unreadable: {error}") from error + if receipt.get("status") != "translated": + raise Retryable("translation has not run for this key") + if receipt.get("key") != key_text(key) or receipt.get("revision") != REVISION: + raise Retryable("translation receipt does not belong to this key") + if receipt.get("record_sha256") != record_digest(record).hex(): + raise Retryable("translation receipt does not describe this record") + if receipt.get("hlsl_sha256") != digest_hex(hlsl): + raise Retryable("translation receipt does not describe this HLSL") + for name in ("translator", "decoder", "pipeline", "llvm"): + if receipt.get(name) != expected[name]: + raise Retryable(f"translation receipt {name} is not the pinned identity") + + +# ---------------------------------------------------------------- jobs + +def record_from_request(directory, key): + return _load_record(cache_paths(directory, key), key) + + +def stage_request(directory, records, required, evidence=None): + results = [] + for record in records: + validate(record) + key = cache_key(record) + body = serialize(record) + if cache_key(parse(body)) != key: + raise RecordError("The canonical record does not round-trip") + try: + with writer_lock(directory, key) as writer: + state = inspect_entry(directory, key, required)["state"] + if state in ("hit", "refused"): + results.append((key, state, "")) + continue + writer.assert_owner() + paths = cache_paths(directory, key) + write_atomic(paths["request"], body) + write_atomic(paths["request_manifest"], manifest_text([ + ("key", key_text(key)), ("revision", REVISION), ("status", "request"), + ("record_version", record["version"]), + ("record_sha256", record_digest(record).hex()), + ("code_bytes", len(record["code"])), + ("code_sha256", digest_hex(record["code"])), + ]).encode("ascii")) + paths["corrupt"].unlink(missing_ok=True) + if evidence is not None: + evidence(key, "request", {"bytes": len(body), "record_sha256": + record_digest(record).hex()}) + results.append((key, "requested", "")) + except Retryable as error: + results.append((key, "busy", str(error))) + except OSError as error: + results.append((key, "error", str(error))) + return results + + +def stage_translate(directory, library, required, evidence=None): + verify_translate_toolchain(library) + expected = expected_identity() + results = [] + for request in sorted(directory.glob("req_*.csn")): + key = int(request.name[4:-4], 16) + try: + with writer_lock(directory, key) as writer: + state = inspect_entry(directory, key, required)["state"] + if state in ("hit", "refused", "backend-missing"): + results.append((key, state, "")) + continue + try: + record = record_from_request(directory, key) + except RecordError as error: + try: + publish_corrupt(writer, directory, key, f"malformed request: {error}") + except (Retryable, OSError): + results.append((key, "error", f"quarantine failed: {error}")) + else: + results.append((key, "quarantined", str(error))) + continue + except OSError as error: + try: + publish_error(writer, directory, key, str(error)) + except (Retryable, OSError): + pass + results.append((key, "error", str(error))) + continue + try: + hlsl = translate(record, library).encode("ascii") + except Refusal as error: + try: + publish_refusal(writer, directory, key, record, str(error)) + except (Retryable, OSError) as failure: + results.append((key, "error", f"refusal publication failed: {failure}")) + else: + results.append((key, "refused", str(error))) + continue + paths = cache_paths(directory, key) + writer.assert_owner() + write_atomic(paths["hlsl"], hlsl) + writer.assert_owner() + write_atomic(paths["request_manifest"], manifest_text([ + ("key", key_text(key)), ("revision", REVISION), ("status", "translated"), + ("record_version", record["version"]), + ("record_sha256", record_digest(record).hex()), + ("code_bytes", len(record["code"])), + ("code_sha256", digest_hex(record["code"])), + ("hlsl_sha256", digest_hex(hlsl)), + ("translator", expected["translator"]), + ("decoder", expected["decoder"]), + ("pipeline", expected["pipeline"]), + ("llvm", expected["llvm"]), + ]).encode("ascii")) + if evidence is not None: + evidence(key, "translation", {"bytes": len(hlsl), "hlsl_sha256": digest_hex(hlsl), + "identity": expected["translator"]}) + results.append((key, "translated", len(hlsl))) + except Retryable as error: + results.append((key, "busy", str(error))) + except OSError as error: + results.append((key, "error", str(error))) + return results + + +def stage_compile(directory, dxc, probe, pso_probe, required, *, validator=None, evidence=None): + verify_compile_toolchain(dxc, validator) + expected = expected_identity() + results = [] + for request in sorted(directory.glob("req_*.csn")): + key = int(request.name[4:-4], 16) + try: + with writer_lock(directory, key) as writer: + finding = inspect_entry(directory, key, required) + state = finding["state"] + if state in ("hit", "refused"): + results.append((key, state, "")) + continue + try: + record = record_from_request(directory, key) + except RecordError as error: + try: + publish_corrupt(writer, directory, key, f"malformed request: {error}") + except (Retryable, OSError): + results.append((key, "error", f"quarantine failed: {error}")) + else: + results.append((key, "quarantined", str(error))) + continue + except OSError as error: + try: + publish_error(writer, directory, key, str(error)) + except (Retryable, OSError): + pass + results.append((key, "error", str(error))) + continue + try: + if state == "backend-missing" and finding["output"] is not None: + output = finding["output"] + hlsl = finding["hlsl"] + checks, signed, gate = validate_and_sign(output, probe) + if signed != output: + raise Retryable("the published output does not match its re-signed form") + if evidence is not None: + evidence(key, "validation", checks) + collected = collect_backends(signed, checks["ir"]["xbox_intrinsics"], + pso_probe, required) + if evidence is not None: + evidence(key, "pso", collected["raw"]) + publish_validated(writer, directory, key, record, hlsl, signed, checks, gate, + collected["backends"], expected) + results.append((key, "revalidated", ",".join(sorted(collected["backends"])))) + continue + hlsl = finding["hlsl"] + if hlsl is None: + paths = cache_paths(directory, key) + if not paths["hlsl"].exists(): + raise Retryable("translation has not run for this key") + hlsl = read_bounded(paths["hlsl"], MAX_HLSL) + verify_translation_receipt(directory, key, record, hlsl, expected) + work = directory / f"work-{key_text(key)}" + work.mkdir(exist_ok=True) + output, tags = compile_dxil(hlsl, dxc, work) + if evidence is not None: + evidence(key, "compile", {"tags": tags, "bytes": len(output), + "sha256": digest_hex(output)}) + checks, signed, gate = validate_and_sign(output, probe) + if evidence is not None: + evidence(key, "validation", checks) + collected = collect_backends(signed, checks["ir"]["xbox_intrinsics"], + pso_probe, required) + if evidence is not None: + evidence(key, "pso", collected["raw"]) + publish_validated(writer, directory, key, record, hlsl, signed, checks, gate, + collected["backends"], expected) + results.append((key, "validated", ",".join(sorted(collected["backends"])))) + except Refusal as error: + try: + publish_refusal(writer, directory, key, record, str(error)) + except (Retryable, OSError) as failure: + results.append((key, "error", f"refusal publication failed: {failure}")) + else: + results.append((key, "refused", str(error))) + except (Retryable, RecordError, OSError) as error: + try: + publish_error(writer, directory, key, str(error)) + except (Retryable, OSError): + pass + results.append((key, "error", str(error))) + except Retryable as error: + results.append((key, "busy", str(error))) + except OSError as error: + results.append((key, "error", str(error))) + return results + + +def load_records(paths): + records = [] + for path in paths: + text = Path(path).read_text(encoding="utf-8") + try: + payload = json.loads(text, object_pairs_hook=_no_duplicate_keys) + except json.JSONDecodeError as error: + raise RecordError(f"{path}: not JSON: {error}") from error + records.append(record_from_json(payload)) + return records + + +def _no_duplicate_keys(pairs): + seen = {} + for name, value in pairs: + if name in seen: + raise RecordError(f"Duplicate JSON field {name!r}") + seen[name] = value + return seen + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--pending", type=Path, help="cache directory") + parser.add_argument("--stage", choices=("request", "translate", "compile")) + parser.add_argument("--record", type=Path, action="append", default=[], + help="record description JSON (request stage)") + parser.add_argument("--llvm") + parser.add_argument("--dxc") + parser.add_argument("--validator") + parser.add_argument("--probe") + parser.add_argument("--pso-probe") + parser.add_argument("--require-backend", action="append", default=[], choices=("warp", "hardware")) + parser.add_argument("--print-key", type=Path, help="print the canonical key of a record JSON") + args = parser.parse_args(argv) + + required = tuple(args.require_backend or ("warp", "hardware")) + try: + if args.print_key: + record = load_records([args.print_key])[0] + validate(record) + print(key_text(cache_key(record))) + return 0 + if not args.pending or not args.stage: + parser.error("--pending and --stage are required") + directory = args.pending.resolve() + directory.mkdir(parents=True, exist_ok=True) + if args.stage == "request": + records = load_records(args.record) + results = stage_request(directory, records, required) + elif args.stage == "translate": + if not args.llvm: + parser.error("--llvm is required for the translate stage") + results = stage_translate(directory, args.llvm, required) + else: + if not (args.dxc and args.probe and args.pso_probe): + parser.error("--dxc, --probe and --pso-probe are required for the compile stage") + results = stage_compile(directory, args.dxc, args.probe, args.pso_probe, required, + validator=args.validator) + except ToolchainMismatch as error: + print(f"native compute: {error}") + return 2 + except RecordError as error: + print(f"native compute: {error}") + return 3 + except OSError as error: + print(f"native compute: {error}") + return 3 + + for key, outcome, detail in results: + print(f"{key_text(key)} {outcome} {detail}") + if not results: + print("native compute: nothing to do") + outcomes = {outcome for _, outcome, _ in results} + if "quarantined" in outcomes: + return 4 + if "error" in outcomes or "busy" in outcomes: + return 2 + if "refused" in outcomes: + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main())