d3d12-shader: make chains() and loop-counter lowering deterministic #2872

Merged
kirigayakazima merged 1 commit from upstream-pr/2872 into main 2026-12-02 10:55:45 +00:00
kirigayakazima commented 2026-12-01 12:56:22 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by kirigayakazima on 2026-12-01T12:56:22Z.


Claimed in the coordination issue as: D3D12-SHADER-DETERMINISTIC-EMIT (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7311583627)

What and why

Addresses @bobcatchris's finding (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7298226194) on non-deterministic DXIL emission across runs:

  1. In d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs (Module::chains()), rewritten condition-chain plans were grouped into by_block: std::collections::HashMap<usize, Vec<(u32, Vec<Cond>)>> and then iterated in randomized RandomState bucket order while allocating new V::Inst(x) IDs (self.insts.push(...)). Because tree.order already visits each reachable block once and self.blocks[b].body is already in instruction order, chains() now builds by_block directly as Vec<(usize, Vec<(u32, Vec<Cond>)>)> in tree.order and consumes per-block plans sequentially with peekable().next_if(...), eliminating both HashMaps in chains() (and removing the now-unused std::collections::HashMap import).
  2. In d3d12/crates/leonida-shader/src/emit/lower.rs, counters is switched from HashMap<usize, (V, Vec<(V, usize)>)> to BTreeMap so std::mem::take(&mut self.counters).into_values() in phi completion iterates in deterministic ascending IR-block order and find_exit_caps() no longer needs headers.sort_unstable() (reducing lower.rs size slightly).

Tested

Verified locally (Windows 11, Rust 1.98.1, Windows SDK dxil.dll, no game data):

  • Red before fix: cargo test --locked -p leonida-shader --lib chains_emits_deterministic_instruction_ids_across_blocks panicked across blocks ([[40, 41], [30, 31], [36, 37], [32, 33], [34, 35], [38, 39]]).
  • Green after fix:
    • cargo test --locked -p leonida-shader --lib: 410 passed; 0 failed; 5 ignored (including chains_emits_deterministic_instruction_ids_across_blocks)
    • cargo clippy --locked -p leonida-shader -- -D warnings: 0 warnings
    • python -I scripts/check_no_game_data.py & git diff --check: clean

GPUs tested: n/a (translator unit tests only; validated against local Windows SDK dxil.dll)

