Skip to content

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

Open
Luislariosss wants to merge 1 commit into
Marvisak:mainfrom
Luislariosss:feat/twin-scratch-reclaim
Open

Luislariosss wants to merge 1 commit into
Marvisak:mainfrom
Luislariosss:feat/twin-scratch-reclaim

Conversation

@Luislariosss

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor Author

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

oni-swr commented Nov 27, 2026

Copy link
Copy Markdown

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

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown

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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants