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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/experiments/native-compile-dxil-watch.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
containers are skipped, truncated or missing stage `.cso` files are resumed, `.psin` additions/updates/removals
trigger rechecks, pre-existing `.fail` entries are retried once on the first pass, and unchanged `.fail` entries
are skipped on subsequent passes until the marker or `.psin` is rewritten.
- The published `<key>.psinh` digest is taken from the base `.psin`/`.ps57in` pair. An `.rtv` variant resolves the
same base sidecars as its mtime check, so a deliberate or preserved-mtime base sidecar change withdraws the
variant too. The digest is computed before and after the graphic translation; a change during compilation
refuses the publish instead of pairing new bytes with DXIL made from the old ones.

## Verification

Expand All @@ -19,6 +23,7 @@
cmake --preset release
cmake --build --preset release --target compile_dxil
ctest --preset release --no-tests=error -V -R "^native_compile_dxil_watch$"
ctest --preset release --no-tests=error -j 1 -R "^(native_startup_request_cache_controls|native_rtv_variant_controls)$"
```

## Limits
Expand Down
4 changes: 4 additions & 0 deletions docs/experiments/native-startup-request-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ the startup runtime cache loaders on WARP and hardware without manual renaming o
`<key>.ps.cso`, `<key>.gs.cso` for `gfx1013-container-rect`, and `<key>.cs.cso` for compute), withdraws any
prior `<key>.txt` before rewriting stages or on refusal, records `<key>.psdep` when `.psin` was used, and
atomically publishes `<key>.txt` after all stage `.cso` files are in place.
- The watch and batch writers also publish `<key>.psinh`, an FNV-1a digest of the base `.psin`/`.ps57in`
extension, length and bytes. A `.rtv` variant resolves its base sidecars, so the digest and mtime checks
invalidate the variant with its base. The digest is computed before and after translation; a sidecar that
changes during the compile refuses the manifest write.

## Verification and negative controls

Expand Down
84 changes: 83 additions & 1 deletion tests/native_startup_request_cache_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@
COMPUTE_RSRC2 = C.USER7 | C.TGID_X | C.TGID_Y | C.TGID_Z | C.tidig(3)


def put_variant(cache: Path, base: int, formats: tuple[int, ...]) -> int:
line = "rtv1 " + " ".join(map(str, (base, *formats)))
key = G.fnv(line.encode("ascii"))
(cache / f"req_{key:016x}.rtv").write_text(line, encoding="ascii")
return key


def fullscreen_vs_words() -> bytes:
vop1 = lambda op, dst, src: 0x7E000000 | dst << 17 | op << 9 | src
vop2 = lambda op, dst, src0, vsrc1: op << 25 | dst << 17 | vsrc1 << 9 | src0
Expand Down Expand Up @@ -301,7 +308,82 @@ def expect_graphics_refusal(label: str, setup, expected_stderr: str) -> None:
assert not (bad_cs_dir / f"{bad_cs_key:016x}.txt").exists()
assert not (bad_cs_dir / f"{bad_cs_key:016x}.cs.cso").exists()

print("native_startup_request_cache controls: current and archived graphics (.psin) + compute (.c67) cache entries and 8 refusal controls passed")
# 7. Watch invalidation: sidecar content, not its timestamp, decides whether a published manifest is current.
watch_cache = work / "watch-sidecar"
watch_cache.mkdir()
watch_key = put_graphics_request(watch_cache, VS_WORDS, ps_words(4), g_root, TARGET_MASKS)
watch_manifest = watch_cache / f"{watch_key:016x}.txt"
watch_psin = watch_cache / f"req_{watch_key:016x}.psin"
watch_sidecar = watch_cache / f"req_{watch_key:016x}.ps57in"
watch_fail = watch_cache / f"{watch_key:016x}.fail"
watch_digest = watch_cache / f"{watch_key:016x}.psinh"

variant_key = put_variant(watch_cache, watch_key, (28,))
variant_manifest = watch_cache / f"{variant_key:016x}.txt"

def run_watch() -> list[str]:
result = subprocess.run(
[cli, "--watch", sdk, frontend, watch_cache, "--once"],
capture_output=True, text=True,
)
assert result.returncode == 0, (result.stdout, result.stderr)
return result.stdout.splitlines()

first_lines = run_watch()
assert any(line.endswith(": compiled graphics") for line in first_lines), first_lines
assert watch_manifest.is_file() and watch_digest.is_file()
assert f"{variant_key:016x}: compiled graphics" in first_lines, first_lines
assert variant_manifest.is_file(), variant_manifest
published_ns = watch_manifest.stat().st_mtime_ns
variant_ns = variant_manifest.stat().st_mtime_ns

# Unchanged sidecar bytes: the published manifest is a cache hit and is not rewritten.
second_lines = run_watch()
assert not any("compiled graphics" in line for line in second_lines), second_lines
assert watch_manifest.stat().st_mtime_ns == published_ns
assert variant_manifest.stat().st_mtime_ns == variant_ns

# A contradictory slot-57 sidecar with an older mtime must withdraw the stale manifest.
conflicting = b"PSI1" + struct.pack("<II", 0x8002, 0x8002)
watch_sidecar.write_bytes(conflicting)
older_ns = published_ns - 3_600_000_000_000
os.utime(watch_sidecar, ns=(older_ns, older_ns))
older_lines = run_watch()
assert any("conflicting stream and slot-57 pixel entry records" in line for line in older_lines), older_lines
assert not watch_manifest.exists(), "an older-mtime sidecar kept its stale manifest"
assert not variant_manifest.exists(), "an older-mtime base sidecar kept the RTV variant"
older_fail = watch_fail.read_bytes()

# The same bytes with a newer mtime, from a fresh publication, must withdraw it identically.
watch_sidecar.unlink()
watch_fail.unlink()
republished = run_watch()
assert any(line.endswith(": compiled graphics") for line in republished), republished
assert watch_manifest.is_file()
assert variant_manifest.is_file(), variant_manifest
watch_sidecar.write_bytes(conflicting)
os.utime(watch_sidecar, None)
newer_lines = run_watch()
assert any("conflicting stream and slot-57 pixel entry records" in line for line in newer_lines), newer_lines
assert not watch_manifest.exists()
assert not variant_manifest.exists(), "a newer-mtime base sidecar kept the RTV variant"
assert watch_fail.read_bytes() == older_fail

# A changed .psin with a preserved mtime is invalidated instead of served from cache.
watch_sidecar.unlink()
watch_fail.unlink()
restored = run_watch()
assert any(line.endswith(": compiled graphics") for line in restored), restored
assert variant_manifest.is_file(), variant_manifest
preserved_ns = watch_psin.stat().st_mtime_ns
watch_psin.write_text(describe_psin(watch_key, DECOY_MASKS), encoding="ascii")
os.utime(watch_psin, ns=(preserved_ns, preserved_ns))
changed_lines = run_watch()
assert any("pixel input description" in line for line in changed_lines), changed_lines
assert not watch_manifest.exists(), "a changed sidecar with a preserved mtime kept its stale manifest"
assert not variant_manifest.exists(), "a changed sidecar with a preserved mtime kept the RTV variant"

print("native_startup_request_cache controls: current and archived graphics (.psin) + compute (.c67) cache entries, 8 refusal controls and watch-sidecar invalidation passed")
return 0


Expand Down
89 changes: 88 additions & 1 deletion tools/startup/compile_dxil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,61 @@ static double elapsed_ms(Clock::time_point since) {

namespace fs = std::filesystem;

// FNV-1a over the pixel-input sidecars. The digest, not a timestamp, decides whether a published manifest
// still describes the sidecar bytes: a content change with a preserved or older mtime must invalidate it.
static void sidecar_hash_bytes(uint64_t& hash, const void* data, size_t size) {
const auto* bytes = static_cast<const unsigned char*>(data);
for (size_t i = 0; i < size; ++i) {
hash ^= bytes[i];
hash *= 1099511628211ull;
}
}

static std::optional<fs::path> graphics_psin_path(const fs::path& marker);

static bool pixel_sidecar_hash(const fs::path& marker, std::string& digest) {
uint64_t hash = 1469598103934665603ull;
bool any = false;
fs::path psin = marker;
if (marker.extension() == L".rtv") {
const auto base = graphics_psin_path(marker);
if (!base)
return false;
psin = *base;
} else {
psin.replace_extension(L".psin");
}
for (const auto& path : {psin, fs::path(psin).replace_extension(L".ps57in")}) {
std::error_code ec;
if (!fs::is_regular_file(path, ec))
continue;
std::ifstream file(path, std::ios::binary);
if (!file)
return false;
const std::vector<char> bytes((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
const auto name = path.extension().wstring();
sidecar_hash_bytes(hash, name.data(), name.size() * sizeof(wchar_t));
const uint64_t count = bytes.size();
sidecar_hash_bytes(hash, &count, sizeof(count));
sidecar_hash_bytes(hash, bytes.data(), bytes.size());
any = true;
}
if (!any)
return false;
char text[17]{};
std::snprintf(text, sizeof(text), "%016llx", static_cast<unsigned long long>(hash));
digest = text;
return true;
}

static bool read_published_digest(const fs::path& path, std::string& digest) {
std::ifstream file(path, std::ios::binary);
if (!file)
return false;
digest.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return !digest.empty();
}

static void publish_atomic(const fs::path& destination, const void* data, size_t size) {
static std::atomic<unsigned long long> serial{};
auto temp=destination;
Expand Down Expand Up @@ -717,7 +772,16 @@ static bool is_watch_request_pending(const fs::path& request_dir, const WatchReq
const bool has_manifest = fs::is_regular_file(manifest_path, ec);
if (has_manifest && !lost) {
const auto manifest_mtime = fs::last_write_time(manifest_path, ec);
if (!ec && !(psin_mtime.has_value() && *psin_mtime > manifest_mtime)) {
bool sidecar_changed = false;
if (!req.compute) {
std::string sidecar_digest;
if (pixel_sidecar_hash(req.marker, sidecar_digest)) {
std::string published_digest;
sidecar_changed = !read_published_digest(fs::path(stem) += L".psinh", published_digest) ||
published_digest != sidecar_digest;
}
}
if (!ec && !sidecar_changed && !(psin_mtime.has_value() && *psin_mtime > manifest_mtime)) {
if (req.compute) {
if (has_complete_dxbc(fs::path(stem) += L".cs.cso"))
return false;
Expand Down Expand Up @@ -797,6 +861,8 @@ static const char* compile_watch_item(x2w::ShaderDxilCompiler& compiler, const f
fs::remove(fail_path, ignored);
return "compiled compute";
}
std::string sidecar_before;
const bool sidecar_present_before = pixel_sidecar_hash(req.marker, sidecar_before);
auto input = x2w::read_graphics_request(req.marker);
bool hit = false;
auto pair = x2w::prepare_direct_graphics(input.a, input.b, cache_dir, hit, input.root, input.input_layout,
Expand All @@ -809,13 +875,23 @@ static const char* compile_watch_item(x2w::ShaderDxilCompiler& compiler, const f
: "RTV variant has no runtime manifest: its vertex inputs, target types or bindings are not described");
auto vs_dxil = compile_to_dxil(compiler, pair.vertex.dxil_ir, L"vs_6_6", cache_dir, true, sink);
auto ps_dxil = compile_to_dxil(compiler, pair.pixel.dxil_ir, L"ps_6_6", cache_dir, true, sink);
std::string sidecar_after;
const bool sidecar_present_after = pixel_sidecar_hash(req.marker, sidecar_after);
if (sidecar_present_before != sidecar_present_after || sidecar_before != sidecar_after) {
fs::remove(manifest_path, ignored);
throw std::runtime_error("pixel input sidecar changed during compilation");
}
publish_atomic(fs::path(stem) += L".vs.cso", vs_dxil.data(), vs_dxil.size());
publish_atomic(fs::path(stem) += L".ps.cso", ps_dxil.data(), ps_dxil.size());
const fs::path psdep_path = fs::path(stem) += L".psdep";
if (!input.pixel_input_description.empty())
publish_atomic(psdep_path, input.pixel_input_description.data(), input.pixel_input_description.size());
else
fs::remove(psdep_path, ignored);
if (sidecar_present_before)
publish_atomic(fs::path(stem) += L".psinh", sidecar_before.data(), sidecar_before.size());
else
fs::remove(fs::path(stem) += L".psinh", ignored);
publish_atomic(manifest_path, manifest->data(), manifest->size());
fs::remove(fail_path, ignored);
return "compiled graphics";
Expand Down Expand Up @@ -1085,6 +1161,7 @@ int wmain(int argc, wchar_t** argv) {
if(graphics_batch) {
reserve_output(fs::path(stems[i]) += L".ps.cso");
reserve_output(fs::path(stems[i]) += L".psdep");
reserve_output(fs::path(stems[i]) += L".psinh");
if(rectangles) reserve_output(fs::path(stems[i]) += L".gs.cso");
}
}
Expand All @@ -1107,6 +1184,8 @@ int wmain(int argc, wchar_t** argv) {
const fs::path psdep_path = fs::path(stems[i]) += L".psdep";
std::error_code ignored;
fs::remove(manifest_path, ignored);
std::string sidecar_before;
const bool sidecar_present_before = pixel_sidecar_hash(inputs[i], sidecar_before);
auto input = x2w::read_graphics_request(inputs[i]);
bool hit = false;
auto pair = x2w::prepare_direct_graphics(input.a, input.b, argv[2], hit, input.root, input.input_layout, input.pixel_entry,
Expand Down Expand Up @@ -1134,13 +1213,21 @@ int wmain(int argc, wchar_t** argv) {
}
auto vs_dxil = compile_to_dxil(compiler, pair.vertex.dxil_ir, L"vs_6_6", argv[2], true, report);
auto ps_dxil = compile_to_dxil(compiler, pair.pixel.dxil_ir, L"ps_6_6", argv[2], true, report);
std::string sidecar_after;
const bool sidecar_present_after = pixel_sidecar_hash(inputs[i], sidecar_after);
if (sidecar_present_before != sidecar_present_after || sidecar_before != sidecar_after)
throw std::runtime_error("pixel input sidecar changed during compilation");
if (!gs_dxil.empty())
publish_atomic(fs::path(stems[i]) += L".gs.cso", gs_dxil.data(), gs_dxil.size());
publish_atomic(outputs[i], vs_dxil.data(), vs_dxil.size());
publish_atomic(fs::path(stems[i]) += L".ps.cso", ps_dxil.data(), ps_dxil.size());
if (manifest) {
if (!input.pixel_input_description.empty())
publish_atomic(psdep_path, input.pixel_input_description.data(), input.pixel_input_description.size());
if (sidecar_present_before)
publish_atomic(fs::path(stems[i]) += L".psinh", sidecar_before.data(), sidecar_before.size());
else
fs::remove(fs::path(stems[i]) += L".psinh", ignored);
publish_atomic(manifest_path, manifest->data(), manifest->size());
}
fs::remove(fs::path(stems[i]) += L".fail", ignored);
Expand Down