d3d12-shader/rayquery: fix multi-query attr overwrites, prove mask PHIs, and harden lifting soundness (D3D12-SHADER-RAYQUERY-SOUNDNESS) #3324

Open
djrolfes wants to merge 1 commit from upstream-pr/3324 into main
djrolfes commented 2026-12-03 11:07:59 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by djrolfes on 2026-12-03T11:07:59Z.


Claimed in the coordination issue as: D3D12-SHADER-RAYQUERY-SOUNDNESS (https://github.com/ProjectLeonida/mandy/issues/3312#issuecomment-7376245921)

What and why

Fixes verified soundness bugs in DXR 1.1 RayQuery lifting (d3d12/crates/leonida-shader/src/emit/rayquery.rs) and adds fail-closed guards with synthetic RDNA unit tests:

  1. Multi-query attribute-load overwrites & shared-TLAS / precomputed instance-address merges:

    • expand_ptr_vals previously stepped through v_mov_b32/s_mov_b32 without checking is_explicit_read, allowing an earlier query's hit_inst pointer to propagate through an implicit old-destination read of a guarded clear (v_mov_b32 dst, 0) into a later query's unrelated attribute loads. Requiring explicit reads eliminates those false claims.
    • Phase 3 previously inserted every query's post-loop attr_loads and BLAS-base dead_sites directly into plan, silently overwriting an earlier query's AttrSource::Single and hiding shared sites from Phase 4 (find_merged_attr_loads). Multi-owner post-loop attribute loads and BLAS-base dead sites are now deferred to Phase 4, which now also handles shared-TLAS merges and precomputed tlas_lo + ((hit_inst >> 3) << 6) instance-address PHIs (expanded strictly via expand_exact_vals in descending RPO order). Any multi-owner site still unclaimed after Phase 4 evicts its conflicting queries via analyze_with_exclusions instead of silently overwriting.
  2. Demand-driven prebound_mask_phis with BDD truth proofs:

    • Callback analysis previously scanned all callback-block st.phi_masks (pulling in dead SGPR loop-control PHIs) and bound every external in-loop mask PHI unconditionally to true during DXIL lowering.
    • Collection is now demand-driven from actual callback roots (st.guards, st.exits, read st.masks/st.highs, and commit_decision), and any demanded pre-callback mask PHI must have its constant truth value proven at callback entry via forced_atom_in_bdd (otherwise lifting is rejected cleanly).
  3. Additional fail-closed lifting hardenings:

    • Guarded AttrSource::Single DXIL emission: branches around RayQuery::Committed*() / Candidate*() when guard is Some(g) so inactive lanes never query untraced handles.
    • Reject CULL_OPAQUE without callback: both bvh64 and bvh32 paths reject CULL_OPAQUE when callback.is_none(), since an opaque-only Proceed loop cannot commit non-opaque candidates.
    • Explicit CommitDecision::Always / Never proofs: Always requires an unguarded v_mov_b32 flowing strictly along unguarded explicit movs / loop PHIs (unconditionally_feeds_header_phi), and Never fails closed when reachability analysis hits its traversal budget.
    • High-byte (bits 24..31) guard on instance+48 / instance+52: value_reads_high_byte tracks a bit-exact dirty_mask across shifts (masked & 31), bitfield extracts, bitwise ops, non-carry modular arithmetic, and guarded old-destination writes, failing closed on any other observable use (stores, comparisons, carry-out adds, dynamic shifts, or budget exhaustion) so InstanceMask / InstanceFlags cannot be silently zeroed.

Tested

  • python3 -I scripts/check_no_game_data.py d3d12/crates/leonida-shader/src/emit/rayquery.rs — PASS (0 violations).
  • cargo test -p leonida-shader --lib --locked — 259 passed, 0 failed (including 5 new synthetic RDNA unit tests: expand_ptr_vals_ignores_implicit_old_dst_writes, forced_atom_in_bdd_proves_true_false_and_ambiguous, value_reads_high_byte_detects_bits_24_to_31_and_allows_low_24, extract_node_ptr_from_byte_offset_matches_shr3_shl6, and expand_exact_vals_rejects_mixed_phi_arms).
  • Windows cross-check: cargo check --target x86_64-pc-windows-msvc -p leonida-shader --tests --locked — 0 errors, 0 warnings.
  • Local offline RT shader-cache DXIL translation check (64 RT compute programs, LEONIDA_HW_RT=1): attribute-load overwrites 21 → 0, unverified prebound_mask_phis 10 → 0, bvh32 lifted 299/315 → 301/315 (+2), bvh64 lifted 73/76 (with 1 precomputed-address multi-query merge promoted to HWRT-MERGE and 1 unmasked instance+52 path into an image store rejected fail-closed).

GPUs tested: n/a (CPU-only unit tests, Windows MSVC cross-check, and offline shader-cache DXIL translation check on Linux)

AI-assisted: yes — authored with Gemini 4 Neon (Antigravity) and independently audited in read-only mode with GPT-6.1 Sol (Codex CLI) across three review iterations until PASS.

Checklist

  • Based on current main (bfd03e7f3) and merges cleanly.
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a — d3d12/crates/leonida-shader DXR 1.1 RayQuery lifting, not tools/rdna2spirv.py)
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5625238285 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3324). Originally posted by [djrolfes](https://github.com/djrolfes) on 2026-12-03T11:07:59Z. --- Claimed in the coordination issue as: D3D12-SHADER-RAYQUERY-SOUNDNESS (https://github.com/ProjectLeonida/mandy/issues/3312#issuecomment-7376245921) ### What and why Fixes verified soundness bugs in DXR 1.1 `RayQuery` lifting (`d3d12/crates/leonida-shader/src/emit/rayquery.rs`) and adds fail-closed guards with synthetic RDNA unit tests: 1. **Multi-query attribute-load overwrites & shared-TLAS / precomputed instance-address merges:** - `expand_ptr_vals` previously stepped through `v_mov_b32`/`s_mov_b32` without checking `is_explicit_read`, allowing an earlier query's `hit_inst` pointer to propagate through an implicit old-destination read of a guarded clear (`v_mov_b32 dst, 0`) into a later query's unrelated attribute loads. Requiring explicit reads eliminates those false claims. - Phase 3 previously inserted every query's post-loop `attr_loads` and BLAS-base `dead_sites` directly into `plan`, silently overwriting an earlier query's `AttrSource::Single` and hiding shared sites from Phase 4 (`find_merged_attr_loads`). Multi-owner post-loop attribute loads and BLAS-base dead sites are now deferred to Phase 4, which now also handles shared-TLAS merges and precomputed `tlas_lo + ((hit_inst >> 3) << 6)` instance-address PHIs (expanded strictly via `expand_exact_vals` in descending RPO order). Any multi-owner site still unclaimed after Phase 4 evicts its conflicting queries via `analyze_with_exclusions` instead of silently overwriting. 2. **Demand-driven `prebound_mask_phis` with BDD truth proofs:** - Callback analysis previously scanned all callback-block `st.phi_masks` (pulling in dead SGPR loop-control PHIs) and bound every external in-loop mask PHI unconditionally to `true` during DXIL lowering. - Collection is now demand-driven from actual callback roots (`st.guards`, `st.exits`, read `st.masks`/`st.highs`, and `commit_decision`), and any demanded pre-callback mask PHI must have its constant truth value proven at callback entry via `forced_atom_in_bdd` (otherwise lifting is rejected cleanly). 3. **Additional fail-closed lifting hardenings:** - **Guarded `AttrSource::Single` DXIL emission:** branches around `RayQuery::Committed*()` / `Candidate*()` when `guard` is `Some(g)` so inactive lanes never query untraced handles. - **Reject `CULL_OPAQUE` without callback:** both `bvh64` and `bvh32` paths reject `CULL_OPAQUE` when `callback.is_none()`, since an opaque-only `Proceed` loop cannot commit non-opaque candidates. - **Explicit `CommitDecision::Always` / `Never` proofs:** `Always` requires an unguarded `v_mov_b32` flowing strictly along unguarded explicit `mov`s / loop PHIs (`unconditionally_feeds_header_phi`), and `Never` fails closed when reachability analysis hits its traversal budget. - **High-byte (`bits 24..31`) guard on `instance+48` / `instance+52`:** `value_reads_high_byte` tracks a bit-exact `dirty_mask` across shifts (masked `& 31`), bitfield extracts, bitwise ops, non-carry modular arithmetic, and guarded old-destination writes, failing closed on any other observable use (stores, comparisons, carry-out adds, dynamic shifts, or budget exhaustion) so `InstanceMask` / `InstanceFlags` cannot be silently zeroed. ### Tested - `python3 -I scripts/check_no_game_data.py d3d12/crates/leonida-shader/src/emit/rayquery.rs` — PASS (0 violations). - `cargo test -p leonida-shader --lib --locked` — **259 passed, 0 failed** (including 5 new synthetic RDNA unit tests: `expand_ptr_vals_ignores_implicit_old_dst_writes`, `forced_atom_in_bdd_proves_true_false_and_ambiguous`, `value_reads_high_byte_detects_bits_24_to_31_and_allows_low_24`, `extract_node_ptr_from_byte_offset_matches_shr3_shl6`, and `expand_exact_vals_rejects_mixed_phi_arms`). - Windows cross-check: `cargo check --target x86_64-pc-windows-msvc -p leonida-shader --tests --locked` — 0 errors, 0 warnings. - Local offline RT shader-cache DXIL translation check (64 RT compute programs, `LEONIDA_HW_RT=1`): attribute-load overwrites `21 → 0`, unverified `prebound_mask_phis` `10 → 0`, `bvh32` lifted `299/315 → 301/315` (+2), `bvh64` lifted `73/76` (with 1 precomputed-address multi-query merge promoted to `HWRT-MERGE` and 1 unmasked `instance+52` path into an image store rejected fail-closed). GPUs tested: n/a (CPU-only unit tests, Windows MSVC cross-check, and offline shader-cache DXIL translation check on Linux) AI-assisted: yes — authored with Gemini 4 Neon (Antigravity) and independently audited in read-only mode with GPT-6.1 Sol (Codex CLI) across three review iterations until `PASS`. ### Checklist - [x] Based on current `main` (`bfd03e7f3`) and merges cleanly. - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (`CONTRIBUTING.md`), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. *(n/a — `d3d12/crates/leonida-shader` DXR 1.1 RayQuery lifting, not `tools/rdna2spirv.py`)*
merzleckeier commented 2026-12-03 11:16:58 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by merzleckeier on 2026-12-03T11:16:58Z.


Review of 02f37bcf on 6e979905. The 259 existing shader tests passed locally.

Account for SDWA when tracing the high byte of an instance attribute. At value_reads_high_byte, the v_mov_b32 case propagates dirty without checking the source selection. A move with src0_sel:WORD_1 puts bits 16–31 in the low word. In this synthetic sequence the flags from bits 24–31 reach the final comparison:

global_load_dword v0, v[2:3], off offset:52
v_mov_b32 v1, v0 src0_sel:WORD_1
v_and_b32 v2, 0xffff, v1
v_cmp_eq_u32 vcc, 0, v2

With the recognized instance-address input supplied to find_attr_loads, the analysis returned Ok(()) and scheduled this load for replacement with InstanceContribution, losing the flags. I added a local synthetic regression test using the normal decoder. Returning true for a tracked input to a VALU instruction with SDWA made that test pass and left the full suite green at 260 passed. That is a conservative fallback until the analysis can track the effect of the byte and word selectors.

AI-assisted with OpenAI Codex.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7376471282 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3324#issuecomment-7376471282). Originally posted by [merzleckeier](https://github.com/merzleckeier) on 2026-12-03T11:16:58Z. --- Review of `02f37bcf` on `6e979905`. The 259 existing shader tests passed locally. **Account for SDWA when tracing the high byte of an instance attribute.** At `value_reads_high_byte`, the `v_mov_b32` case propagates `dirty` without checking the source selection. A move with `src0_sel:WORD_1` puts bits 16–31 in the low word. In this synthetic sequence the flags from bits 24–31 reach the final comparison: ```asm global_load_dword v0, v[2:3], off offset:52 v_mov_b32 v1, v0 src0_sel:WORD_1 v_and_b32 v2, 0xffff, v1 v_cmp_eq_u32 vcc, 0, v2 ``` With the recognized instance-address input supplied to `find_attr_loads`, the analysis returned `Ok(())` and scheduled this load for replacement with `InstanceContribution`, losing the flags. I added a local synthetic regression test using the normal decoder. Returning `true` for a tracked input to a VALU instruction with SDWA made that test pass and left the full suite green at 260 passed. That is a conservative fallback until the analysis can track the effect of the byte and word selectors. AI-assisted with OpenAI Codex.
merzleckeier commented 2026-12-03 11:41:52 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by merzleckeier on 2026-12-03T11:41:52Z.


Follow-up on 02f37bcf merged into b053a181. Require every relevant incoming path for CommitDecision::Always. unconditionally_feeds_header_phi() follows every intermediate PHI that uses the candidate value. It returns true as soon as one of those paths reaches tmax_phi, even when another predecessor of that PHI supplies a different value. Always then emits a constant-true condition for RayQuery commit.

In a synthetic RDNA loop, the candidate block copies T into the working register. One branch leaves it there. The other branch writes a different value before the latch PHI, then both return to the header. The helper returns true for both the control (both arms keep T) and the mixed-arm case. This test exercises the helper with the normal decoder and structured CFG.

I locally checked a conservative version that finds the back-edges reachable from the candidate block before returning to the header and uses expand_exact_vals to reject a PHI with mixed inputs. It accepts the control and rejects the mixed case. With this and the SDWA guard from the earlier comment, all 261 synthetic/unit tests passed. The conservative proof can reject other valid shader shapes, so it still needs coverage representative of the shaders this pass lifts.

AI-assisted with OpenAI Codex.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7377057081 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3324#issuecomment-7377057081). Originally posted by [merzleckeier](https://github.com/merzleckeier) on 2026-12-03T11:41:52Z. --- Follow-up on `02f37bcf` merged into `b053a181`. **Require every relevant incoming path for `CommitDecision::Always`.** `unconditionally_feeds_header_phi()` follows every intermediate PHI that *uses* the candidate value. It returns true as soon as one of those paths reaches `tmax_phi`, even when another predecessor of that PHI supplies a different value. `Always` then emits a constant-true condition for `RayQuery` commit. In a synthetic RDNA loop, the candidate block copies T into the working register. One branch leaves it there. The other branch writes a different value before the latch PHI, then both return to the header. The helper returns true for both the control (both arms keep T) and the mixed-arm case. This test exercises the helper with the normal decoder and structured CFG. I locally checked a conservative version that finds the back-edges reachable from the candidate block before returning to the header and uses `expand_exact_vals` to reject a PHI with mixed inputs. It accepts the control and rejects the mixed case. With this and the SDWA guard from the earlier comment, all 261 synthetic/unit tests passed. The conservative proof can reject other valid shader shapes, so it still needs coverage representative of the shaders this pass lifts. AI-assisted with OpenAI Codex.
MoonEyes commented 2026-12-03 12:46:37 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-03T12:46:37Z.


RUN (in game, third party, batch of four pull requests), each head merged with git merge --no-ff onto main 6e9799050, in one build: #2642 4b4d99a82, #3151 8894c5812, #3323 0c836e32e, #3324 02f37bcf8. RTX 4060 8 GB, driver 610.88, Windows 11. Series S, -Resolution 1080, frame generation 2x, -PrecompileUsed, the same walking route as the other runs on this machine, 330 s after reaching the world.

What Result
Device lost / device removed 0
Exceptions, panics, hang watchdog, GPU stall, title suspended 0
Process alive at the end yes, stopped by the time limit
Rendered fps, last 240 s (45 samples) median 17.6, mean 17.1
Rendered fps, last 120 s median 17.2
Time under 5 fps in the world 0 %

For reference, the same machine and route rendered 13.3 to 17.4 fps on other runs in the last day: a check that nothing fell over, not a measurement of a gain.

Verdict: PASS for the in-game gate (300 s or more in the world, no device loss) for this batch, on the heads listed above. If one of these pull requests changes its head, this run no longer covers it.

Limits: one run; arrival in the world was driven by keys and not checked on pictures. The precompile before the world took 529 s, against about 110 s for main alone: the translator change in #3324 left the pipeline cache cold. Switches that are off by default (for example #3323's own-pass timing) were not turned on: this run covers their default path only. #2642 targets Wine and was run on Windows only. #3151 changes what happens on a lost device; no device was lost, so that path was not exercised.

AI-assisted (Claude Code, Claude Opus 5.5).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7378819244 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3324#issuecomment-7378819244). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-03T12:46:37Z. --- RUN (in game, third party, batch of four pull requests), each head merged with `git merge --no-ff` onto main `6e9799050`, in one build: #2642 `4b4d99a82`, #3151 `8894c5812`, #3323 `0c836e32e`, #3324 `02f37bcf8`. RTX 4060 8 GB, driver 610.88, Windows 11. Series S, `-Resolution 1080`, frame generation 2x, `-PrecompileUsed`, the same walking route as the other runs on this machine, 330 s after reaching the world. | What | Result | |---|---| | Device lost / device removed | 0 | | Exceptions, panics, hang watchdog, GPU stall, title suspended | 0 | | Process alive at the end | yes, stopped by the time limit | | Rendered fps, last 240 s (45 samples) | median 17.6, mean 17.1 | | Rendered fps, last 120 s | median 17.2 | | Time under 5 fps in the world | 0 % | For reference, the same machine and route rendered 13.3 to 17.4 fps on other runs in the last day: a check that nothing fell over, not a measurement of a gain. Verdict: PASS for the in-game gate (300 s or more in the world, no device loss) for this batch, on the heads listed above. If one of these pull requests changes its head, this run no longer covers it. Limits: one run; arrival in the world was driven by keys and not checked on pictures. The precompile before the world took 529 s, against about 110 s for main alone: the translator change in #3324 left the pipeline cache cold. Switches that are off by default (for example #3323's own-pass timing) were not turned on: this run covers their default path only. #2642 targets Wine and was run on Windows only. #3151 changes what happens on a lost device; no device was lost, so that path was not exercised. AI-assisted (Claude Code, Claude Opus 5.5).
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3324:upstream-pr/3324'
git switch 'upstream-pr/3324'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3324'
git switch 'upstream-pr/3324'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3324'
git switch 'upstream-pr/3324'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3324'
git switch 'main'
git merge --squash 'upstream-pr/3324'
git switch 'main'
git merge --ff-only 'upstream-pr/3324'
git switch 'main'
git merge 'upstream-pr/3324'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!3324
No description provided.