Skip to content

D3D12.X: a split compute program keeps its console code, not its whole DXIL - #3047

Draft
Prime1997 wants to merge 1 commit into
xcl-dev:mainfrom
Prime1997:contrib/nv-split-console-code
Draft

Prime1997 wants to merge 1 commit into
xcl-dev:mainfrom
Prime1997:contrib/nv-split-console-code

Conversation

@Prime1997

@Prime1997 Prime1997 commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

A split compute chain now retains its smaller console shader source instead of an additional whole-program DXIL copy. When an indirect dispatch needs the whole form, it reconstructs it with the original wave mode and memory-window form. Part of #2688.

Rebased onto main (2026-11-28). nvidia-dev was merged into main by #3203, so this PR now targets main and its branch was rebased onto main 765b2c5bfff6754e8c9886a73e188a86aca3c64c: head e87bdba4e37aebbe4853d93ff9292da2efd694eb (was 37802271a56db9201209b801cc15fe9fa09ab83b). main had added indirect split pipelines to dispatch_chain.rs since (12 commits), so this is a hand port. The chain keeps the console program with its window and wave settings as before; build still receives the whole DXIL for the immediate cached-blob check; the indirect variant translates the whole form again when it is built. The README sentence moved under main's rewritten preparation text. That port needs a review. The test run leaves out one main test that already fails alone on plain main 765b2c5b on this PC with adopted class. On the rebased head, on the same RTX 3060 Ti PC, debug profile: cargo check -p xcl --all-targets exited 0, and cargo test -p xcl --lib -- --test-threads=4 dispatch_chain whole --skip failed_binding_keeps_indirect_commands_until_allocator_reset gave 63 passed, 0 failed, 1 ignored, and dispatch_chain_native_wave64_builds_whole SKIPPED (no wave64). The whole suite and the paired title runs have not been rerun on this head; every other result below is from the earlier head. The rebase and its conflict resolution were done with Claude Code.

What is in it

Tested

  • Windows 11 Pro 26200, Intel i5-10400, RTX 3060 Ti driver 32.0.16.1714, Rust 1.100.0, pinned DXC 1.9.2609.5. Debug/test builds with debug symbols disabled and two build jobs.
  • cargo test --locked -p xcl --lib --target-dir <isolated-target> --no-run: both control and corrected binaries built.
  • Corrected source: cargo test --locked -p xcl --lib --target-dir <isolated-target> hle::d3d12x::real::dispatch_chain::tests:: -- --nocapture --test-threads=1: 7 passed, 0 failed, 0 ignored, 1,801 filtered; no SKIPPED messages.
  • Control restored the original worker's settings-recomputation behavior in the refreshed source, leaving the new test unchanged: selecting the_whole_worker_preserves_each_programs_memory_windows with --exact gave 0 passed, 1 failed, 0 ignored, 1,807 filtered; no skips. It reconstructed the wrong 0x104 memory-window form. This is a behavioral control, not a run of the untouched old PR head.
  • The authored memory-store shader is compiled only, never dispatched. Existing worker recovery and scratch-limit tests also passed.
  • Executions preceded committing the unchanged source. Exact commands, hashes, logs, the previous PR description and previous head are retained locally.

Regression run
Pending new paired clean-head main/PR title runs for 37802271a56db9201209b801cc15fe9fa09ab83b. The old 79aaead0 smoke results are historical and do not validate this refresh.

Not tested

  • Full workspace on the refreshed head, clean-head retail comparison, whole-form GPU output equivalence, AMD/Intel, or gameplay RAM savings on this version.
  • The earlier version's reported retail memory measurements have not been reproduced here. Current synthetic retained-source checks do not establish total-process savings or a fix for the black-world symptom.
  • Full baseline validation exposed a separate diagnostic thread-slot exhaustion defect under repair. This PR stays draft until required validation is complete.

AI use
The original retention change was written with Claude Code (Claude Opus 5.5), as recorded in the previous description. Codex (GPT-6) reviewed duplication and worker identity, refreshed the change, added and ran the focused control/tests, and updated this PR at Prime's request.

Optional temporary Discord for coordinating contributor work, testing and comparing results: https://discord.gg/6B4TykyC4W

@Prime1997 Prime1997 self-assigned this Nov 27, 2026
@andrewDoing

Copy link
Copy Markdown
Contributor

I checked GPU output parity for the indirect whole-pipeline fallback on RTX 5070 / NVIDIA 616.92 at head 79aaead0f115aa74fdf9eda2b7df983b1a24391e using a test-only native harness.

The guarded console compute program went through the production CreateComputePipelineState hook and chain registry. With split threshold 20 and the per-instruction translator, it registered four pieces with no whole PSO initially; production whole_ready built and cached the whole fallback. A native ExecuteIndirect(1,1,1) through the readback runner produced the independently computed values for all 32 lanes and left 32 guard words unchanged. With threshold 12500, the same program registered no chain, whole_ready returned the ordinary PSO, and the 64-word output matched.

I repeated both controls in fresh processes with the translated cache disabled and enabled: four focused passes, zero skips. Settings included XCL_DIRECT_DXIL=1, XCL_DIRECT_COMPACT=0, XCL_PER_LANE=0, and XCL_PSO_DISK_CACHE=0.

This validates the selected whole fallback and GPU results for this synthetic program. The harness does not execute the title's bind_abi or guest command wrapper, and it does not test the asynchronous Late path, retail behavior, or latency.

AI use: OpenAI Codex with GPT-6.2 Astra built and ran the fixture; Codex reviewed and prepared this report.

@Prime1997

Copy link
Copy Markdown
Collaborator Author

Thanks for running the parity check through the production hook and whole_ready, with the translation cache both on and off. As you say, the asynchronous Late path and a retail run aren't covered by it; the retail run in the description only showed whole forms being built from the second translation without a warning. No change from this review.

AI use: Claude Code (Claude Opus 5.5) wrote this reply; Prime posted it.

@thehollowedone

Copy link
Copy Markdown
Contributor

Combined Windows check of #3047, #3048, #3049, and #3050. I applied exact heads 79aaead0, edc2b458, 1d46e4b6, and d6d529c2 to their common nvidia-dev parent d1be8103. The only integration conflict was host.rs; one shared ten-tick counter retained both RAM report lines. This is a local, uncommitted combination, not any PR's exact head.

cargo build --locked --workspace passed on the base and combination. cargo test --locked --workspace --no-fail-fast -- --test-threads=4 on the RTX 3080 Ti gave:

Tree Passed Failed Ignored GPU skip notices
Clean nvidia-dev parent 1,823 9 48 27
Four drafts combined 1,829 9 48 27

The same nine test instances failed on both trees, including the shader-cache test; the combination added six passes and no new suite failure on this machine. I would not call the four drafts ready together yet: the two boundary failures below still need fixes. This test does not establish world-load RAM savings.

I found a correctness gap in #3047's deferred whole shader. If with_switch_fallback creates a split chain in switch form after a driver refusal, WholeSource::code() later calls console_to_dxil_for on a worker or dispatch thread, where the thread-local switch scope has ended. It can regenerate heap-window DXIL for a chain whose pieces were made in switch form. A synthetic memory-store program made the variants distinguishable: the new isolated regression failed on the unchanged combined tree (0 passed / 1 failed), then passed (1 / 0) with the local change below. The existing the_whole_form_is_made_again_from_the_console_program test also passed (1 / 0). Capture the resolved window mode while constructing the chain and pass it to console_to_dxil_in when regenerating the whole form. This candidate has not had a full-suite or title run.

Candidate #3047 fix and isolated regression
diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
index 4f8f069e..2da19c2f 100644
--- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
+++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
@@ -71,11 +71,12 @@ impl PipelineBuilder {
 struct WholeSource {
     console: Vec<u8>,
     wave32: bool,
+    windows: u32,
 }
 
 impl WholeSource {
     fn code(&self) -> Result<Vec<u8>, String> {
-        crate::gpu::recomp::pso::console_to_dxil_for(&self.console, pso::Stage::Compute, 0, self.wave32).map(|c| c.dxil)
+        crate::gpu::recomp::pso::console_to_dxil_in(&self.console, pso::Stage::Compute, 0, self.wave32, self.windows).map(|c| c.dxil)
     }
 }
 
@@ -132,7 +133,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT
     let mut pieces = built.into_iter().collect::<Option<Vec<_>>>()?.into_iter();
     let first = pieces.next()?;
     let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group,
-        whole_source: WholeSource { console: console.to_vec(), wave32 }, whole: OnceLock::new(), build_whole: Mutex::new(()), whole_sent: Default::default() });
+        whole_source: WholeSource { console: console.to_vec(), wave32, windows: pso::mem_windows() }, whole: OnceLock::new(), build_whole: Mutex::new(()), whole_sent: Default::default() });
     PROGRAMS.fetch_add(1, Ordering::Relaxed);
     PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed);
     *result = first.into_raw();
@@ -351,11 +352,52 @@ mod tests {
             }
             Err(e) => panic!("the console program does not translate: {e}"),
         };
-        let source = super::WholeSource { console: blob.clone(), wave32: false };
+        let source = super::WholeSource { console: blob.clone(), wave32: false, windows: crate::gpu::recomp::pso::mem_windows() };
         assert_eq!(source.code().unwrap(), first, "the DXIL the chain was split from");
         assert!(source.console.len() < first.len(), "a chain keeps less than the DXIL: {} against {}", source.console.len(), first.len());
     }
 