AI-assisted: yes

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • 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: no new instruction rule)
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5586134431 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2872). Originally posted by [kirigayakazima](https://github.com/kirigayakazima) on 2026-12-01T12:56:22Z. --- Claimed in the coordination issue as: D3D12-SHADER-DETERMINISTIC-EMIT (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7311583627) ### What and why Addresses @bobcatchris's finding (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7298226194) on non-deterministic DXIL emission across runs: 1. In `d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs` (`Module::chains()`), rewritten condition-chain plans were grouped into `by_block: std::collections::HashMap<usize, Vec<(u32, Vec<Cond>)>>` and then iterated in randomized `RandomState` bucket order while allocating new `V::Inst(x)` IDs (`self.insts.push(...)`). Because `tree.order` already visits each reachable block once and `self.blocks[b].body` is already in instruction order, `chains()` now builds `by_block` directly as `Vec<(usize, Vec<(u32, Vec<Cond>)>)>` in `tree.order` and consumes per-block plans sequentially with `peekable().next_if(...)`, eliminating both `HashMap`s in `chains()` (and removing the now-unused `std::collections::HashMap` import). 2. In `d3d12/crates/leonida-shader/src/emit/lower.rs`, `counters` is switched from `HashMap<usize, (V, Vec<(V, usize)>)>` to `BTreeMap` so `std::mem::take(&mut self.counters).into_values()` in phi completion iterates in deterministic ascending IR-block order and `find_exit_caps()` no longer needs `headers.sort_unstable()` (reducing `lower.rs` size slightly). ### Tested Verified locally (Windows 11, Rust 1.98.1, Windows SDK `dxil.dll`, no game data): - Red before fix: `cargo test --locked -p leonida-shader --lib chains_emits_deterministic_instruction_ids_across_blocks` panicked across blocks (`[[40, 41], [30, 31], [36, 37], [32, 33], [34, 35], [38, 39]]`). - Green after fix: - `cargo test --locked -p leonida-shader --lib`: `410 passed; 0 failed; 5 ignored` (including `chains_emits_deterministic_instruction_ids_across_blocks`) - `cargo clippy --locked -p leonida-shader -- -D warnings`: 0 warnings - `python -I scripts/check_no_game_data.py` & `git diff --check`: clean GPUs tested: n/a (translator unit tests only; validated against local Windows SDK `dxil.dll`) AI-assisted: yes ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [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: no new instruction rule)
merzleckeier commented 2026-12-01 13:07:06 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by merzleckeier on 2026-12-01T13:07:06Z.


Independent cross-process check of the optimizer regression from 9bb420346 on ed867d7b2. I put precisely the new six-block chains test on main with the old optimizer and built both with the Windows MSVC Rust target. The test failed in 3/3 fresh Wine 11.22 processes on main, each with a different non-monotonic assignment of new instruction IDs. The PR passed in 3/3 fresh processes, with identical emitted bytes across the 16 builds within each run. Its complete emit::bitcode::opt::tests filter passed 19/19. This directly checks the chains change on synthetic IR. The loop-counter change has no separate fixture in this run.

AI-assisted with OpenAI Codex.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7312130270 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2872#issuecomment-7312130270). Originally posted by [merzleckeier](https://github.com/merzleckeier) on 2026-12-01T13:07:06Z. --- Independent cross-process check of the optimizer regression from `9bb420346` on `ed867d7b2`. I put precisely the new six-block `chains` test on main with the old optimizer and built both with the Windows MSVC Rust target. The test failed in 3/3 fresh Wine 11.22 processes on main, each with a different non-monotonic assignment of new instruction IDs. The PR passed in 3/3 fresh processes, with identical emitted bytes across the 16 builds within each run. Its complete `emit::bitcode::opt::tests` filter passed 19/19. This directly checks the `chains` change on synthetic IR. The loop-counter change has no separate fixture in this run. AI-assisted with OpenAI Codex.
KelboLive commented 2026-12-01 13:28:10 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by KelboLive on 2026-12-01T13:28:10Z.

Review: COMMENTED


Nice catch — the outer HashMap in chains() was the real bug: it decided the order in which new and/xor ids were allocated, and replacing it with a Vec filled in tree.order gives a genuine total order. Reverting it reliably fails the new test (new instruction IDs must advance monotonically in tree order: [[32,33],[36,37],[40,41],[34,35],[38,39],[30,31]]), and my repeated-run probe is stable over 32 in-process runs and 8 independent threads × 8 (module bytes 0x355c3da5eb8360f7, id hash 0x888268bd2da29585).

Two things to fix or state before merge:

  1. The emitted DXIL was already deterministic — Module::write() encodes relative value ids (bitcode.rs:572, :852) and per-block body order was already stable, so under the old code the output bytes were byte-identical; only the internal Module.insts numbering (and dumps/tests that print ids) diverged. Worth saying in the commit so it doesn't read as a cache-key/output fix.
  2. The counters HashMap→BTreeMap change is inert. The only ordered consumer (find_exit_caps) already did headers.sort_unstable() before this PR, and into_values() (:15688) writes disjoint phi slots. I reverted it to HashMap + sort and got identical DXIL (0xf9e31b0f5f6a0fb6), no failing test, and the same on a two-header program. Drop it, or label it as cleanup with no behaviour change.

Minor: the plans.next_if(|id| id == i) walk silently relies on plans being a subsequence of the body it is matched against — true today, but one line of comment would save the next refactor. Also note the branch's merge-base with main is stale (git diff main...pr shows 211 files); the commit itself is the two files.

Everything else checks out: leaves.sort_by_key in terms_of is a stable sort on (born, neg) with a contains-only HashSet, and the other HashMaps in lower.rs are get/insert/remove-only.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6132175927 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2872#pullrequestreview-6132175927). Originally posted by [KelboLive](https://github.com/KelboLive) on 2026-12-01T13:28:10Z. **Review:** COMMENTED --- Nice catch — the outer `HashMap` in `chains()` was the real bug: it decided the order in which new `and`/`xor` ids were allocated, and replacing it with a `Vec` filled in `tree.order` gives a genuine total order. Reverting it reliably fails the new test (`new instruction IDs must advance monotonically in tree order: [[32,33],[36,37],[40,41],[34,35],[38,39],[30,31]]`), and my repeated-run probe is stable over 32 in-process runs and 8 independent threads × 8 (module bytes `0x355c3da5eb8360f7`, id hash `0x888268bd2da29585`). Two things to fix or state before merge: 1. **The emitted DXIL was already deterministic** — `Module::write()` encodes *relative* value ids (`bitcode.rs:572`, `:852`) and per-block body order was already stable, so under the old code the output bytes were byte-identical; only the internal `Module.insts` numbering (and dumps/tests that print ids) diverged. Worth saying in the commit so it doesn't read as a cache-key/output fix. 2. **The `counters` `HashMap`→`BTreeMap` change is inert.** The only ordered consumer (`find_exit_caps`) already did `headers.sort_unstable()` before this PR, and `into_values()` (`:15688`) writes disjoint phi slots. I reverted it to `HashMap` + sort and got identical DXIL (`0xf9e31b0f5f6a0fb6`), no failing test, and the same on a two-header program. Drop it, or label it as cleanup with no behaviour change. Minor: the `plans.next_if(|id| id == i)` walk silently relies on `plans` being a subsequence of the body it is matched against — true today, but one line of comment would save the next refactor. Also note the branch's merge-base with main is stale (`git diff main...pr` shows 211 files); the commit itself is the two files. Everything else checks out: `leaves.sort_by_key` in `terms_of` is a stable sort on `(born, neg)` with a contains-only `HashSet`, and the other `HashMap`s in `lower.rs` are get/insert/remove-only.
imShangLi commented 2026-12-01 15:43:38 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by imShangLi on 2026-12-01T15:43:38Z.


VERIFY-2872 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files

Verdict: PASS. The repository's own red/green tool says the new test is red on main and green with the pull request.

Head 9bb42034, base the current main 88a9f133, merge base 2d4f316b, 1 commit, 2 files, +76/−15: d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs and d3d12/crates/leonida-shader/src/emit/lower.rs.

1. The change

Two places where a HashMap decided an order:

opt.rs, in chains() — the rewrites were collected per block into a HashMap<usize, Vec<(u32, Vec<Cond>)>> and then walked in the map's iteration order. Rust's HashMap uses a randomly seeded hasher, so that order differs between processes; the pull request keeps the blocks in a Vec in tree order and walks the plans of a block with a peekable iterator instead of plans.remove(&i).

lower.rs, in the loop-counter lowering — counters: HashMap<usize, (V, Vec<(V, usize)>)> becomes a BTreeMap, and the headers.sort_unstable() that followed the keys() call is dropped because the keys are already in order.

Both are the same defect: an order that is not fixed, in a stage whose result is hashed into the shader cache's key.

2. Red and green

python -I scripts/red_green.py pr2872 --crate leonida-shader (the repository's own tool: red is the base with only this pull request's test hunks, green is the base with the pull request merged):

verdict: "red then green"
red_to_green: leonida_shader::emit::bitcode::opt::tests::chains_emits_deterministic_instruction_ids_across_blocks
regressions:  []
fail_on_both: []
pass_on_both: 246

On the red side the new test fails; on the green side the crate is green.

3. What the new test checks

chains_emits_deterministic_instruction_ids_across_blocks builds a module with six blocks, each holding a three-term conjunction, runs chains(), and then checks two things:

  • the newly emitted instruction IDs advance monotonically in tree order — the maximum of one block's new IDs is below the minimum of the next block's, so block n's rewrite is numbered before block n+1's, whatever order the blocks were visited in;
  • running the whole thing 16 times gives the same result each time.

The second half is the part that catches the HashMap: each run builds fresh maps, and a randomly seeded HashMap gives a different iteration order each time, so the 16 runs would disagree.

4. It does not collide with #2800

#2800 also changes chains() in opt.rs (it makes the canonical test accept a commutative and). I merged both onto today's main and ran the crate:

test result: ok. 249 passed; 0 failed; 2 ignored

No conflict, and neither pull request's test breaks the other's.

5. What I did not check

  • The translation of a real shader, and the cache. The consequence of a varying instruction numbering is a varying shader cache key, which costs a re-translation; I did not measure that, and I did not translate a game shader (they are not in the repository, and the pull request's own note in opt.rs says the optimisation flags are "part of the translation and so of the shader cache's key").
  • The whole lower.rs change. I checked that BTreeMap's keys() is sorted, so dropping sort_unstable() keeps the same order, and that the type change is the only use of the field. I did not trace every reader of counters.
  • The other crates in the workspace — leonida-gpu, leonida-hle and leonida-loader do not build on Linux for reasons that predate this pull request (upstream: "The crates are Windows-only today … Linux follows #2577"), so I ran leonida-shader on its own.
  • Whether there are other HashMaps in the shader crate whose iteration order reaches the output. I looked at the two this pull request touches; I did not audit the crate for others.
  • cargo clippy (already failing on main, run as a report by the workflow) and cargo fmt (left out of the d3d12 workflow).

AI-assisted: MiniMax M3.1 Flash.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7316403977 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2872#issuecomment-7316403977). Originally posted by [imShangLi](https://github.com/imShangLi) on 2026-12-01T15:43:38Z. --- ## VERIFY-2872 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files **Verdict: PASS.** The repository's own red/green tool says the new test is red on `main` and green with the pull request. Head `9bb42034`, base the current `main` `88a9f133`, merge base `2d4f316b`, 1 commit, 2 files, +76/−15: `d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs` and `d3d12/crates/leonida-shader/src/emit/lower.rs`. ### 1. The change Two places where a `HashMap` decided an order: **`opt.rs`, in `chains()`** — the rewrites were collected per block into a `HashMap<usize, Vec<(u32, Vec<Cond>)>>` and then walked in the map's iteration order. Rust's `HashMap` uses a randomly seeded hasher, so that order differs between processes; the pull request keeps the blocks in a `Vec` in tree order and walks the plans of a block with a peekable iterator instead of `plans.remove(&i)`. **`lower.rs`, in the loop-counter lowering** — `counters: HashMap<usize, (V, Vec<(V, usize)>)>` becomes a `BTreeMap`, and the `headers.sort_unstable()` that followed the `keys()` call is dropped because the keys are already in order. Both are the same defect: an order that is not fixed, in a stage whose result is hashed into the shader cache's key. ### 2. Red and green `python -I scripts/red_green.py pr2872 --crate leonida-shader` (the repository's own tool: red is the base with only this pull request's test hunks, green is the base with the pull request merged): ``` verdict: "red then green" red_to_green: leonida_shader::emit::bitcode::opt::tests::chains_emits_deterministic_instruction_ids_across_blocks regressions: [] fail_on_both: [] pass_on_both: 246 ``` On the red side the new test fails; on the green side the crate is green. ### 3. What the new test checks `chains_emits_deterministic_instruction_ids_across_blocks` builds a module with six blocks, each holding a three-term conjunction, runs `chains()`, and then checks two things: - the newly emitted instruction IDs **advance monotonically in tree order** — the maximum of one block's new IDs is below the minimum of the next block's, so block *n*'s rewrite is numbered before block *n+1*'s, whatever order the blocks were visited in; - running the whole thing **16 times** gives the same result each time. The second half is the part that catches the `HashMap`: each run builds fresh maps, and a randomly seeded `HashMap` gives a different iteration order each time, so the 16 runs would disagree. ### 4. It does not collide with #2800 #2800 also changes `chains()` in `opt.rs` (it makes the canonical test accept a commutative `and`). I merged both onto today's `main` and ran the crate: ``` test result: ok. 249 passed; 0 failed; 2 ignored ``` No conflict, and neither pull request's test breaks the other's. ### 5. What I did not check - **The translation of a real shader, and the cache.** The consequence of a varying instruction numbering is a varying shader cache key, which costs a re-translation; I did not measure that, and I did not translate a game shader (they are not in the repository, and the pull request's own note in `opt.rs` says the optimisation flags are "part of the translation and so of the shader cache's key"). - **The whole `lower.rs` change.** I checked that `BTreeMap`'s `keys()` is sorted, so dropping `sort_unstable()` keeps the same order, and that the type change is the only use of the field. I did not trace every reader of `counters`. - **The other crates in the workspace** — `leonida-gpu`, `leonida-hle` and `leonida-loader` do not build on Linux for reasons that predate this pull request (upstream: "The crates are Windows-only today … Linux follows #2577"), so I ran `leonida-shader` on its own. - **Whether there are other `HashMap`s in the shader crate whose iteration order reaches the output.** I looked at the two this pull request touches; I did not audit the crate for others. - `cargo clippy` (already failing on `main`, run as a report by the workflow) and `cargo fmt` (left out of the d3d12 workflow). AI-assisted: MiniMax M3.1 Flash.
DadaCap commented 2026-12-01 16:15:02 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by DadaCap on 2026-12-01T16:15:02Z.


Independent red/green on Windows 11 (RTX 5080, NVIDIA 621.24), head 9bb420346 merged into main 0ff8a532f, with python -I scripts/red_green.py 2872:

  • red then green (1): leonida_shader::emit::bitcode::opt::tests::chains_emits_deterministic_instruction_ids_across_blocks fails on main with only the PR's tests and passes with the PR;
  • pass on both: 414 (leonida-shader).

No in-game run from me. AI-assisted (Claude Code), posted for DadaCap.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7317287012 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2872#issuecomment-7317287012). Originally posted by [DadaCap](https://github.com/DadaCap) on 2026-12-01T16:15:02Z. --- Independent red/green on Windows 11 (RTX 5080, NVIDIA 621.24), head `9bb420346` merged into main `0ff8a532f`, with `python -I scripts/red_green.py 2872`: - red then green (1): `leonida_shader::emit::bitcode::opt::tests::chains_emits_deterministic_instruction_ids_across_blocks` fails on main with only the PR's tests and passes with the PR; - pass on both: 414 (`leonida-shader`). No in-game run from me. AI-assisted (Claude Code), posted for DadaCap.
MoonEyes commented 2026-12-01 22:07:26 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-01T22:07:26Z.


main moved and this PR now conflicts in d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs: both sides appended a test at the end of the same module. I resolved it by keeping both tests (merge commit aa13e59fb on MoonEyes/leonida branch carry/2872, based on main c4ca57615; cargo test -p leonida-shader --lib on the two conflicting tests plus bounded_budget_caps_wide_phi_dag: 4 passed).

Please rebase or merge main into this branch yourself. If it is still conflicting in 6 hours I will open a carry PR that keeps your commit. Nothing else changes in your diff.

AI-assisted (Claude Code)

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7327301498 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2872#issuecomment-7327301498). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-01T22:07:26Z. --- main moved and this PR now conflicts in `d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs`: both sides appended a test at the end of the same module. I resolved it by keeping both tests (merge commit `aa13e59fb` on `MoonEyes/leonida` branch `carry/2872`, based on main `c4ca57615`; `cargo test -p leonida-shader --lib` on the two conflicting tests plus `bounded_budget_caps_wide_phi_dag`: 4 passed). Please rebase or merge main into this branch yourself. If it is still conflicting in 6 hours I will open a carry PR that keeps your commit. Nothing else changes in your diff. AI-assisted (Claude Code)
MoonEyes commented 2026-12-02 06:44:33 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T06:44:33Z.


As said above, this PR still conflicts with main and has not moved. I opened #3059, which is main merged with this head: your commit is kept, both tests are kept. This PR stays open until a maintainer decides. If you rebase it yourself, say so and I will close #3059.

AI-assisted (Claude Code)

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7337355790 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2872#issuecomment-7337355790). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T06:44:33Z. --- As said above, this PR still conflicts with `main` and has not moved. I opened #3059, which is `main` merged with this head: your commit is kept, both tests are kept. This PR stays open until a maintainer decides. If you rebase it yourself, say so and I will close #3059. AI-assisted (Claude Code)
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!2872
No description provided.