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

Open
BBareth wants to merge 1 commit from upstream-pr/3514 into main
BBareth commented 2026-11-30 07:58:46 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-11-30T07:58:46Z.


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. The fence thread (fence_x.rs) checks a few times a second: while the pool holds an idle buffer it waits at most 250 ms, since no fence may wake it once downloads stop; with none idle it waits for a fence as before. A buffer returned to an empty pool sets the thread's event once (trim_wait_started): a title thread that publishes the download can return it while the thread sleeps with no limit. 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 (next_download_fence_value) and is retired before it would signal u64::MAX, the device-removal value.
    • 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
    • download_pool_limits_the_trim_wait_only_while_a_buffer_is_idle
    • the_first_idle_buffer_wakes_the_trimming_thread
    • a_pooled_download_fence_counts_up_and_is_retired_before_the_removal_sentinel

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 the head 7fa1f2b6 (on main 078358a0): 3014 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.
  • Merges cleanly into main 395405e4.
  • A retail title 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: 7fa1f2b60ff428b5d8ebf155147faf5876305567
gpu: NVIDIA GeForce RTX 5070 Ti
title: 9cc6a39e
seconds: 120
exit: 0x0
frames shown: 3049 (PresentX 3049)
presents per 2 s (last 3): 26 37 5
device removals: 0
crashes: 0
peak commit: 31669 MB

The A button is pressed once at 70 s. The main run follows one warm-up run of the same build. The warm-up before the PR's run did not start (another run was using the GPU), so the PR's run is the build's first full run.

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) wrote the timed wait, the fence-value test and the wake on the first idle buffer after review, reviewed the diff, ran the suite and the smoke runs, and wrote this description.

🤖 Generated with Claude Code

<!-- greyfinch-sync:ivall/xcl:issue:5561329524 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514). Originally posted by [BBareth](https://github.com/BBareth) on 2026-11-30T07:58:46Z. --- 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. The fence thread (`fence_x.rs`) checks a few times a second: while the pool holds an idle buffer it waits at most 250 ms, since no fence may wake it once downloads stop; with none idle it waits for a fence as before. A buffer returned to an empty pool sets the thread's event once (`trim_wait_started`): a title thread that publishes the download can return it while the thread sleeps with no limit. 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 (`next_download_fence_value`) and is retired before it would signal `u64::MAX`, the device-removal value. - 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` - `download_pool_limits_the_trim_wait_only_while_a_buffer_is_idle` - `the_first_idle_buffer_wakes_the_trimming_thread` - `a_pooled_download_fence_counts_up_and_is_retired_before_the_removal_sentinel` **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 the head 7fa1f2b6 (on main 078358a0): 3014 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. - Merges cleanly into main 395405e4. - A retail title 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: 7fa1f2b60ff428b5d8ebf155147faf5876305567 gpu: NVIDIA GeForce RTX 5070 Ti title: 9cc6a39e seconds: 120 exit: 0x0 frames shown: 3049 (PresentX 3049) presents per 2 s (last 3): 26 37 5 device removals: 0 crashes: 0 peak commit: 31669 MB ``` The A button is pressed once at 70 s. The `main` run follows one warm-up run of the same build. The warm-up before the PR's run did not start (another run was using the GPU), so the PR's run is the build's first full run. **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) wrote the timed wait, the fence-value test and the wake on the first idle buffer after review, reviewed the diff, ran the suite and the smoke runs, and wrote this description. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
thehollowedone commented 2026-11-30 09:00:19 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by thehollowedone on 2026-11-30T09:00:19Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7273615324 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7273615324). Originally posted by [thehollowedone](https://github.com/thehollowedone) on 2026-11-30T09:00:19Z. --- 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](https://github.com/xcl-dev/xcl/blob/3e00f2b6b9ae51572772d65bac7ec8a2a636d6c0/crates/xcl/src/hle/d3d12x/title_textures.rs#L4322-L4361) · [Skipped preparation](https://github.com/xcl-dev/xcl/blob/3e00f2b6b9ae51572772d65bac7ec8a2a636d6c0/crates/xcl/src/hle/d3d12x/title_textures.rs#L3980) 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. <details> <summary>Candidate diff</summary> ```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() { ``` </details> 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 commented 2026-11-30 09:27:38 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-11-30T09:27:38Z.


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 58815f7c (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 d52ff48c 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.

<!-- greyfinch-sync:ivall/xcl:comment:7274236804 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7274236804). Originally posted by [BBareth](https://github.com/BBareth) on 2026-11-30T09:27:38Z. --- 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 58815f7c (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 d52ff48c 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 commented 2026-11-30 10:53:31 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Gevroska on 2026-11-30T10:53:31Z.


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

<!-- greyfinch-sync:ivall/xcl:comment:7276227621 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7276227621). Originally posted by [Gevroska](https://github.com/Gevroska) on 2026-11-30T10:53:31Z. --- @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 commented 2026-11-30 19:53:13 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by AAsobu on 2026-11-30T19:53:13Z.


merge-check claim
head: 58815f7c3f

<!-- greyfinch-sync:ivall/xcl:comment:7290082918 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7290082918). Originally posted by [AAsobu](https://github.com/AAsobu) on 2026-11-30T19:53:13Z. --- merge-check claim head: 58815f7c3f3c0e17df5cb70f80b33c9ac9a6a319
AAsobu commented 2026-11-30 21:09:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by AAsobu on 2026-11-30T21:09:29Z.


merge-check
base: 16c2fd082a
head: 2f806d335c
merge: clean (merged tree 31185be6)
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3019 passed, 0 failed, 56 ignored; SKIPPED: 28 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps, 3 no D3D12 debug layer); failing: none (no gpu_compute_e2e hang this time)
review: read the change since 60f04988 (+41/-3, fence_x.rs, title_textures.rs): the xcl-fences thread now waits at most 250 ms while the pool holds an idle readback buffer, so trim releases it without a new fence (my earlier point and Foniass's point 1), and the fence-value step has its own test. No findings.
performance: two 360 s runs of this merge in the world (same settings as below, caches not re-warmed): presents per 2 s 2.61 / 3.71, peak commit 39232 / 39030 MB, peak VRAM 15791 / 15935 MB. The warmed main 16c2fd08 runs of my earlier A/B and of a later one had 39606-40376 MB commit and 15773-16221 MB VRAM, so the ~0.5 GB of extra VRAM and commit I measured on 60f04988 does not show here. Two runs without a fresh main arm in the same series is a small sample; the lower first run is the cold start after the new build. Not checked: whether the pool frees its buffers once downloads stop (in these runs commit keeps rising until the end and the log says nothing about the pool), AMD.
smoke (scripts/smoke.ps1 -Game <folder>, 60 s): main 16c2fd08 2 frames, 0 removals, 0 crashes, peak commit 10285 MB; this merge 31185be6 2 frames, 0 removals, 0 crashes, peak commit 10259 MB.
verdict: safe to merge: the cost behind my earlier "not yet" is addressed in the code and no longer shows in the world here.
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 / Claude Code (Claude Opus 5.5), results checked by me

My earlier checks of 60f04988 and 58815f7c

merge-check
base: 16c2fd082a
head: 60f049885c
merge: clean (merged tree 97976aee)
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3007 passed, 1 failed, 56 ignored; SKIPPED: 27 (22 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no GPU_UPLOAD heaps, 1 no heap windows); failing: frame_clock::token_on_timeout_and_token_in_origin_refresh (frame_clock.rs:132, 0 vs 1), which passed 4 of 4 when rerun alone, so I count it as timing noise (the suite ran while the title was running on the same GPU). Also gpu_compute_e2e (9 tests, 4 threads) hung in that suite and in its first rerun (4 tests "running for over 60 seconds", one core busy, killed after 30+ and 7 min); after that it passed 43 of 43 on this merge and 42 of 42 on main 16c2fd08 (each test alone and with 1 thread: pass). Both hangs were the first two runs of a freshly built test binary; I cannot tie them to this PR. The full suite was not run on main 16c2fd08.
review: diff of 60f04988 read in full (+308/-42, real.rs, title_textures.rs). The points of my earlier check are addressed: an idle readback buffer is released after 2 s (DownloadPool::trim, with a test), the two comments moved, the Close failure is logged. I agree with Foniass's follow-up point 1: trim runs only when the xcl-fences thread wakes, so after the last downloads their buffers can stay committed. My in-world runs below point the same way. No other finding.
performance: A/B on the retail title in the world, release builds of main 16c2fd08 (A) and this merge (B), order A, B, A, B, B, A, 360 s each, warm caches (3 unmeasured runs of each build first, until no compute-pipeline waits), settings XCL_PREPARE=0 XCL_DIRECT_DXIL=1 XCL_TEXTURE_LEVEL_PAGES=1 XCL_HUGE_PSO_CONCURRENCY=4 XCL_DXC_THREADS=4 XCL_NETWORK=0 XCL_DRED=1 XCL_ACTIVITY=1, start prompt held by XCL_PRESS_A_AT at 21-34 s, world entry at 121-132 s, measured window from world entry +30 s to +140 s (frames and draws from the 2 s activity lines), peaks over the whole run.

run presents / 2 s draws / 2 s peak commit MB peak VRAM MB
A1 4.17 19807 39606 16025
B1 3.97 18905 40034 16547
A2 4.10 19756 39700 15773
B2 3.91 18950 39816 16266
B3 3.74 17031 40534 16452
mean A / B 4.14 / 3.87 (-6 %) 19782 / 18295 (-8 %) 39653 / 40128 (+475) 15899 / 16422 (+523)

All three B runs are above both A runs in peak VRAM and below them in presents; commit overlaps (B2 < A2). The last A run (A3) hit a device removal at 188 s (0x887a0006, DRED page fault at VA 0x0 with vs 505022186d7aeaa4 / ps c1cffdc3f13a4f2f, the removal I reported on #3655 for main), before its window was complete, so it is left out. With 2 A and 3 B runs this is a small sample, but it is the opposite of what the description reports for the 60 s smoke run (32252 vs 32465 MB), which does not reach the world. On the earlier head 58815f7c my in-world runs (different base and settings) had shown lower commit with the PR.
smoke (scripts/smoke.ps1 -Game <folder>, 60 s): main 16c2fd08 2 frames, 0 removals, 0 crashes, peak commit 10959 MB; this merge 97976aee 2 frames, 0 removals, 0 crashes, peak commit 10907 MB. The title does not reach the world in 60 s here.
verdict: not yet: in the world this head ends up with about 0.5 GB more VRAM and commit than main and about 6 % fewer presents (3 of 3 runs vs 2 of 2), which matches buffers kept in the pool after the downloads stop (Foniass's point 1). Running trim on a path that runs every frame, or a timed wait while the pool holds buffers, would let me check whether the difference goes away.
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 / Claude Code (Claude Opus 5.5), results checked by me

My earlier check of 58815f7c (2026-12-01)

merge-check
base: ff0c364b3d
head: 58815f7c3f
merge: clean (main has since moved to 86e86fcb 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

<!-- greyfinch-sync:ivall/xcl:comment:7291995866 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7291995866). Originally posted by [AAsobu](https://github.com/AAsobu) on 2026-11-30T21:09:29Z. --- merge-check base: 16c2fd082ae2e96967a2ab553bc2e1032e491f70 head: 2f806d335c8fae6d44d88ceb67b957a52d9430f4 merge: clean (merged tree 31185be6) build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3019 passed, 0 failed, 56 ignored; SKIPPED: 28 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps, 3 no D3D12 debug layer); failing: none (no `gpu_compute_e2e` hang this time) review: read the change since `60f04988` (+41/-3, `fence_x.rs`, `title_textures.rs`): the `xcl-fences` thread now waits at most 250 ms while the pool holds an idle readback buffer, so `trim` releases it without a new fence (my earlier point and Foniass's point 1), and the fence-value step has its own test. No findings. performance: two 360 s runs of this merge in the world (same settings as below, caches not re-warmed): presents per 2 s 2.61 / 3.71, peak commit 39232 / 39030 MB, peak VRAM 15791 / 15935 MB. The warmed `main` `16c2fd08` runs of my earlier A/B and of a later one had 39606-40376 MB commit and 15773-16221 MB VRAM, so the ~0.5 GB of extra VRAM and commit I measured on `60f04988` does not show here. Two runs without a fresh `main` arm in the same series is a small sample; the lower first run is the cold start after the new build. Not checked: whether the pool frees its buffers once downloads stop (in these runs commit keeps rising until the end and the log says nothing about the pool), AMD. smoke (`scripts/smoke.ps1 -Game <folder>`, 60 s): `main` `16c2fd08` 2 frames, 0 removals, 0 crashes, peak commit 10285 MB; this merge `31185be6` 2 frames, 0 removals, 0 crashes, peak commit 10259 MB. verdict: safe to merge: the cost behind my earlier "not yet" is addressed in the code and no longer shows in the world here. 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 / Claude Code (Claude Opus 5.5), results checked by me <details><summary>My earlier checks of 60f04988 and 58815f7c</summary> merge-check base: 16c2fd082ae2e96967a2ab553bc2e1032e491f70 head: 60f049885cdbb9c3b35dbb944ff165cd15234533 merge: clean (merged tree 97976aee) build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3007 passed, 1 failed, 56 ignored; SKIPPED: 27 (22 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no GPU_UPLOAD heaps, 1 no heap windows); failing: `frame_clock::token_on_timeout_and_token_in_origin_refresh` (frame_clock.rs:132, 0 vs 1), which passed 4 of 4 when rerun alone, so I count it as timing noise (the suite ran while the title was running on the same GPU). Also `gpu_compute_e2e` (9 tests, 4 threads) hung in that suite and in its first rerun (4 tests "running for over 60 seconds", one core busy, killed after 30+ and 7 min); after that it passed 43 of 43 on this merge and 42 of 42 on `main` `16c2fd08` (each test alone and with 1 thread: pass). Both hangs were the first two runs of a freshly built test binary; I cannot tie them to this PR. The full suite was not run on `main` `16c2fd08`. review: diff of `60f04988` read in full (+308/-42, `real.rs`, `title_textures.rs`). The points of my earlier check are addressed: an idle readback buffer is released after 2 s (`DownloadPool::trim`, with a test), the two comments moved, the `Close` failure is logged. I agree with Foniass's follow-up point 1: `trim` runs only when the `xcl-fences` thread wakes, so after the last downloads their buffers can stay committed. My in-world runs below point the same way. No other finding. performance: A/B on the retail title in the world, release builds of `main` `16c2fd08` (A) and this merge (B), order A, B, A, B, B, A, 360 s each, warm caches (3 unmeasured runs of each build first, until no compute-pipeline waits), settings `XCL_PREPARE=0 XCL_DIRECT_DXIL=1 XCL_TEXTURE_LEVEL_PAGES=1 XCL_HUGE_PSO_CONCURRENCY=4 XCL_DXC_THREADS=4 XCL_NETWORK=0 XCL_DRED=1 XCL_ACTIVITY=1`, start prompt held by `XCL_PRESS_A_AT` at 21-34 s, world entry at 121-132 s, measured window from world entry +30 s to +140 s (frames and draws from the 2 s activity lines), peaks over the whole run. | run | presents / 2 s | draws / 2 s | peak commit MB | peak VRAM MB | |---|---|---|---|---| | A1 | 4.17 | 19807 | 39606 | 16025 | | B1 | 3.97 | 18905 | 40034 | 16547 | | A2 | 4.10 | 19756 | 39700 | 15773 | | B2 | 3.91 | 18950 | 39816 | 16266 | | B3 | 3.74 | 17031 | 40534 | 16452 | | mean A / B | 4.14 / 3.87 (-6 %) | 19782 / 18295 (-8 %) | 39653 / 40128 (+475) | 15899 / 16422 (+523) | All three B runs are above both A runs in peak VRAM and below them in presents; commit overlaps (B2 < A2). The last A run (A3) hit a device removal at 188 s (0x887a0006, DRED page fault at VA 0x0 with `vs 505022186d7aeaa4 / ps c1cffdc3f13a4f2f`, the removal I reported on #3655 for `main`), before its window was complete, so it is left out. With 2 A and 3 B runs this is a small sample, but it is the opposite of what the description reports for the 60 s smoke run (32252 vs 32465 MB), which does not reach the world. On the earlier head `58815f7c` my in-world runs (different base and settings) had shown lower commit with the PR. smoke (`scripts/smoke.ps1 -Game <folder>`, 60 s): `main` `16c2fd08` 2 frames, 0 removals, 0 crashes, peak commit 10959 MB; this merge `97976aee` 2 frames, 0 removals, 0 crashes, peak commit 10907 MB. The title does not reach the world in 60 s here. verdict: not yet: in the world this head ends up with about 0.5 GB more VRAM and commit than `main` and about 6 % fewer presents (3 of 3 runs vs 2 of 2), which matches buffers kept in the pool after the downloads stop (Foniass's point 1). Running `trim` on a path that runs every frame, or a timed wait while the pool holds buffers, would let me check whether the difference goes away. 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 / Claude Code (Claude Opus 5.5), results checked by me <details><summary>My earlier check of 58815f7c (2026-12-01)</summary> merge-check base: ff0c364b3de011c13ed45865480c21918a79ec89 head: 58815f7c3f3c0e17df5cb70f80b33c9ac9a6a319 merge: clean (main has since moved to 86e86fcb 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 </details> </details>
BBareth commented 2026-11-30 21:51:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-11-30T21:51:48Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7293009980 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7293009980). Originally posted by [BBareth](https://github.com/BBareth) on 2026-11-30T21:51:48Z. --- 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 commented 2026-12-01 08:48:17 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T08:48:17Z.


merge-check
base: 7d86c5d2b7
head: 58815f7c3f
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 7d86c5d2 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.

<!-- greyfinch-sync:ivall/xcl:comment:7305807091 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7305807091). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T08:48:17Z. --- merge-check base: 7d86c5d2b7845695031eeea1327aa81b6c439323 head: 58815f7c3f3c0e17df5cb70f80b33c9ac9a6a319 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 7d86c5d2 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.
Foniass commented 2026-12-01 10:07:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T10:07:05Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7307694891 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7307694891). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T10:07:05Z. --- **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 commented 2026-12-01 10:24:21 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-01T10:24:21Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7308140643 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7308140643). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-01T10:24:21Z. --- 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.
bmjask commented 2026-12-02 10:15:53 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T10:15:53Z.

Code review location: crates/xcl/src/hle/d3d12x/title_textures.rs; line 4381

@@ -4240,27 +4336,60 @@ pub(super) unsafe fn prepare_texture_download(
             .ok_or("driver footprint overflow")?;
     }
     let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?;
-    let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?;
-    let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?;
-    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: bytes as u64,
-            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())?;
-    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(|| {
+        let reset = pooled_set.and_then(|(commands, _)| {
+            (commands.allocator.Reset().is_ok() && commands.graphics.Reset(&commands.allocator, None).is_ok())
+                .then_some(commands)
+        });
+        let commands = match reset {
+            Some(commands) => commands,
+            None => {
+                let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?;
+                let graphics = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?;
+                let fence = super::real::create_download_fence(dev).map_err(|e| e.to_string())?;
+                DownloadCommands { graphics, allocator, fence, fence_value: 1 }
+            }
+        };
+        let readback = match pooled_buffer {
+            Some((readback, _)) => readback,
+            None => {
+                let desc = 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()
+                };
+                let create = || {
+                    let mut readback: Option<ID3D12Resource> = None;
+                    dev.CreateCommittedResource(
+                        &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
+                        D3D12_HEAP_FLAG_NONE,
+                        &desc,
+                        D3D12_RESOURCE_STATE_COPY_DEST,
+                        None,
+                        &mut readback,
+                    )
+                    .map(|()| readback)
+                };
+                // The idle buffers are dropped after the pool's lock is released.
+                let reclaim = || {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4767988071 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#discussion_r4767988071). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T10:15:53Z. **Code review location:** `crates/xcl/src/hle/d3d12x/title_textures.rs`; line 4381 ~~~~diff @@ -4240,27 +4336,60 @@ pub(super) unsafe fn prepare_texture_download( .ok_or("driver footprint overflow")?; } let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?; - let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?; - let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?; - 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: bytes as u64, - 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())?; - 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(|| { + let reset = pooled_set.and_then(|(commands, _)| { + (commands.allocator.Reset().is_ok() && commands.graphics.Reset(&commands.allocator, None).is_ok()) + .then_some(commands) + }); + let commands = match reset { + Some(commands) => commands, + None => { + let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?; + let graphics = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?; + let fence = super::real::create_download_fence(dev).map_err(|e| e.to_string())?; + DownloadCommands { graphics, allocator, fence, fence_value: 1 } + } + }; + let readback = match pooled_buffer { + Some((readback, _)) => readback, + None => { + let desc = 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() + }; + let create = || { + let mut readback: Option<ID3D12Resource> = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .map(|()| readback) + }; + // The idle buffers are dropped after the pool's lock is released. + let reclaim = || { ~~~~ --- 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.
bmjask commented 2026-12-02 10:15:53 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T10:15:53Z.

Code review location: crates/xcl/src/hle/d3d12x/title_textures.rs; line 3800

@@ -3698,15 +3783,22 @@ pub(super) struct PendingDownload {
 
 impl Drop for PendingDownload {
     fn drop(&mut self) {
-        let done = self.fence_value.is_some_and(|v| {
-            let got = unsafe { super::real::native_fence_completed(&self.fence) };
-            got != u64::MAX && got >= v
-        });
-        if !done {
-            if let Some(objects) = self.objects.take() {
-                std::mem::forget(objects);
-            }
+        let Some(objects) = self.objects.take() else { return };
+        if !self.is_complete() {
+            std::mem::forget(objects);
+            return;
         }
+
+        let DownloadObjects { readback, readback_size, mut commands, device, queue_type, .. } = objects;
+        let key = device.as_raw() as usize;
+        // MAX is the device-removal sentinel. Retire a fence before it would signal that value.
+        let next_value = commands.fence_value.checked_add(1).filter(|&v| v < u64::MAX);
+        let set = next_value.map(|value| {
+            commands.fence_value = value;
+            (commands, device.clone())
+        });
+        let rejected = DOWNLOAD_POOL.lock().unwrap().put(key, queue_type, readback_size, set, (readback, device));

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4767988080 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#discussion_r4767988080). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T10:15:53Z. **Code review location:** `crates/xcl/src/hle/d3d12x/title_textures.rs`; line 3800 ~~~~diff @@ -3698,15 +3783,22 @@ pub(super) struct PendingDownload { impl Drop for PendingDownload { fn drop(&mut self) { - let done = self.fence_value.is_some_and(|v| { - let got = unsafe { super::real::native_fence_completed(&self.fence) }; - got != u64::MAX && got >= v - }); - if !done { - if let Some(objects) = self.objects.take() { - std::mem::forget(objects); - } + let Some(objects) = self.objects.take() else { return }; + if !self.is_complete() { + std::mem::forget(objects); + return; } + + let DownloadObjects { readback, readback_size, mut commands, device, queue_type, .. } = objects; + let key = device.as_raw() as usize; + // MAX is the device-removal sentinel. Retire a fence before it would signal that value. + let next_value = commands.fence_value.checked_add(1).filter(|&v| v < u64::MAX); + let set = next_value.map(|value| { + commands.fence_value = value; + (commands, device.clone()) + }); + let rejected = DOWNLOAD_POOL.lock().unwrap().put(key, queue_type, readback_size, set, (readback, device)); ~~~~ --- 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.
bmjask commented 2026-12-02 10:15:53 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T10:15:53Z.

Code review location: crates/xcl/src/hle/d3d12x/title_textures.rs; line 4341

@@ -4240,27 +4336,60 @@ pub(super) unsafe fn prepare_texture_download(
             .ok_or("driver footprint overflow")?;
     }
     let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?;
-    let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?;
-    let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?;
-    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: bytes as u64,
-            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())?;
-    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(|| {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4767988089 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#discussion_r4767988089). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T10:15:53Z. **Code review location:** `crates/xcl/src/hle/d3d12x/title_textures.rs`; line 4341 ~~~~diff @@ -4240,27 +4336,60 @@ pub(super) unsafe fn prepare_texture_download( .ok_or("driver footprint overflow")?; } let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?; - let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?; - let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?; - 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: bytes as u64, - 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())?; - 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(|| { ~~~~ --- 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.
bmjask commented 2026-12-02 10:15:53 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T10:15:53Z.

Review: COMMENTED


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.

<!-- greyfinch-sync:ivall/xcl:review:6148832054 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#pullrequestreview-6148832054). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T10:15:53Z. **Review:** COMMENTED --- 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._
bmjask commented 2026-12-02 14:12:17 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T14:12:17Z.


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

<!-- greyfinch-sync:ivall/xcl:comment:7348158490 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7348158490). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T14:12:17Z. --- @Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.
BBareth commented 2026-12-03 03:17:57 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T03:17:57Z.

Code review location: crates/xcl/src/hle/d3d12x/title_textures.rs; line 4381

@@ -4240,27 +4336,60 @@ pub(super) unsafe fn prepare_texture_download(
             .ok_or("driver footprint overflow")?;
     }
     let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?;
-    let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?;
-    let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?;
-    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: bytes as u64,
-            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())?;
-    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(|| {
+        let reset = pooled_set.and_then(|(commands, _)| {
+            (commands.allocator.Reset().is_ok() && commands.graphics.Reset(&commands.allocator, None).is_ok())
+                .then_some(commands)
+        });
+        let commands = match reset {
+            Some(commands) => commands,
+            None => {
+                let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?;
+                let graphics = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?;
+                let fence = super::real::create_download_fence(dev).map_err(|e| e.to_string())?;
+                DownloadCommands { graphics, allocator, fence, fence_value: 1 }
+            }
+        };
+        let readback = match pooled_buffer {
+            Some((readback, _)) => readback,
+            None => {
+                let desc = 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()
+                };
+                let create = || {
+                    let mut readback: Option<ID3D12Resource> = None;
+                    dev.CreateCommittedResource(
+                        &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
+                        D3D12_HEAP_FLAG_NONE,
+                        &desc,
+                        D3D12_RESOURCE_STATE_COPY_DEST,
+                        None,
+                        &mut readback,
+                    )
+                    .map(|()| readback)
+                };
+                // The idle buffers are dropped after the pool's lock is released.
+                let reclaim = || {

Addressed in 60f04988. 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 078358a0's 32465 MB (blocks in the description).

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

<!-- greyfinch-sync:ivall/xcl:review-comment:4779445205 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#discussion_r4779445205). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T03:17:57Z. **Code review location:** `crates/xcl/src/hle/d3d12x/title_textures.rs`; line 4381 ~~~~diff @@ -4240,27 +4336,60 @@ pub(super) unsafe fn prepare_texture_download( .ok_or("driver footprint overflow")?; } let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?; - let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?; - let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?; - 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: bytes as u64, - 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())?; - 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(|| { + let reset = pooled_set.and_then(|(commands, _)| { + (commands.allocator.Reset().is_ok() && commands.graphics.Reset(&commands.allocator, None).is_ok()) + .then_some(commands) + }); + let commands = match reset { + Some(commands) => commands, + None => { + let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?; + let graphics = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?; + let fence = super::real::create_download_fence(dev).map_err(|e| e.to_string())?; + DownloadCommands { graphics, allocator, fence, fence_value: 1 } + } + }; + let readback = match pooled_buffer { + Some((readback, _)) => readback, + None => { + let desc = 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() + }; + let create = || { + let mut readback: Option<ID3D12Resource> = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .map(|()| readback) + }; + // The idle buffers are dropped after the pool's lock is released. + let reclaim = || { ~~~~ --- Addressed in 60f04988. 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 078358a0's 32465 MB (blocks in the description). AI use: Claude Code, Claude Opus 5.5 wrote this reply.
BBareth commented 2026-12-03 03:17:59 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T03:17:59Z.

Code review location: crates/xcl/src/hle/d3d12x/title_textures.rs; line 3800

@@ -3698,15 +3783,22 @@ pub(super) struct PendingDownload {
 
 impl Drop for PendingDownload {
     fn drop(&mut self) {
-        let done = self.fence_value.is_some_and(|v| {
-            let got = unsafe { super::real::native_fence_completed(&self.fence) };
-            got != u64::MAX && got >= v
-        });
-        if !done {
-            if let Some(objects) = self.objects.take() {
-                std::mem::forget(objects);
-            }
+        let Some(objects) = self.objects.take() else { return };
+        if !self.is_complete() {
+            std::mem::forget(objects);
+            return;
         }
+
+        let DownloadObjects { readback, readback_size, mut commands, device, queue_type, .. } = objects;
+        let key = device.as_raw() as usize;
+        // MAX is the device-removal sentinel. Retire a fence before it would signal that value.
+        let next_value = commands.fence_value.checked_add(1).filter(|&v| v < u64::MAX);
+        let set = next_value.map(|value| {
+            commands.fence_value = value;
+            (commands, device.clone())
+        });
+        let rejected = DOWNLOAD_POOL.lock().unwrap().put(key, queue_type, readback_size, set, (readback, device));

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4779445407 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#discussion_r4779445407). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T03:17:59Z. **Code review location:** `crates/xcl/src/hle/d3d12x/title_textures.rs`; line 3800 ~~~~diff @@ -3698,15 +3783,22 @@ pub(super) struct PendingDownload { impl Drop for PendingDownload { fn drop(&mut self) { - let done = self.fence_value.is_some_and(|v| { - let got = unsafe { super::real::native_fence_completed(&self.fence) }; - got != u64::MAX && got >= v - }); - if !done { - if let Some(objects) = self.objects.take() { - std::mem::forget(objects); - } + let Some(objects) = self.objects.take() else { return }; + if !self.is_complete() { + std::mem::forget(objects); + return; } + + let DownloadObjects { readback, readback_size, mut commands, device, queue_type, .. } = objects; + let key = device.as_raw() as usize; + // MAX is the device-removal sentinel. Retire a fence before it would signal that value. + let next_value = commands.fence_value.checked_add(1).filter(|&v| v < u64::MAX); + let set = next_value.map(|value| { + commands.fence_value = value; + (commands, device.clone()) + }); + let rejected = DOWNLOAD_POOL.lock().unwrap().put(key, queue_type, readback_size, set, (readback, device)); ~~~~ --- 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.
BBareth commented 2026-12-03 03:18:01 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T03:18:01Z.

Code review location: crates/xcl/src/hle/d3d12x/title_textures.rs; line 4341

@@ -4240,27 +4336,60 @@ pub(super) unsafe fn prepare_texture_download(
             .ok_or("driver footprint overflow")?;
     }
     let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?;
-    let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?;
-    let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?;
-    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: bytes as u64,
-            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())?;
-    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(|| {

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 60f04988 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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4779445644 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#discussion_r4779445644). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T03:18:01Z. **Code review location:** `crates/xcl/src/hle/d3d12x/title_textures.rs`; line 4341 ~~~~diff @@ -4240,27 +4336,60 @@ pub(super) unsafe fn prepare_texture_download( .ok_or("driver footprint overflow")?; } let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?; - let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?; - let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?; - 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: bytes as u64, - 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())?; - 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(|| { ~~~~ --- 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 60f04988 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.
BBareth commented 2026-12-03 03:18:12 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T03:18:12Z.


Pushed 60f04988 (rebased on main 078358a0; merges cleanly into 395405e4).

  • 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 078358a0. 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.

<!-- greyfinch-sync:ivall/xcl:comment:7366419241 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7366419241). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T03:18:12Z. --- Pushed 60f04988 (rebased on main 078358a0; merges cleanly into 395405e4). - **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 078358a0. 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 commented 2026-12-03 03:21:35 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T03:21:35Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7366479665 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7366479665). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-03T03:21:35Z. --- **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 3. **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`. <details><summary>Checked and fine</summary> - 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. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
BBareth commented 2026-12-03 08:52:21 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T08:52:21Z.


On the follow-up review of 60f04988, pushed 2f806d33:

  1. The idle release depends on the fence thread waking: confirmed. The xcl-fences thread waited with INFINITE, so the last downloads' buffers stayed until the next wake. While the pool holds an idle readback buffer, the thread now waits at most 250 ms (DownloadPool::trim_wait_ms, used in fence_x.rs). With none idle it waits for a fence as before. Test: download_pool_limits_the_trim_wait_only_while_a_buffer_is_idle.
  2. The fence-value reuse is untested: the next-value rule is now next_download_fence_value, with a CPU test that covers the retirement before u64::MAX (a_pooled_download_fence_counts_up_and_is_retired_before_the_removal_sentinel). The two-download GPU test is not added.
  3. Suite counts for a commit that is not public: the suite is rerun on 2f806d33: 3013 passed, 0 failed, 52 ignored, 28 SKIPPED (the same 28 as before).

Smoke on 2f806d33: 3093 frames, peak commit 32331 MB, no device removal, no crash (main 078358a0: 3046 frames, 32465 MB). The block is in the description.

AI use: Claude Code, Claude Opus 5.5 checked the points, wrote the change and this comment.

<!-- greyfinch-sync:ivall/xcl:comment:7372858272 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7372858272). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T08:52:21Z. --- On the follow-up review of 60f04988, pushed 2f806d33: 1. **The idle release depends on the fence thread waking**: confirmed. The `xcl-fences` thread waited with `INFINITE`, so the last downloads' buffers stayed until the next wake. While the pool holds an idle readback buffer, the thread now waits at most 250 ms (`DownloadPool::trim_wait_ms`, used in `fence_x.rs`). With none idle it waits for a fence as before. Test: `download_pool_limits_the_trim_wait_only_while_a_buffer_is_idle`. 2. **The fence-value reuse is untested**: the next-value rule is now `next_download_fence_value`, with a CPU test that covers the retirement before `u64::MAX` (`a_pooled_download_fence_counts_up_and_is_retired_before_the_removal_sentinel`). The two-download GPU test is not added. 3. **Suite counts for a commit that is not public**: the suite is rerun on 2f806d33: 3013 passed, 0 failed, 52 ignored, 28 SKIPPED (the same 28 as before). Smoke on 2f806d33: 3093 frames, peak commit 32331 MB, no device removal, no crash (main 078358a0: 3046 frames, 32465 MB). The block is in the description. AI use: Claude Code, Claude Opus 5.5 checked the points, wrote the change and this comment.
Foniass commented 2026-12-03 08:53:47 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T08:53:47Z.


Follow-up review of 2f806d33, since 60f04988 (code reading only, not a merge-check) · no new findings

In short: This push fixes all three points from my last review:

  • the xcl-fences thread now waits at most 250 ms while the pool holds an idle readback buffer, so idle buffers are released even after downloads stop;
  • the next-fence-value rule is a small function with a test;
  • the suite was run on this head (3013 passed, 0 failed, 52 ignored), and the smoke block names it.

Nothing blocks it.

Checked and fine
  • Earlier finding fixed: the idle release depended on the fence thread waking. WaitForSingleObject now takes download_poll_wait_ms(): DOWNLOAD_POOL_IDLE_US / 8 (250 ms) while buffer_bytes != 0, otherwise INFINITE as before. Idle command sets alone do not shorten the wait. download_pool_limits_the_trim_wait_only_while_a_buffer_is_idle covers both cases.
  • Earlier finding fixed: the fence-value reuse was untested. next_download_fence_value gives last + 1 and retires the set before u64::MAX, the device-removal sentinel. a_pooled_download_fence_counts_up_and_is_retired_before_the_removal_sentinel covers both ends.
  • Earlier nit fixed: Tested reports the whole suite on 2f806d33.
  • download_poll_wait_ms takes the pool lock, a leaf lock, only to read buffer_bytes, before the wait.
  • The pool, trim and fence handling are otherwise the same as at 60f04988.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7372891179 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7372891179). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-03T08:53:47Z. --- **Follow-up review** of `2f806d33`, since `60f04988` (code reading only, not a merge-check) · no new findings **In short:** This push fixes all three points from my last review: - the `xcl-fences` thread now waits at most 250 ms while the pool holds an idle readback buffer, so idle buffers are released even after downloads stop; - the next-fence-value rule is a small function with a test; - the suite was run on this head (3013 passed, 0 failed, 52 ignored), and the smoke block names it. Nothing blocks it. <details><summary>Checked and fine</summary> - Earlier finding fixed: the idle release depended on the fence thread waking. `WaitForSingleObject` now takes `download_poll_wait_ms()`: `DOWNLOAD_POOL_IDLE_US / 8` (250 ms) while `buffer_bytes != 0`, otherwise `INFINITE` as before. Idle command sets alone do not shorten the wait. `download_pool_limits_the_trim_wait_only_while_a_buffer_is_idle` covers both cases. - Earlier finding fixed: the fence-value reuse was untested. `next_download_fence_value` gives `last + 1` and retires the set before `u64::MAX`, the device-removal sentinel. `a_pooled_download_fence_counts_up_and_is_retired_before_the_removal_sentinel` covers both ends. - Earlier nit fixed: **Tested** reports the whole suite on `2f806d33`. - `download_poll_wait_ms` takes the pool lock, a leaf lock, only to read `buffer_bytes`, before the wait. - The pool, trim and fence handling are otherwise the same as at `60f04988`. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
Gevroska commented 2026-12-03 11:15:11 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Gevroska on 2026-12-03T11:15:11Z.


@BBareth I followed up on 2f806d33 with a test-only fixture on my RTX 3080. Two texture downloads completed on the same direct queue. At fence 1, all 4,096 R8 texels read back as 0x21; at fence 2, all 4,096 read back as 0xC4. The second download reused the same readback buffer, command allocator, command list, and private fence.

After returning the buffer to the pool, the fixture supplied one wake. The production worker then used its 250 ms timed wait and reclaimed the idle buffer without another test wake or a direct trim call. I first observed the pooled readback count fall from 65,536 bytes to zero at 2.13 seconds idle, with one reusable command set retained.

The native check and both CPU controls passed with zero skips. This confirms reclamation once the worker has been woken. The source of that first wake in production remains untested.

AI disclosure: OpenAI Codex GPT-6.2 Sol adapted the fixture and ran the tests. A separate GPT-6.2 Sol reviewer verified the evidence. GPT-6.2 Astra drafted this comment.

I reviewed and approved this comment before posting.

<!-- greyfinch-sync:ivall/xcl:comment:7376428811 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7376428811). Originally posted by [Gevroska](https://github.com/Gevroska) on 2026-12-03T11:15:11Z. --- @BBareth I followed up on `2f806d33` with a test-only fixture on my RTX 3080. Two texture downloads completed on the same direct queue. At fence 1, all 4,096 R8 texels read back as `0x21`; at fence 2, all 4,096 read back as `0xC4`. The second download reused the same readback buffer, command allocator, command list, and private fence. After returning the buffer to the pool, the fixture supplied **one wake**. The production worker then used its 250 ms timed wait and reclaimed the idle buffer without another test wake or a direct trim call. I first observed the pooled readback count fall from 65,536 bytes to zero at **2.13 seconds idle**, with one reusable command set retained. The native check and both CPU controls passed with zero skips. This confirms reclamation once the worker has been woken. The source of that first wake in production remains untested. AI disclosure: OpenAI Codex GPT-6.2 Sol adapted the fixture and ran the tests. A separate GPT-6.2 Sol reviewer verified the evidence. GPT-6.2 Astra drafted this comment. I reviewed and approved this comment before posting.
BBareth commented 2026-12-03 13:05:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T13:05:40Z.


Thanks for running the fixture. On where the first wake comes from in production: the fences' thread waits on one auto-reset event, and three things arm it:

  • each download's own private fence (tie_downloads → ticket.arm);
  • the title fence value the download batch is tied to (SetEventOnCompletion at the end of tie_downloads);
  • the completed-value mirrors of the title's fences (fence_x::arm).

So the download's own completion wakes the thread. If the thread publishes it, the buffer is back in the pool before its next wait, and that wait is the 250 ms one.

Your question did show a gap. A title thread can publish the download too (safe_fence_value from the hooked GetCompletedValue) and return the buffer after the fences' thread has already chosen an unlimited wait. Then the buffer waited for the next fence event, which is every frame while the title renders, but nothing once it stops.

7fa1f2b6 closes that: a buffer returned to an empty pool sets the event once (trim_wait_started, with the_first_idle_buffer_wakes_the_trimming_thread for the rule). Suite on 7fa1f2b6: 3014 passed, 0 failed, 52 ignored (28 SKIPPED). The regression run in the description is of 7fa1f2b6.

Claude Code (Claude Opus 5.5).

<!-- greyfinch-sync:ivall/xcl:comment:7379304491 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7379304491). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T13:05:40Z. --- Thanks for running the fixture. On where the first wake comes from in production: the fences' thread waits on one auto-reset event, and three things arm it: - each download's own private fence (`tie_downloads` → `ticket.arm`); - the title fence value the download batch is tied to (`SetEventOnCompletion` at the end of `tie_downloads`); - the completed-value mirrors of the title's fences (`fence_x::arm`). So the download's own completion wakes the thread. If the thread publishes it, the buffer is back in the pool before its next wait, and that wait is the 250 ms one. Your question did show a gap. A title thread can publish the download too (`safe_fence_value` from the hooked `GetCompletedValue`) and return the buffer after the fences' thread has already chosen an unlimited wait. Then the buffer waited for the next fence event, which is every frame while the title renders, but nothing once it stops. 7fa1f2b6 closes that: a buffer returned to an empty pool sets the event once (`trim_wait_started`, with `the_first_idle_buffer_wakes_the_trimming_thread` for the rule). Suite on 7fa1f2b6: 3014 passed, 0 failed, 52 ignored (28 SKIPPED). The regression run in the description is of 7fa1f2b6. <sub>Claude Code (Claude Opus 5.5).</sub>
Foniass commented 2026-12-03 13:07:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T13:07:40Z.


Follow-up review of 7fa1f2b6, since 2f806d33 (code reading only, not a merge-check) · no new findings

In short: This push closes the last gap in the idle release. When a title thread publishes a download and returns its readback buffer to an empty pool, it sets the fence thread's event once, so a thread sleeping with no limit wakes and starts its 250 ms trim waits. A test covers it, and nothing blocks the PR.

Checked and fine
  • Drop for PendingDownload reads trim_wait_ms() before and after put under the pool lock, and sets the event only when the wait goes from no limit to a limit (trim_wait_started). A second buffer does not wake it again. The event is set after the pool lock is dropped.
  • fence_x::wake_event returns the same auto-reset event the xcl-fences thread waits on. It is created with that thread on first use, as before.
  • An incomplete download still forgets its objects without touching the pool.
  • The rest is the same as at 2f806d33.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7379353665 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7379353665). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-03T13:07:40Z. --- **Follow-up review** of `7fa1f2b6`, since `2f806d33` (code reading only, not a merge-check) · no new findings **In short:** This push closes the last gap in the idle release. When a title thread publishes a download and returns its readback buffer to an empty pool, it sets the fence thread's event once, so a thread sleeping with no limit wakes and starts its 250 ms trim waits. A test covers it, and nothing blocks the PR. <details><summary>Checked and fine</summary> - `Drop for PendingDownload` reads `trim_wait_ms()` before and after `put` under the pool lock, and sets the event only when the wait goes from no limit to a limit (`trim_wait_started`). A second buffer does not wake it again. The event is set after the pool lock is dropped. - `fence_x::wake_event` returns the same auto-reset event the `xcl-fences` thread waits on. It is created with that thread on first use, as before. - An incomplete download still forgets its objects without touching the pool. - The rest is the same as at `2f806d33`. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
Gevroska commented 2026-12-03 15:54:43 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Gevroska on 2026-12-03T15:54:43Z.


@BBareth I retested the part my previous fixture had to supply manually. On 7fa1f2b6, returning the first completed 64 KiB buffer to an empty pool woke the fence worker in all three trials. Its next wait was 250 ms.

Returning a second buffer while the pool still held the first produced no extra signal. The worker reclaimed both buffers 2.024–2.101 seconds after the second return. Returning another completed buffer after the pool emptied woke it again. On the old head (2f806d33), the first buffer was still retained after 2.25 seconds in all three trials and drained once the fixture supplied a signal.

I used the publisher and worker code from each revision with a real Windows auto-reset event, controlled fence values, and resource stand-ins. That directly answers the first-wake question left open by my earlier GPU test.

AI disclosure: OpenAI Codex GPT-6.2 Sol ran the Windows comparison. An independent Codex reviewer checked all six trial logs. GPT-6.2 Astra drafted this comment.

I reviewed and approved this comment before posting.

<!-- greyfinch-sync:ivall/xcl:comment:7383939693 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3514#issuecomment-7383939693). Originally posted by [Gevroska](https://github.com/Gevroska) on 2026-12-03T15:54:43Z. --- @BBareth I retested the part my previous fixture had to supply manually. On `7fa1f2b6`, returning the first completed 64 KiB buffer to an empty pool woke the fence worker in all three trials. Its next wait was 250 ms. Returning a second buffer while the pool still held the first produced no extra signal. The worker reclaimed both buffers **2.024–2.101 seconds after the second return**. Returning another completed buffer after the pool emptied woke it again. On the old head (`2f806d33`), the first buffer was still retained after 2.25 seconds in all three trials and drained once the fixture supplied a signal. I used the publisher and worker code from each revision with a real Windows auto-reset event, controlled fence values, and resource stand-ins. That directly answers the first-wake question left open by my earlier GPU test. AI disclosure: OpenAI Codex GPT-6.2 Sol ran the Windows comparison. An independent Codex reviewer checked all six trial logs. GPT-6.2 Astra drafted this comment. I reviewed and approved this comment before posting.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3514:upstream-pr/3514'
git switch 'upstream-pr/3514'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3514'
git switch 'upstream-pr/3514'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3514'
git switch 'upstream-pr/3514'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3514'
git switch 'main'
git merge --squash 'upstream-pr/3514'
git switch 'main'
git merge --ff-only 'upstream-pr/3514'
git switch 'main'
git merge 'upstream-pr/3514'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!3514
No description provided.