GPU: let go of the idle snapshot pool, and shrink it under memory pressure #41

Manually merged
github merged 1 commit from github-bot/gh-41 into main 2026-11-26 19:44:32 +00:00 AGit
Owner

@⁠welisonzika14-jpg on GitHub · 2026-11-26 17:58 UTC · original
welisonzika14-jpg:fix/shadow-pool-idle → main · +156 −0 · 1 files · 2 commits · merged 2026-11-26 19:39 UTC

Problem

shadow::POOL keeps snapshot buffers for reuse, up to 512 MiB (give_back, KEPT). Only give_back ever trims it, and only when another buffer comes back. So once snapshots stop, the last 512 MiB stays for the rest of the run, even when the host is short of memory. The largest buffer is always kept (kept > 0), so a single snapshot larger than 512 MiB stays too.

Change

shadow::let_go_idle already runs once a second from host::sweep. It now first calls let_go_idle_snapshots, which does this:

  • When the pool is idle for host::ram_idle_ms and 4 frames (the same rule as the loose windows), it frees all of it.
  • While residency::pressured() holds, it keeps only the smallest buffers, up to 32 MiB (POOL_PRESSURED_KEPT), and frees the rest, largest first.
  • Otherwise it does nothing, and the behaviour is the same as before.

pooled and give_back record the last use in POOL_USED, as a host::moment(). The freeing happens outside the lock, as give_back already does. The next snapshot after a trim is fresh memory, the same as every snapshot past the pool was before. With plenty of free RAM, ram_idle_ms is 5 minutes, so normal play keeps the pool. The FPS cost should only show after an idle stretch or under pressure. I did not measure FPS in game.

Tests

New shadow::pool_tests:

  • trimming_keeps_the_smallest_up_to_the_limit
  • trimming_to_nothing_empties_the_pool
  • a_buffer_past_the_limit_goes_even_alone
  • an_idle_pool_goes_and_a_pressed_one_shrinks
  • pool_memory_load (#[ignore], run alone, because the pool is global):
    cargo test -p victory-gpu --lib shadow::pool_tests::pool_memory_load -- --ignored --nocapture --test-threads=1

Load test on Windows 11 with an RTX 5070, in a debug build. It runs 256 snapshots of 1 to 32 MiB:

State Pool Private bytes over start
Full (main behaviour, stays forever) 520,192 KiB 521,336 KiB
Under pressure (new) ≤ 32 MiB 25,684 KiB
Idle (new) 0 12 KiB

Results:

  • cargo test -p victory-gpu --lib: 401 passed, 0 failed, 37 ignored.
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo clippy -p victory-gpu --all-targets --all-features -- -D warnings: clean.

Related: HumanlyDev/HUMAN#7 also bounds this pool, in a different way. This PR is written separately and is smaller. It touches only shadow.rs.

Written with AI help (Claude/Kiro).

**@⁠welisonzika14-jpg** on GitHub · 2026-11-26 17:58 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/41) `welisonzika14-jpg:fix/shadow-pool-idle` → `main` · +156 −0 · 1 files · 2 commits · merged 2026-11-26 19:39 UTC ## Problem `shadow::POOL` keeps snapshot buffers for reuse, up to 512 MiB (`give_back`, `KEPT`). Only `give_back` ever trims it, and only when another buffer comes back. So once snapshots stop, the last 512 MiB stays for the rest of the run, even when the host is short of memory. The largest buffer is always kept (`kept > 0`), so a single snapshot larger than 512 MiB stays too. ## Change `shadow::let_go_idle` already runs once a second from `host::sweep`. It now first calls `let_go_idle_snapshots`, which does this: - When the pool is idle for `host::ram_idle_ms` and 4 frames (the same rule as the loose windows), it frees all of it. - While `residency::pressured()` holds, it keeps only the smallest buffers, up to 32 MiB (`POOL_PRESSURED_KEPT`), and frees the rest, largest first. - Otherwise it does nothing, and the behaviour is the same as before. `pooled` and `give_back` record the last use in `POOL_USED`, as a `host::moment()`. The freeing happens outside the lock, as `give_back` already does. The next snapshot after a trim is fresh memory, the same as every snapshot past the pool was before. With plenty of free RAM, `ram_idle_ms` is 5 minutes, so normal play keeps the pool. The FPS cost should only show after an idle stretch or under pressure. I did not measure FPS in game. ## Tests New `shadow::pool_tests`: - `trimming_keeps_the_smallest_up_to_the_limit` - `trimming_to_nothing_empties_the_pool` - `a_buffer_past_the_limit_goes_even_alone` - `an_idle_pool_goes_and_a_pressed_one_shrinks` - `pool_memory_load` (`#[ignore]`, run alone, because the pool is global): `cargo test -p victory-gpu --lib shadow::pool_tests::pool_memory_load -- --ignored --nocapture --test-threads=1` Load test on Windows 11 with an RTX 5070, in a debug build. It runs 256 snapshots of 1 to 32 MiB: | State | Pool | Private bytes over start | |---|---:|---:| | Full (main behaviour, stays forever) | 520,192 KiB | 521,336 KiB | | Under pressure (new) | ≤ 32 MiB | 25,684 KiB | | Idle (new) | 0 | 12 KiB | Results: - `cargo test -p victory-gpu --lib`: 401 passed, 0 failed, 37 ignored. - `cargo clippy -p victory-gpu --all-targets -- -D warnings`: clean. - `cargo clippy -p victory-gpu --all-targets --all-features -- -D warnings`: clean. Related: [HumanlyDev/HUMAN#7](https://github.com/HumanlyDev/HUMAN/pull/7) also bounds this pool, in a different way. This PR is written separately and is smaller. It touches only `shadow.rs`. Written with AI help (Claude/Kiro).
POOL kept up to 512 MiB of snapshot buffers for the rest of the run once snapshots stopped: only give_back trimmed it, and only when another buffer came back. The once-a-second sweep now empties it after the idle time of the other host caches (ram_idle_ms) and four frames, and keeps only the smallest 32 MiB while residency::pressured() holds.

Load test (ignored): 508 MiB private kept full, 25 MiB pressed, 0 idle.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 18:03:11 +00:00
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-26 19:18 UTC · original

The sweep drops returned buffers outside the pool mutex. One ordering detail needs attention before integration. A worker can return a buffer between checking POOL_USED and taking the mutex, so an idle sweep can discard a newly used buffer. Please take the idle decision under the same lock that records the last use. The 32 MiB figure should also be described as the post-sweep target, since give_back can refill the pool before the next sweep.

**@⁠TaynanGT** on GitHub · 2026-11-26 19:18 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/41#issuecomment-7201445844) The sweep drops returned buffers outside the pool mutex. One ordering detail needs attention before integration. A worker can return a buffer between checking `POOL_USED` and taking the mutex, so an idle sweep can discard a newly used buffer. Please take the idle decision under the same lock that records the last use. The 32 MiB figure should also be described as the post-sweep target, since `give_back` can refill the pool before the next sweep.
github manually merged commit a8573332b1 into main 2026-11-26 19:44:32 +00:00
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-26 19:21 UTC · original · reviewed

Here are the three edits for the idle-sweep race. Please batch them together. Both paths that touch the pool record their activity under its mutex, and the sweep checks that timestamp before trimming under the same mutex. The RAM and pressure queries and the buffer drops remain outside the lock.

**@⁠TaynanGT** on GitHub · 2026-11-26 19:21 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/41#pullrequestreview-6079471176) · **reviewed** Here are the three edits for the idle-sweep race. Please batch them together. Both paths that touch the pool record their activity under its mutex, and the sweep checks that timestamp before trimming under the same mutex. The RAM and pressure queries and the buffer drops remain outside the lock.
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-26 19:21 UTC · original
On crates/victory-gpu/src/shadow.rs line 1272 (outdated):

@@ -1259,11 +1259,16 @@ mod relay_tests {
 /// Snapshot memory kept for reuse (already touched, so no page faults).
 static POOL: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new());
 
+/// When a snapshot buffer was last taken from or given back to [`POOL`]
+/// ([`crate::host::moment`]), for [`let_go_idle_snapshots`].
+static POOL_USED: AtomicU64 = AtomicU64::new(0);
+
 /// An empty buffer with room for `n` bytes, from the pool if it has one
 /// of about that size: a small copy's snapshot took the 174 MB buffer kept
 /// for the big heap's, which then got another, until eight of them were
 /// reserved (1.4 GB in run 24).
 fn pooled(n: usize) -> Vec<u8> {
+    POOL_USED.store(crate::host::moment(), Ordering::Relaxed);
     let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());

Move the POOL_USED.store(...) to immediately after this lock acquisition.

