Skip to content

D3D12.X: reclaim two-pass buffers on submit fence completion - #2815

Open
coolpersonnn wants to merge 1 commit into
xcl-dev:nvidia-devfrom
coolpersonnn:ws2/two-pass-fence-reuse
Open

coolpersonnn wants to merge 1 commit into
xcl-dev:nvidia-devfrom
coolpersonnn:ws2/two-pass-fence-reuse

Conversation

@coolpersonnn

@coolpersonnn coolpersonnn commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Reclaim retired two-pass mesh buffers on submit queue fence completion rather than waiting for the owning command allocator to reset, and rebase cleanly onto nvidia-dev (eae01502).

Part of #2688

What is in it

  • README.md: document XCL_TWO_PASS_MB alongside two-pass mesh pool behavior.
  • crates/xcl/src/hle/d3d12x/alloc_pool.rs: poll reclaim_fenced() before freeing idle two-pass buffers so completed recordings can be recycled immediately without holding allocator-lifetime memory, and track FenceState::Removed so lost devices never recycle in-flight buffers.
  • crates/xcl/src/hle/d3d12x/bind.rs: replace reset-only holding with fence-tracked batches (FencedBatch, monotonic per-queue record_queue_fence .max, explicit Pending / Completed / Removed polling with u64::MAX device-removal short-circuiting), preserve closed command lists' buffers across FREE_RES_IDLE trims so Reset-less replays remain valid (in_flight list tracking), track upstream batch_buf allocations via submit fences, and add 7 unit/GPU tests covering fence reclamation, monotonic queue fence merging, closed-list replay preservation, and device removal.

Tested

  • Hardware / toolchain: NVIDIA GeForce RTX 5090 (driver 32.0.16.2101, 32187 MiB VRAM, wave32 / split wave64), WARP (software renderer), AMD Ryzen 9 9950X3D, Windows 11 Pro (10.0.26300), rustc 1.100.0 (0ef1bc386 2026-11-09), DXC 1.8.2502.11.
  • Targeted suite on clean 42532264:
    • cargo test --offline --locked -p xcl --lib -- hle::d3d12x::bind hle::d3d12x::alloc_pool --test-threads=4 (NVIDIA + WARP): 68 passed; 0 failed (1 opt-in SKIPPED: hle::d3d12x::bind::tests::two_pass_binds_set_the_shared_view_heap: no heap windows (opt-in: XCL_HEAP_WINDOWS=1)).
    • With XCL_HEAP_WINDOWS=1: two_pass_binds_set_the_shared_view_heap 1 passed; 0 failed.
  • Clean workspace release build + test suite (cargo build --offline --locked --release --workspace && cargo test --offline --locked --release --workspace --no-fail-fast -- --test-threads=4) on RTX 5090:
    • 42532264 (this PR): total_passed=1819, total_failed=13, total_ignored=48, skips=27 (xcl lib: 1692 passed; 7 failed; 28 ignored).
    • Baseline nvidia-dev (eae01502): total_passed=1812, total_failed=13, total_ignored=48, skips=27 (xcl lib: 1685 passed; 7 failed; 28 ignored).
    • Zero new failures: all 13 failures match pre-existing RTX 5090 baseline (fuzz_validate_and_gpu_{0,1,2,3}, gpu_compute_thread_limits_leave_the_lanes_past_them_out, texture_upload::{pieces_hold_the_texels_of_their_levels, gpu_parts_of_a_texture_go_up_and_the_rest_stays}, console_ms_in_as_slot_and_ms_with_as_are_refused_cleanly, async_compute_pso_registers_real_pso_and_not_standin, split_compute_prefers_the_offline_whole_pipeline x2, two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs x2).
    • 27 SKIPPED GPU tests on RTX 5090: no wave64 (20), wave32, per-lane form: refused (3), no heap windows (2), cannot disable the driver cache (1), plus opt-in XCL_HEAP_WINDOWS=1 skip above (1).
  • 60 s retail startup smoke (scripts/smoke.ps1, title: a93b40d7, RTX 5090, XCL_PREPARE=0): 42532264 produced 1671 frames (PresentX 1671), 0 device removals, 0 crashes, 15915 MB peak commit vs nvidia-dev eae01502 (1628 frames, 0 removals, 0 crashes, 15793 MB peak commit) and main b49be183 (1654 frames, 16446 MB peak commit).

Regression run

xcl-smoke v1
commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7
gpu: NVIDIA GeForce RTX 5090
title: a93b40d7
seconds: 60
exit: 0x0
frames shown: 1654 (PresentX 1654)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 16446 MB
xcl-smoke v1
commit: 42532264a221ac975b745b01097bf751e0e56712
gpu: NVIDIA GeForce RTX 5090
title: a93b40d7
seconds: 60
exit: 0x0
frames shown: 1671 (PresentX 1671)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15915 MB

Not tested

AI use

  • T3 Code / Antigravity (gemini-pro-orchestrator-neon) and Codex (GPT-6.2 Sol) wrote and reviewed the fence-tracking fixes, tests, and PR description; all builds, tests, and smoke runs were executed directly on local hardware.

@thehollowedone

Copy link
Copy Markdown

Independent Windows/NVIDIA check of #2815 head 71b1a932 against its clean nvidia-dev base af2cecc4. I ran cargo build --offline --locked --workspace, then cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4 with XCL_ADAPTER=3080 and a persistent local DXIL test cache. Windows 11 build 26300, RTX 3080 Ti / driver 621.35, Ryzen 7 9800X3D, rustc 1.99.1 MSVC, DXC 1.8.2502.11.

Clean revision Passed Failed Ignored GPU SKIPPED notices
Base af2cecc4 1,745 6 48 26
Head 71b1a932 1,749 6 48 26

The same six named tests failed in both runs: two texture_upload tests, console_ms_in_as_slot_and_ms_with_as_are_refused_cleanly, async_compute_pso_registers_real_pso_and_not_standin, and two two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs instances. The head adds four passing tests. Of the 26 skip notices, 21 require wave64, three per-lane forms were refused, and two heap-window cases were disabled in the default run; I do not count skips as coverage.

I also ran the opt-in two_pass_binds_set_the_shared_view_heap fixture separately on both revisions with XCL_HEAP_WINDOWS=1: cargo test --offline --locked -p xcl --lib two_pass_binds_set_the_shared_view_heap -- --nocapture --test-threads=1. Each passed 1/1 with no skip. This synthetic check exercises the opt-in descriptor-heap binding path; it does not measure an in-world memory saving.

Not tested: paired retail-title smoke, sustained world load, AMD/Intel, or the full workspace suite with heap windows enabled. These results alone do not establish merge readiness.

AI use: Codex (GPT-6.2 Sol) ran the builds and tests, compared the exact base and head results, and drafted this report.

@KDenKC

KDenKC commented Nov 26, 2026

Copy link
Copy Markdown

Source review of 71b1a932, no run. One ordering gap:

alloc_pool's submit path (around alloc_pool.rs:322-340) increments and signals the queue's fence under STATE, then drop(g) and calls bind::two_pass_submitted(queue, Some(&fence), value, lists). There, an existing entry for the queue is overwritten unconditionally (bind.rs:~132: m.1 = f.clone(); m.2 = value;). Two threads submitting to the same queue can reach two_pass_submitted in the opposite order to their Signals. The list then keeps the older value, and its two-pass buffers can be reclaimed once that older value completes while the newer submit still runs. Keeping the larger value (m.2 = m.2.max(value) when it is the same fence) closes it. #2816 and #2817 carry the same code, and #2816's mark_indirect_feedback_used has the same overwrite on pending_fences.

Not tested: no build or run on our side.

AI use: Gemini (Antigravity) flagged it in a review. Claude Code (Claude Opus 5.5) checked it against the source at 71b1a932 and wrote this.

@GodlyBDS

GodlyBDS commented Nov 26, 2026 •

Copy link
Copy Markdown

Retail-title A/B on RTX 3090 Ti (24 GiB, driver 621.40), Windows 10 19045, Ryzen 9 5950X, 32 GiB RAM, Agility v620 and rustc 1.98.1 MSVC release. This adds a world-transition sample to the existing smoke and suite reports.

Tested

I replayed af2cecc40886a8682ecf3267f5328c6dc4b66ad7 with the lab's startup, timing, DRED and graceful-stop patches, then the same tree plus 71b1a93201456a655a5b23fe45348257c0658018. Separate Cargo targets and identical embedded translator IDs. Each run used its own copy of the same warm shader cache and 11,721 verified native PSOs, the same profile and timed input, 30/32 logical CPUs, a 1 GiB app-specific NVIDIA shader heap, XCL_TWO_PASS_MB=4096, XCL_TEXTURE_LEVEL_PAGES=1, XCL_PSO_WAIT_AT_RECORDING=1 and XCL_GPU_PROFILE=1. One run per arm, sequentially, with the same memory guard.

Sampled observation Base +71b1a932
Peak live two-pass buffer widths before stop or device removal 2,430 MiB 1,371 MiB
Peak waiting for allocator resets 1,027 MiB 0 MiB
Made / reused / let go at last pre-end buffer sample 175 / 73 / 10 165 / 343 / 66
Peak system commit / minimum available RAM 54.60 GiB / 380 MiB 53.83 GiB / 447 MiB
Peak sampled DXGI local / non-local 17,974 / 963 MiB 17,541 / 1,025 MiB
Two-pass cap refusals / logged skipped draws or dispatches 0 / 0 0 / 0
Presents in activity buckets 1,554 1,908

All five tracked allocator fences on the base were caught up from 100.506 s through the last sample. The base still held 998 MiB for allocator resets at 115.199 s. On the patched arm, all tracked fences were caught up at 156.646 s and live two-pass widths fell from 636 to 243 MiB between 153.694 and 157.585 s while the released buffer count increased from 23 to 46. The sampled fence-wait bucket was 0 MiB throughout. The counters show lower retention and more reuse in this run. Per-recording release order is covered by the existing unit tests.

The base showed loading artwork followed by a black capture and stopped gracefully at 116.4 s on the physical RAM floor. The patched arm captured two very dark world frames with sparse horizon and building lights at 149.869 and 165.276 s. It returned DXGI_ERROR_DEVICE_HUNG at 182.162 s before the guard requested a stop. Windows logged nvlddmkm 153, Display 4101 and LiveKernelEvent 141. The last tracked q0 fence was 7840/7841. DRED stopped at 3041/3962 on q0, with ExecuteIndirect next and CS 1ada490879c33c0e bound. GPU timestamp diagnostics showed eight earlier completions of that program and a later invocation still outstanding after 9.958 s. DRED reported VA zero and no matching allocation.

Coverage limits

The arms progressed through different content for different durations. This measures observed buffer retention and records a concrete later hang. It leaves the cause of the hang, matched in-world memory use, steady-state FPS and playability unresolved. AMD and other drivers were outside this replay.

AI use

OpenAI Codex (GPT-6 family) verified the archived build and source identity, ran and analyzed the two replays, and prepared this report.

Focused regression for out-of-order fence notifications

I tested the ordering case described in the earlier source review. The fixture attaches q0 mark 15, q1 mark 2, then a delayed q0 mark 10 to one recording. After retiring the recording and completing q1, the original code makes the buffer reusable with q0 only at 13. A local change that retains the highest mark per queue keeps it out of the reuse pool until q0 reaches 15.

On exact head 71b1a93201456a655a5b23fe45348257c0658018 with the test overlay, the new assertion failed (0 passed, 1 failed). With the monotonic mark check, it passed alongside the existing reset, multi-queue resubmission, split-segment, and untracked-submit cases. This fixture uses a real WARP allocation with synthetic fence values to reproduce the callback ordering deterministically.

On this Windows 10 19045 host (RTX 3090 Ti, driver 621.40, rustc 1.98.1 MSVC), the broader bind filter returned 37 passed / 1 failed on clean head and 38 passed / 1 failed with the fix and new test, zero ignored and five capability-skip notices in each. The same gpu_two_pass_indirect_commands_keep_their_own_records test failed with 0x80070057 in both invocations. Command base cargo test --offline --locked -j 30 -p xcl --lib, filter late_submit_notification_keeps_the_newest_mark_on_each_queue or hle::d3d12x::bind::tests::, and -- --test-threads=1 --nocapture.

This test reproduces a lifetime error. Its connection to the retail indirect hang remains unresolved. OpenAI Codex (GPT-6 family) added and ran the test and checked the local change.

Patch for @coolpersonnn on 71b1a93. This applies the per-queue maximum and adds the deterministic regression described above. The allocator pool assigns monotonically increasing values under its lock. Bind notifications occur after it releases that lock. The regression also completes the other queue independently.

Minimal fence-order fix and regression
diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs
index 53d11d6a..f0318fd8 100644
--- a/crates/xcl/src/hle/d3d12x/bind.rs
+++ b/crates/xcl/src/hle/d3d12x/bind.rs
@@ -130,8 +130,11 @@ pub(super) unsafe fn two_pass_submitted(queue: *mut c_void, fence: Option<&ID3D1
             match fence {
                 Some(f) => {
                     if let Some(m) = s.res_marks.iter_mut().find(|(k, ..)| *k == q) {
-                        m.1 = f.clone();
-                        m.2 = value;
+                        // Notifications run outside the lock that orders a queue's signals.
+                        if value > m.2 {
+                            m.1 = f.clone();
+                            m.2 = value;
+                        }
                     } else {
                         s.res_marks.push((q, f.clone(), value));
                     }
@@ -4374,6 +4377,45 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u)
         assert_eq!(held, vec![rec_raw]);
     }
 
+    #[test]
+    fn late_submit_notification_keeps_the_newest_mark_on_each_queue() {
+        let _warp_guard = lock_warp_tests();
+        let Some(dev) = warp_device_for_test() else { return };
+        let key = dev.as_raw() as usize;
+        let ids = Box::new([0u8; 4]);
+        let list = ids.as_ptr() as *mut c_void;
+        let (q1, q2) = (
+            (ids.as_ptr() as usize + 1) as *mut c_void,
+            (ids.as_ptr() as usize + 2) as *mut c_void,
+        );
+        let allocator = ids.as_ptr() as usize + 3;
+        reset(list, allocator, 0);
+        let rec = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "record buffer") }.unwrap();
+        let rec_raw = rec.res.as_raw() as usize;
+        with(list, |s| s.res_buf = Some(rec));
+        track_two_pass_list(list as usize);
+
+        let (f1, v1) = make_test_fence(13);
+        let (f2, v2) = make_test_fence(1);
+        unsafe {
+            two_pass_submitted(q1, Some(&f1), 15, &[list]);
+            two_pass_submitted(q2, Some(&f2), 2, &[list]);
+            // alloc_pool publishes its fence marks after releasing the submit bookkeeping lock.
+            two_pass_submitted(q1, Some(&f1), 10, &[list]);
+        }
+        reset(list, 0, 0);
+        let blocked_on_both = take_free(key, RECORD_MIN, u64::MAX).is_none();
+        v2.store(2, Ordering::Release);
+        let early = take_free(key, RECORD_MIN, u64::MAX);
+        v1.store(15, Ordering::Release);
+        let after = take_free(key, RECORD_MIN, u64::MAX);
+        forget(list);
+
+        assert!(blocked_on_both);
+        assert!(early.is_none(), "an older notification must not release a resubmitted recording");
+        assert_eq!(after.map(|b| b.res.as_raw() as usize), Some(rec_raw));
+    }
+
     #[test]
     fn resubmitted_list_waits_for_all_queue_fences() {
         let _warp_guard = lock_warp_tests();

@Decodere

Copy link
Copy Markdown
Contributor

Independent RTX 4060 (8 GB) / Windows 11 release verification of PR #2815 at 71b1a93201456a655a5b23fe45348257c0658018 (parent & merge-base origin/nvidia-dev af2cecc40886a8682ecf3267f5328c6dc4b66ad7). Measurements and targeted test results only; not a full source review.

Setup

  • GPU: NVIDIA GeForce RTX 4060 (8 GB / 7956 MiB reported by D3D12), driver 32.0.16.2114 (NVIDIA 621.14, WDDM 3.2)
  • CPU / RAM / OS: Intel Core i5-11400F (6 cores / 12 threads), 32 GB RAM (31.9 GiB usable), Windows 11 Home 26200
  • Toolchain / caches: rustc 1.100.0 (0ef1bc386 2026-11-09), DXC 1.9.2609.5, release builds, warm DXIL/pipeline caches, quiet machine (zero concurrent builds/tests during timed runs)
  • Workload: Retail workload title: 29640639 via scripts/smoke.ps1 -Seconds 60 (XCL_NETWORK=0, default flags, no input)

Targeted RTX 4060 release unit & GPU tests (71b1a932)

  • cargo test --release -p xcl --lib submitted_two_pass_buffers_reclaim_via_fence_without_allocator_reset -- --nocapture: 1 passed, 0 failed, 0 ignored (0.02 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib split_segment_without_allocator_reclaims_via_fence_instead_of_aging -- --nocapture: 1 passed, 0 failed, 0 ignored (0.02 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib untracked_submit_falls_back_to_allocator_res -- --nocapture: 1 passed, 0 failed, 0 ignored (0.02 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib resubmitted_list_waits_for_all_queue_fences -- --nocapture: 1 passed, 0 failed, 0 ignored (0.02 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib hle::d3d12x::alloc_pool:: (3 consecutive parallel passes): 8 passed, 0 failed, 0 ignored on all 3 passes (0.22 s / 0.22 s / 0.22 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib hle::d3d12x::bind::: 38 passed, 0 failed, 0 ignored (0.33 s; 1 opt-in SKIPPED notice: two_pass_binds_set_the_shared_view_heap skipped without XCL_HEAP_WINDOWS=1).

Paired 60 s RTX 4060 smoke (nvidia-dev af2cecc4 vs 71b1a932)

Both runs completed cleanly at steady 60/2 s pacing with 0 device removals and 0 crashes:

Metric (60 s quiet default-flags run) nvidia-dev base (af2cecc4) PR #2815 (71b1a932)
Frames shown / PresentX 1547 / 1547 1496 / 1496
Presents per 2 s (last 3) 60 60 60 61 60 60
Peak process commit 16342 MB 15504 MB
End process commit (xcl.log) 15009 MB 15308 MB
Peak / end local VRAM 6245 MB / 6182 MB 6182 MB / 6182 MB
End non-local VRAM 4749 MB 4730 MB
Translated draws / dispatches (last log line) 18,382 draws / 1,024 dispatches (0 skipped) 18,640 draws / 1,024 dispatches (0 skipped)
  • Note: xcl.log recorded 0 two-pass buffer/draw log lines during this 60 s no-input menu/intro smoke, so the lower single-run transient peak commit (15504 MB vs 16342 MB, while steady-state end commit was 15308 MB vs 15009 MB and end local VRAM was 6182 MB on both) should not be attributed to two-pass buffer reclamation.

Base origin/nvidia-dev (af2cecc4):

xcl-smoke v1
commit: af2cecc40886a8682ecf3267f5328c6dc4b66ad7
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1547 (PresentX 1547)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 16342 MB

PR #2815 head (71b1a932):

xcl-smoke v1
commit: 71b1a93201456a655a5b23fe45348257c0658018
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1496 (PresentX 1496)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 15504 MB

Limits of coverage

  • Full workspace test suite was not run on 71b1a932 (only the 4 new tests individually, 3 parallel passes of hle::d3d12x::alloc_pool::, hle::d3d12x::bind::, and the paired 60 s default-flags smokes); hle::d3d12x::bind::tests::two_pass_binds_set_the_shared_view_heap skipped without opt-in XCL_HEAP_WINDOWS=1.
  • The 60 s no-input menu/intro smoke did not exercise heavy in-world two-pass draw streams or multi-threaded alloc_pool submit/signal races; two-pass fence reclamation was exercised by the targeted unit tests rather than live world-load telemetry on this host.
  • Single discrete NVIDIA 8 GB GPU (RTX 4060) on native Windows 11; no AMD, Intel, or Wine/Linux run on this host.

AI use

Ran the targeted release tests, paired quiet 60 s smoke runs, and xcl.log comparisons with assistance from Google Antigravity (Gemini 4 Neon); all test counts, memory figures, and smoke blocks were extracted directly from cargo test, xcl.log, and scripts/smoke.ps1 outputs.

@Aniseto

Aniseto commented Nov 26, 2026

Copy link
Copy Markdown

Ran the two-pass fence-reclamation tests at 71b1a932 serially on a second Blackwell desktop part:

System

  • GPU: NVIDIA GeForce RTX 5070 Ti (Blackwell, 32-lane waves only, mesh shaders, 16 GB), driver 32.0.16.2124
  • CPU: Intel Core i5-12400F, 64 GB RAM
  • OS: Windows 11 Pro build 26200 x64
  • Toolchain: rustc 1.100.0 (0ef1bc386 2026-11-09), MSVC 14.44.35207, DXC 1.9.2609.5
  • Build: debug

Results

  • XCL_ADAPTER=NVIDIA cargo test -p xcl --lib hle::d3d12x::alloc_pool -- --test-threads=1: 8 passed, 0 failed, 0 ignored (1644 filtered out, exit 0)
  • XCL_ADAPTER=NVIDIA cargo test -p xcl --lib hle::d3d12x::bind -- --test-threads=1: 38 passed, 0 failed, 0 ignored (1614 filtered out, exit 0); two_pass_binds_set_the_shared_view_heap was SKIPPED (opt-in XCL_HEAP_WINDOWS=1)

What this adds
The author's full workspace run was on an RTX 5090 (driver 621.01, DXC 1.8.2502.11) with 10 failures also present on the unmodified base; the thread also has RTX 3090 Ti, RTX 4060 and independent Windows/NVIDIA reports, but no 5070 Ti. I used --test-threads=1 because of the parallel-only flakes reported on this stack. The fence-reclamation tests (submitted_two_pass_buffers_reclaim_via_fence_without_allocator_reset, split_segment_without_allocator_reclaims_via_fence_instead_of_aging, resubmitted_list_waits_for_all_queue_fences, untracked_submit_falls_back_to_allocator_res) pass here. They exercise allocator and fence bookkeeping with a mock device, not a real stalled GPU queue.

Not tested
The full workspace suite and its 10 known failures, a paired smoke run, a real stalled sparse queue, XCL_HEAP_WINDOWS=1, release profile, AMD and Intel GPUs, native wave64, 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.

@grahamster2

Copy link
Copy Markdown
Collaborator

Independent data point for this series, from a 10 GB card (RTX 3080). I measured a local version of the same idea (fence reclaim of retired two-pass buffers) before I saw this PR, so it's not your exact code.

  • Measured on a 3080: with 32 MiB records and the 2048 MiB cap, refusals came back once the world loaded: 44,880 "not made past" by about 260 s, and a quarter of all draws skipped. Fence reclaim alone helped, but not enough. At peaks most of the cap is held by closed lists that haven't been reset yet, about 1.5 GiB in my log, and those can't be given back early because a closed list may be submitted again.
  • What worked here: 32 MiB records with XCL_TWO_PASS_MB=3072, giving 0 skipped draws until about 600 s in the world. Local video memory ran 3 to 4 GB over budget.
  • Heads-up for D3D12.X: size two-pass indirect buffers from GPU feedback and finer buckets #2816, so it can be checked there: shrinking the per-command record buffer to 8 MiB stopped the refusals but visibly tore big meshes (characters broken into shards, a long stretched triangle across a window frame). The same shots were clean at 32 MiB. The scale shader clamps a command to the buffer's group capacity, so the lost groups are silent. If D3D12.X: size two-pass indirect buffers from GPU feedback and finer buckets #2816 sizes from GPU feedback, a counter for clamped commands would make undersizing visible.

Reclaim retired and reset two-pass record, batch, and argument scratch
buffers when their recording's submit queue fences pass, without waiting
for the owning command allocator to reset. Guard fence polling against
device removal (`u64::MAX` / `FenceState::Removed`) so in-flight buffers
are never returned to the reuse pool on a lost device, keep closed command
lists' buffers intact across idle trims for Reset-less replay, and track
upstream `batch_buf` allocations through the same submit fences.

Part of xcl-dev#2688

Assisted-by: T3 Code / Antigravity (Gemini Pro Orchestrator Neon)
Assisted-by: Codex (GPT-6.2 Sol)
@KDenKC

KDenKC commented Nov 26, 2026

Copy link
Copy Markdown

Checked at 839df6de: record_queue_fence (bind.rs:109-115) keeps the larger value for the same queue and fence, so a callback that arrives out of Signal order no longer lowers it. Thanks.

AI use: Claude Code (Claude Opus 5.5) checked the source and wrote this.

@thehollowedone

Copy link
Copy Markdown

Focused follow-up on current head 839df6de: a removed device can make an unfinished two-pass buffer reusable. This is separate from the out-of-order submit callback that was already fixed.

In bind.rs, both retire_recording_res and reclaim_fenced treat real::fence_completed(f) >= mark as completion. That helper reads the native fence value; D3D12 returns UINT64_MAX when the device is removed. A mark of 5 with a still-unfinished value of 4 is correctly held, but a removal value of UINT64_MAX puts its buffer into FREE_RES. A later take_free can return that same resource. #2831 uses the necessary value != u64::MAX && value >= mark rule for the allocator; this PR's two-pass pool needs it at both checks too.

I added two local fake-fence/WARP regressions: one presents removal before retirement, and one after the buffer enters FENCED_RES. On the unchanged PR behavior, cargo test --offline --locked -p xcl --lib removed_device_does_not -- --test-threads=1 --nocapture reported 0 passed, 2 failed, 0 ignored: both returned the same buffer early. With the candidate below, 2 passed, 0 failed, 0 ignored; normal fence completion still returned that buffer afterward. No capability skip occurred.

On the candidate, cargo build --offline --locked --workspace passed. cargo test --offline --locked -p xcl --lib hle::d3d12x::bind::tests:: -- --test-threads=1 reported 40 passed, 0 failed, 0 ignored, with one XCL_HEAP_WINDOWS=1 opt-in skip. The full cargo test --offline --locked --workspace --no-fail-fast -- --test-threads=4 reported 1,750 passed, 7 failed, 48 ignored across 41 targets, with 26 GPU subcase skip notices. Failures were the mesh shader-cache test, two texture-upload tests, the AS-slot mesh diagnostic, async compute registration, and two instances of the two-pass driver-cache test. I did not rerun the whole suite on the unmodified current head, so I cannot attribute those failures to or exclude this patch.

Windows 11 build 26300, Ryzen 7 9800X3D, RTX 3080 Ti (driver 621.35), rustc 1.99.1 MSVC, DXC 1.8.2502.11. The regression uses a synthetic fence and a WARP resource; no game data. Not tested: retail smoke, sustained world load, AMD or Intel. This demonstrates incorrect buffer reuse after removal; it does not establish the cause of any reported retail hang. The diff is an uncommitted suggestion against this exact head; the author can share #2831's helper when integrating the branches.

Candidate fix and two regressions against 839df6d
diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs
index e4033d39..a956a4fd 100644
--- a/crates/xcl/src/hle/d3d12x/bind.rs
+++ b/crates/xcl/src/hle/d3d12x/bind.rs
@@ -312,13 +312,18 @@ fn put_free_bufs(bufs: Vec<TwoPassBuf>) {
     drop(gone);
 }
 
+fn submit_completed(fence: &ID3D12Fence, mark: u64) -> bool {
+    let value = unsafe { super::real::fence_completed(fence) };
+    value != u64::MAX && value >= mark
+}
+
 fn retire_recording_res(allocator: usize, bufs: Vec<TwoPassBuf>, marks: Vec<(usize, ID3D12Fence, u64)>, untracked: bool) {
     if bufs.is_empty() {
         return;
     }
     if !untracked && !marks.is_empty() {
         let marks: Vec<(ID3D12Fence, u64)> = marks.into_iter().map(|(_, f, v)| (f, v)).collect();
-        if marks.iter().all(|(f, v)| unsafe { super::real::fence_completed(f) } >= *v) {
+        if marks.iter().all(|(f, v)| submit_completed(f, *v)) {
             put_free_bufs(bufs);
             return;
         }
@@ -340,7 +345,7 @@ fn reclaim_fenced() -> u64 {
         let mut fenced = FENCED_RES.lock().unwrap();
         let mut i = 0;
         while i < fenced.len() {
-            let done = fenced[i].marks.iter().all(|(f, v)| unsafe { super::real::fence_completed(f) } >= *v);
+            let done = fenced[i].marks.iter().all(|(f, v)| submit_completed(f, *v));
             if done {
                 let batch = fenced.remove(i).unwrap();
                 reclaimed += batch.bytes;
@@ -4327,6 +4332,46 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u)
         assert!(got.contains(&first_scratch_raw) && got.contains(&rec_raw), "fence completion reclaims both without allocator reset: got={got:?}");
     }
 
+    #[test]
+    fn removed_device_does_not_reuse_fenced_two_pass_buffer() {
+        let _warp_guard = lock_warp_tests();
+        let Some(dev) = warp_device_for_test() else { return };
+        let key = dev.as_raw() as usize;
+        let rec = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "record buffer") }.unwrap();
+        let raw = rec.res.as_raw() as usize;
+        let (fence, value) = make_test_fence(4);
+        retire_recording_res(0, vec![rec], vec![(1, fence, 5)], false);
+        assert!(take_free(key, RECORD_MIN, u64::MAX).is_none());
+        value.store(u64::MAX, Ordering::Release); // D3D12's device-removal sentinel.
+        let early = take_free(key, RECORD_MIN, u64::MAX);
+        value.store(5, Ordering::Release);
+        let after = take_free(key, RECORD_MIN, u64::MAX);
+        let early_raw = early.as_ref().map(|b| b.res.as_raw() as usize);
+        let after_raw = after.as_ref().map(|b| b.res.as_raw() as usize);
+        drop((early, after));
+        assert_ne!(early_raw, Some(raw), "device removal must not make a live buffer reusable");
+        assert_eq!(after_raw, Some(raw), "normal fence completion reclaims the buffer");
+    }
+
+    #[test]
+    fn removed_device_does_not_immediately_retire_two_pass_buffer() {
+        let _warp_guard = lock_warp_tests();
+        let Some(dev) = warp_device_for_test() else { return };
+        let key = dev.as_raw() as usize;
+        let rec = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "record buffer") }.unwrap();
+        let raw = rec.res.as_raw() as usize;
+        let (fence, value) = make_test_fence(u64::MAX);
+        retire_recording_res(0, vec![rec], vec![(1, fence, 5)], false);
+        let early = take_free(key, RECORD_MIN, u64::MAX);
+        value.store(5, Ordering::Release);
+        let after = take_free(key, RECORD_MIN, u64::MAX);
+        let early_raw = early.as_ref().map(|b| b.res.as_raw() as usize);
+        let after_raw = after.as_ref().map(|b| b.res.as_raw() as usize);
+        drop((early, after));
+        assert_ne!(early_raw, Some(raw), "device removal must not immediately retire the buffer");
+        assert_eq!(after_raw, Some(raw), "normal fence completion reclaims the buffer");
+    }
+
     #[test]
     fn split_segment_without_allocator_reclaims_via_fence_instead_of_aging() {
         let _warp_guard = lock_warp_tests();

AI use: Codex (GPT-6.2 Sol) traced the fence paths, wrote and ran the local candidate and tests, and drafted this report. I checked each review point against the source and test output.

@coolpersonnn
coolpersonnn force-pushed the ws2/two-pass-fence-reuse branch from 839df6d to 4253226 Compare November 26, 2026 18:53
@Decodere

Copy link
Copy Markdown
Contributor

Updated RTX 4060 (8 GB) / Windows 11 release verification of PR #2815 rebased head 42532264a221ac975b745b01097bf751e0e56712 (exact parent & merge-base nvidia-dev eae015021c639866ab061cdff2e9daf8ba9daac5; supersedes our earlier check of pre-rebase head 71b1a932 off af2cecc4). Measurements and targeted test results only; not a full source review.

Setup

  • GPU: NVIDIA GeForce RTX 4060 (8 GB / 7956 MiB reported by D3D12), driver 32.0.16.2114 (NVIDIA 621.14, WDDM 3.2)
  • CPU / RAM / OS: Intel Core i5-11400F (6 cores / 12 threads), 32 GB RAM (31.9 GiB usable), Windows 11 Home 26200
  • Toolchain / caches: rustc 1.100.0 (0ef1bc386 2026-11-09), DXC 1.9.2609.5, release builds, warm DXIL/pipeline caches, quiet machine (zero concurrent builds/tests during timed runs)
  • Workload: Retail workload title: 29640639 via scripts/smoke.ps1 -Seconds 60 (XCL_NETWORK=0, default flags, no input)

Targeted RTX 4060 release unit & GPU tests (42532264)

  • cargo test --release -p xcl --lib submitted_two_pass_buffers_reclaim_via_fence_without_allocator_reset -- --nocapture: 1 passed, 0 failed, 0 ignored (0.02 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib split_segment_without_allocator_reclaims_via_fence_instead_of_aging -- --nocapture: 1 passed, 0 failed, 0 ignored (0.01 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib hle::d3d12x::alloc_pool:: -- --test-threads=4 (3 consecutive parallel passes): 8 passed, 0 failed, 0 ignored on all 3 passes (0.21 s / 0.21 s / 0.21 s, 0 SKIPPED).
  • cargo test --release -p xcl --lib hle::d3d12x::bind:: -- --test-threads=4 (3 consecutive parallel passes): 60 passed, 0 failed, 0 ignored on all 3 passes (0.29 s / 0.30 s / 0.28 s; 1 opt-in SKIPPED notice per run: two_pass_binds_set_the_shared_view_heap skipped without XCL_HEAP_WINDOWS=1).

Paired 60 s RTX 4060 smoke (nvidia-dev eae01502 vs 42532264)

Both runs completed cleanly at steady 60/2 s pacing with 0 device removals and 0 crashes (42532264 vs eae01502 xcl.log: 6,118 vs 6,117 MB peak/end local VRAM, 4,746 vs 4,754 MB end non-local VRAM, 18,922 vs 19,006 translated draws / 1,024 dispatches with 0 skipped; note 0 two-pass buffer/draw log lines fired during this 60 s menu smoke, so single-run commit variance 15436 vs 15926 MB should not be attributed to two-pass buffer reclamation).

Exact parent nvidia-dev (eae01502):

xcl-smoke v1
commit: eae015021c639866ab061cdff2e9daf8ba9daac5
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1551 (PresentX 1551)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15926 MB

PR #2815 head (42532264):

xcl-smoke v1
commit: 42532264a221ac975b745b01097bf751e0e56712
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1557 (PresentX 1557)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15436 MB

Limits of coverage

  • Full workspace test suite was not run on 42532264 (only 2 targeted tests individually, 3 parallel --test-threads=4 passes each of alloc_pool:: and bind::, release build, and exact-parent paired 60 s smokes); two_pass_binds_set_the_shared_view_heap skipped without opt-in XCL_HEAP_WINDOWS=1.
  • The 60 s no-input menu/intro smoke did not trigger heavy live two-pass draw streams (0 two-pass log lines); submit-fence reclamation, lost-device handling, and batch tracking were exercised by the 60 passing tests in bind:: and 8 in alloc_pool:: rather than in-world two-pass load.
  • Single discrete NVIDIA 8 GB GPU (RTX 4060) on native Windows 11; no AMD, Intel, or Wine/Linux run on this host.

AI use

Ran the targeted release tests, release build, and exact-parent paired quiet 60 s smoke runs with assistance from Google Antigravity (Gemini 4 Neon); all test counts, timings, memory figures, and smoke blocks were extracted directly from cargo test, xcl.log, and scripts/smoke.ps1 outputs.

@MatyEjsr

Copy link
Copy Markdown

Independent Windows/NVIDIA verification and diff review of PR #2815 at head 42532264a221ac975b745b01097bf751e0e56712 (merge-base origin/nvidia-dev eae015021c639866ab061cdff2e9daf8ba9daac5).

System

  • OS: Windows 11 Pro for Workstations build 26200 x64 (Developer Mode ON)
  • CPU: AMD Ryzen 7 7800X3D (31.4 GB RAM)
  • GPU: NVIDIA GeForce RTX 3090 (24322 MiB VRAM, driver 32.0.16.1742, wave32 / split wave64)
  • Toolchain: rustc 1.100.0 (0ef1bc386 2026-11-09) MSVC, DXC 1.9.0.5512 (dxcompiler 1.9.2602.17)

Tested

  • Targeted default (debug): cargo test -p xcl --lib -- hle::d3d12x::bind hle::d3d12x::alloc_pool --test-threads=8 --nocapture -> 68 passed, 0 failed, 0 ignored (1,659 filtered out), 1 SKIPPED (hle::d3d12x::bind::tests::two_pass_binds_set_the_shared_view_heap: no heap windows (opt-in: XCL_HEAP_WINDOWS=1)). All 7 new tests pass.
  • Targeted opt-in (debug): XCL_HEAP_WINDOWS=1 cargo test -p xcl --lib two_pass_binds_set_the_shared_view_heap -- --test-threads=1 --nocapture -> 1 passed, 0 failed, 0 ignored (0 skipped).
  • Full workspace (debug): cargo test --workspace -j 8 --no-fail-fast -- --test-threads=8 --show-output -> 1826 passed, 9 failed, 48 ignored across 45 targets (xcl --lib: 1696 passed, 3 failed, 28 ignored), plus 29 SKIPPED notices (21 no wave64, 3 wave32, per-lane form: refused, 3 no D3D12 debug layer / no d3d12SDKLayers.dll, 2 no heap windows including the opt-in test).
    • Baseline attribution on unmodified origin/nvidia-dev (eae01502): all 9 failures (gpu_compute_thread_limits_leave_the_lanes_past_them_out, pieces_hold_the_texels_of_their_levels, gpu_parts_of_a_texture_go_up_and_the_rest_stays, console_ms_in_as_slot_and_ms_with_as_are_refused_cleanly, async_compute_pso_registers_real_pso_and_not_standin, split_compute_prefers_the_offline_whole_pipeline x2, two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs x2) reproduce identically (0 passed, 9 failed) on eae01502 — 0 new failures introduced by PR D3D12.X: reclaim two-pass buffers on submit fence completion #2815.
  • Paired 60 s retail smoke (release, scripts/smoke.ps1 -Seconds 60 -Title 'c1cc91a4'):
xcl-smoke v1
commit: eae015021c639866ab061cdff2e9daf8ba9daac5
gpu: NVIDIA GeForce RTX 3090
title: c1cc91a4
seconds: 60
exit: 0x0
frames shown: 1599 (PresentX 1599)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14760 MB
xcl-smoke v1
commit: 42532264a221ac975b745b01097bf751e0e56712
gpu: NVIDIA GeForce RTX 3090
title: c1cc91a4
seconds: 60
exit: 0x0
frames shown: 1588 (PresentX 1588)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14894 MB
  • Telemetry (42532264 vs eae01502, 29 x 2 s samples): 99.3% frames (1588 vs 1599), 100.9% peak commit (14894 vs 14760 MB), VRAM local peak 6129 MB (vs 6188 MB), non-local peak 4845 MB (vs 4885 MB), target pages peak 3546 MB (vs 3548 MB), sparse pools peak 896 MB / 838 MB mapped (identical).

Code review findings (42532264)

  • Prior review fixes verified in source and tests: record_queue_fence (crates/xcl/src/hle/d3d12x/bind.rs) uses .max(value) per (queue, fence) for out-of-order submit callbacks, and fence_state maps u64::MAX to FenceState::Removed in both retire_recording_res and reclaim_fenced.
  • Minor atomic/lock ordering in crates/xcl/src/hle/d3d12x/bind.rs (retire_recording_res): FENCED_BYTES.fetch_add(bytes, Ordering::Release) runs after FENCED_RES.lock() is released, whereas reclaim_fenced() runs FENCED_BYTES.fetch_sub(reclaimed, Ordering::Release) inside FENCED_RES.lock(). Concurrent reclaim_fenced() draining the new batch before fetch_add executes can transiently underflow FENCED_BYTES until fetch_add completes (visible in note_two_pass logs). Moving fetch_add inside the FENCED_RES lock fixes this cleanly.
  • Minor PR description drift: reclaim_fenced() polling and FenceState::Removed live in bind.rs rather than alloc_pool.rs, and the README.md diff documents retired two-pass buffer reuse without naming XCL_TWO_PASS_MB.
  • Branch / duplicate check: merges cleanly onto origin/nvidia-dev (eae01502); no duplicates/redos flagged (duplicate_candidates: [], seems_to_redo_merged: []); stacked with D3D12.X: size two-pass indirect buffers from GPU feedback and finer buckets #2816 and D3D12.X: cap two-pass buffers by DXGI headroom with wait and shrink #2817, and overlaps with D3D12.X: keep allocator recordings held on device removal #2831 on alloc_pool.rs for device-removal handling.

Not tested

  • AMD / Intel GPUs, native wave64 hardware, Linux/Wine, sustained in-world gameplay exercising active two-pass mesh draws (the 60 s startup/menu smoke stayed in menus), and the full workspace suite with XCL_HEAP_WINDOWS=1.

AI use

  • Antigravity (agy) with gemini-pro-orchestrator-argon (audited by gemini-pro-orchestrator-argon): checked out PR D3D12.X: reclaim two-pass buffers on submit fence completion #2815, reviewed the diff, executed all builds, targeted/full workspace tests, baseline attribution checks, and the 60 s retail smoke run on local hardware, and wrote and audited this report.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants