GPU: release unused depth-twin scratch buffers via Weak cache and keep 1 spare placement heap #3454

Open
Luislariosss wants to merge 1 commit from upstream-pr/3454 into main
Luislariosss commented 2026-11-27 03:09:02 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Luislariosss on 2026-11-27T03:09:02Z.


Summary

Reclaims idle D3D12 DEFAULT-heap memory from depth-twin scratch buffers and spare texture-placement heaps:

  1. Weak-referenced depth-twin scratch cache (twin.rs): SCRATCH previously held strong ID3D12Resource references for every power-of-two size class ever created, keeping all scratch buffers alive for the lifetime of the process even after the twins using them were destroyed. Storing Weak<SharedScratch> in SCRATCH and Arc<SharedScratch> on Twin preserves full sharing among live twins of the same size class while automatically releasing the ID3D12Resource once the last Twin referencing it drops. Buffer creation and any duplicate drop also run outside SCRATCH.lock().
  2. Texture placement spare heap (placement.rs): lower SPARE from 2 (128 MiB of idle 64 MiB DEFAULT heaps) to 1 (64 MiB), returning an extra 64 MiB once textures are evicted while keeping one warm heap to avoid churn at a heap boundary.

Validation

  • cargo test -p victory-gpu --lib -- twin:: placement::: 5/5 passed (including new shared_scratch_reuses_live_buffer_and_releases_when_last_owner_drops).
  • cargo clippy -p victory-gpu --all-targets -- -D warnings (default and --features diagnostics): clean.
  • cargo xtask policy: 191 files ok.
<!-- greyfinch-sync:Marvisak/VIctory:issue:5520498780 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3454). Originally posted by [Luislariosss](https://github.com/Luislariosss) on 2026-11-27T03:09:02Z. --- ### Summary Reclaims idle D3D12 `DEFAULT`-heap memory from depth-twin scratch buffers and spare texture-placement heaps: 1. **Weak-referenced depth-twin scratch cache (`twin.rs`)**: `SCRATCH` previously held strong `ID3D12Resource` references for every power-of-two size class ever created, keeping all scratch buffers alive for the lifetime of the process even after the twins using them were destroyed. Storing `Weak<SharedScratch>` in `SCRATCH` and `Arc<SharedScratch>` on `Twin` preserves full sharing among live twins of the same size class while automatically releasing the `ID3D12Resource` once the last `Twin` referencing it drops. Buffer creation and any duplicate drop also run outside `SCRATCH.lock()`. 2. **Texture placement spare heap (`placement.rs`)**: lower `SPARE` from `2` (128 MiB of idle 64 MiB `DEFAULT` heaps) to `1` (64 MiB), returning an extra 64 MiB once textures are evicted while keeping one warm heap to avoid churn at a heap boundary. ### Validation - `cargo test -p victory-gpu --lib -- twin:: placement::`: 5/5 passed (including new `shared_scratch_reuses_live_buffer_and_releases_when_last_owner_drops`). - `cargo clippy -p victory-gpu --all-targets -- -D warnings` (default and `--features diagnostics`): clean. - `cargo xtask policy`: 191 files ok.
Luislariosss commented 2026-11-27 03:16:59 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Luislariosss on 2026-11-27T03:16:59Z.


Note: the only CI failure on run \45932472460\ (231/232 passed) is the unrelated timing-sensitive test \ ictory-gpu::frame::tests::waits_end_on_ticks_and_count_frames\ (this PR only touches \placement.rs\ and \ win.rs). Could a maintainer re-run the failed job?

<!-- greyfinch-sync:Marvisak/VIctory:comment:7208857845 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3454#issuecomment-7208857845). Originally posted by [Luislariosss](https://github.com/Luislariosss) on 2026-11-27T03:16:59Z. --- Note: the only CI failure on run \45932472460\ (231/232 passed) is the unrelated timing-sensitive test \ ictory-gpu::frame::tests::waits_end_on_ticks_and_count_frames\ (this PR only touches \placement.rs\ and \ win.rs\). Could a maintainer re-run the failed job?
oni-swr commented 2026-11-27 03:27:24 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by oni-swr on 2026-11-27T03:27:24Z.


WARP test report (AI-assisted with Claude; synthetic tests only, no game files)

  • Head: e746a9e1986f82e907c5d9a6388affa4e1c0ea7a, base: origin/main @ 63bcca4 (this PR's merge base)
  • Windows 11 Pro, build 10.0.26200; D3D12 on WARP only (VICTORY_WARP=1, VICTORY_D3D12_WARP=1, adapter vendor 0x1414 / software flag), DXIL validator dxil.dll from the Windows SDK 10.0.26100
  • Note: VICTORY_D3D12_WARP is only honored with --features diagnostics (host.rs create()); without it cargo test -p victory-gpu --lib picks the hardware GPU. I ran with --features diagnostics.
  • cargo test -p victory-gpu --lib --locked --features diagnostics: 247 passed, 0 failed, 1 ignored (base: 246/0/1; +1 is twin::tests::shared_scratch_reuses_live_buffer_and_releases_when_last_owner_drops, which passes with a WARP device)
  • No new failures vs base. waits_end_on_ticks_and_count_frames passed on base and on this head here, so it looks like the timing flake mentioned in the CI note (not caused by this change). I did not re-run clippy.

Review: no failure found, one point to check. Before, the shared scratch buffer lived for the whole process, so no submission could lose it. Now the ID3D12Resource is released as soon as the last Twin drops. If a recorded or running list still copies through it, that is a use-after-release unless the owning Resource is already dropped only after the GPU is done; host::retire exists for this. I did not verify the drop timing of Resource::twin, so please confirm or retire the buffer. The test returns early when there is no host device; it did run here.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7209002402 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3454#issuecomment-7209002402). Originally posted by [oni-swr](https://github.com/oni-swr) on 2026-11-27T03:27:24Z. --- **WARP test report** (AI-assisted with Claude; synthetic tests only, no game files) - Head: `e746a9e1986f82e907c5d9a6388affa4e1c0ea7a`, base: `origin/main` @ `63bcca4` (this PR's merge base) - Windows 11 Pro, build 10.0.26200; D3D12 on WARP only (`VICTORY_WARP=1`, `VICTORY_D3D12_WARP=1`, adapter vendor 0x1414 / software flag), DXIL validator `dxil.dll` from the Windows SDK 10.0.26100 - Note: `VICTORY_D3D12_WARP` is only honored with `--features diagnostics` (`host.rs` `create()`); without it `cargo test -p victory-gpu --lib` picks the hardware GPU. I ran with `--features diagnostics`. - `cargo test -p victory-gpu --lib --locked --features diagnostics`: **247 passed, 0 failed, 1 ignored** (base: 246/0/1; +1 is `twin::tests::shared_scratch_reuses_live_buffer_and_releases_when_last_owner_drops`, which passes with a WARP device) - No new failures vs base. `waits_end_on_ticks_and_count_frames` passed on base and on this head here, so it looks like the timing flake mentioned in the CI note (not caused by this change). I did not re-run clippy. **Review:** no failure found, one point to check. Before, the shared scratch buffer lived for the whole process, so no submission could lose it. Now the `ID3D12Resource` is released as soon as the last `Twin` drops. If a recorded or running list still copies through it, that is a use-after-release unless the owning `Resource` is already dropped only after the GPU is done; `host::retire` exists for this. I did not verify the drop timing of `Resource::twin`, so please confirm or retire the buffer. The test returns early when there is no host device; it did run here.
futurepro62 commented 2026-11-27 08:47:48 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by futurepro62 on 2026-11-27T08:47:48Z.


NVIDIA full-suite run, to go with the reports above by oni-swr, since none of them names a GPU run. Tested exact head e746a9e (on its base 63bcca4).

Tested

  • NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 621.40, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.98.1 MSVC (pinned), dxil.dll from Windows SDK 10.0.26100 (the loader's default), debug.
  • cargo build --workspace --locked, then cargo test --workspace --locked --no-fail-fast -- --test-threads=4 --skip emit::memory_tests::heap_direct_texture_reads_mark_their_heap_index --skip descriptor::host::tests::dynamic_slots_are_held_until_released --skip memory::tests::lists_share_a_table_and_copies_keep_their_views --skip emit::stride_tests::a_heap_buffer_read_by_element_takes_the_views_stride --skip emit::stride_tests::a_heap_buffer_read_where_no_buffer_view_is_reads_zeros --skip emit::synthetic_tests::gathers_at_a_level_match_the_hardware: 867 passed, 0 failed, 10 ignored.
  • The new tests ran and passed: shared_scratch_reuses_live_buffer_and_releases_when_last_owner_drops.
  • --skip leaves out tests that fail on main 63bcca4 on this card too, not because of this PR: heap_direct_texture_reads_mark_their_heap_index ends the victory-shader test process with 0xc0000005 (#2571), so without the skip the rest of that crate never reports; dynamic_slots_are_held_until_released, lists_share_a_table_and_copies_keep_their_views and the two stride_tests hit the 1,000,000-view heap cap of NVIDIA drivers (#1835, #2317); gathers_at_a_level_match_the_hardware fails on lane 0 (#1744).

Not tested

  • AMD (the tests take the default adapter), a release build, the title (test run only).

AI use

  • Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.
<!-- greyfinch-sync:Marvisak/VIctory:comment:7213930850 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3454#issuecomment-7213930850). Originally posted by [futurepro62](https://github.com/futurepro62) on 2026-11-27T08:47:48Z. --- NVIDIA full-suite run, to go with the reports above by oni-swr, since none of them names a GPU run. Tested exact head `e746a9e` (on its base `63bcca4`). **Tested** - NVIDIA GeForce RTX 5070 Ti 16 GB (Blackwell, 32-lane waves only, mesh shaders), driver 621.40, Ryzen 7 9800X3D, Windows 11 Home 26300, Rust 1.98.1 MSVC (pinned), `dxil.dll` from Windows SDK 10.0.26100 (the loader's default), debug. - `cargo build --workspace --locked`, then `cargo test --workspace --locked --no-fail-fast -- --test-threads=4 --skip emit::memory_tests::heap_direct_texture_reads_mark_their_heap_index --skip descriptor::host::tests::dynamic_slots_are_held_until_released --skip memory::tests::lists_share_a_table_and_copies_keep_their_views --skip emit::stride_tests::a_heap_buffer_read_by_element_takes_the_views_stride --skip emit::stride_tests::a_heap_buffer_read_where_no_buffer_view_is_reads_zeros --skip emit::synthetic_tests::gathers_at_a_level_match_the_hardware`: **867 passed, 0 failed, 10 ignored**. - The new tests ran and passed: `shared_scratch_reuses_live_buffer_and_releases_when_last_owner_drops`. - `--skip` leaves out tests that fail on main `63bcca4` on this card too, not because of this PR: `heap_direct_texture_reads_mark_their_heap_index` ends the `victory-shader` test process with `0xc0000005` (#2571), so without the skip the rest of that crate never reports; `dynamic_slots_are_held_until_released`, `lists_share_a_table_and_copies_keep_their_views` and the two `stride_tests` hit the 1,000,000-view heap cap of NVIDIA drivers (#1835, #2317); `gathers_at_a_level_match_the_hardware` fails on lane 0 (#1744). **Not tested** - AMD (the tests take the default adapter), a release build, the title (test run only). **AI use** - Claude Code (Claude Opus 5.5) ran the tests and wrote this report. I checked it before posting.
reallyvibe commented 2026-11-29 01:47:21 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by reallyvibe on 2026-11-29T01:47:21Z.


On oni-swr's open point (scratch release versus in-flight work): the list keeps the scratch alive until its reset, with a test

oni-swr asked whether the scratch buffer can now be released while a recorded or running list still copies through it. Reading this head e746a9e1, the ownership chain prevents that. The two paths that record a copy through scratch are twin::route and the submission prelude. Both start from the list's own twin use: route calls HostList::twin_use, which stores the Arc<HostTexture> in twins, and the prelude takes its copies from that same twins map. The Twin lives inside that HostTexture, and the Arc<SharedScratch> inside the Twin. twins is cleared only in HostList::reset, which runs after the list's last submission finished. So the scratch has the same lifetime guarantee as the twin's planes, which already drop with the Twin on main.

I checked this with a test written against this head; you're welcome to add it:

    /// A twin's scratch buffer, released with its last twin, stays alive
    /// while a list that recorded a copy through it holds the depth texture,
    /// and goes once that list is reset (after its last submission finished).
    #[test]
    fn scratch_outlives_the_lists_that_copy_through_it() {
        let Some(host) = host() else {
            return; // no host GPU here
        };
        let desc = D3D12_RESOURCE_DESC {
            Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
            Width: 64,
            Height: 64,
            DepthOrArraySize: 1,
            MipLevels: 1,
            Format: DXGI_FORMAT_R16_TYPELESS,
            SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
            Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
            ..Default::default()
        };
        let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
        let mut texture: Option<ID3D12Resource> = None;
        // SAFETY: plain creation; our out pointer.
        unsafe { host.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, None, &mut texture) }.unwrap();
        let depth = Arc::new(HostTexture::new(texture.unwrap(), DEPTH_WRITE, Vec::new()));
        let list = host.new_list().unwrap();
        let scratch = {
            let twin = depth.twin.get_or_init(|| make(53, &depth.texture)).as_ref().unwrap();
            // The twin written, then the depth texture read: a copy through
            // the scratch buffer is recorded into the list.
            assert!(route(&list, &depth, twin, UNORDERED_ACCESS));
            const PIXEL_SHADER_RESOURCE: u32 = 0x80;
            assert!(!route(&list, &depth, twin, PIXEL_SHADER_RESOURCE));
            Arc::downgrade(&twin.scratch)
        };
        drop(depth);
        assert!(scratch.upgrade().is_some(), "the list holds the twin, so its scratch");
        list.close();
        host.execute(&[&list]);
        assert!(scratch.upgrade().is_some(), "held until the list is reset");
        list.reset();
        assert!(scratch.upgrade().is_none(), "released with the list's last hold");
    }

With it, WARP twin:: + placement:: pass 6/6. cargo build -p victory-gpu --lib and cargo clippy -p victory-gpu --all-targets -- -D warnings (default and --all-features) are clean. Run alone, the test fails if either side is undone:

change fails
an extra strong reference kept to the scratch (main's lifetime) this test ("released with the list's last hold") and this PR's shared_scratch_reuses_live_buffer_and_releases_when_last_owner_drops
twin_use does not keep the list's use this test ("the list holds the twin, so its scratch")

What this validates, and what it doesn't: on WARP, the test shows the CPU-side ownership chain (list → HostTexture → Twin → Arc<SharedScratch>) keeps the buffer alive until reset. That the GPU has finished with the buffer by then rests on HostList::reset's contract (it runs only after the list's last submission finished) and on host.execute waiting for that. I didn't run this on a hardware GPU, and the test doesn't observe GPU completion itself.

This head merges cleanly with 11 open PRs on main 63bcca43 that touch twin.rs or placement.rs. Only four of their diffs mention scratch, all through the unchanged scratch_buffer or in comments (#3409's and #3064's tests, doc lines in #2973 and #2969), and #2955 only rewords SPARE's doc. #3447, #3360, #3266, #2919 and #1964 conflict textually.

Windows 11, Ryzen 7 7445HS, WARP, synthetic data only.

AI-assisted (Claude Code).

<!-- greyfinch-sync:Marvisak/VIctory:comment:7249013260 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3454#issuecomment-7249013260). Originally posted by [reallyvibe](https://github.com/reallyvibe) on 2026-11-29T01:47:21Z. --- **On oni-swr's open point (scratch release versus in-flight work): the list keeps the scratch alive until its reset, with a test** oni-swr asked whether the scratch buffer can now be released while a recorded or running list still copies through it. Reading this head `e746a9e1`, the ownership chain prevents that. The two paths that record a copy through `scratch` are `twin::route` and the submission prelude. Both start from the list's own twin use: `route` calls `HostList::twin_use`, which stores the `Arc<HostTexture>` in `twins`, and the prelude takes its copies from that same `twins` map. The `Twin` lives inside that `HostTexture`, and the `Arc<SharedScratch>` inside the `Twin`. `twins` is cleared only in `HostList::reset`, which runs after the list's last submission finished. So the scratch has the same lifetime guarantee as the twin's planes, which already drop with the `Twin` on main. I checked this with a test written against this head; you're welcome to add it: ```rust /// A twin's scratch buffer, released with its last twin, stays alive /// while a list that recorded a copy through it holds the depth texture, /// and goes once that list is reset (after its last submission finished). #[test] fn scratch_outlives_the_lists_that_copy_through_it() { let Some(host) = host() else { return; // no host GPU here }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R16_TYPELESS, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, ..Default::default() }; let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let mut texture: Option<ID3D12Resource> = None; // SAFETY: plain creation; our out pointer. unsafe { host.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, None, &mut texture) }.unwrap(); let depth = Arc::new(HostTexture::new(texture.unwrap(), DEPTH_WRITE, Vec::new())); let list = host.new_list().unwrap(); let scratch = { let twin = depth.twin.get_or_init(|| make(53, &depth.texture)).as_ref().unwrap(); // The twin written, then the depth texture read: a copy through // the scratch buffer is recorded into the list. assert!(route(&list, &depth, twin, UNORDERED_ACCESS)); const PIXEL_SHADER_RESOURCE: u32 = 0x80; assert!(!route(&list, &depth, twin, PIXEL_SHADER_RESOURCE)); Arc::downgrade(&twin.scratch) }; drop(depth); assert!(scratch.upgrade().is_some(), "the list holds the twin, so its scratch"); list.close(); host.execute(&[&list]); assert!(scratch.upgrade().is_some(), "held until the list is reset"); list.reset(); assert!(scratch.upgrade().is_none(), "released with the list's last hold"); } ``` With it, WARP `twin::` + `placement::` pass 6/6. `cargo build -p victory-gpu --lib` and `cargo clippy -p victory-gpu --all-targets -- -D warnings` (default and `--all-features`) are clean. Run alone, the test fails if either side is undone: | change | fails | |---|---| | an extra strong reference kept to the scratch (main's lifetime) | this test ("released with the list's last hold") and this PR's `shared_scratch_reuses_live_buffer_and_releases_when_last_owner_drops` | | `twin_use` does not keep the list's use | this test ("the list holds the twin, so its scratch") | What this validates, and what it doesn't: on WARP, the test shows the CPU-side ownership chain (list → `HostTexture` → `Twin` → `Arc<SharedScratch>`) keeps the buffer alive until `reset`. That the GPU has finished with the buffer by then rests on `HostList::reset`'s contract (it runs only after the list's last submission finished) and on `host.execute` waiting for that. I didn't run this on a hardware GPU, and the test doesn't observe GPU completion itself. This head merges cleanly with 11 open PRs on main `63bcca43` that touch `twin.rs` or `placement.rs`. Only four of their diffs mention scratch, all through the unchanged `scratch_buffer` or in comments (#3409's and #3064's tests, doc lines in #2973 and #2969), and #2955 only rewords `SPARE`'s doc. #3447, #3360, #3266, #2919 and #1964 conflict textually. Windows 11, Ryzen 7 7445HS, WARP, synthetic data only. AI-assisted (Claude Code).
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/3454:upstream-pr/3454'
git switch 'upstream-pr/3454'

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/3454'
git switch 'upstream-pr/3454'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3454'
git switch 'upstream-pr/3454'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3454'
git switch 'main'
git merge --squash 'upstream-pr/3454'
git switch 'main'
git merge --ff-only 'upstream-pr/3454'
git switch 'main'
git merge 'upstream-pr/3454'
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
Marvisak/VIctory!3454
No description provided.