**@⁠TaynanGT** on GitHub · 2026-11-26 19:21 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/41#discussion_r4712623294) On `crates/victory-gpu/src/shadow.rs` line 1272 (outdated): ```diff @@ -1259,11 +1259,16 @@ mod relay_tests { /// Snapshot memory kept for reuse (already touched, so no page faults). static POOL: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new()); +/// When a snapshot buffer was last taken from or given back to [`POOL`] +/// ([`crate::host::moment`]), for [`let_go_idle_snapshots`]. +static POOL_USED: AtomicU64 = AtomicU64::new(0); + /// An empty buffer with room for `n` bytes, from the pool if it has one /// of about that size: a small copy's snapshot took the 174 MB buffer kept /// for the big heap's, which then got another, until eight of them were /// reserved (1.4 GB in run 24). fn pooled(n: usize) -> Vec<u8> { + POOL_USED.store(crate::host::moment(), Ordering::Relaxed); let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); ``` Move the `POOL_USED.store(...)` to immediately after this lock acquisition.
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-26 19:21 UTC · original
On crates/victory-gpu/src/shadow.rs line 1308 (outdated):

@@ -1299,6 +1304,7 @@ fn snapshots_kept() -> usize {
 /// bytes in all.
 fn give_back(v: Vec<u8>) {
     const KEPT: usize = 512 << 20;
+    POOL_USED.store(crate::host::moment(), Ordering::Relaxed);
     let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());

Move the POOL_USED.store(...) to immediately after this lock acquisition.

**@⁠TaynanGT** on GitHub · 2026-11-26 19:21 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/41#discussion_r4712623313) On `crates/victory-gpu/src/shadow.rs` line 1308 (outdated): ```diff @@ -1299,6 +1304,7 @@ fn snapshots_kept() -> usize { /// bytes in all. fn give_back(v: Vec<u8>) { const KEPT: usize = 512 << 20; + POOL_USED.store(crate::host::moment(), Ordering::Relaxed); let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); ``` Move the `POOL_USED.store(...)` to immediately after this lock acquisition.
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-26 19:21 UTC · original
On crates/victory-gpu/src/shadow.rs line 1352 (outdated):

@@ -1316,6 +1322,154 @@ fn give_back(v: Vec<u8>) {
     drop(gone);
 }
 
+/// What [`POOL`] keeps while the host is short of memory
+/// ([`crate::residency::pressured`]): the smallest buffers, up to this many
+/// bytes in all. They are the ones asked for most (most of a frame's 330
+/// ranges are small), and the large ones are what fills the 512 MiB.
+const POOL_PRESSURED_KEPT: usize = 32 << 20;
+
+/// Lets go of the snapshot buffers [`POOL`] keeps when nobody wants them.
+/// Only [`give_back`] ever trimmed the pool, and only when another buffer
+/// came back, so once snapshots stopped the last 512 MiB stayed for the
+/// rest of the run, low memory or not (a load test: 524,123 KiB kept after
+/// five idle seconds; 13 MiB private once emptied by hand). Now
+/// - idle for the time the other host caches wait ([`crate::host::ram_idle_ms`])
+///   and four frames, all of it goes;
+/// - while the host is short of memory, all but [`POOL_PRESSURED_KEPT`]
+///   goes, the largest first, whatever the size of the largest.
+///
+/// The next snapshot is then memory fresh from the kernel, as it was for
+/// every snapshot past the pool before. Called by the once-a-second sweep.
+fn let_go_idle_snapshots() {
+    const IDLE_FRAMES: u64 = 4;
+    let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram());
+    let idle = crate::host::long_ago(POOL_USED.load(Ordering::Relaxed), idle_ms, IDLE_FRAMES);
+    let Some(most) = snapshots_to_keep(idle, crate::residency::pressured()) else {
+        return;
+    };
+    let gone = {
+        let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
+        trim_pool(&mut pool, most)

Replace the lines from let idle = ... through this trim_pool call with the block below. Keep the closing }; and drop(gone) after it.

    let pressured = crate::residency::pressured();
    let gone = {
        let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
        let idle = crate::host::long_ago(POOL_USED.load(Ordering::Relaxed), idle_ms, IDLE_FRAMES);
        let Some(most) = snapshots_to_keep(idle, pressured) else { return };
        trim_pool(&mut pool, most)
**@⁠TaynanGT** on GitHub · 2026-11-26 19:21 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/41#discussion_r4712623324) On `crates/victory-gpu/src/shadow.rs` line 1352 (outdated): ```diff @@ -1316,6 +1322,154 @@ fn give_back(v: Vec<u8>) { drop(gone); } +/// What [`POOL`] keeps while the host is short of memory +/// ([`crate::residency::pressured`]): the smallest buffers, up to this many +/// bytes in all. They are the ones asked for most (most of a frame's 330 +/// ranges are small), and the large ones are what fills the 512 MiB. +const POOL_PRESSURED_KEPT: usize = 32 << 20; + +/// Lets go of the snapshot buffers [`POOL`] keeps when nobody wants them. +/// Only [`give_back`] ever trimmed the pool, and only when another buffer +/// came back, so once snapshots stopped the last 512 MiB stayed for the +/// rest of the run, low memory or not (a load test: 524,123 KiB kept after +/// five idle seconds; 13 MiB private once emptied by hand). Now +/// - idle for the time the other host caches wait ([`crate::host::ram_idle_ms`]) +/// and four frames, all of it goes; +/// - while the host is short of memory, all but [`POOL_PRESSURED_KEPT`] +/// goes, the largest first, whatever the size of the largest. +/// +/// The next snapshot is then memory fresh from the kernel, as it was for +/// every snapshot past the pool before. Called by the once-a-second sweep. +fn let_go_idle_snapshots() { + const IDLE_FRAMES: u64 = 4; + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + let idle = crate::host::long_ago(POOL_USED.load(Ordering::Relaxed), idle_ms, IDLE_FRAMES); + let Some(most) = snapshots_to_keep(idle, crate::residency::pressured()) else { + return; + }; + let gone = { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + trim_pool(&mut pool, most) ``` Replace the lines from `let idle = ...` through this `trim_pool` call with the block below. Keep the closing `};` and `drop(gone)` after it. ```rust let pressured = crate::residency::pressured(); let gone = { let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); let idle = crate::host::long_ago(POOL_USED.load(Ordering::Relaxed), idle_ms, IDLE_FRAMES); let Some(most) = snapshots_to_keep(idle, pressured) else { return }; trim_pool(&mut pool, most) ```
Author
Owner

@⁠efsebayern on GitHub · 2026-11-26 19:29 UTC · original

I tested a local follow-up on bd270273 on Windows 11 with an i7-13700K and RTX 4080 SUPER. It keeps the pool's last-use timestamp under the same mutex as returns, takes, and the idle decision, as requested in the review. The RAM and pressure queries and the buffer drops stay outside the lock.

The synthetic memory load still passed. The patched process held about 25 MiB of extra private memory after the pressure sweep and returned to its starting level after the idle trim. The 32 MiB cap is a post-sweep target.

The same local patch also keeps the buffers sorted by capacity and allocates fresh buffers outside the mutex. In a synthetic release benchmark with eight threads and 80,000 take/return pairs, median wall time fell from 200.5 ms to 37.3 ms over six alternating runs per build. That number covers the combined local patch and measures the pool only. I would keep the buffer-search optimization as a separate follow-up after #41 lands.

The victory-gpu release suite reported 402 passed, 0 failed, 38 ignored. Both ignored load tests were run separately and passed. Package Clippy with all features and the asset check also passed. AI-assisted with Codex.

**@⁠efsebayern** on GitHub · 2026-11-26 19:29 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/41#issuecomment-7201652844) I tested a local follow-up on `bd270273` on Windows 11 with an i7-13700K and RTX 4080 SUPER. It keeps the pool's last-use timestamp under the same mutex as returns, takes, and the idle decision, as requested in the review. The RAM and pressure queries and the buffer drops stay outside the lock. The synthetic memory load still passed. The patched process held about 25 MiB of extra private memory after the pressure sweep and returned to its starting level after the idle trim. The 32 MiB cap is a post-sweep target. The same local patch also keeps the buffers sorted by capacity and allocates fresh buffers outside the mutex. In a synthetic release benchmark with eight threads and 80,000 take/return pairs, median wall time fell from **200.5 ms to 37.3 ms** over six alternating runs per build. That number covers the combined local patch and measures the pool only. I would keep the buffer-search optimization as a separate follow-up after #41 lands. The `victory-gpu` release suite reported **402 passed, 0 failed, 38 ignored**. Both ignored load tests were run separately and passed. Package Clippy with all features and the asset check also passed. AI-assisted with Codex.
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-26 19:34 UTC · original

@⁠efsebayern, the pressure and idle measurements are helpful. I added the mutex-ordering fix in 4ff4ea1 while keeping the capacity search unchanged. The 32 MiB target applies after a sweep. The 200.5 ms to 37.3 ms result came from the combined synthetic benchmark, so the search and allocation changes can be measured separately in a follow-up.

**@⁠TaynanGT** on GitHub · 2026-11-26 19:34 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/41#issuecomment-7201734257) @⁠efsebayern, the pressure and idle measurements are helpful. I added the mutex-ordering fix in `4ff4ea1` while keeping the capacity search unchanged. The 32 MiB target applies after a sweep. The 200.5 ms to 37.3 ms result came from the combined synthetic benchmark, so the search and allocation changes can be measured separately in a follow-up.
This discussion has been locked. Commenting is limited to contributors.
No description provided.