Skip to content

GPU: reclaim idle snapshot and texture staging pools and compact pipeline/heap metadata - #3230

Open
0xKaji wants to merge 3 commits into
Marvisak:mainfrom
0xKaji:perf/reclaim-idle-pools-and-metadata
Open

0xKaji wants to merge 3 commits into
Marvisak:mainfrom
0xKaji:perf/reclaim-idle-pools-and-metadata

Conversation

@0xKaji

@0xKaji 0xKaji commented Nov 26, 2026

Copy link
Copy Markdown

Summary

Reclaims idle host memory held by internal pools and metadata after loading spikes, without lowering burst ceilings or regressing active frame performance.

Changes

  • Idle-window trimming for shadow::POOL (shadow.rs, host.rs): Keeps the 512 MiB burst ceiling (POOL_BYTES), but tracks peak live demand across 128-submission windows (trim_snapshot_pool() called once per submission in Host::execute) and trims excess pooled buffers down to recent peak demand (floor POOL_SPARE_BYTES = 32 MiB).
  • Idle-window trimming for texture::BUFFERS and bounded per-thread Scratch (texture.rs): Trims BUFFERS.free down to recent 64-submission peak usage (floor 8 MiB, ceiling 64 MiB), and caps per-thread Scratch retention at 8 MiB checking capacity() <= KEEP (avoiding 32 MiB/thread permanent retention).
  • Release boot-time Heap::pending vector (descriptor.rs): Uses std::mem::take(&mut *pending) when initializing HostHeap so the boot-time Vec<u32> capacity is freed immediately.
  • Compact library::CREATED (pipeline/library.rs): Stores 16-byte BLAKE3 key prefixes ([u8; 16]) instead of heap-allocated Strings for 60k+ created pipeline keys.
  • Tighter BITMAP_POOL_CAP (memory.rs): Lowers the idle dirty-page bitmap pool cap from 64 (16 MiB) to 16 (4 MiB).

Verification

  • cargo xwin clippy --workspace --all-targets --locked --target x86_64-pc-windows-msvc -- -D warnings
  • cargo xwin clippy --workspace --all-targets --all-features --locked --target x86_64-pc-windows-msvc -- -D warnings
  • cargo test -p xtask --locked (6/6 passed)
  • Wine unit tests: snapshot_pool_trims_after_idle_window, note_created_counts_total_and_distinct_keys, mark_runs_are_reused_and_joined, memory::tests::bitmap_pool_reuses_and_zeroes_across_resets + 5 non-DXC memory::tests passed (9/11 passed; the 2 DXC-dependent memory::tests fail on Wine's d3dcompiler_47 due to pre-existing E5017: Unbounded resource arrays).

Partial Overlaps / Related PRs

  • #2153 and #472 also touch shadow::POOL (lowering the hard cap or draining on allocation failure); this PR preserves the 512 MiB burst cap and trims only after idle submission windows.
  • #2972 trims texture::Chunks, HostList::scratch, and shadow::Arena; this PR covers the complementary texture::BUFFERS, per-thread texture::Scratch, shadow::POOL, Heap::pending, library::CREATED, and memory::BITMAP_POOL_CAP.

@Dukestar69 Dukestar69 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Verified on RTX 5090 against origin/main (63bcca4):

  • cargo test -p victory-gpu --lib shadow:: -- --test-threads=1: 11/11 passed (including snapshot_pool_trims_after_idle_window).
  • cargo test -p victory-gpu --lib pipeline:: -- --test-threads=1: 24/24 passed (including note_created_counts_total_and_distinct_keys); texture::: 2/2 passed.
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Cleanly reclaims idle snapshot/staging pools and compacts pipeline/heap metadata.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

@potatoe0100

Copy link
Copy Markdown

Tested d2d85cb merged onto main 63bcca4 on an RTX 4060 8 GB (driver 621.14, i5-13600KF, Windows 11 Pro 26300). No game files. cargo test -p victory-gpu --lib --locked -- --test-threads=1 gives 231 passed and 2 failed. The new snapshot_pool_trims_after_idle_window and note_created_counts_total_and_distinct_keys pass. The 2 failures are the known capped-heap ones (#1835), the same as on main with this card.

Two things from reading it:

  1. SnapshotPool::live_bytes can only drift upward. take adds a buffer's capacity and give_back subtracts it. But snapshot segments only go back through give_back in Shadow::snapshot (merging) and when pending empties. impl Drop for Shadow returns its slice and marks, not segments. So if a copy is dropped while a snapshot is still pending, its bytes stay counted as live forever. step_window then sets peak_bytes = live_bytes, so over a long session the trim budget creeps up to POOL_BYTES and stops trimming. That's harmless, but it's the opposite of what the PR is for. One option is to count the bytes taken within each window instead of a running live total, so nothing has to be given back to keep the count right.
  2. Scratch keep limit 32 MiB → 8 MiB. A 2048×2048 RGBA8 texture needs a 16 MiB scratch, so those are no longer reused. On this CPU, a fresh 16 MiB Vec filled once costs 4.8 ms, against 0.7 ms reused, because of first-touch page faults (8 MiB: 2.1 vs 0.5 ms; 32 MiB: 7.3 vs 1.8 ms; a standalone rustc -O loop, median of 20). That's about 4 ms more per such texture on the thread preparing the frame, while streaming. Unless the 24 MiB per thread is a real problem, 16 MiB, or keeping the old 32 MiB with the len → capacity fix, may be a safer default. The capacity fix itself looks right.

AI-assisted (Claude)

@0xKaji

0xKaji commented Nov 26, 2026

Copy link
Copy Markdown
Author

Thanks for catching both! Updated PR #3230:

  1. Replaced SnapshotPool::live_bytes with per-submission submission_bytes (reset each step_window()), so a dropped Shadow with pending snapshots cannot leak into peak_bytes and defeat idle trimming; updated snapshot_pool_trims_after_idle_window to cover a dropped buffer.
  2. Raised texture::Scratch KEEP from 8 MiB to 16 MiB (still checking capacity() <= KEEP) so 2048x2048 RGBA8 textures reuse their scratch buffer without page faults.

@fuzeofficlal fuzeofficlal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed and verified bc4382251a2ec76003877fdd1f787acb4d9bb6c8 on both RTX 5090 and WARP with VICTORY_D3D12_DEBUG=1.

Checks run:

  • cargo xtask policy — pass
  • cargo clippy --tests -p victory-gpu -- -D warnings (default and --features diagnostics) — clean
  • shadow::tests (10/10), pipeline::library::tests (12/12), texture::tests (2/2), memory::tests (8/8 on WARP, 7/7 on RTX 5090 excluding the pre-existing lists_share_a_table_and_copies_keep_their_views baseline failure), descriptor::tests (7/7 on WARP) — all pass with 0 D3D12 Debug Layer errors
  • Live probe exercising texture::recycle() across two 64-submission windows (36 MiB -> 36 MiB -> 4 MiB under the 8 MiB spare cap) and Scratch's 16 MiB capacity() retention check — passes cleanly on both RTX 5090 and WARP with 0 Debug Layer errors.

Lifetimes and locking look sound: texture::recycle() runs in bindless::uploads (bindless.rs:204) before the next submission's uploads once the prior submission has completed, shadow::trim_snapshot_pool() runs in host.rs:1429 after GPU completion and release_retired(), and std::mem::take(&mut *pending) (descriptor.rs:101) releases the pending vector's capacity while holding the lock before publishing OnceLock.

One non-blocking edge case worth polishing in a follow-up (crates/victory-gpu/src/shadow.rs:132-139):

  • In SnapshotPool::trim_to, total += v.capacity(); total <= max_bytes keeps adding dropped buffers' capacities into total. Since buffers are sorted descending, if a single pooled buffer exceeds budget (e.g. [64 MiB, 16 MiB, 8 MiB] trimmed to POOL_SPARE_BYTES = 32 MiB), total jumps to 64 MiB on the first buffer and evicts the 16 MiB and 8 MiB buffers as well (emptying the pool to 0 bytes instead of retaining 24 MiB of warm spare buffers). Guarding the increment fixes it:
    self.buffers.retain(|v| {
        if total + v.capacity() <= max_bytes {
            total += v.capacity();
            true
        } else {
            false
        }
    });

LGTM!

@pickles976

Copy link
Copy Markdown

Wine verification at clean exact head bc4382251a2ec76003877fdd1f787acb4d9bb6c8, base 63bcca43c6a00a758510398fa43096ce7e4f7df0:

VICTORY_SOURCE_DIR="$PWD/VIctory-pr3230" \
 /usr/bin/bash .compat-tools/cargo-victory-wine.sh \
 test -p victory-gpu --lib shadow::tests::snapshot_pool_trims_after_idle_window \
 -- --exact --nocapture --test-threads=1

1 passed,0 failed/ignored,0.00s reported test time; fresh compilation8.12s from the intended checkout, total guarded command8.85s. Rust1.98.1 Windows-MSVC, Wine11/Linux6.17, i7-13620H/15693MiB RAM. CPU ownership/pool policy only: no D3D12 device or GPU execution in this fixture. No source changes; touching crate roots only forced correct shared-target provenance.

The fixture checks the first window retains its96MiB peak demand despite a taken buffer being dropped, and the next idle window trims the two retained32MiB buffers to one. It does not touch/measure all reserved pages, prove an RSS delta, or test title progress.

Evidence: .compat-runtime/logs/verify-pr3230-idle-pool-20261127T012936Z/, including exact command/provenance and machine-readable build/test/resource observations. External9GiB scope/512MiB swap and2048MiB available-RAM floor remained intact.

Not tested: matched base, title, full suite, physical RAM release or staging GPU fences. This bounds/reclaims idle snapshot capacity, not aggregate live shadows/XMem/process RAM. Our older main owner census sampled idle snapshots/standalone staging at zero; that is a different stack/stage, not proof they remain zero in the later scoped-backing stack. No new title trial justified by this isolated pass. The already-discussed oversized-leading-buffer over-trim remains a warm-spare-policy edge, not new evidence from this run.

AI assistance: omp (openai-codex/gpt-6-astra) for verification and reporting.

@0xKaji

0xKaji commented Nov 27, 2026

Copy link
Copy Markdown
Author

Thanks @fuzeofficlal for the review and catching that edge case! Fixed SnapshotPool::trim_to so dropped oversized buffers are not added to total (retaining smaller warm spare buffers within budget), and added snapshot_pool_trim_to_retains_smaller_buffers_past_oversized to cover it.

@reallyvibe

Copy link
Copy Markdown

I benchmarked the snapshot pool at this head (40cbe842) against main (63bcca43), #3442 and #3384 in a CPU-only harness. Pool code is copied verbatim from each head; the caller (Shadow::writing's merge and the copy-back return) is ported once from main, as it is the same at all four heads apart from #3384's POOL. call syntax. trim_snapshot_pool() runs once per submission, as in Host::execute; every 128th call is a trim window (trim_to the window's peak, clamp(32 MiB, 512 MiB)). The workload is synthetic: no game files, no GPU. Claim: #1633 (comment)

The idle trim releases memory in most cases I tried. It has a reload cost, and in one case its trim windows run but evict nothing.

The sequence is load (230 world submissions) → idle (1000 small-only submissions, eight trim windows) → reload (230):

world snapshot idle pool, main → this PR (median) reload re-allocation (median) first reload submission (median over seeds) slowest reload submission (max over 5 seeds)
96 MiB in 4 growth steps 250 → 81 MiB 0 → 242 MiB not recorded not recorded
174 MiB in 4 steps 445 → 139 MiB 0 → 439 MiB 30 → 108 ms (seeds 67–147) 79 → 147 ms
256 MiB, one piece 279 → 21 MiB 4 → 257 MiB 19 → 95 ms (seeds 18–98) 30 → 98 ms
256 MiB in 4 steps 467 → 512 MiB (8 windows, 0 evictions) see below

The cost is re-allocation in the first one or two reload submissions. Observed reload p50 medians were within 0.9 ms of main's; no equivalence test was performed. Maxima varied up to 2.7× between repeated same-seed runs, so the last column is approximate.

Where it does not work: a large set in pieces that fills the 512 MiB cap (256 MiB in 4 growth steps: 64 + 128 + 192 + 256 MiB).

  1. The return rule keeps exactly the cap. trim_to skips buffers that don't fit and keeps smaller ones, so the pool keeps 256 + 192 + 64 = 512 MiB and drops the small buffers returned afterwards. Main's rule stops at the first buffer that crosses the cap (256 + 192, then small buffers). For [400, 200, 64] MiB, main keeps 400 and this PR 400 + 64.
    • 38–40% misses in steady state and reload (50% with the heap in a quarter of submissions), against main's 0–0.1%, with heap-first, heap-last and random return order.
    • With the small buffers in the same submission, 90.6% of the next small takes miss. With the 256 MiB snapshot in a single piece it is 0%.
    • Peak commit is 771 vs 641 MiB: one fresh 256 MiB allocation, because best fit hands the 192 MiB buffer to the 128 MiB request and the 256 MiB buffer to the 192 MiB request.
  2. The idle trim windows run but evict nothing. take adds v.capacity() of what it hands out (self.submission_bytes += v.capacity();). Small requests get the large leftovers, so the window sum reaches the cap and the budget clamps to 512 MiB. All eight idle windows ran, none evicted anything, and 31% of small takes miss. At a smaller scale, an idle period of one 5 MiB snapshot per submission keeps 44 MiB.

40cbe842 added the skip rule on purpose, and it has a measured upside: when the harness returns a quarter of the small shadows one submission late, this PR had the lowest steady miss rate of the six policies I ran (0.1% median, 264 MiB allocated over 460 submissions; main 2.3%, seeds 0.1–11.1%, and 2.3 GiB).

Hypothetical variants, to separate the two effects (not proposals):

variant idle pool (174 / 256 MiB in 4 steps) measured costs
count n instead of capacity 26 / 20 MiB keeps the skip-rule failure; reload at 256 MiB in 4 steps re-allocates 1,628 MiB
main's rule in give_back, window unchanged 139 / 201 MiB no failure in any of the three return orders; with late returns, the same steady misses as main
main's rule and count n 26 / 23 MiB 2.0–2.3× the re-allocation with rare large snapshots, 1.2–6× with mid-size shadows; highest steady misses with late returns (6.2% median)

Each has a measured cost, so I'm not suggesting one. Counting n is closer to the description's "demand", but both counts sum every take in a submission, including growth pieces returned before it ends, so neither is live demand. A live-bytes window held 15–20 MiB at idle and re-allocated more than either count when large snapshots were rare. From the code, not measured: if submissions stop, the window never advances, so nothing is trimmed until they resume.

Limitations: the submission mix is a model, not a capture; marked writes (which skip snapshots) aren't modelled; snapshot lifetimes are the harness's (returned at copy-back, or one submission late), not upstream's (returned when the shadow's last pending range completes, not measured); sizes are assumptions, and 174 MiB is the earlier-discussed heap size; page faults are process-wide, so none are attributed to the pool; pool figures are pool bytes, not process commit, unless "peak commit" is stated; one Windows machine at 79–95% memory load (at run end), single-threaded, 5 seeds per case, no significance test.

With real per-submission snapshot sizes I can rerun.

Harness, pins, scripts, raw results and reproduction steps: 1,240 original runs plus 631 targeted follow-up runs (36 superseded runs kept, labelled). Byte-for-byte snapshot verification: 6,288 submissions, then 96,096 snapshots, 0 failures. Corrections to my earlier write-ups: CORRECTIONS.md.

https://github.com/farhankhan8571811-star/victory-snapshot-pool-bench

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.

6 participants