+    #[test]
+    fn deferred_whole_keeps_the_original_memory_window_mode() {
+        // The title-window setting is process-global; keep the variant comparison
+        // out of the parallel workspace test process.
+        const CHILD: &str = "XCL_TEST_DEFERRED_WHOLE_MODE_CHILD";
+        if std::env::var_os(CHILD).is_none() {
+            let status = std::process::Command::new(std::env::current_exe().unwrap())
+                .args(["--exact", "hle::d3d12x::real::dispatch_chain::tests::deferred_whole_keeps_the_original_memory_window_mode", "--nocapture", "--test-threads=1"])
+                .env(CHILD, "1")
+                .status()
+                .unwrap();
+            assert!(status.success(), "isolated memory-window regression failed");
+            return;
+        }
+        use crate::gpu::recomp::{pso, HEAP_WINDOWS};
+        use crate::gpu::recomp::pso::Stage;
+        use crate::gpu::xbox::tests::{fssm, sample};
+        let code: Vec<u8> = [
+            crate::gpu::rdna2::encode("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 0), ("SADDR", 0)], None).unwrap(),
+            crate::gpu::rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap(),
+        ].concat();
+        let mut f = fssm(&code, &[(6, 0)]);
+        f[0x138..0x13c].copy_from_slice(&4u32.to_le_bytes());
+        for offset in [0x13C, 0x140, 0x144] {
+            f[offset..offset + 4].copy_from_slice(&1u32.to_le_bytes());
+        }
+        let blob = sample(5, &[f]);
+        pso::set_title_windows(2 | HEAP_WINDOWS);
+        assert_eq!(pso::mem_windows(), 2 | HEAP_WINDOWS);
+        let (expected, source) = pso::in_switch_form(|| {
+            assert_eq!(pso::mem_windows(), 2);
+            let expected = pso::console_to_dxil_for(&blob, Stage::Compute, 0, false).unwrap().dxil;
+            let source = super::WholeSource { console: blob.clone(), wave32: false, windows: pso::mem_windows() };
+            (expected, source)
+        });
+        let ambient = pso::console_to_dxil_for(&blob, Stage::Compute, 0, false).unwrap().dxil;
+        assert_ne!(ambient, expected, "fixture must distinguish heap and switch forms");
+        assert!(source.code().unwrap() == expected, "whole form must use the chain's memory mode");
+        pso::set_title_windows(0);
+    }
+
     const MB: u64 = 1 << 20;
 
     #[test]

For #3048, a separate focused regression shows that the opt-in driver-cache switch can deny a title-owned lookalike path. The #3049 heap-counter self-attribution was already reported, and #3050 has existing upload-cap and readback coverage. I did not duplicate those tests.

I have not run a combined retail title, measured RAM or frame times, or produced clean-commit paired smoke blocks for these drafts. Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti (621.35), rustc 1.99.1 MSVC, SDK DXC 1.8.2502.11. AI use: Codex (GPT-6.2 Sol) combined the drafts, resolved the local conflict, ran both suites and the focused regressions, and drafted this report; Codex (GPT-6.2 Astra) independently traced the #3047 and #3048 code paths.

@pickles976

pickles976 commented Nov 27, 2026 •

Copy link
Copy Markdown

Wine corroboration of @thehollowedone's deferred-window finding above, on standalone #3047 head 79aaead0f115aa74fdf9eda2b7df983b1a24391e rather than the four-PR combination.

A local ignored/fresh-process CPU regression builds a real synthetic memory-store program inside pso::in_switch_form with effective windows=2, leaves that scope (ambient 2 | HEAP_WINDOWS), and asks WholeSource::code() to rebuild it. The heap/switch control bytecodes are explicitly required to differ. Unmodified production: 0/1, delayed hash16982255943155419730 versus original switch hash16925848744296737581. Retaining the effective windows in WholeSource and using console_to_dxil_in, as your proposed fix does: 1/1, with full DXIL byte equality. No hardware dispatch or deliberate driver OOM is involved.

Wine11/Linux6.17, Rust1.98.1 Windows-MSVC target, DXC/dxil1.9.2609.5. Original fresh build32.77s; corrected source was freshly compiled33.62s in the intervening fixture build, then this isolated check reused that same binary (0.05s Cargo /0.03s test). Local paths:

  • verify-xcl3047-window-mode-20261127T211814Z/
  • verify-xcl3047-corrected-split-on-20261127T212035Z/ (compile provenance only; its separate split-fixture admission failed, not a GPU pass)
  • verify-xcl3047-window-mode-fixed-20261127T212201Z/

This supports preserving the successful fallback choice/cache identity. It does not demonstrate a root-signature incompatibility—the source documents common bindings—or a retail crash, memory saving, Game-Init fence fix, or asynchronous Late-path correctness. Local production correction/test retained; no contribution PR. AI-assisted local verification.

Completed retained-source GPU follow-through (same local mode correction)

On 79aaead0f115aa74fdf9eda2b7df983b1a24391e plus the above retained-window correction and test-only probes, two fresh-process tests now pass on the physical RTX 4060 Laptop / Wine 11 / NVIDIA 590.48.1. This is the diagnostic relaxed-vkd3d 2576c0b4adfae4a+ stack, not stock certification.

The earlier absent-chain fixture was misconfigured: it omitted the FSSM Wave32 header (0xD4 = 0x20), causing logical-Wave64 split eligibility to force the effective split limit to zero. Opt-in planner diagnostics established that before any GPU creation; it was not an owner failure. The corrected bounded-loop kernel reports threshold20, 277 optimized instructions, 14 pieces. Through production translated_compute_pso_once, the fixture seeds/hits the in-process translation cache, poisons and drops the caller's console bytes, drops its compiled handle, obtains the retained-source whole fallback, and dispatches that PSO. All32 varied lane words (0x30470000 + 24*lane) and32 untouched guard words pass.

  • Disk translation cache enabled: 1/1,0.97s, fresh intended-tree33.17s compile; verify-xcl3047-wave32-retained-20261127T213056Z/console.log.
  • Disk translation cache disabled (XCL_TRANSLATED_CACHE=0): separate fresh process,1/1,0.88s, same verified executable; verify-xcl3047-wave32-retained-off-20261127T213141Z/console.log.

Each process uses a distinct private disk-cache directory. The in-process translation cache remains enabled and its hit counts are asserted in both legs; this is not an all-caches-disabled test. No ExecuteIndirect, asynchronous Whole::Late, actual driver-OOM fallback, retail title, memory-saving or startup-stall verdict. All resource guards unchanged. Local fixture and narrow mode correction retained; no code contribution pushed.

@andrewDoing

Copy link
Copy Markdown
Contributor

I checked the previously untested asynchronous Late path on RTX 5070 / NVIDIA 616.92 at head 79aaead0f115aa74fdf9eda2b7df983b1a24391e, using a test-only native fixture and stable window mode.

With XCL_CS_PSO_WAIT_MS=10000, the guarded console program registered four pieces and initially had no whole PSO. The first production whole_ready call returned Late; after the worker completed, it returned Ready, and a subsequent lookup returned the same COM identity. Native ExecuteIndirect with that PSO produced all 32 expected lane values and left 32 guard words unchanged. A fresh-process unsplit control returned Plain and produced the same 64 words. Both focused runs passed without skips.

The harness invokes whole_ready directly, then dispatches when ready. It does not verify guest draw skipping or catch-up, retail latency, or the separately reported switch-form-to-heap-form mismatch.

AI use: OpenAI Codex with GPT-6.2 Astra built and ran the fixture; Codex reviewed and prepared this report.

Prime1997 added a commit to Prime1997/xcl that referenced this pull request Nov 28, 2026
Refresh xcl-dev#3047 on the current NVIDIA base while preserving its worker protections. Keep smaller console shader sources instead of whole DXIL copies and save the original window and wave settings for later whole-form builds. The legacy worker-setting control fails as expected and all seven targeted module tests pass; clean-head retail and full workspace validation remain pending.

Assisted-by: Codex (GPT-6)
@Prime1997
Prime1997 force-pushed the contrib/nv-split-console-code branch from 79aaead to 3780227 Compare November 28, 2026 07:08
@Aniseto

Aniseto commented Nov 28, 2026

Copy link
Copy Markdown

Ran the split-chain reconstruction tests at 37802271 on an NVIDIA Blackwell desktop part:

Environment: Windows 11 Pro build 26200 x64, NVIDIA GeForce RTX 5070 Ti (Blackwell, wave32 only, 16 GB) driver 32.0.16.2124, Intel Core i5-12400F, 64 GB RAM, rustc 1.100.0 (0ef1bc386 2026-11-09), MSVC 14.44.35207, DXC 1.9.2609.5, debug build.

XCL_ADAPTER=NVIDIA cargo test -p xcl --lib hle::d3d12x::real::dispatch_chain::tests:: -- --test-threads=1
7 passed; 0 failed; 0 ignored; 0 measured; 1801 filtered out      (exit 0)

All seven tests pass, including the retained-size/reconstruction case and the real-worker test that distinguishes root-UAV from descriptor-heap translations. They are CPU-side tests; I did not run a title with an indirect whole-form fallback. The thread has GPU-parity runs on RTX 5070 and other cards, but no desktop 5070 Ti.

Not tested: a retail indirect dispatch, a paired smoke run, the full workspace suite, release profile, AMD and Intel GPUs, native wave64 hosts, Wine, game data.

AI-assisted (OpenCode), model: DeepSeek V4.1 Flash Free - checked out the PR's head commit in a detached worktree, built it, ran the tests, wrote this report; the worktree was not modified; no game data was used.

@thehollowedone

thehollowedone commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Independent Windows/NVIDIA check of #3047 head 37802271 against its exact nvidia-dev parent 54225f58. Hardware: RTX 3080 Ti (driver 621.35), Ryzen 7 9800X3D, Windows 11 build 26300, Rust 1.99.1 MSVC, DXC 1.8.2502.11.

The unfiltered workspace run on the head terminated its xcl --lib binary when a UMA restoration test could not restore the coherent window, as described in the PR. I then ran the same command on clean head and parent with only the three documented aborting uma_driver::tests cases excluded:

$env:XCL_ADAPTER='3080'; cargo test --offline --locked -j 4 --workspace --no-fail-fast --quiet -- --test-threads=4 --skip uma_driver::tests::a_refused_gpu_upload_segment_becomes_custom --skip uma_driver::tests::mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment --skip uma_driver::tests::failed_restore_stops_before_importing_an_unbacked_window

Tree Passed Failed Ignored GPU SKIPPED notices
Parent 54225f58 1,906 1 48 26
Head 37802271 1,908 1 48 26

The only failed test on both is gpu::recomp::pso::shader_cache_tests::console_mesh_caches_hlsl_compute_pass_in_memory_and_on_disk (DXIL not compiled yet). The two additional head tests passed. The skips are not counted as GPU coverage.

I also checked the revised source path: initial translation captures the wave and resolved window mode, and deferred reconstruction uses those same values. I found no new correctness blocker in that path. This is a source review, not a GPU output comparison of an indirect whole-form dispatch.

Not tested here: world-load behavior, indirect whole-form GPU output, retail RAM savings on this revision, AMD or Intel. The PR remains draft while its description and branch checks are outstanding.

Paired clean-head smoke follow-up: I built cargo build --offline --locked -j 4 --release -p xcl on clean current main and the clean PR head, then ran scripts/smoke.ps1 -Seconds 60 -StartupTimeoutSeconds 120 with XCL_PREPARE=0, the same anonymous title and RTX 3080 Ti. These are the script's generated blocks:

xcl-smoke v1
commit: bb9a6b4bfc7632b09f3a633e983c86cd72b0fa8f
gpu: NVIDIA GeForce RTX 3080 Ti
title: 9cc6a39e
seconds: 60
exit: 0x0
frames shown: 1269 (PresentX 1269)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15147 MB
xcl-smoke v1
commit: 37802271a56db9201209b801cc15fe9fa09ab83b
gpu: NVIDIA GeForce RTX 3080 Ti
title: 9cc6a39e
seconds: 60
exit: 0x0
frames shown: 1444 (PresentX 1444)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 16821 MB

The head clears the numeric smoke gates (frames at least 80% of main; peak commit at most 125% of main), with zero removals and crashes. The script supplied no menu input, so this checks launch/menu stability, not world load or the indirect whole-form path. The author can paste these two blocks under Regression run in the PR description; the comment alone does not satisfy the description check.

AI use: Codex (GPT-6.2 Sol) ran the suites and paired smoke; Codex (GPT-6.2 Astra) independently traced the deferred shader path.

Refresh xcl-dev#3047 on the current NVIDIA base while preserving its worker protections. Keep smaller console shader sources instead of whole DXIL copies and save the original window and wave settings for later whole-form builds. The legacy worker-setting control fails as expected and all seven targeted module tests pass; clean-head retail and full workspace validation remain pending.

Assisted-by: Codex (GPT-6)
@Prime1997
Prime1997 force-pushed the contrib/nv-split-console-code branch from 3780227 to e87bdba Compare November 28, 2026 22:00
@github-actions github-actions Bot added area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance gpu:nvidia Code is specific to NVIDIA / wave32 GPUs (scope tag; see needs:nvidia-test) gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks) and removed gpu:nvidia Code is specific to NVIDIA / wave32 GPUs (scope tag; see needs:nvidia-test) labels Nov 28, 2026
@thehollowedone

