Skip to content

D3D12.X: stop retaining strong ID3D12CommandQueue refs in sparse tile quarantine and prune stale queue fences - #2638

Open
Decodere wants to merge 1 commit into
xcl-dev:mainfrom
Decodere:fix-sparse-queue-fences-com-ref-leak
Open

Decodere wants to merge 1 commit into
xcl-dev:mainfrom
Decodere:fix-sparse-queue-fences-com-ref-leak

Conversation

@Decodere

@Decodere Decodere commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

What is in it

Part of #1668
Part of #1773
Part of #1833

sparse::State::queue_fences (crates/xcl/src/hle/d3d12x/sparse.rs:238) previously stored FxHashMap<usize, (ID3D12CommandQueue, ID3D12Fence, u64)>, populated by State::note_queue on every before_execute, readback_after_execute, and sync_known_queues call without ever removing entries:

  1. Cloning ID3D12CommandQueue into queue_fences permanently leaked an extra strong COM reference on every title command queue that submitted work while sparse windows were active, keeping released title queues alive (refcount >= 2) and re-triggering D3D12.X: E_OUTOFMEMORY after 63 submitted command queues #1668's 63-submitted-queue E_OUTOFMEMORY limit even when present::QUEUES drops its reference.
  2. Released queues stayed in queue_fences indefinitely, leaking their ID3D12Fence objects and causing quarantine_tiles to keep signaling dead queues on every flush_parked().
  3. note_queue short-circuited on queue_fences.contains_key(&key), creating a raw-pointer ABA hazard where a newly created queue allocated at a recycled address was ignored while the old leaked queue continued to be signaled.

Scope and dependency note on b49be183: On current main, present::QUEUES (present::note_execute / present::known_queues()) is still a monotonically growing registry until #1691 (or equivalent queue-removal wiring in present.rs / late_release.rs / real.rs) lands. On this base standalone, this PR immediately removes sparse::State::queue_fences's strong ID3D12CommandQueue reference retention and puts the queue_fences.retain(...) pruning mechanism in place; production shrinking of present::known_queues() — and switching flush_parked_with to a ref-holding snapshot such as #1691's present::known_queues_held() so concurrent q_release cannot race borrowed raw pointers — activates once #1691 lands. Kept strictly scoped to crates/xcl/src/hle/d3d12x/sparse.rs (+165/-51 lines; State::waited and release_if_unused untouched) to avoid conflicting with #1691:

  • Changed State::queue_fences to FxHashMap<usize, (ID3D12Fence, u64)> so State never clones or retains strong ID3D12CommandQueue references.
  • Removed note_queue and sync_known_queues, and removed s.note_queue(queue) from before_execute and readback_after_execute.
  • Split flush_parked into:
    • flush_parked(&mut self) -> bool delegating to flush_parked_with(None).
    • flush_parked_with(&mut self, extra: Option<&ID3D12CommandQueue>) -> bool (called as s.flush_parked_with(Some(queue)) in before_execute): returns false immediately when self.parked.is_empty(), otherwise collects unique non-null raw queue pointers from super::present::known_queues() plus extra, borrows them via ID3D12CommandQueue::from_raw_borrowed (zero AddRef/Release), and delegates to flush_parked_for.
    • flush_parked_for(&mut self, queues: &[&ID3D12CommandQueue]) -> bool: unmaps parked tiles, signals self.queue, and calls quarantine_tiles_for(tiles, queues).
  • In quarantine_tiles_for:
    • Pass 1 (before any signaling loop, so an early CreateFence/Signal failure cannot falsely prune another live queue): deduplicates live same-device queues (skipping null pointers, self.queue, and foreign-device queues) into active + live_keys, then unconditionally prunes stale entries via self.queue_fences.retain(|k, _| live_keys.contains(k)). Earlier in-flight RetiredTiles batches remain safely gated because each batch owns its own ID3D12Fence clone in marks.
    • Pass 2 (when !tiles.is_empty()): lazily creates (ID3D12Fence, 0) per live queue, signals q.Signal(&fence, next), records (fence.clone(), next) in marks, and preserves fail-closed marks: None on any CreateFence/Signal error.
  • Honored XCL_WARP=1 in test helper test_state_with_reserved so WARP coverage runs locally without touching hardware GPUs, updated flush_parked_quarantines_tiles_until_title_queues_finish to call flush_parked_for(&[&title_q]), and added three regression tests:
    • flush_parked_does_not_retain_title_queue_com_refs
    • flush_parked_prunes_stale_queue_fences_while_inflight_batches_stay_gated
    • repeated_queue_quarantine_and_release_does_not_leak_queues_or_fences (80 create/quarantine/drop/prune cycles on one device)

Tested

  • Hardware & toolchain: Windows 11 Home (build 26200), Intel Core i5-11400F (6C/12T), 32 GB RAM, NVIDIA GeForce RTX 4060 8 GB (driver 621.14), rustc 1.100.0, DXC 1.9.2609.5 (01b62ad4), release builds.
  • Failing-first reproduction on unmodified b49be183 (XCL_WARP=1): a temporary probe calling unmodified s.note_queue(&title_q) + s.flush_parked() failed with unmodified State::note_queue leaked a strong COM ref on title_q (1 -> 2).
  • WARP (XCL_ADAPTER=warp, XCL_WARP=1): cargo test --release -p xcl --lib -- hle::d3d12x::sparse::tests:: --nocapture -> 20 passed; 0 failed; 1 ignored (pre-existing #[ignore] benchmark early_commit_timing; 0 skipped).
  • RTX 4060 targeted: cargo test --release -p xcl --lib -- hle::d3d12x::sparse::tests:: --nocapture -> 20 passed; 0 failed; 1 ignored (0 skipped).
  • Full release workspace on RTX 4060: cargo test --release --workspace --no-fail-fast -- --test-threads=4 --nocapture: 37 binaries, 1438 passed, 0 failed, 47 ignored (0 warnings in sparse.rs), 29 pre-existing environment-gated SKIPPED lines (none in sparse::tests):
    • 21 wave64-only GPU tests (no wave64 on RTX 4060 32-lane waves)
    • 3 per-lane wave32 shader tests (refused)
    • 3 D3D12 debug layer tests (no d3d12SDKLayers.dll / debug layer unavailable)
    • 1 heap-window OOM fallback test (no heap windows)
    • 1 PSO driver-cache measurement test (cannot disable the driver cache)

Regression run

Paired 60 s retail smoke (scripts/smoke.ps1, RTX 4060): both base and HEAD sustained 60 60 60 presents per 2 s with 0 device removals and 0 crashes (1533 vs 1579 total frames, 13998 MB vs 13974 MB peak commit).

Base (origin/main):

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

HEAD (fix-sparse-queue-fences-com-ref-leak):

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

Not tested

  • End-to-end production pruning through flush_parked_with / present::known_queues() and title churn of > 63 distinct ID3D12CommandQueue lifetimes combined with #1691 (present::QUEUES removal + known_queues_held()), since #1691 is an open PR in separate files (present.rs / late_release.rs / real.rs); on b49be183, present::known_queues() does not remove released queues yet, so the unit tests verify queue refcount invariance, stale fence pruning, in-flight gating, and 80-cycle create/quarantine/drop/prune resilience directly via flush_parked_for on both WARP and RTX 4060.
  • The 29 hardware/environment-skipped workspace tests listed above (native wave64 GPUs, D3D12 debug layer SDK, heap windows, driver-cache-disabled PSO measurement) and non-Windows hosts.

AI use

Google Antigravity (Gemini 4 Neon) authored the sparse::State::queue_fences refactoring, regression tests, and verification runs; verified via failing-first probe, WARP and RTX 4060 unit tests, full RTX 4060 release workspace tests, and paired 60 s retail smoke runs.

… quarantine and prune stale queue fences

Stop storing cloned `ID3D12CommandQueue` COM pointers in
`sparse::State::queue_fences` (`FxHashMap<usize, (ID3D12Fence, u64)>`
instead of retaining strong references forever). Remove `note_queue` and
`sync_known_queues`, borrow active queues transiently via
`from_raw_borrowed` in `flush_parked_with` (passing the executing queue
from `before_execute`), filter deduplicated same-device queues in a
pre-pass before signaling, and unconditionally prune stale fence entries
while existing `RetiredTiles` batches keep their own fence clones until
drained. Eliminates the permanent title-queue COM refcount leak, stale
fence leaks, and raw-pointer ABA collisions.

Part of xcl-dev#1668
Part of xcl-dev#1773
Part of xcl-dev#1833

Assisted-by: Google Antigravity (Gemini 4 Neon)

@luckyteagirl luckyteagirl 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.

Source-derived production-path dependency on the open queue-release change; no local test run.

return false;
}
let mut raw_ptrs: Vec<*mut c_void> =
super::present::known_queues().into_iter().filter(|&raw| raw != 0).map(|raw| raw as *mut c_void).collect();

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.

On this PR's b49be18 base, present::known_queues() is a monotonically growing registry: present::note_execute AddRefs and stores each queue, and no path removes it. That retained ref also prevents q_release's zero-ref callback. As a result, flush_parked_with keeps passing every once-submitted queue into flush_parked_for; live_keys never loses those queue addresses, so the new fence-entry retain cannot prune released title queues in production on this base. The added pruning test supplies flush_parked_for(&[]) directly, bypassing that production source. The PR description already notes #1691 is separate; could this explicitly depend on/stack with #1691's queue-removal wiring, with an integration test through flush_parked_with after a title queue is released, or qualify the stale-fence-pruning claim until that lands? This is source review only; I did not run the test.

AI-assisted review: OpenAI Codex (GPT-6; exact serving variant unavailable) and two Luna subagents independently checked the current source and PR diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — you're right about the b49be183 base. On current main, present::QUEUES is still monotonically growing until #1691 lands, so on this base standalone this PR removes sparse::State::queue_fences's strong ID3D12CommandQueue retention and puts the queue_fences.retain(...) pruning path in place, while production shrinking of present::known_queues() (and switching flush_parked_with to a ref-holding snapshot like #1691's present::known_queues_held() so concurrent q_release cannot race borrowed pointers) activates once #1691 merges.

Kept strictly scoped to crates/xcl/src/hle/d3d12x/sparse.rs rather than stacking on #1691 so it stays conflict-free with #1691's present.rs / late_release.rs / real.rs edits, and updated the PR description (both What is in it and Not tested) to qualify the production pruning claim and unit-test entry point (flush_parked_for) explicitly. Thanks for the careful source review!

@pickles976

Copy link
Copy Markdown

Wine/NVIDIA cross-check of all four new/updated tests — 5/5 pass on the real adapter. Head 647234a21299ea308ba27d3ececab0f5db2bf6d2, Linux + Wine 11.0, vkd3d-proton 3.2.0 (2576c0b4adfae4a), NVIDIA 590.48.1, RTX 4060 Laptop GPU 8 GiB, --locked --target x86_64-pc-windows-msvc, one test thread, fresh Compiling xcl .../xcl-pr2638/... provenance for each leg, DXVK_CONFIG='dxgi.hideNvidiaGpu = False'.

Note on the environment: XCL_WARP=1 has no WARP under Wine (DXVK falls back to the NVIDIA adapter), so both legs below ran against the real device.

  • flush_parked filter (4 tests, 4/4, 2.22 s): flush_parked_does_not_free_or_reuse_tiles_while_unmap_is_in_flight, flush_parked_does_not_retain_title_queue_com_refs, flush_parked_prunes_stale_queue_fences_while_inflight_batches_stay_gated, flush_parked_quarantines_tiles_until_title_queues_finish — all on the RTX 4060 Laptop, including the new COM-refcount invariance and stale-fence pruning checks.
  • repeated_queue_quarantine_and_release_does_not_leak_queues_or_fences — 1/1 pass (1.03 s): the 80 create/quarantine/drop/prune cycles ran clean on the real device.

So on this stack the fix verifies exactly as scoped: no strong ID3D12CommandQueue retention in queue_fences, stale fences pruned while in-flight RetiredTiles batches stay gated. The acknowledged dependency gap stands as written: with present::QUEUES still monotonic on this base, production pruning of known_queues() itself waits on #1691 — no end-to-end >63-queue title churn measured here, and no title run.

Logs: .compat-xcl/logs/verify-pr2638-wine-quarantine.log, verify-pr2638-wine-80cycles.log (local). AI-assisted verification and report (OpenAI Codex).

rootw0rm pushed a commit to rootw0rm/xcl that referenced this pull request Nov 26, 2026
…cl-dev#2531 + xcl-dev#2638)

(cherry picked from commit fa5b533156ecdf632edcb1b703c54a16948928bf)
bmjask pushed a commit to bmjask/xcl that referenced this pull request Nov 26, 2026
Replace sparse tile quarantine's process-lifetime command-queue references with temporary active-queue snapshots and independently owned completion fences. Include installed central retirement markers, wait through the short Preparing state, and fail closed when retirement cannot provide a trustworthy completion source.\n\nPrune raw queue keys only through the exact Stage C retirement callback before address reuse; in-flight batches retain their own fence clones.\n\nAdapted from xcl-dev#2638 after central queue retirement was active.\n\nAssisted-by: Codex (GPT-5.6-sol)
bmjask pushed a commit to bmjask/xcl that referenced this pull request Nov 26, 2026
Replace sparse tile quarantine's process-lifetime command-queue references with temporary active-queue snapshots and independently owned completion fences. Include installed central retirement markers, wait through the short Preparing state, and fail closed when retirement cannot provide a trustworthy completion source.\n\nPrune raw queue keys only through the exact Stage C retirement callback before address reuse; in-flight batches retain their own fence clones.\n\nAdapted from xcl-dev#2638 after central queue retirement was active.\n\nAssisted-by: Codex (GPT-5.6-sol)
@rgroenewoudt

Copy link
Copy Markdown

Tested on AMD Radeon RX 9070 (RDNA4) at this PR's head 647234a: no new failures; the sparse tests behave as on main.

Tested

Not tested

  • No regression run on a real title (no game data here); this covers only the test suite on AMD

AI use

  • Claude Code (Claude Opus 5.5) ran the commands and wrote this report from the logs.

@razormontana

Copy link
Copy Markdown
Contributor

Native Windows validation of #2638 on RTX 3070

Tested

  • Clean PR head 647234a21299ea308ba27d3ececab0f5db2bf6d2, based on b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7. Windows 11 Pro build 22631, Intel Core i7-10700K, 32 GB RAM, NVIDIA GeForce RTX 3070 8 GB, driver 617.42 (32.0.16.1742), Rust 1.100.0 MSVC, debug.
  • XCL_ADAPTER=3070 with XCL_WARP and external game sample variables unset. An independent D3D12 probe used the same default-device selection as the fixtures and identified the RTX 3070 (8,018 MiB dedicated, no software flag).
  • cargo test --offline --locked -j 1 -p xcl --lib --no-run compiled the library tests.
  • cargo test --offline --locked -j 1 -p xcl --lib hle::d3d12x::sparse::tests::flush_parked_ -- --test-threads=1 --nocapture reported 4 passed, 0 failed, 0 ignored, and 0 explicit skips.
  • cargo test --offline --locked -j 1 -p xcl --lib hle::d3d12x::sparse::tests::repeated_queue_quarantine_and_release_does_not_leak_queues_or_fences -- --exact --test-threads=1 --nocapture reported 1 passed, 0 failed, 0 ignored, and 0 explicit skips. The fixture completed 80 sequential queue lifecycles.

The fixtures drive sparse retirement directly. They checked that a flush does not add a strong queue reference, that stale queue-fence entries are pruned while pending tile batches still honor their fences, and that tiles become reusable after both queues complete.

Not tested

The original end-to-end submitted-queue limit in #1668, the full workspace suite, the base at runtime, retail world loading, and VRAM savings.

On the pinned source, present::note_execute still retains submitted queues in the registry read by present::known_queues(). #1691 changes that separate submit-tracking path and was outside this validation. A combined review should check that queue references stay valid from the snapshot through fence signaling.

AI use

Codex GPT-6.2 inspected the exact diff, built and ran the existing fixtures, verified the native adapter selection, and drafted 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.

5 participants