Skip to content

D3D12.X: reuse the command objects and readback buffers of texture downloads - #3514

Open
BBareth wants to merge 1 commit into
xcl-dev:mainfrom
BBareth:d3d12x/pool-texture-download-objects
Open

BBareth wants to merge 1 commit into
xcl-dev:mainfrom
BBareth:d3d12x/pool-texture-download-objects

Conversation

@BBareth

@BBareth BBareth commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

A GPU-written title texture is copied back into the title's memory through a readback buffer, a command allocator, a command list and a fence. prepare_texture_download created all four for every download and released them when the download was published. A title that has hundreds of such downloads every second pays for that on the thread that signals its queues.

This keeps the objects of a finished download and hands them to the next one.

What is in it

  • crates/xcl/src/hle/d3d12x/title_textures.rs:
    • DownloadPool holds idle command sets (allocator, list, fence) by device and list type, and idle readback buffers by device and size. Sizes are rounded up to 64 KiB. Limits: 1024 sets and 1 GiB of buffers; anything over is released as before.
    • A readback buffer that no download has taken for 2 s (DOWNLOAD_POOL_IDLE_US) is released. This is checked a few times a second as download fences complete. The pool no longer keeps up to 1 GiB committed for the rest of the run.
    • When a new readback buffer cannot be allocated for lack of memory (E_OUTOFMEMORY), the idle buffers are released, outside the pool's lock, and the allocation is tried once more (retry_after_reclaim). Other errors are returned as before.
    • Drop for PendingDownload returns the objects once the download's fence has completed; an incomplete one is released, not pooled. A pooled fence continues from its last value and is retired before the value could wrap.
    • Each idle entry holds a reference to its device, so its address cannot be reused while the entry is cached.
    • A failed Close of the download list is logged. It is XCL's own list, so no hook logs it.
  • crates/xcl/src/hle/d3d12x/real.rs: create_download_fence makes the pool's fences without entering them in the title fence registry. They are XCL's own; the title never sees them.
  • Tests (CPU only):
    • download_pool_rounds_readback_sizes
    • download_pool_keys_sets_by_queue_type_and_buffers_by_size
    • download_pool_caps_idle_sets_and_readback_bytes_independently
    • download_pool_releases_buffers_idle_past_the_limit
    • download_pool_gives_up_its_idle_buffers_for_one_retry_after_out_of_memory

Tested

  • RTX 5070 Ti, driver 32.0.16.2124; i7-12700K; Windows 11 Pro 26200; rustc 1.95.0; debug suite, release smoke.
  • cargo build --workspace, then cargo test --workspace --no-fail-fast -- --test-threads=4 on bbcef6c6 (on main 078358a): 3011 passed, 0 failed, 52 ignored.
    • 28 SKIPPED: 22 no wave64, 2 no heap windows, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 driver cache.
    • The head 60f0498 differs from bbcef6c6 only in where two comments sit (2 lines moved), so the suite was not run again for it.
  • Merges cleanly into main 395405e.
  • GTA 6 (Xbox 1.0.2.1) in the world, on a local tree with other open PRs and an earlier version of this pool (one run each):
    • time in download preparation went from about 600 ms to about 300 ms per 2 s;
    • presents went from 4.53 to 4.85 per 2 s.
    • In a later 740 s run of that tree, the pool handed out 15,641 command sets and created 94.

Regression run

xcl-smoke v1
commit: 078358a058f7ba5d16690dba8dc4e55d2c88ae0a
gpu: NVIDIA GeForce RTX 5070 Ti
title: 9cc6a39e
seconds: 120
exit: 0x0
frames shown: 3046 (PresentX 3046)
presents per 2 s (last 3): 15 27 19
device removals: 0
crashes: 0
peak commit: 32465 MB
xcl-smoke v1
commit: 60f049885cdbb9c3b35dbb944ff165cd15234533
gpu: NVIDIA GeForce RTX 5070 Ti
title: 9cc6a39e
seconds: 120
exit: 0x0
frames shown: 3020 (PresentX 3020)
presents per 2 s (last 3): 29 22 24
device removals: 0
crashes: 0
peak commit: 32252 MB

Each run follows one warm-up run of the same build; the A button is pressed once at 70 s.

Not tested

  • AMD and Intel adapters.
  • A real D3D12 out-of-memory failure: the retry is tested with a stand-in allocator only.
  • A device being destroyed while the pool still holds its objects (no title here does that).
  • The world measurement was not repeated with this exact commit; the smoke runs end before the world loads.

AI use

  • Codex (GPT-6.2-Sol) ported the change and wrote the first tests from a brief.
  • Claude Code (Claude Fable 5.2) wrote the original experiment and the idle release.
  • Claude Code (Claude Opus 5.5) reviewed the diff, ran the suite and the smoke runs, and wrote this description.

🤖 Generated with Claude Code

@github-actions github-actions Bot added area:d3d12 D3D12.X runtime, command lists, resources, sparse memory gpu:both Code affects both AMD and NVIDIA GPUs (scope tag; see needs:*-test for remaining checks) labels Nov 30, 2026
@thehollowedone

thehollowedone commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

I confirmed a recoverable allocation failure in the current-head path. The pool stores readback buffers by exact size. When a request misses its size bucket and CreateCommittedResource returns E_OUTOFMEMORY, prepare_downloads skips that texture while the title’s following signal still goes through. If the same allocation keeps failing, the CPU-visible texture bytes can remain stale. The pool’s idle buffers may be the reclaimable memory that would let the allocation succeed. Allocation and retry path · Skipped preparation

A bounded fix is to reclaim the idle readback buffers only for E_OUTOFMEMORY, drop them after releasing the pool lock, and retry allocation once. Other errors keep their current behavior. If the retry still fails, the existing failure path remains. The candidate below tests a full 1 GiB pool with a different-size request; its fake allocator returns OOM until the buffer is dropped, and the test checks that destruction happens outside the lock. A second test verifies non-OOM errors neither reclaim nor retry.

Local candidate verification

  • cargo test -p xcl --lib download_pool_ -- --nocapture --test-threads=1: 5 passed, 0 failed, 0 ignored (2,765 filtered out).
  • The tests are CPU-only. I did not inject a real D3D12 allocation failure or run the full suite, GPU readback, or retail smoke on this candidate; this is not a merge-check.
Candidate diff
diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs
@@
     fn take(&mut self, device: usize, queue_type: i32, size: u64) -> (Option<S>, Option<B>) {
@@
         (set, buffer)
     }
+
+    fn drain_buffers(&mut self) -> BTreeMap<(usize, u64), Vec<B>> {
+        self.buffer_bytes = 0;
+        std::mem::take(&mut self.buffers)
+    }
@@
 static DOWNLOAD_POOL: Mutex<DownloadPool<(DownloadCommands, ID3D12Device), (ID3D12Resource, ID3D12Device)>> =
     Mutex::new(DownloadPool::new());
 
+fn reclaim_idle_download_buffers<S, B>(pool: &Mutex<DownloadPool<S, B>>) {
+    let buffers = {
+        let mut pool = pool.lock().unwrap();
+        pool.drain_buffers()
+    };
+    drop(buffers);
+}
+
+fn retry_after_oom<T, E>(
+    mut create: impl FnMut() -> Result<T, E>,
+    is_oom: impl Fn(&E) -> bool,
+    reclaim: impl FnOnce(),
+) -> Result<T, E> {
+    match create() {
+        Err(error) if is_oom(&error) => {
+            reclaim();
+            create()
+        }
+        result => result,
+    }
+}
@@
             Some((readback, _)) => readback,
             None => {
                 let mut readback = None;
-                dev.CreateCommittedResource(
-                    &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
-                    D3D12_HEAP_FLAG_NONE,
-                    &D3D12_RESOURCE_DESC {
-                        Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
-                        Width: readback_size,
-                        Height: 1,
-                        DepthOrArraySize: 1,
-                        MipLevels: 1,
-                        SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
-                        Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
-                        ..Default::default()
-                    },
-                    D3D12_RESOURCE_STATE_COPY_DEST,
-                    None,
-                    &mut readback,
-                ).map_err(|e| e.to_string())?;
+                retry_after_oom(
+                    || {
+                        readback = None;
+                        dev.CreateCommittedResource(
+                            &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
+                            D3D12_HEAP_FLAG_NONE,
+                            &D3D12_RESOURCE_DESC {
+                                Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+                                Width: readback_size,
+                                Height: 1,
+                                DepthOrArraySize: 1,
+                                MipLevels: 1,
+                                SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+                                Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+                                ..Default::default()
+                            },
+                            D3D12_RESOURCE_STATE_COPY_DEST,
+                            None,
+                            &mut readback,
+                        )
+                    },
+                    |e| e.code() == windows::core::HRESULT(crate::util::E_OUTOFMEMORY),
+                    || reclaim_idle_download_buffers(&DOWNLOAD_POOL),
+                ).map_err(|e| e.to_string())?;
                 readback.ok_or("no readback resource")?
             }
@@
     fn download_pool_caps_idle_sets_and_readback_bytes_independently() {
@@
         assert_eq!(pool.buffer_bytes, 2 * size);
     }
 
+    #[test]
+    fn download_pool_releases_other_size_buckets_before_retrying_out_of_memory() {
+        struct ReclaimProbe {
+            pool: std::sync::Weak<Mutex<DownloadPool<(), ReclaimProbe>>>,
+            released: Arc<AtomicBool>,
+            lock_free: Arc<AtomicBool>,
+        }
+        impl Drop for ReclaimProbe {
+            fn drop(&mut self) {
+                let lock_free = self.pool.upgrade().is_some_and(|pool| pool.try_lock().is_ok());
+                self.lock_free.store(lock_free, Ordering::SeqCst);
+                self.released.store(true, Ordering::SeqCst);
+            }
+        }
+
+        let pool: Arc<Mutex<DownloadPool<(), ReclaimProbe>>> = Arc::new(Mutex::new(DownloadPool::new()));
+        let released = Arc::new(AtomicBool::new(false));
+        let lock_free = Arc::new(AtomicBool::new(false));
+        let (set, buffer) = pool.lock().unwrap().put(
+            1,
+            0,
+            DOWNLOAD_POOL_BYTES,
+            None,
+            ReclaimProbe { pool: Arc::downgrade(&pool), released: Arc::clone(&released), lock_free: Arc::clone(&lock_free) },
+        );
+        assert!(set.is_none());
+        assert!(buffer.is_none());
+        let mut attempts = 0;
+        let result = retry_after_oom(
+            || {
+                attempts += 1;
+                if released.load(Ordering::SeqCst) { Ok(42) } else { Err(crate::util::E_OUTOFMEMORY) }
+            },
+            |error| *error == crate::util::E_OUTOFMEMORY,
+            || reclaim_idle_download_buffers(&pool),
+        );
+        assert_eq!(result, Ok(42));
+        assert_eq!(attempts, 2);
+        assert!(released.load(Ordering::SeqCst));
+        assert!(lock_free.load(Ordering::SeqCst), "COM buffers must be released after dropping the pool lock");
+        let pool = pool.lock().unwrap();
+        assert!(pool.buffers.is_empty());
+        assert_eq!(pool.buffer_bytes, 0);
+    }
+
+    #[test]
+    fn download_pool_does_not_reclaim_or_retry_non_out_of_memory_errors() {
+        let pool = Mutex::new(DownloadPool::<(), i32>::new());
+        assert_eq!(pool.lock().unwrap().put(1, 0, 0x10000, None, 7), (None, None));
+        let mut attempts = 0;
+        let mut reclaimed = false;
+        let result: Result<(), _> = retry_after_oom(
+            || {
+                attempts += 1;
+                Err(crate::util::E_INVALIDARG)
+            },
+            |error| *error == crate::util::E_OUTOFMEMORY,
+            || {
+                reclaimed = true;
+                reclaim_idle_download_buffers(&pool);
+            },
+        );
+        assert_eq!(result, Err(crate::util::E_INVALIDARG));
+        assert_eq!(attempts, 1);
+        assert!(!reclaimed);
+        assert_eq!(pool.lock().unwrap().buffer_bytes, 0x10000);
+    }
+
     #[test]
     fn download_plans_use_writer_capable_queue_types() {

AI use: Codex (GPT-6.2 Sol) prepared and tested this candidate; GPT-6.2 Astra independently reviewed the reclaim, lock, and retry path.

@BBareth
BBareth force-pushed the d3d12x/pool-texture-download-objects branch from 3e00f2b to 58815f7 Compare November 30, 2026 09:27
@BBareth

BBareth commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, that is a real hole: with up to 1 GiB idle in other size buckets, an allocation that would have succeeded before the pool can now fail and leave the texture's CPU copy stale.

Taken in 58815f7 (folded into the PR's commit): on E_OUTOFMEMORY the idle readback buffers are drained under the pool's lock, dropped after it is released, and the allocation is tried once more; any other error is returned as before. Test: download_pool_gives_up_its_idle_buffers_for_one_retry_after_out_of_memory (out of memory with idle buffers, another error, out of memory twice). The retry is tested with a stand-in allocator only; I did not inject a real D3D12 failure.

Rerun on the new head (RTX 5070 Ti): cargo test --workspace --no-fail-fast -- --test-threads=4: 2880 passed, 1 failed (gpu_direct_image_get_resinfo_d16, fails on main d52ff48 too), 51 ignored, 28 skipped; smoke blocks in the description are updated.

AI use: Claude Code, Claude Fable 5.2 wrote the change and this comment and ran the tests.

@Gevroska

Copy link
Copy Markdown
Contributor

@BBareth I tested completed texture-download reuse on my RTX 3080 10 GB (driver 616.92). I added one test fixture on top of 58815f7c and ran two successive downloads of the same 64×64 R8 texture on one D3D12 direct queue.

After fence value 1, all 4,096 texels read back as 0x21. After fence value 2, all 4,096 read back as 0xC4. The second download reused the same readback buffer, command allocator, command list, and fence. I kept references to the original objects alive during the comparison to rule out address recycling.

An independent repeat in a fresh process reproduced both values and the same object reuse. Both runs passed with zero skips. This confirms the reused buffer returned fresh contents on this GPU. I also ran the CPU retry test with its stand-in allocator. A real D3D12 out-of-memory failure remains untested.

I used Codex GPT-6.2 Sol to add the fixture and run the first test. Codex GPT-6.1 Terra independently reviewed and repeated it. Codex GPT-6.2 Astra drafted this comment.

I reviewed and approved this comment before posting.

@AAsobu

AAsobu commented Nov 30, 2026

Copy link
Copy Markdown

merge-check claim
head: 58815f7

@github-actions github-actions Bot added needs-1st-check Passes gates; needs first independent merge-check (#3041) needs:amd-test Needs a test report or merge-check on an AMD GPU needs:nvidia-test Needs a test report or merge-check on an NVIDIA GPU labels Nov 30, 2026
@AAsobu

AAsobu commented Nov 30, 2026 •

Copy link
Copy Markdown

merge-check
base: ff0c364
head: 58815f7
merge: clean (main has since moved to 86e86fc with #3485, scripts only; the PR still merges cleanly there)
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> every binary but the lib: 148 passed, 0 failed, 20 ignored; the lib binary aborted in that run (STATUS_ACCESS_VIOLATION, early, last line gpu::dxil::bitreader_tests::atomics_use_bitcode_ordering_codes ... ok). Lib alone (cargo test -p xcl --lib -- --test-threads=4) on this merge, checked each time that the 4 new download_pool_* tests ran: 7 runs, 6 with 2745 passed, 0 failed, 31 ignored, and 1 with 2741 passed, 4 failed: placed_title_textures_share_vram_and_preserve_pixels (title_textures.rs:6500, "row 3: new placement readback": the readback held the earlier pattern, not the new one) and the 3 stream_recheck_* tests after it on the poisoned TEST_LOCK. main ff0c364b alone on the same machine: 12 of 12 lib runs clean (2741 passed). SKIPPED: 28, the same as on main (22 no wave64, 2 no heap windows, 3 no D3D12 debug layer / d3d12SDKLayers.dll, 1 no GPU_UPLOAD heaps).
review: the whole diff read (+260/-41, real.rs, title_textures.rs). Objects go back to the pool only after is_complete() saw the download's fence, so Reset of a pooled allocator/list does not race the GPU; fence values keep rising per pooled set and stop before u64::MAX; the caps (1024 sets, 1 GiB of readbacks) and the out-of-memory reclaim with one retry work as described, and their tests pass. Pooled entries keep their device alive for the life of the process. Nit: the comments above drain_buffers and retry_after_reclaim (// Return rejected entries…, // Each entry owns a device reference…) sit on the wrong items. The two lib failures above are kinds others have reported on main (title_textures failures, lib aborts); 2 bad of 8 runs here against 0 of 12 on main is not significant (Fisher p ≈ 0.15). Because the stale readback is in the file this PR changes, I ran the module alone, xcl-*.exe title_textures --test-threads=4, 20 times on this merge and 20 times on main ff0c364b, alternating, from separately built copies of each test binary (69 and 65 tests, the 4 download_pool_* tests present only in this one): 20 of 20 clean on both. So I count both failures as the known intermittent ones that show up only in whole-lib runs, not as this PR's.
performance: A/B on the retail title, release builds of main ff0c364b (A) and this merge (B), runs in the order A, B, A, B, 180 s each (XCL_RUN_SECONDS=180), the same settings (XCL_PREPARE=0 XCL_DIRECT_DXIL=1 XCL_PSO_WAIT_MS=1000 XCL_TEXTURE_LEVEL_PAGES=1 XCL_HUGE_PSO_CONCURRENCY=4 XCL_HUGE_PSO_WANTED_CONCURRENCY=4 XCL_DXC_THREADS=4 XCL_NETWORK=0 XCL_DRED=1), the title's start prompt passed by XCL_PRESS_A_AT at 38-43 s in every run (loading started at 40.2-40.3 s in all four), warm caches, no input; process CPU, memory and handles sampled every 2 s. No device removal in any run.

run CPU s (0-180 s) CPU s (40-180 s) CPU s (120-180 s) peak private MB peak handles frames shown draws
A1 1414.2 1111.4 510.1 31464 2778 2425 28276
B1 1410.2 1118.4 488.4 31929 2792 2550 29154
A2 1256.9 1044.3 497.1 32749 2770 2457 28930
B2 1272.2 1041.0 535.2 32644 2774 2417 28535
mean A / B 1335.6 / 1341.2 (+0.4 %) 1077.9 / 1079.7 (+0.2 %) 503.6 / 511.8 (+1.6 %) 32107 / 32287 (+0.6 %) 2774 / 2783 2441 / 2484 28603 / 28845

No difference above the run-to-run spread (the two A runs differ by 157 CPU-s). This covers the boot and the loading screen only, not the world, where the description measured the gain; I do not know how many texture downloads this phase makes, so it shows no cost, not the absence of the gain.
update (2026-12-01, same head 58815f7c): Foniass's finding is right and I missed it: DOWNLOAD_POOL_BYTES is 1 << 30, and idle readback buffers are only let go by drain_buffers in the out-of-memory retry of a new readback creation, so up to 1 GiB of commit can stay held for the rest of the run. My A/B was too short to rule that cost out: 180 s runs that did not reach the world. My verdict changes to match.
in-world A/B (2026-12-01, same head, merged onto main 493dbd3d as ef5d6a2a): release builds, runs B, A, B, A of 420 s, warm caches except the first B run (new build), same env as above plus XCL_ACTIVITY=1, start prompt held by XCL_PRESS_A_AT at 21-43 s, xcl.exe with the #2590 profile at 2048 MB. From world entry + 30 s: presents per 2 s B 1.06 / 1.12, A 1.11 / 1.08; draws per 2 s B 4733 / 4964, A 4869 / 5027; peak process commit (the log's memory: N MB committed) B 41,682 / 43,830 MB, A 45,304 / 44,896 MB; peak VRAM B 16,827 / 17,758 MB, A 17,230 / 16,812 MB; 0 skipped draws and 0 device removals in all four. So in this part of the world the pool's idle buffers did not show as extra commit (both B runs peaked lower than both A runs; the two runs of one build differ by up to ~2 GB, and the PR logs nothing about the pool's size). That does not bound it elsewhere, so the verdict stays.
verdict: not yet: the download pool can keep up to 1 GiB of idle readback commit for the run, freed only by its own out-of-memory retry (as Foniass found); bound it (a smaller cap, LRU or an idle timeout). The rest of my check above stands
hardware / tool and model: NVIDIA GeForce RTX 3090 24 GB (driver 621.24, wave32 only), Intel Core i5-10600K, 32 GB, Windows 11 Home build 26300, rustc 1.100.0 / Claude Code (Claude Opus 5.5), results checked by me

@github-actions github-actions Bot added needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) and removed needs-1st-check Passes gates; needs first independent merge-check (#3041) needs:nvidia-test Needs a test report or merge-check on an NVIDIA GPU labels Nov 30, 2026
@BBareth

BBareth commented Nov 30, 2026

Copy link
Copy Markdown
Contributor Author

Test report for the intermittent failure noted in the merge check above (placed_title_textures_share_vram_and_preserve_pixels, "row 3: new placement readback").

  • Tree: main ff0c364b merged with this PR's head 58815f7c (merge 58024689), debug build.
  • Command: cargo test -p xcl --lib -- --test-threads=4, 25 runs in a row.
  • Result: 25 of 25 runs with 2745 passed, 0 failed, 31 ignored. The stale readback and the lib abort did not occur here.
  • That test reads back through its own readback buffer and command list, not through the download pool this PR adds.
  • Hardware: NVIDIA GeForce RTX 5070 Ti 16 GB, Windows 11 Pro 26200.

AI use: Claude Code, Claude Fable 5.2 ran the tests and wrote this report.

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: 7d86c5d
head: 58815f7
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2900 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: read the whole diff (title_textures.rs, +260/-41). Every GPU-written title texture download now takes its allocator, list, fence and readback from a pool. Findings: (1) DownloadPool::put (~3712) matches buffers by exact size and never evicts, so once 1 GiB is filled with sizes no longer requested, each new size is created and released as before while that 1 GiB of commit stays held for the run; only this function's own out-of-memory retry frees it, not other commit-sensitive code (the DXC gates, the coherent plan). The PR's smoke runs show peak commit +1,093 and +1,429 MB; an idle timeout, LRU eviction or a smaller cap would bound it. See this run's peak commit above. (2) The fence-value and reuse logic in Drop for PendingDownload (~3784) has no test; the four tests cover the generic container with integers. (3) Creation now runs inside own_work (~4341), so these objects are no longer adopted (is_own_object); worth saying. (4) With #3550: its new GPU test waits on fence value 1, while a reused set signals its last value + 1, so it should wait on ticket.fence_value. Fine: objects are pooled only after their fence completes and the allocator / list are reset only when taken again; the pool lock is a leaf and released before D3D12 calls; sets are keyed by device and queue type and hold a device reference; incomplete downloads are still leaked as before; it merges cleanly with #3549 and #3550.
performance: 60 s smoke of a retail title, main 7d86c5d vs this merge (b4022c3b): 1663 -> 1668 frames shown (100 %; last presents per 2 s: 60 60 61), peak commit 17153 -> 17217 MB, 0 device removals, 0 crashes. An earlier run of the same merge (its lib tests hit the known #1487 driver crash, so they were rerun) showed 1674 frames and 17588 MB peak commit. A 60 s run doesn't reach the steady state where the pool is full.
verdict: not yet: the download pool keeps up to 1 GiB of commit for the rest of the run, with nothing that evicts it except this function's own out-of-memory retry (the PR's own runs show peak commit +1.1 to +1.4 GB); bound it (a smaller cap, LRU or an idle timeout) and test the fence-value reuse in Drop for PendingDownload
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

@github-actions github-actions Bot added checks-disagree Merge-checks disagree (safe vs not yet); needs maintainer/3rd look and removed needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) labels Dec 1, 2026
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Triage (#1607) – head 58815f7

No open or merged PR pools texture-download command objects or readback buffers (#3389, #3549, #3550 touch the same download path for other reasons).
Notes on the diff: title_textures.rs keeps up to 1 GiB of idle READBACK buffers and 1024 allocator/list sets for the life of the process, trimmed only when another readback creation hits E_OUTOFMEMORY; worth stating that commit cost in the description. Two comments are misplaced: "Return rejected entries to the caller..." sits above drain_buffers (it describes put), and "Each entry owns a device reference..." sits above retry_after_reclaim instead of DOWNLOAD_POOL. create_download_fence also stops each download from adding a fence to the FENCES registry, which was a per-download leak on main.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

@BBareth

BBareth commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

On the triage note above: the description now states the memory cost (idle readback buffers, up to the 1 GiB limit, stay committed for the life of the process and are released only when a new readback buffer runs out of memory).

The two misplaced comments (above drain_buffers and retry_after_reclaim) are right as noted; AAsobu's merge check named them too. I will move them with the next push to this branch rather than push a comment-only change, since a push needs the smoke runs again.

AI use: Claude Code, Claude Fable 5.2 wrote this comment.

@github-actions github-actions Bot removed checks-disagree Merge-checks disagree (safe vs not yet); needs maintainer/3rd look needs:amd-test Needs a test report or merge-check on an AMD GPU labels Dec 1, 2026

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

Review of 58815f7c: 3 finding(s). 3 are inline.


These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

.map(|()| readback)
};
// The idle buffers are dropped after the pool's lock is released.
let reclaim = || {

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.

The pool's up to 1 GiB of committed readback memory is only released when XCL's own readback CreateCommittedResource returns E_OUTOFMEMORY. The title's allocations, and XCL's CreateCommandAllocator/CreateCommandList/CreateFence failures, never reclaim it. A title that streams many texture downloads fills the pool to ~1 GiB of READBACK commit (the PR's smoke runs show peak commit +1.1-1.4 GB). When the title's CreateCommittedResource/CreateHeap later hits the commit limit, it gets E_OUTOFMEMORY while 1 GiB of idle XCL readback memory sits in DOWNLOAD_POOL, so the title fails or crashes where main had the memory free. The buffer side also never evicts and matches sizes exactly (~3712), so once the cap fills with sizes no longer requested, new sizes get no reuse but the stale 1 GiB stays. An idle-time or LRU trim, and releasing the pool on any E_OUTOFMEMORY XCL sees, would bound this.

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.

Addressed in 60f0498. A readback buffer that no download took for 2 s is now released (DOWNLOAD_POOL_IDLE_US, checked a few times a second as download fences complete; test download_pool_releases_buffers_idle_past_the_limit). What stays committed is the buffers of sizes downloads asked for in the last 2 s. It is no longer up to 1 GiB held for the rest of the run. The out-of-memory retry stays for XCL's own readback creation. I did not hook the release into the title's allocations, because the idle release already bounds the held memory to what is in use. Smoke on this head: peak commit 32252 MB against main 078358a's 32465 MB (blocks in the description).

AI use: Claude Code, Claude Opus 5.5 wrote this reply.

commands.fence_value = value;
(commands, device.clone())
});
let rejected = DOWNLOAD_POOL.lock().unwrap().put(key, queue_type, readback_size, set, (readback, device));

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.

Not certain about this one: idle entries keep a strong device reference and are never evicted by device, so after device removal or recreation the old device, its command sets and up to 1 GiB of buffers stay pinned and use up the global caps. If device A is removed and the title recreates B, DOWNLOAD_POOL still holds A's sets and buffers, which take() never returns for B's key. sets.len() stays at 1024 and buffer_bytes near the cap, so put() rejects every B entry: B gets no pooling and A's memory is never released. Dropping a device's entries when it's removed, or when a different device starts using the pool, would fix it.

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.

Checked: this does not happen in XCL. A process has one D3D12 device (device_raw()). When it is removed, stop_if_device_removed (real.rs) logs the reason and ends the process with TerminateProcess, so there is no device B that a stale device A's entries could crowd out. The entries are still keyed by device, so a second device would get no wrong objects, only fewer pooled ones. No change made.

AI use: Claude Code, Claude Opus 5.5 wrote this reply.

let readback = readback.ok_or("no readback resource")?;
let readback_size = download_buffer_size(bytes).ok_or("readback buffer size overflow")?;
let (pooled_set, pooled_buffer) = DOWNLOAD_POOL.lock().unwrap().take(dev.as_raw() as usize, queue_type.0, readback_size);
let (commands, readback) = own_work(|| {

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.

Not certain about this one: object creation in prepare_texture_download is now wrapped in own_work, so the allocator, command list and readback buffer silently stop being adopted (is_own_object), a behaviour change the PR doesn't mention or test. On main, prepare_downloads runs outside own_work, so the CreateCommandAllocator/CreateCommandList/CreateCommittedResource hooks adopted these objects. For example, the adopted list's Close hook logs failures with what was recorded. Now a Close failure on the download list isn't logged by that hook, and any tracking the hooks did for these objects stops.

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.

Right that these objects are no longer adopted. I checked what adoption did for them. The one effect that mattered is the list's Close hook logging a failure, and 60f0498 now logs a failed Close of the download list itself (D3D12.X: texture download list Close → …). The rest of the hooks' tracking is for title objects. These are XCL's own, never handed to the title, and released by XCL, so there is nothing for it to track. The description now says so.

AI use: Claude Code, Claude Opus 5.5 wrote this reply.

@bmjask

bmjask commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.

…wnloads

Texture download preparation repeatedly creates the same D3D12 objects
during streaming. Reuse each allocator, command list and private fence
by device and queue type. Reuse committed readback buffers separately
by device and 64 KiB-rounded size.

Return objects only after their private fence confirms GPU completion.
Cap idle storage at 1,024 command sets and 1 GiB of readback buffers.
Each idle entry owns a device reference, so its raw device address
cannot be reused while the entry is cached.

A readback buffer no download took for 2 s is released (checked a few
times a second when fences complete), so sizes no longer asked for do
not keep up to 1 GiB committed for the rest of the run. The download
list is XCL's own object, so no Close hook logs a failure: Close logs
it here.

Assisted-by: Codex (GPT-6)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@BBareth
BBareth force-pushed the d3d12x/pool-texture-download-objects branch from 58815f7 to 60f0498 Compare December 3, 2026 03:17
@BBareth

BBareth commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 60f0498 (rebased on main 078358a; merges cleanly into 395405e).

  • The 1 GiB held for the run (Foniass's merge check, AAsobu, bmjask): a readback buffer no download took for 2 s is now released. Peak commit in the smoke run of this head is 32252 MB, against 32465 MB on main 078358a. The blocks are in the description.
  • The two misplaced comments: moved above put and above static DOWNLOAD_POOL.
  • Close failures: the download list's Close failure is logged again, now by the download code itself.
  • bmjask's three inline points: answered in their threads. The device-removal one does not happen in XCL: one device per process, and the process ends on removal.
  • Suite: 3011 passed, 0 failed, 52 ignored, 28 SKIPPED, run on bbcef6c6. That commit differs from this head only by the two comment moves.

AI use: Claude Code, Claude Opus 5.5 wrote this comment.

@Foniass

Foniass commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator

Follow-up review of 60f04988, since 58815f7 (code reading only, not a merge-check) · 2 medium, 1 nit

In short: The PR reuses the allocator, command list, fence and readback buffer of each texture download. All three points from the triage of 58815f7 are addressed:

  • a readback buffer unused for 2 s is now released (DownloadPool::trim, run from poll_fence_downloads), with a test;
  • the two comments are in the right places;
  • the description states the caps.

A failed Close is also logged now. Two points remain, and neither blocks the PR: the idle release only runs when the fence thread wakes, and the fence-value reuse is still untested.

Medium

  1. The idle release depends on the fence thread waking.

    • trim runs only inside poll_fence_downloads (title_textures.rs ~4335), on the xcl-fences thread. That thread waits with INFINITE (fence_x.rs ~162) and is woken only by download ties, and by signals of fences whose completed-value address the title asked for.
    • The last downloads' buffers go back into the pool during that same poll, after trim has run, so releasing them needs a later wake.
    • In a title that never asks for that address, no later wake comes once downloads stop, and those buffers (up to the 1 GiB cap) stay committed until the next download or an out-of-memory retry.

    Fix: run trim from a path that runs every frame, give the thread a timed wait while the pool holds buffers, or narrow the description's "no longer keeps up to 1 GiB committed for the rest of the run".

  2. The fence-value reuse in Drop for PendingDownload is untested (still open from the earlier merge-check). next_value (~3842), and the reuse of a pooled set's fence with last + 1 in submit, have no test. Moving the next-value rule into a small function would let a CPU test cover it, including the retirement before u64::MAX. A GPU test with two downloads on one device would show the second signals 2 and reads back the right bytes.

Nit

  1. The suite counts are for a commit that is not public. Tested gives cargo test counts for bbcef6c6 and says the head differs only in comment placement. bbcef6c6 is not in the PR's history or on GitHub. Rerun the suite on 60f04988.
Checked and fine
  • Earlier finding fixed: the description now states the commit cost (1024 sets, 1 GiB of buffers, 2 s idle release).
  • Earlier finding fixed: "Return rejected entries..." now sits above put (~3750), and "Each entry owns a device reference..." above DOWNLOAD_POOL (~3781).
  • Earlier note kept: create_download_fence keeps download fences out of FENCES, and the description says so.
  • trim: each bucket stays in time order, because put reads the monotonic clock under the lock and take pops the newest, so partition_point is valid. buffer_bytes subtracts exactly what it frees. The test covers both sides of 2 s.
  • The pool lock is a leaf, held only for the container operations. Trimmed, drained and rejected objects are released after it is dropped.
  • An object goes back to the pool only after its fence completed, and the allocator and list are reset when taken again. A fence is retired before it could signal the u64::MAX sentinel.
  • The objects are made inside own_work, so they are not adopted.
  • The smoke block is on the head: 3020 vs 3046 frames, peak commit 32252 vs 32465 MB, no device removal. 308+/42- in two files.

Written by Claude Code (Claude Opus 5.5) and 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 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.

6 participants