Copy link
Copy Markdown
Contributor

Independent current-head Windows/NVIDIA check of #3047 at e87bdba4. RTX 3080 Ti / driver 621.35, Ryzen 7 9800X3D, Windows build 26300, Rust 1.99.1, DXC 1.8.2502.11.

After cargo build --workspace passed, cargo test --workspace --no-fail-fast -- --test-threads=4 completed with 2,593 passed, 3 failed, 49 ignored, and 26 SKIPPED notices (mostly unavailable wave64). The failed cases were:

  • console_mesh_caches_hlsl_compute_pass_in_memory_and_on_disk: DXIL not compiled yet. The exact case failed with the same error in isolation on current main fa204595.
  • two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs: the two-pass release assertion. The exact case failed with the same assertion in isolation on that main commit.
  • a_preparation_worker_also_builds_a_split_programs_whole_form: no split program in the full run. The exact case passed 1/0/0 in a fresh isolated run on this PR head and also passed 1/0/0 on main. Its full-suite failure remains unexplained; I would not count it as a passing full suite.

I found two source-level allocation paths worth correcting before the next head:

  1. Chain::whole calls whole_source.code() before WholeBuild::get_or_build checks the result, lock, and 10-second OOM cooldown. A rejected or contending request can still reconstruct and hold a full DXIL buffer. Resolve the source inside the gated build closure, preserving the translation error category and message in the cached outcome.
  2. build_indirect reconstructs the whole DXIL before the 64 MiB indirect-source admission check. Save its original byte length when the split chain is built, reserve the plan plus that length first, and hold IndirectCharge through reconstruction so an error releases the reservation. Reconcile the charge if regenerated output has a different length.

A focused regression should count source resolutions under concurrent whole requests, inside the OOM cooldown, and with the indirect budget already exhausted. The count should stay zero for requests rejected before a build. The existing whole-build tests only count driver-build closures, so they do not detect this work.

This is a review and a failed current-head suite, not a merge-ready verdict. I did not run paired smoke on this head. AI use: Codex (GPT-6.2 Sol) checked the source and ran the tests; Codex (GPT-6.2 Astra) independently reviewed the allocation paths.

@vasanex

vasanex commented Nov 29, 2026

Copy link
Copy Markdown
merge-check
base: fa204595a488c60c6c5f905244f0172072c9c2a9
head: e87bdba4e37aebbe4853d93ff9292da2efd694eb
merge: clean
build: cargo build --workspace -> ok
tests: not run alone; in a stack of 11 of your PRs on this base: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2650 passed, 1 failed, 49 ignored; SKIPPED: 27 lines (wave64, refused f16/f32 forms, heap windows, driver cache); failing: #3123's private_physical_pages_reach_the_gpu_on_mapping only. Alone: hle::d3d12x::real:: ends abnormally in failed_binding_keeps_indirect_commands_until_allocator_reset, which does the same on the base (3/3) and passes in the whole suite.
review: confirms thehollowedone's point from today (issuecomment-7250287070) independently: Chain::whole calls self.whole_source.code() before self.whole.get_or_build(..) (dispatch_chain.rs:245-246), outside the build-once guard. What this adds to it: (1) In the retry window after an out-of-memory result every call translates again and discards the result; a translation error is never stored, so it is retried on each call. (2) On the worker a translation error leaves whole.ready() None, so the `Err(_) if ..ready().is_none() => drop(guard)` branch (:518) treats it as out of memory: queued again on every indirect dispatch and never logged. Translating inside the closure and storing the error fixes both. Unlikely in practice (the same inputs translated once already). Otherwise lands on main unchanged; overlaps #2786 (whole_code).
performance: 60 s smoke of the merged tree (98fc43b4): 1679 frames, peak commit 15625 MB, 0 removals, 0 crashes (base 1629-1689 frames, 16065-16596 MB). Load run with #3049's counters (XCL_HEAP_COUNT=2), base + #3049 vs base + #3049 + this PR, one run each: XCL's own heap holds 27-34 live allocations of 1-16 MiB (59-90 MB) with it against 58-103 (134-151 MB) without, at 20/40/60/80 s into loading - about 60 fewer blocks, 45-85 MB less; a third arm without this PR (with #3091) also shows 89-99. The total heap figure varies more than that between runs, so only this size class shows it. No removal or crash (2073 frames in 150 s, base 2014).
verdict: not yet: move the retranslation inside get_or_build (small fix); the saving shows in the load run; draft, description check red
hardware / tool and model: RTX 3080 10 GB 621.40, Ryzen 9 7950X, Windows 11 26200 / Claude Code (Claude Opus 5.5, Claude Fable 5.2)

How this was run: the suite ran once on the 11 of your PRs that build on this base, merged together (#3047 #3048 #3049 #3091 #3092 #3103 #3104 #3105 #3107 #3123 #3125; a local tree, only #3125 needed a resolution in README and the sparse.rs test module); the base alone gave 2608 passed, 0 failed, 49 ignored with the same 27 SKIPPED lines (21 no wave64, 3 refused per-lane f16/f32 forms, 2 heap windows opt-in, 1 driver cache needs Developer Mode). This PR alone was merged onto the base, built (cargo build --workspace, then release), its modules' lib tests run (debug), and smoke-run once for 60 s (scripts/smoke.ps1, retail title, front end, XCL_PREPARE=0). The smoke numbers are for my local merged tree, not a clean-head block for the description. Load runs: 150 s, the save loaded with A presses, XCL_PREPARE=0, after one warm-up, one run per arm; on this 10 GB card main is over the video memory budget while loading, and presents stop after 94-125 s in every arm.

AI use: Claude Code (Claude Opus 5.5 and Claude Fable 5.2) ran the builds, tests and title runs, reviewed the diff and wrote this; the code points cited were checked against the merged tree.

@thehollowedone

thehollowedone commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to my current-head finding on e87bdba4: I tested a local, uncommitted candidate that moves whole-program translation inside the existing build-once/cooldown gate. During cooldown, repeated indirect dispatches no longer regenerate DXIL. A translation error remains retryable with its original message; driver errors retain the existing cache behavior, and an out-of-memory cooldown starts when the build fails.

On Windows 11 build 26300, RTX 3080 Ti / 621.35, Ryzen 7 9800X3D, Rust 1.99.1 MSVC, DXC 1.8.2502.11, cargo build --offline --locked -j 4 --workspace passed. The two whole_preparation_ tests passed (2/0/0), and the slow-preparation cooldown test passed (1/0/0). The candidate's full cargo test --offline --locked -j 4 --workspace --no-fail-fast -- --test-threads=4 had 2,597 passed, 2 failed, 49 ignored, 26 GPU SKIPPED notices. The untouched PR head, built and run with the same command in an isolated Cargo target directory, had 2,594 passed, 2 failed, 49 ignored, 26 GPU SKIPPED notices and the same two failures: console_mesh_caches_hlsl_compute_pass_in_memory_and_on_disk and a_preparation_worker_also_builds_a_split_programs_whole_form. An isolated failed_binding_keeps_indirect_commands_until_allocator_reset also panicked with adopted class on both the candidate and untouched head. These results establish no additional observed suite failure, not a green suite.

The separate build_indirect path still reconstructs whole DXIL before its variant-source reservation; this patch does not address that path. No clean-head paired smoke or memory/latency measurement was run, so the candidate is not merge-ready.

Candidate gate change and focused regressions
diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
index 795cdc2b..ca03d1f0 100644
--- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
+++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
@@ -142,24 +142,32 @@ impl<T: Clone> WholeBuild<T> {
     }
 
     pub(super) fn get_or_build(&self, now: std::time::Instant, build: impl FnOnce() -> Result<T, HRESULT>) -> Result<T, HRESULT> {
+        self.get_or_build_prepared(|| now, || Ok(()), |()| build()).expect("infallible preparation")
+    }
+
+    /// Preparation errors are retryable and retain their message; only driver outcomes are cached
+    /// or subject to the OOM cooldown. Neither preparation nor build runs before admission.
+    fn get_or_build_prepared<P>(&self, now: impl Fn() -> std::time::Instant,
+        prepare: impl FnOnce() -> Result<P, String>, build: impl FnOnce(P) -> Result<T, HRESULT>) -> Result<Result<T, HRESULT>, String> {
         if let Some(result) = self.result.get() {
-            return result.clone();
+            return Ok(result.clone());
         }
-        let mut retry_at = self.retry_at.lock().unwrap();
+        let mut retry_at = self.retry_at.lock().unwrap_or_else(|e| e.into_inner());
         if let Some(result) = self.result.get() {
-            return result.clone();
+            return Ok(result.clone());
         }
-        if retry_at.is_some_and(|at| now < at) {
-            return Err(crate::util::E_OUTOFMEMORY);
+        let started = now();
+        if retry_at.is_some_and(|at| started < at) {
+            return Ok(Err(crate::util::E_OUTOFMEMORY));
         }
-        match build() {
+        match build(prepare()?) {
             Err(hr) if hr == crate::util::E_OUTOFMEMORY => {
-                *retry_at = Some(now + WHOLE_RETRY);
-                Err(hr)
+                *retry_at = Some(now() + WHOLE_RETRY);
+                Ok(Err(hr))
             }
             result => {
                 let _ = self.result.set(result.clone());
-                result
+                Ok(result)
             }
         }
     }
@@ -238,14 +246,15 @@ impl Chain {
     /// thread is synchronously blocked waiting for this compile (registers a long PC call).
     unsafe fn whole(&self, on_title_thread: bool) -> Result<ID3D12PipelineState, String> {
         let result = match self.whole.ready() {
-            Some(result) => result,
+            Some(result) => Ok(result),
             None => {
                 // (only when a title thread is held while this compile lasts, as in any other long PC call)
                 let _call = on_title_thread.then(super::super::pso_async::pc_call);
-                let code = self.whole_source.code().map_err(|e| format!("whole compute program: {e}"))?;
-                self.whole.get_or_build(std::time::Instant::now(), || self.builder.pipeline(&code, &pc_iid(Kind::PipelineState)))
+                self.whole.get_or_build_prepared(std::time::Instant::now,
+                    || self.whole_source.code().map_err(|e| format!("whole compute program: {e}")),
+                    |code| self.builder.pipeline(&code, &pc_iid(Kind::PipelineState)))
             }
-        };
+        }?;
         result.map_err(|hr| if hr == crate::util::E_OUTOFMEMORY { "whole compute pipeline: out of memory".into() } else { format!("whole compute pipeline ({hr:#x})") })
     }
 }
@@ -1103,6 +1112,58 @@ mod tests {
         assert_eq!(deterministic.get_or_build(at + WHOLE_RETRY, || Ok(8)), Err(crate::util::E_INVALIDARG));
     }
 
+    #[test]
+    fn whole_preparation_runs_only_after_admission() {
+        let at = std::time::Instant::now();
+        let whole: WholeBuild<u32> = WholeBuild::new();
+        let mut prepared = 0;
+        let mut built = 0;
+        assert_eq!(whole.get_or_build_prepared(|| at, || {
+            prepared += 1;
+            Ok(11)
+        }, |_| { built += 1; Err(crate::util::E_OUTOFMEMORY) }), Ok(Err(crate::util::E_OUTOFMEMORY)));
+        assert_eq!(whole.get_or_build_prepared(|| at + WHOLE_RETRY / 2, || {
+            prepared += 1;
+            Ok(12)
+        }, |_| { built += 1; Ok(8) }), Ok(Err(crate::util::E_OUTOFMEMORY)));
+        assert_eq!((prepared, built), (1, 1), "the cooling-down chain must not regenerate or build");
+        assert_eq!(whole.get_or_build_prepared(|| at + WHOLE_RETRY, || {
+            prepared += 1;
+            Ok(13)
+        }, |_| { built += 1; Ok(7) }), Ok(Ok(7)));
+        assert_eq!(whole.get_or_build_prepared(|| at + WHOLE_RETRY * 2, || {
+            prepared += 1;
+            Ok(14)
+        }, |_| { built += 1; Ok(8) }), Ok(Ok(7)));
+        assert_eq!((prepared, built), (2, 2), "the ready chain must reuse its result");
+    }
+
+    #[test]
+    fn whole_preparation_error_keeps_its_message_and_can_retry() {
+        let at = std::time::Instant::now();
+        let whole: WholeBuild<u32> = WholeBuild::new();
+        assert_eq!(whole.get_or_build_prepared(|| at, || Err::<(), _>("whole compute program: translation unavailable".into()),
+            |()| unreachable!()),
+            Err("whole compute program: translation unavailable".into()));
+        assert!(whole.ready().is_none(), "a source error is not a permanent driver result");
+        assert_eq!(whole.get_or_build_prepared(|| at, || Ok(()), |()| Ok(7)), Ok(Ok(7)));
+    }
+
+    #[test]
+    fn whole_oom_cooldown_begins_after_a_slow_preparation() {
+        use std::cell::Cell;
+        let at = std::time::Instant::now();
+        let finished = at + WHOLE_RETRY * 2;
+        let calls = Cell::new(0);
+        let clock = || { let n = calls.get(); calls.set(n + 1); if n == 0 { at } else { finished } };
+        let whole: WholeBuild<u32> = WholeBuild::new();
+        assert_eq!(whole.get_or_build_prepared(clock, || Ok(()), |()| Err(crate::util::E_OUTOFMEMORY)),
+            Ok(Err(crate::util::E_OUTOFMEMORY)));
+        assert_eq!(whole.get_or_build_prepared(|| finished + WHOLE_RETRY / 2, || unreachable!(), |()| unreachable!()),
+            Ok(Err(crate::util::E_OUTOFMEMORY)));
+        assert_eq!(whole.get_or_build_prepared(|| finished + WHOLE_RETRY, || Ok(()), |()| Ok(7)), Ok(Ok(7)));
+    }
+
     #[test]
     fn whole_worker_runs_all_jobs_on_one_late_thread() {
         use std::collections::HashSet;

AI use: Codex (GPT-6.2 Sol) wrote and ran the local candidate; Codex (GPT-6.2 Astra) reviewed the low-level gate design.

Second local candidate: admit indirect source before regeneration. The separate build_indirect path in the earlier report can also avoid translating a whole program when its existing 64 MiB source budget is full. This candidate records the initial whole DXIL length when the chain is created, reserves that length plus the piece lengths before WholeSource::code(), and adjusts the live charge if regeneration returns a different length. A failed growth or translation releases its own reservation without releasing a competing variant's charge. The successful variant holds the charge until its final owner drops it. This patch is separate from the whole-build/cooldown candidate above; I did not combine or smoke-test the two.

At unchanged head e87bdba4, Windows 11 build 26300, RTX 3080 Ti / 621.35, Ryzen 7 9800X3D, Rust 1.99.1 MSVC, DXC 1.8.2502.11:

  • cargo test --offline --locked -j 4 -p xcl --lib indirect_source_ -- --test-threads=1: 3 passed, 0 failed, 0 ignored. The tests verify zero translation calls on rejected admission, exact accounting across growth and shrink, a competing reservation, translation failure, and final-owner release.
  • cargo build --offline --locked -j 4 --workspace: passed.
  • cargo test --offline --locked -j 4 --workspace --no-fail-fast -- --test-threads=4: 2,597 passed, 2 failed, 49 ignored; 26 GPU SKIPPED notices. The two failures are console_mesh_caches_hlsl_compute_pass_in_memory_and_on_disk and a_preparation_worker_also_builds_a_split_programs_whole_form, the same two seen on this untouched head in the earlier comparison. This is not a green suite.

The budget tracks admitted source lengths, not transient translator scratch. I did not measure frame time or memory savings, run an indirect whole-form GPU output comparison, or produce clean-commit paired smoke on this uncommitted candidate. The PR remains draft.

Candidate indirect-source reservation and regressions
diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
index 795cdc2b..df8971e5 100644
--- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
+++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
@@ -179,6 +179,7 @@ const WHOLE_RETRY: std::time::Duration = std::time::Duration::from_secs(10);
 struct WholeSource {
     console: Vec<u8>,
     wave32: bool,
+    whole_len: usize,
     // Preserve the first translation's window count and heap/switch form: a later worker
     // does not inherit `in_switch_form` from the thread that built the split pieces.
     windows: u32,
@@ -207,14 +208,17 @@ struct IndirectChain {
     signature: ID3D12RootSignature,
     whole: ID3D12PipelineState,
     pieces: Vec<ID3D12PipelineState>,
-    _charge: IndirectCharge,
+    _charge: IndirectCharge<'static>,
 }
 
-struct IndirectCharge(usize);
+struct IndirectCharge<'a> {
+    used: &'a AtomicUsize,
+    bytes: usize,
+}
 
-impl Drop for IndirectCharge {
+impl Drop for IndirectCharge<'_> {
     fn drop(&mut self) {
-        INDIRECT_VARIANT_SOURCE.fetch_sub(self.0, Ordering::AcqRel);
+        self.used.fetch_sub(self.bytes, Ordering::AcqRel);
     }
 }
 
@@ -323,6 +327,25 @@ fn reserve_indirect_source(used: &AtomicUsize, bytes: usize, limit: usize) -> bo
     }).is_ok()
 }
 
+/// Admit source bytes before recreating the whole DXIL. The original translation supplies an
+/// estimate; reconcile any size difference before creating driver objects.
+fn indirect_source_with_budget<'a>(used: &'a AtomicUsize, plan_bytes: usize, whole_len: usize, limit: usize,
+    translate: impl FnOnce() -> Result<Vec<u8>, HRESULT>) -> Result<(Vec<u8>, IndirectCharge<'a>), HRESULT> {
+    let expected = plan_bytes.checked_add(whole_len).ok_or(E_OUTOFMEMORY)?;
+    if !reserve_indirect_source(used, expected, limit) { return Err(E_OUTOFMEMORY); }
+    let mut charge = IndirectCharge { used, bytes: expected };
+    let code = translate()?;
+    let actual = plan_bytes.checked_add(code.len()).ok_or(E_OUTOFMEMORY)?;
+    if actual > expected {
+        if !reserve_indirect_source(used, actual - expected, limit) { return Err(E_OUTOFMEMORY); }
+        charge.bytes = actual;
+    } else if actual < expected {
+        charge.bytes = actual;
+        used.fetch_sub(expected - actual, Ordering::AcqRel);
+    }
+    Ok((code, charge))
+}
+
 #[derive(Default)]
 struct PlanCache {
     bytes: usize,
@@ -353,15 +376,12 @@ fn retain_indirect_plan(plan: Arc<DispatchChain>) {
 fn build_indirect(chain: &Arc<Chain>) -> Result<Arc<IndirectChain>, HRESULT> {
     let plan = chain.plan.upgrade().ok_or(E_INVALIDARG)?;
     // (the whole form is not kept: made again from the console program, `WholeSource`)
-    let whole_code = chain.whole_source.code().map_err(|e| {
-        crate::xlog_warn!("D3D12.X: whole compute program for an indirect split variant: {e}");
-        E_INVALIDARG
-    })?;
-    let source_bytes = plan.pieces.iter().map(Vec::len).sum::<usize>().saturating_add(whole_code.len());
-    if !reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, source_bytes, INDIRECT_VARIANT_BYTES) {
-        return Err(E_OUTOFMEMORY);
-    }
-    let charge = IndirectCharge(source_bytes);
+    let plan_bytes = plan.pieces.iter().try_fold(0usize, |bytes, code| bytes.checked_add(code.len())).ok_or(E_OUTOFMEMORY)?;
+    let (whole_code, charge) = indirect_source_with_budget(&INDIRECT_VARIANT_SOURCE, plan_bytes,
+        chain.whole_source.whole_len, INDIRECT_VARIANT_BYTES, || chain.whole_source.code().map_err(|e| {
+            crate::xlog_warn!("D3D12.X: whole compute program for an indirect split variant: {e}");
+            E_INVALIDARG
+        }))?;
     let signature = unsafe { signature_for(&chain.builder.device, &chain.builder.samplers, true) }.ok_or(E_INVALIDARG)?;
     let builder = Arc::new(PipelineBuilder {
         device: chain.builder.device.clone(),
@@ -458,7 +478,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT
     let mut pieces = built.into_iter().collect::<Option<Vec<_>>>()?.into_iter();
     let first = pieces.next()?;
     let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group,
-        whole_source: WholeSource { console: console.to_vec(), wave32, windows }, whole: WholeBuild::new(), plan: Arc::downgrade(&plan),
+        whole_source: WholeSource { console: console.to_vec(), wave32, windows, whole_len: whole.len() }, whole: WholeBuild::new(), plan: Arc::downgrade(&plan),
         indirect: IndirectBuild::new(), indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) });
     retain_indirect_plan(plan.clone());
     // Initialize the journal on this preparation worker, never on the first recording call.
@@ -861,7 +881,7 @@ mod tests {
             }
             Err(e) => panic!("the console program does not translate: {e}"),
         };
-        let source = super::WholeSource { console: blob.clone(), wave32: false, windows };
+        let source = super::WholeSource { console: blob.clone(), wave32: false, windows, whole_len: first.len() };
         assert_eq!(source.code().unwrap(), first, "the DXIL the chain was split from");
         assert!(source.console.len() < first.len(), "a chain keeps less than the DXIL: {} against {}", source.console.len(), first.len());
     }
@@ -886,7 +906,7 @@ mod tests {
         let mut forms = Vec::new();
         for windows in [4, 4 | HEAP_WINDOWS] {
             let expected = pso::console_to_dxil_in(&blob, pso::Stage::Compute, 0, false, windows).unwrap().dxil;
-            let source = super::WholeSource { console: blob.clone(), wave32: false, windows };
+            let source = super::WholeSource { console: blob.clone(), wave32: false, windows, whole_len: expected.len() };
             let (tx, rx) = mpsc::channel();
             assert!(super::enqueue_whole(Box::new(move || { let _ = tx.send(source.code()); })));
             let actual = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("whole worker completed").unwrap();
@@ -933,6 +953,58 @@ mod tests {
         assert_eq!(used.load(Ordering::Relaxed), 100);
     }
 
+    #[test]
+    fn indirect_source_rejection_does_not_translate() {
+        let used = AtomicUsize::new(9);
+        let mut calls = 0;
+        let result = indirect_source_with_budget(&used, 1, 1, 10, || {
+            calls += 1;
+            Ok(vec![0])
+        });
+        assert_eq!(result.err(), Some(E_OUTOFMEMORY));
+        assert_eq!((calls, used.load(Ordering::Relaxed)), (0, 9));
+    }
+
+    #[test]
+    fn indirect_source_charge_reconciles_growth_and_shrink() {
+        let used = AtomicUsize::new(2);
+        let (code, charge) = indirect_source_with_budget(&used, 2, 3, 10, || {
+            assert_eq!(used.load(Ordering::Relaxed), 7, "reserve before translation");
+            Ok(vec![0; 6])
+        }).unwrap();
+        assert_eq!((code.len(), used.load(Ordering::Relaxed)), (6, 10));
+        let shared = Arc::new(charge);
+        let second = shared.clone();
+        drop(shared);
+        assert_eq!(used.load(Ordering::Relaxed), 10, "charge lives through the final owner");
+        drop(second);
+        assert_eq!(used.load(Ordering::Relaxed), 2);
+
+        let (_, charge) = indirect_source_with_budget(&used, 2, 6, 10, || {
+            assert_eq!(used.load(Ordering::Relaxed), 10);
+            Ok(vec![0; 2])
+        }).unwrap();
+        assert_eq!(used.load(Ordering::Relaxed), 6);
+        drop(charge);
+        assert_eq!(used.load(Ordering::Relaxed), 2);
+    }
+
+    #[test]
+    fn indirect_source_failure_restores_only_its_own_reservation() {
+        let used = AtomicUsize::new(1);
+        let result = indirect_source_with_budget(&used, 2, 3, 10, || {
+            assert!(reserve_indirect_source(&used, 4, 10), "competing source");
+            Ok(vec![0; 6])
+        });
+        assert_eq!(result.err(), Some(E_OUTOFMEMORY));
+        assert_eq!(used.load(Ordering::Relaxed), 5, "retain the competing four bytes");
+        used.fetch_sub(4, Ordering::AcqRel);
+
+        let result = indirect_source_with_budget(&used, 2, 3, 10, || Err(E_INVALIDARG));
+        assert_eq!(result.err(), Some(E_INVALIDARG));
+        assert_eq!(used.load(Ordering::Relaxed), 1, "translation error refunds admission");
+    }
+
     #[test]
     fn signature_identity_includes_sampler_words_order_and_comparison() {
         let a = ([1, 2, 3, 4], false);
@@ -1061,12 +1133,12 @@ mod tests {
             let plan = Arc::new(DispatchChain { pieces: vec![dxil.clone(), dxil.clone()], dwords_per_group: 4 });
             assert!(reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, 1, INDIRECT_VARIANT_BYTES));
             let indirect = Arc::new(IndirectChain { signature: rs.clone(), whole: first.clone(),
-                pieces: vec![first.clone(), first.clone()], _charge: IndirectCharge(1) });
+                pieces: vec![first.clone(), first.clone()], _charge: IndirectCharge { used: &INDIRECT_VARIANT_SOURCE, bytes: 1 } });
             let indirect_build = IndirectBuild::new();
             indirect_build.requested.store(true, Ordering::Relaxed);
             indirect_build.result.set(Ok(indirect)).unwrap_or_else(|_| unreachable!());
             CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4,
-                whole_source: WholeSource { console: Vec::new(), wave32: false, windows: 0 }, whole, plan: Arc::downgrade(&plan), indirect: indirect_build,
+                whole_source: WholeSource { console: Vec::new(), wave32: false, windows: 0, whole_len: 0 }, whole, plan: Arc::downgrade(&plan), indirect: indirect_build,
                 indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) }));
             let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE;
             let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap();

AI use for this follow-up: Codex (GPT-6.2 Sol) wrote the candidate and tests, ran them, and drafted the report; Codex (GPT-6.2 Astra) independently reviewed reservation ownership and concurrency.

Combined-candidate check: I applied both collapsed diffs above, in order, to the unchanged #3047 head e87bdba4. They applied without a conflict; git diff --check was clean. This is a local uncommitted combination, not a new PR revision.

On the same RTX 3080 Ti / 621.35 Windows setup, cargo build --offline --locked -j 4 --workspace passed. Focused tests passed: whole_preparation_ 2/0/0, indirect_source_ 3/0/0, and whole_oom_cooldown_begins_after_a_slow_preparation 1/0/0. The full cargo test --offline --locked -j 4 --workspace --no-fail-fast -- --test-threads=4 reported 2,600 passed, 2 failed, 49 ignored, 26 GPU SKIPPED notices. The two failures have the same names as the untouched-head failures already documented above. No additional suite failure appeared when the fixes were combined.

This checks build and test interaction. The combined candidate's indirect whole-form GPU output, memory or latency benefit, and clean-commit paired smoke remain untested. Prime can apply or adapt both changes on a new head, then run those gates. AI use: Codex (GPT-6.2 Sol) combined the patches and ran the checks; Codex (GPT-6.2 Astra) reviewed their interaction.

Exact-head GPU readback: I added a test-only fixture to unchanged #3047 head e87bdba4. It creates a synthetic split compute program, requests the production indirect variant, executes its reconstructed whole PSO with ExecuteIndirect(1,1,1), and reads back the output. Descriptor-heap windows point to the checked output buffer; root UAV windows point to a separate buffer, so a root-window translation cannot satisfy the assertion. All 32 lane results matched the independently calculated values and 32 guard words stayed unchanged. On the same RTX 3080 Ti / 621.35, cargo test -p xcl --lib reconstructed_indirect_whole_executes_and_reads_back -- --nocapture passed 1/0/0, with zero GPU skips. The split threshold was set only in an isolated child process. This checks exact-head synthetic execution, not the two proposed fixes together, the title command path, AMD/Intel, or gameplay performance. AI use: Codex (GPT-6.2 Sol) wrote and ran the test and reviewed its readback scope.

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical review of current head e87bdba4. Repeated indirect dispatch can defeat the intended memory/compile saving: when the whole-program DXIL is absent, its translation occurs before the existing build-once/cooldown gate. A failing or slow driver build can therefore make each retry regenerate the whole DXIL, including during cooldown. Move translation inside the same single-build gate and test repeated indirect submissions with slow/failing builds. The current-head Windows follow-up tested such a candidate locally. The source-retention change itself is sound, but this retry path needs fixing. No local Windows run.

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Review (head e87bdba, diff read, not a merge-check; draft and conflicting, so not built or run):

  • Needs a re-port, not a conflict fix. D3D12.X: indirect dispatches of a split program run its direct pieces #3499 (e8a3666) removed IndirectBuild, build_indirect, retain_indirect_plan and indirect_blobs_present, so about half the diff edits code main no longer has. The change is still wanted: main keeps Chain::whole_code (dispatch_chain.rs ~176, ~303) for whole_ready (bind.rs ~3859).
  • Re-translation outside the lock. In Chain::whole the new translation (whole_source.code(), ~245) runs before get_or_build, outside its lock and before its out-of-memory retry check. With the default (XCL_CS_PSO_WAIT_MS unset, so whole(true) runs on the title's thread), every ExecuteIndirect within WHOLE_RETRY after an out-of-memory error translates again (a copy, a disk read, or DXC when both caches miss) and then returns out-of-memory, exactly under the memory pressure this targets; concurrent callers also translate twice. Moving the translation into the get_or_build closure would fix both.
  • A translation error isn't stored in WholeBuild, so queue_whole treats it as temporary and translates again on every later ExecuteIndirect.
  • No smoke blocks; the 4 CI failures (pipeline_library / warm_library) also failed on main that day.

Fine: the memory-window form is captured at the first translation (tested), the console bytes are copied out of title memory, driver-cache names don't change when the new translation is identical (tested), and the GPU tests use skip_test.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants