Add an opt-in RAM throttle for low-RAM PCs #96

Open
github-bot wants to merge 2 commits from github-bot/gh-96 into main AGit
Owner

@⁠nidscode on GitHub · 2026-11-27 00:37 UTC · original
nidscode:perf/ram-throttle → main · +385 −1 · 3 files · 2 commits · open

What

An opt-in RAM throttle for PCs whose physical RAM runs out before the card's memory does (16 GB and a 6 GB card here). Everything is off by default; with none of the new variables set, nothing changes.

Setting What it does Default
VICTORY_RAM_FLOOR_MB A new buffer in the PC's memory (upload_buffer, shared_buffer: upload heaps and memory shared with the card, both held in RAM while alive) waits while less than the floor would be left free. Waits run in 10 ms steps. It only slows the making; it never refuses a buffer. 0 (off)
VICTORY_RAM_WAIT_MS Longest wait for one buffer. 250
VICTORY_RAM_WAIT_SHARE_MS Most milliseconds of each second that all threads together may spend waiting; past it buffers are made at once, so the title always moves on. 600 (≤ 1000)
VICTORY_RAM_FRAME_WAIT_MS While free RAM is under the floor, a submission also waits at its start (before the sweep), up to this long. After a wait the title runs at least as long again, so it's held back half the time at most, far inside its 30 s heartbeat watchdog. 0 (off)
VICTORY_WINDOWS_BAR_PERCENT Share of the card's budget up to which windows outside buffers go to the card's memory (VICTORY_WINDOWS_BAR_MB), 50–95. A byte of a window there is a byte of RAM not locked for the card. 80 (as before)

Free RAM is read with available_physical_ram() and cached for 20 ms, since the buffer gate is asked thousands of times a second while the world streams in. The memory line reports what the throttle did: buffers that waited and for how long, waits cut short, buffers made at once, the least free RAM seen, submissions held back, and the windows on the card. While it holds things back it also reports every 5 s, because a world load can go many seconds without a frame report.

Why

On a 16 GB laptop, physical RAM runs out while the world streams in, not during play. Within about 20 s, the memory shared with the card goes from under 1 GB to 4–5 GB, faster than Windows writes other processes' pages to the page file, and free RAM drops to a few MB. After the load, free RAM holds at 0.5–1.2 GB. Each buffer that waits gives the system time to write those pages out. Holding the title's submissions back slows its own streaming the same way. This is the same family as the memory exhaustion in #36, but that report is about later in a session on 32 GB, and this PR doesn't claim to fix it.

Measurements

Machine: i7-13700H, RTX 3050 6 GB Laptop (budget 5,233 MB, Resizable BAR), 16 GB RAM, NVMe, Windows 11. Vice-Tay cc9ed86, diag build, Series S, windowed, shaders translated ahead.

Each run is 240 s, under an external guard that stops the game below 400 MB of free RAM (so the laptop never hard-pages) and caps its working set at 4.5 GB. Scripted Enter presses reach the story load in 60–100 s. "World" counts frame reports with 300 or more draws.

All runs below use this base set: VICTORY_DSTORAGE_IO=direct VICTORY_INPLACE=2 VICTORY_WINDOW_KB=64 VICTORY_WINDOW_TAILS=1 VICTORY_WINDOWS_BAR_MB=3072 VICTORY_CARD_BUFFERS_MB=256 VICTORY_LEVELS_ON_DEMAND=1 VICTORY_UPSCALER=6 VICTORY_RENDER_SCALE=0.5 VICTORY_OUTPUT=1920x1080 VICTORY_POKE=71B6330:1. The poke pauses the heartbeat watchdog for the slower throttled load. With the plain auto (4090) preset, the guard stopped the run at the world load with 3 MB free.

Run Throttle Ended by World frames World median Lowest free RAM
1 off time limit 111 819 ms 114 MB
2 off guard, at the world load 5 – 2 MB
3 on time limit 82 1,764 ms 465 MB
4 on time limit 132 1,304 ms 428 MB

"On" means VICTORY_RAM_FLOOR_MB=1500 VICTORY_RAM_WAIT_MS=500 VICTORY_RAM_WAIT_SHARE_MS=900 VICTORY_RAM_FRAME_WAIT_MS=1000 VICTORY_WINDOWS_BAR_PERCENT=92.

  • Without the throttle, 1 of 2 runs passed the world load; with it, 2 of 2, and free RAM stayed above the guard's line. The same code on another fork with the same base (VIctory-NVIDIA) passed the load in 6 of 7 runs on this laptop.
  • The cost: in run 4 the throttle held submissions back for 66.8 s of the 240, and 574 buffers waited 121 s in total. World frames are slower than in the one unthrottled run that survived. It's a trade of speed for not running out of RAM, so it stays opt-in.
  • Runs vary a lot: identical settings gave 263, 131 and 71 world frames on that other fork. Read these four as "the load survives", not as frame-rate numbers.

Tests

  • New: the_ram_throttle_holds_a_buffer_only_below_its_floor and windows_on_the_card_go_to_the_percent_asked_for_within_bounds.
  • cargo test --locked --profile diag -p victory-gpu --features diagnostics: 471 passed, 0 failed. One earlier run of the same suite hung in the test binary and passed on rerun; it looks like the timing-sensitive kind of test from #55, but I didn't pin it down.
  • cargo clippy --locked --profile diag -p victory-gpu --features diagnostics: no warnings.
  • cargo check --locked -p victory (no diagnostics) builds.
  • cargo fmt --check reports nothing new in the changed code (the files already had differences on main, and their count is unchanged).

Not in this PR

  • A small-PC launcher preset that turns this on automatically below some RAM size. That can follow once the numbers settle on more than one laptop.
  • The memory shared with the card still grows through the world (about 4.4 → 5.2 GB in 2 minutes). Windows that a descriptor slot still views can't be let go (shadow.rs let_go_idle), so this throttle buys time but doesn't stop that growth.

Update after review (d5c5d61)

  • The share of a second is one atomic word now, charged with fetch_update. Before, a reset could erase another thread's charge. A concurrency test covers the turn of a second, with late callers.
  • The heartbeat change moved to #126, as asked. This PR is the throttle only.
  • Caveat, measured since: with the title's watchdog active, this throttle ended 6 of 6 world loads on the 16 GB laptop (submission waits of 1,000, 300 or 0 ms: the buffer waits alone hold the title's main loop past 30 s). On this title it needs #126 to get through a load; with both, 4 of 4 loads passed. #100 no longer uses it.
  • Tests: victory-gpu 472 passed. Clippy has no warnings.

🤖 Generated with Claude Code

**@⁠nidscode** on GitHub · 2026-11-27 00:37 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/96) `nidscode:perf/ram-throttle` → `main` · +385 −1 · 3 files · 2 commits · open ## What An opt-in RAM throttle for PCs whose physical RAM runs out before the card's memory does (16 GB and a 6 GB card here). Everything is **off by default**; with none of the new variables set, nothing changes. | Setting | What it does | Default | |---|---|---| | `VICTORY_RAM_FLOOR_MB` | A new buffer in the PC's memory (`upload_buffer`, `shared_buffer`: upload heaps and memory shared with the card, both held in RAM while alive) waits while less than the floor would be left free. Waits run in 10 ms steps. It only slows the making; it never refuses a buffer. | 0 (off) | | `VICTORY_RAM_WAIT_MS` | Longest wait for one buffer. | 250 | | `VICTORY_RAM_WAIT_SHARE_MS` | Most milliseconds of each second that all threads together may spend waiting; past it buffers are made at once, so the title always moves on. | 600 (≤ 1000) | | `VICTORY_RAM_FRAME_WAIT_MS` | While free RAM is under the floor, a submission also waits at its start (before the sweep), up to this long. After a wait the title runs at least as long again, so it's held back half the time at most, far inside its 30 s heartbeat watchdog. | 0 (off) | | `VICTORY_WINDOWS_BAR_PERCENT` | Share of the card's budget up to which windows outside buffers go to the card's memory (`VICTORY_WINDOWS_BAR_MB`), 50–95. A byte of a window there is a byte of RAM not locked for the card. | 80 (as before) | Free RAM is read with `available_physical_ram()` and cached for 20 ms, since the buffer gate is asked thousands of times a second while the world streams in. The memory line reports what the throttle did: buffers that waited and for how long, waits cut short, buffers made at once, the least free RAM seen, submissions held back, and the windows on the card. While it holds things back it also reports every 5 s, because a world load can go many seconds without a frame report. ## Why On a 16 GB laptop, physical RAM runs out **while the world streams in**, not during play. Within about 20 s, the memory shared with the card goes from under 1 GB to 4–5 GB, faster than Windows writes other processes' pages to the page file, and free RAM drops to a few MB. After the load, free RAM holds at 0.5–1.2 GB. Each buffer that waits gives the system time to write those pages out. Holding the title's submissions back slows its own streaming the same way. This is the same family as the memory exhaustion in #36, but that report is about later in a session on 32 GB, and this PR doesn't claim to fix it. ## Measurements Machine: i7-13700H, RTX 3050 6 GB Laptop (budget 5,233 MB, Resizable BAR), 16 GB RAM, NVMe, Windows 11. Vice-Tay `cc9ed86`, diag build, Series S, windowed, shaders translated ahead. Each run is 240 s, under an external guard that stops the game below 400 MB of free RAM (so the laptop never hard-pages) and caps its working set at 4.5 GB. Scripted Enter presses reach the story load in 60–100 s. "World" counts frame reports with 300 or more draws. All runs below use this base set: `VICTORY_DSTORAGE_IO=direct VICTORY_INPLACE=2 VICTORY_WINDOW_KB=64 VICTORY_WINDOW_TAILS=1 VICTORY_WINDOWS_BAR_MB=3072 VICTORY_CARD_BUFFERS_MB=256 VICTORY_LEVELS_ON_DEMAND=1 VICTORY_UPSCALER=6 VICTORY_RENDER_SCALE=0.5 VICTORY_OUTPUT=1920x1080 VICTORY_POKE=71B6330:1`. The poke pauses the heartbeat watchdog for the slower throttled load. With the plain auto (4090) preset, the guard stopped the run at the world load with 3 MB free. | Run | Throttle | Ended by | World frames | World median | Lowest free RAM | |---|---|---|---|---|---| | 1 | off | time limit | 111 | 819 ms | 114 MB | | 2 | off | **guard, at the world load** | 5 | – | **2 MB** | | 3 | on | time limit | 82 | 1,764 ms | 465 MB | | 4 | on | time limit | 132 | 1,304 ms | 428 MB | "On" means `VICTORY_RAM_FLOOR_MB=1500 VICTORY_RAM_WAIT_MS=500 VICTORY_RAM_WAIT_SHARE_MS=900 VICTORY_RAM_FRAME_WAIT_MS=1000 VICTORY_WINDOWS_BAR_PERCENT=92`. - Without the throttle, 1 of 2 runs passed the world load; with it, 2 of 2, and free RAM stayed above the guard's line. The same code on another fork with the same base (VIctory-NVIDIA) passed the load in 6 of 7 runs on this laptop. - **The cost:** in run 4 the throttle held submissions back for 66.8 s of the 240, and 574 buffers waited 121 s in total. World frames are slower than in the one unthrottled run that survived. It's a trade of speed for not running out of RAM, so it stays opt-in. - Runs vary a lot: identical settings gave 263, 131 and 71 world frames on that other fork. Read these four as "the load survives", not as frame-rate numbers. ## Tests - New: `the_ram_throttle_holds_a_buffer_only_below_its_floor` and `windows_on_the_card_go_to_the_percent_asked_for_within_bounds`. - `cargo test --locked --profile diag -p victory-gpu --features diagnostics`: 471 passed, 0 failed. One earlier run of the same suite hung in the test binary and passed on rerun; it looks like the timing-sensitive kind of test from #55, but I didn't pin it down. - `cargo clippy --locked --profile diag -p victory-gpu --features diagnostics`: no warnings. - `cargo check --locked -p victory` (no diagnostics) builds. - `cargo fmt --check` reports nothing new in the changed code (the files already had differences on `main`, and their count is unchanged). ## Not in this PR - A small-PC launcher preset that turns this on automatically below some RAM size. That can follow once the numbers settle on more than one laptop. - The memory shared with the card still grows through the world (about 4.4 → 5.2 GB in 2 minutes). Windows that a descriptor slot still views can't be let go (`shadow.rs` `let_go_idle`), so this throttle buys time but doesn't stop that growth. ## Update after review (d5c5d61) - **The share of a second** is one atomic word now, charged with `fetch_update`. Before, a reset could erase another thread's charge. A concurrency test covers the turn of a second, with late callers. - **The heartbeat change moved to #126**, as asked. This PR is the throttle only. - **Caveat, measured since:** with the title's watchdog active, this throttle ended **6 of 6** world loads on the 16 GB laptop (submission waits of 1,000, 300 or 0 ms: the buffer waits alone hold the title's main loop past 30 s). On this title it needs #126 to get through a load; with both, 4 of 4 loads passed. #100 no longer uses it. - **Tests:** victory-gpu 472 passed. Clippy has no warnings. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
On a 16 GB PC physical RAM runs out while the world streams in: the
memory the layer shares with the card goes from under 1 GB to 4-5 GB in
about 20 s, faster than Windows writes other pages out, and free RAM
falls to nothing. These settings, all off by default, slow that down:

- VICTORY_RAM_FLOOR_MB: a new buffer in the PC's memory (upload or
  shared with the card) waits while less than the floor would be left
  free, VICTORY_RAM_WAIT_MS at most (250 by default), and all threads
  together at most VICTORY_RAM_WAIT_SHARE_MS of every second (600, at
  most 1000). It only slows the making; it never refuses.
- VICTORY_RAM_FRAME_WAIT_MS: under the floor a submission also waits at
  its start, up to that long and at most half of the time, so the
  title's own streaming slows too (well inside its 30 s watchdog).
- VICTORY_WINDOWS_BAR_PERCENT: the share of the card's budget up to
  which windows outside buffers go to the card's memory
  (VICTORY_WINDOWS_BAR_MB), 50 to 95; 80 by default, as before.

The memory line reports what the throttle did and the windows on the
card; while it holds things back it reports every 5 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-27 00:42:15 +00:00
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-27 01:28 UTC · original · requested changes

Thanks for the paired runs on the 16 GB laptop. The load survival and frame-time measurements make the trade-off clear. I started CI on 0addae35. Please fix the shared wait budget before we rely on the throttle in #100.

**@⁠TaynanGT** on GitHub · 2026-11-27 01:28 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/96#pullrequestreview-6082280587) · **requested changes** Thanks for the paired runs on the 16 GB laptop. The load survival and frame-time measurements make the trade-off clear. I started CI on `0addae35`. Please fix the shared wait budget before we rely on the throttle in #100.
@ -157,0 +283,4 @@
// The second's share, for all threads together.
let second = now / 1000;
if RAM_SHARE[0].swap(second, Ordering::Relaxed) != second {
RAM_SHARE[1].store(0, Ordering::Relaxed);
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-27 01:28 UTC · original

The reset can drop a reservation made by another thread. A can publish the new second, B can charge its 10 ms and start sleeping, and A can then erase that charge with store(0). Please update the second and its spent time in one operation, and cover a rollover with concurrent callers.

**@⁠TaynanGT** on GitHub · 2026-11-27 01:28 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/96#discussion_r4714796974) The reset can drop a reservation made by another thread. A can publish the new second, B can charge its 10 ms and start sleeping, and A can then erase that charge with `store(0)`. Please update the second and its spent time in one operation, and cover a rollover with concurrent callers.
The share of a second the throttle may wait (VICTORY_RAM_WAIT_SHARE_MS)
was a second and its spent milliseconds in two atomics: a thread moving to
a new second reset the spent time and could erase a charge another thread
had just made. They are one word now (the second above 20 bits, the
milliseconds below), charged with fetch_update; a thread that read the
clock before another moved the word on is charged to the word's own
second, so the word never goes back and no charge is lost. A test runs
eight threads over two seconds, half of them asking for the earlier
second after the turn: each second gives exactly its share.

VICTORY_RAM_KEEP_ALIVE=1 (off by default): while the throttle holds a
buffer or a submission back, it sets the title's heartbeat flag as the
title's own tick function does, so a world load it slows doesn't meet
the title's 30 s watchdog. Only in its own waits (bounded by
VICTORY_RAM_WAIT_MS and VICTORY_RAM_FRAME_WAIT_MS): a hang anywhere
else still ends the title. victory_loader::heartbeat checks the 1.0.2.1
tick function first (+0x2214a90: mov byte [rip+disp32], 1; ret) and takes
the flag's address from it; another build is left alone, said so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Author
Owner

@⁠nidscode on GitHub · 2026-11-27 02:03 UTC · original
On crates/victory-gpu/src/host.rs line 286 (outdated):

@@ -154,6 +154,264 @@ pub(crate) fn available_physical_ram() -> Option<u64> {
     ok.then_some(m.ullAvailPhys)
 }
 
+/// The floor of the RAM throttle in bytes (`VICTORY_RAM_FLOOR_MB`; 0, the
+/// default, no throttle). See [`ram_gate`].
+fn ram_floor() -> u64 {
+    static FLOOR: OnceLock<u64> = OnceLock::new();
+    *FLOOR.get_or_init(|| {
+        let mb = std::env::var("VICTORY_RAM_FLOOR_MB")
+            .ok()
+            .and_then(|v| v.trim().parse::<u64>().ok())
+            .unwrap_or(0);
+        if mb > 0 {
+            tracing::info!(
+                floor_mb = mb,
+                wait_ms = ram_wait_most(),
+                share_ms = ram_wait_share(),
+                frame_wait_ms = ram_frame_wait(),
+                "RAM throttle on: buffers in the PC's memory wait while less is free"
+            );
+        }
+        mb << 20
+    })
+}
+
+/// The longest one buffer waits at the RAM throttle, in milliseconds
+/// (`VICTORY_RAM_WAIT_MS`, 250 by default).
+fn ram_wait_most() -> u64 {
+    static MOST: OnceLock<u64> = OnceLock::new();
+    *MOST.get_or_init(|| {
+        std::env::var("VICTORY_RAM_WAIT_MS")
+            .ok()
+            .and_then(|v| v.trim().parse().ok())
+            .unwrap_or(250)
+    })
+}
+
+/// Of every second, the most milliseconds spent waiting at the RAM throttle,
+/// all threads together (`VICTORY_RAM_WAIT_SHARE_MS`, 600 by default, 1000
+/// at most): past it buffers are made at once, so the title always moves on.
+fn ram_wait_share() -> u64 {
+    static MOST: OnceLock<u64> = OnceLock::new();
+    *MOST.get_or_init(|| {
+        std::env::var("VICTORY_RAM_WAIT_SHARE_MS")
+            .ok()
+            .and_then(|v| v.trim().parse().ok())
+            .unwrap_or(600)
+            .min(1000)
+    })
+}
+
+/// Free RAM as last looked at, and when (milliseconds since the start, 0:
+/// never): looked at again after 20 ms ([`ram_gate`] is asked thousands of
+/// times a second while the world streams in).
+static RAM_SEEN: [std::sync::atomic::AtomicU64; 2] =
+    [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+fn ram_free_now() -> Option<u64> {
+    let now = now_ms();
+    let at = RAM_SEEN[0].load(Ordering::Relaxed);
+    if at != 0 && now < at + 20 {
+        return Some(RAM_SEEN[1].load(Ordering::Relaxed));
+    }
+    let free = available_physical_ram()?;
+    RAM_SEEN[1].store(free, Ordering::Relaxed);
+    RAM_SEEN[0].store(now.max(1), Ordering::Relaxed);
+    Some(free)
+}
+
+/// The RAM throttle, since the start: buffers that waited, milliseconds
+/// waited, buffers made at once for the second's share being spent, waits
+/// cut at [`ram_wait_most`], the longest wait in ms, the least RAM free
+/// seen while waiting (MB, `u64::MAX` before any wait).
+static RAM_GATE: [std::sync::atomic::AtomicU64; 6] = [
+    std::sync::atomic::AtomicU64::new(0),
+    std::sync::atomic::AtomicU64::new(0),
+    std::sync::atomic::AtomicU64::new(0),
+    std::sync::atomic::AtomicU64::new(0),
+    std::sync::atomic::AtomicU64::new(0),
+    std::sync::atomic::AtomicU64::new(u64::MAX),
+];
+/// The second [`ram_wait_share`] is counted in, and the milliseconds spent
+/// of it.
+static RAM_SHARE: [std::sync::atomic::AtomicU64; 2] =
+    [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+/// Whether the RAM throttle holds back a buffer of `size` bytes about to be
+/// made in the PC's memory, with `free` bytes of RAM free and `floor` the
+/// throttle's floor (0: no throttle).
+fn ram_held(free: Option<u64>, size: u64, floor: u64) -> bool {
+    floor > 0 && free.is_some_and(|free| free < floor.saturating_add(size))
+}
+
+/// Holds back a buffer of `size` bytes about to be made in the PC's memory
+/// (shared with the card, or upload memory: either is locked in RAM as long
+/// as it lives) while less than the floor ([`ram_floor`]) would be left
+/// free: for up to [`ram_wait_most`] ms each, at most [`ram_wait_share`] ms
+/// of every second for all threads, in steps of 10 ms. Then it is made,
+/// room or not: the throttle only slows the making, it never refuses.
+///
+/// Why: as the world streams in, the layer makes gigabytes of such buffers
+/// in seconds (on the RTX 3050 laptop with 16 GB, the memory shared with
+/// the card went from 0.7 to 5.3 GB in 20 s of one measured run), faster than
+/// Windows writes what it takes from others to the page file (2.5 GB were
+/// waiting to be written then). Free RAM fell under 300 MB for seconds and
+/// the PC paged the game itself in and out (28,000 pages a second). Each
+/// buffer that waits gives the system time to write those pages out. A
+/// frame there takes a second or two anyway.
+pub(crate) fn ram_gate(size: u64) {
+    let floor = ram_floor();
+    if floor == 0 || !ram_held(ram_free_now(), size, floor) {
+        return;
+    }
+    let (most, share) = (ram_wait_most(), ram_wait_share());
+    let begun = now_ms();
+    let mut waited = false;
+    loop {
+        let free = ram_free_now();
+        if !ram_held(free, size, floor) {
+            break;
+        }
+        if let Some(free) = free {
+            RAM_GATE[5].fetch_min(free >> 20, Ordering::Relaxed);
+        }
+        let now = now_ms();
+        if now >= begun + most {
+            RAM_GATE[3].fetch_add(1, Ordering::Relaxed);
+            break;
+        }
+        // The second's share, for all threads together.
+        let second = now / 1000;
+        if RAM_SHARE[0].swap(second, Ordering::Relaxed) != second {
+            RAM_SHARE[1].store(0, Ordering::Relaxed);

Fixed in fc74f10. The second and its spent milliseconds are now one AtomicU64 (the second above bit 20, the milliseconds below), charged with fetch_update in take_share, so a new second and a charge to it are one operation. A caller that read the clock before another thread moved the word on is charged to the word's own second, so the word never goes back.

the_ram_throttle_share_holds_across_a_second_with_concurrent_callers runs 8 threads × 400 tries over two seconds against a 900 ms share. In the second half, half the threads keep asking for the earlier second. Each second gives exactly 90 charges of 10 ms, and the word ends at the later second, full. One more change: a charge the share has no room for is no longer recorded, where the old code added it and then gave up.

**@⁠nidscode** on GitHub · 2026-11-27 02:03 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/96#discussion_r4714955469) On `crates/victory-gpu/src/host.rs` line 286 (outdated): ```diff @@ -154,6 +154,264 @@ pub(crate) fn available_physical_ram() -> Option<u64> { ok.then_some(m.ullAvailPhys) } +/// The floor of the RAM throttle in bytes (`VICTORY_RAM_FLOOR_MB`; 0, the +/// default, no throttle). See [`ram_gate`]. +fn ram_floor() -> u64 { + static FLOOR: OnceLock<u64> = OnceLock::new(); + *FLOOR.get_or_init(|| { + let mb = std::env::var("VICTORY_RAM_FLOOR_MB") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(0); + if mb > 0 { + tracing::info!( + floor_mb = mb, + wait_ms = ram_wait_most(), + share_ms = ram_wait_share(), + frame_wait_ms = ram_frame_wait(), + "RAM throttle on: buffers in the PC's memory wait while less is free" + ); + } + mb << 20 + }) +} + +/// The longest one buffer waits at the RAM throttle, in milliseconds +/// (`VICTORY_RAM_WAIT_MS`, 250 by default). +fn ram_wait_most() -> u64 { + static MOST: OnceLock<u64> = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_RAM_WAIT_MS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(250) + }) +} + +/// Of every second, the most milliseconds spent waiting at the RAM throttle, +/// all threads together (`VICTORY_RAM_WAIT_SHARE_MS`, 600 by default, 1000 +/// at most): past it buffers are made at once, so the title always moves on. +fn ram_wait_share() -> u64 { + static MOST: OnceLock<u64> = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_RAM_WAIT_SHARE_MS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(600) + .min(1000) + }) +} + +/// Free RAM as last looked at, and when (milliseconds since the start, 0: +/// never): looked at again after 20 ms ([`ram_gate`] is asked thousands of +/// times a second while the world streams in). +static RAM_SEEN: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +fn ram_free_now() -> Option<u64> { + let now = now_ms(); + let at = RAM_SEEN[0].load(Ordering::Relaxed); + if at != 0 && now < at + 20 { + return Some(RAM_SEEN[1].load(Ordering::Relaxed)); + } + let free = available_physical_ram()?; + RAM_SEEN[1].store(free, Ordering::Relaxed); + RAM_SEEN[0].store(now.max(1), Ordering::Relaxed); + Some(free) +} + +/// The RAM throttle, since the start: buffers that waited, milliseconds +/// waited, buffers made at once for the second's share being spent, waits +/// cut at [`ram_wait_most`], the longest wait in ms, the least RAM free +/// seen while waiting (MB, `u64::MAX` before any wait). +static RAM_GATE: [std::sync::atomic::AtomicU64; 6] = [ + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(u64::MAX), +]; +/// The second [`ram_wait_share`] is counted in, and the milliseconds spent +/// of it. +static RAM_SHARE: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether the RAM throttle holds back a buffer of `size` bytes about to be +/// made in the PC's memory, with `free` bytes of RAM free and `floor` the +/// throttle's floor (0: no throttle). +fn ram_held(free: Option<u64>, size: u64, floor: u64) -> bool { + floor > 0 && free.is_some_and(|free| free < floor.saturating_add(size)) +} + +/// Holds back a buffer of `size` bytes about to be made in the PC's memory +/// (shared with the card, or upload memory: either is locked in RAM as long +/// as it lives) while less than the floor ([`ram_floor`]) would be left +/// free: for up to [`ram_wait_most`] ms each, at most [`ram_wait_share`] ms +/// of every second for all threads, in steps of 10 ms. Then it is made, +/// room or not: the throttle only slows the making, it never refuses. +/// +/// Why: as the world streams in, the layer makes gigabytes of such buffers +/// in seconds (on the RTX 3050 laptop with 16 GB, the memory shared with +/// the card went from 0.7 to 5.3 GB in 20 s of one measured run), faster than +/// Windows writes what it takes from others to the page file (2.5 GB were +/// waiting to be written then). Free RAM fell under 300 MB for seconds and +/// the PC paged the game itself in and out (28,000 pages a second). Each +/// buffer that waits gives the system time to write those pages out. A +/// frame there takes a second or two anyway. +pub(crate) fn ram_gate(size: u64) { + let floor = ram_floor(); + if floor == 0 || !ram_held(ram_free_now(), size, floor) { + return; + } + let (most, share) = (ram_wait_most(), ram_wait_share()); + let begun = now_ms(); + let mut waited = false; + loop { + let free = ram_free_now(); + if !ram_held(free, size, floor) { + break; + } + if let Some(free) = free { + RAM_GATE[5].fetch_min(free >> 20, Ordering::Relaxed); + } + let now = now_ms(); + if now >= begun + most { + RAM_GATE[3].fetch_add(1, Ordering::Relaxed); + break; + } + // The second's share, for all threads together. + let second = now / 1000; + if RAM_SHARE[0].swap(second, Ordering::Relaxed) != second { + RAM_SHARE[1].store(0, Ordering::Relaxed); ``` Fixed in fc74f10. The second and its spent milliseconds are now one `AtomicU64` (the second above bit 20, the milliseconds below), charged with `fetch_update` in `take_share`, so a new second and a charge to it are one operation. A caller that read the clock before another thread moved the word on is charged to the word's own second, so the word never goes back. `the_ram_throttle_share_holds_across_a_second_with_concurrent_callers` runs 8 threads × 400 tries over two seconds against a 900 ms share. In the second half, half the threads keep asking for the earlier second. Each second gives exactly 90 charges of 10 ms, and the word ends at the later second, full. One more change: a charge the share has no room for is no longer recorded, where the old code added it and then gave up.
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-27 02:06 UTC · original
On crates/victory-gpu/src/host.rs line 286 (outdated):

@@ -154,6 +154,264 @@ pub(crate) fn available_physical_ram() -> Option<u64> {
     ok.then_some(m.ullAvailPhys)
 }
 
+/// The floor of the RAM throttle in bytes (`VICTORY_RAM_FLOOR_MB`; 0, the
+/// default, no throttle). See [`ram_gate`].
+fn ram_floor() -> u64 {
+    static FLOOR: OnceLock<u64> = OnceLock::new();
+    *FLOOR.get_or_init(|| {
+        let mb = std::env::var("VICTORY_RAM_FLOOR_MB")
+            .ok()
+            .and_then(|v| v.trim().parse::<u64>().ok())
+            .unwrap_or(0);
+        if mb > 0 {
+            tracing::info!(
+                floor_mb = mb,
+                wait_ms = ram_wait_most(),
+                share_ms = ram_wait_share(),
+                frame_wait_ms = ram_frame_wait(),
+                "RAM throttle on: buffers in the PC's memory wait while less is free"
+            );
+        }
+        mb << 20
+    })
+}
+
+/// The longest one buffer waits at the RAM throttle, in milliseconds
+/// (`VICTORY_RAM_WAIT_MS`, 250 by default).
+fn ram_wait_most() -> u64 {
+    static MOST: OnceLock<u64> = OnceLock::new();
+    *MOST.get_or_init(|| {
+        std::env::var("VICTORY_RAM_WAIT_MS")
+            .ok()
+            .and_then(|v| v.trim().parse().ok())
+            .unwrap_or(250)
+    })
+}
+
+/// Of every second, the most milliseconds spent waiting at the RAM throttle,
+/// all threads together (`VICTORY_RAM_WAIT_SHARE_MS`, 600 by default, 1000
+/// at most): past it buffers are made at once, so the title always moves on.
+fn ram_wait_share() -> u64 {
+    static MOST: OnceLock<u64> = OnceLock::new();
+    *MOST.get_or_init(|| {
+        std::env::var("VICTORY_RAM_WAIT_SHARE_MS")
+            .ok()
+            .and_then(|v| v.trim().parse().ok())
+            .unwrap_or(600)
+            .min(1000)
+    })
+}
+
+/// Free RAM as last looked at, and when (milliseconds since the start, 0:
+/// never): looked at again after 20 ms ([`ram_gate`] is asked thousands of
+/// times a second while the world streams in).
+static RAM_SEEN: [std::sync::atomic::AtomicU64; 2] =
+    [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+fn ram_free_now() -> Option<u64> {
+    let now = now_ms();
+    let at = RAM_SEEN[0].load(Ordering::Relaxed);
+    if at != 0 && now < at + 20 {
+        return Some(RAM_SEEN[1].load(Ordering::Relaxed));
+    }
+    let free = available_physical_ram()?;
+    RAM_SEEN[1].store(free, Ordering::Relaxed);
+    RAM_SEEN[0].store(now.max(1), Ordering::Relaxed);
+    Some(free)
+}
+
+/// The RAM throttle, since the start: buffers that waited, milliseconds
+/// waited, buffers made at once for the second's share being spent, waits
+/// cut at [`ram_wait_most`], the longest wait in ms, the least RAM free
+/// seen while waiting (MB, `u64::MAX` before any wait).
+static RAM_GATE: [std::sync::atomic::AtomicU64; 6] = [
+    std::sync::atomic::AtomicU64::new(0),
+    std::sync::atomic::AtomicU64::new(0),
+    std::sync::atomic::AtomicU64::new(0),
+    std::sync::atomic::AtomicU64::new(0),
+    std::sync::atomic::AtomicU64::new(0),
+    std::sync::atomic::AtomicU64::new(u64::MAX),
+];
+/// The second [`ram_wait_share`] is counted in, and the milliseconds spent
+/// of it.
+static RAM_SHARE: [std::sync::atomic::AtomicU64; 2] =
+    [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+/// Whether the RAM throttle holds back a buffer of `size` bytes about to be
+/// made in the PC's memory, with `free` bytes of RAM free and `floor` the
+/// throttle's floor (0: no throttle).
+fn ram_held(free: Option<u64>, size: u64, floor: u64) -> bool {
+    floor > 0 && free.is_some_and(|free| free < floor.saturating_add(size))
+}
+
+/// Holds back a buffer of `size` bytes about to be made in the PC's memory
+/// (shared with the card, or upload memory: either is locked in RAM as long
+/// as it lives) while less than the floor ([`ram_floor`]) would be left
+/// free: for up to [`ram_wait_most`] ms each, at most [`ram_wait_share`] ms
+/// of every second for all threads, in steps of 10 ms. Then it is made,
+/// room or not: the throttle only slows the making, it never refuses.
+///
+/// Why: as the world streams in, the layer makes gigabytes of such buffers
+/// in seconds (on the RTX 3050 laptop with 16 GB, the memory shared with
+/// the card went from 0.7 to 5.3 GB in 20 s of one measured run), faster than
+/// Windows writes what it takes from others to the page file (2.5 GB were
+/// waiting to be written then). Free RAM fell under 300 MB for seconds and
+/// the PC paged the game itself in and out (28,000 pages a second). Each
+/// buffer that waits gives the system time to write those pages out. A
+/// frame there takes a second or two anyway.
+pub(crate) fn ram_gate(size: u64) {
+    let floor = ram_floor();
+    if floor == 0 || !ram_held(ram_free_now(), size, floor) {
+        return;
+    }
+    let (most, share) = (ram_wait_most(), ram_wait_share());
+    let begun = now_ms();
+    let mut waited = false;
+    loop {
+        let free = ram_free_now();
+        if !ram_held(free, size, floor) {
+            break;
+        }
+        if let Some(free) = free {
+            RAM_GATE[5].fetch_min(free >> 20, Ordering::Relaxed);
+        }
+        let now = now_ms();
+        if now >= begun + most {
+            RAM_GATE[3].fetch_add(1, Ordering::Relaxed);
+            break;
+        }
+        // The second's share, for all threads together.
+        let second = now / 1000;
+        if RAM_SHARE[0].swap(second, Ordering::Relaxed) != second {
+            RAM_SHARE[1].store(0, Ordering::Relaxed);

Thanks, @⁠nidscode. Packing the time window and charge into one atomic update addresses the race I raised. The rollover test also covers callers that arrive with an older timestamp. I’ve started the fresh CI run for fc74f10.

Could you keep #96 focused on the RAM throttle and move VICTORY_RAM_KEEP_ALIVE to a separate PR? That change borrows the entire mapped image as a Rust slice, including ranges that could be unreadable, and writes to an address supplied through a safe public API. The heartbeat can also be accessed by the title and multiple host threads. That needs its own checks for readable and writable ranges, pointer lifetime and concurrent access.

**@⁠TaynanGT** on GitHub · 2026-11-27 02:06 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/96#discussion_r4714973541) On `crates/victory-gpu/src/host.rs` line 286 (outdated): ```diff @@ -154,6 +154,264 @@ pub(crate) fn available_physical_ram() -> Option<u64> { ok.then_some(m.ullAvailPhys) } +/// The floor of the RAM throttle in bytes (`VICTORY_RAM_FLOOR_MB`; 0, the +/// default, no throttle). See [`ram_gate`]. +fn ram_floor() -> u64 { + static FLOOR: OnceLock<u64> = OnceLock::new(); + *FLOOR.get_or_init(|| { + let mb = std::env::var("VICTORY_RAM_FLOOR_MB") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(0); + if mb > 0 { + tracing::info!( + floor_mb = mb, + wait_ms = ram_wait_most(), + share_ms = ram_wait_share(), + frame_wait_ms = ram_frame_wait(), + "RAM throttle on: buffers in the PC's memory wait while less is free" + ); + } + mb << 20 + }) +} + +/// The longest one buffer waits at the RAM throttle, in milliseconds +/// (`VICTORY_RAM_WAIT_MS`, 250 by default). +fn ram_wait_most() -> u64 { + static MOST: OnceLock<u64> = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_RAM_WAIT_MS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(250) + }) +} + +/// Of every second, the most milliseconds spent waiting at the RAM throttle, +/// all threads together (`VICTORY_RAM_WAIT_SHARE_MS`, 600 by default, 1000 +/// at most): past it buffers are made at once, so the title always moves on. +fn ram_wait_share() -> u64 { + static MOST: OnceLock<u64> = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_RAM_WAIT_SHARE_MS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(600) + .min(1000) + }) +} + +/// Free RAM as last looked at, and when (milliseconds since the start, 0: +/// never): looked at again after 20 ms ([`ram_gate`] is asked thousands of +/// times a second while the world streams in). +static RAM_SEEN: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +fn ram_free_now() -> Option<u64> { + let now = now_ms(); + let at = RAM_SEEN[0].load(Ordering::Relaxed); + if at != 0 && now < at + 20 { + return Some(RAM_SEEN[1].load(Ordering::Relaxed)); + } + let free = available_physical_ram()?; + RAM_SEEN[1].store(free, Ordering::Relaxed); + RAM_SEEN[0].store(now.max(1), Ordering::Relaxed); + Some(free) +} + +/// The RAM throttle, since the start: buffers that waited, milliseconds +/// waited, buffers made at once for the second's share being spent, waits +/// cut at [`ram_wait_most`], the longest wait in ms, the least RAM free +/// seen while waiting (MB, `u64::MAX` before any wait). +static RAM_GATE: [std::sync::atomic::AtomicU64; 6] = [ + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(u64::MAX), +]; +/// The second [`ram_wait_share`] is counted in, and the milliseconds spent +/// of it. +static RAM_SHARE: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether the RAM throttle holds back a buffer of `size` bytes about to be +/// made in the PC's memory, with `free` bytes of RAM free and `floor` the +/// throttle's floor (0: no throttle). +fn ram_held(free: Option<u64>, size: u64, floor: u64) -> bool { + floor > 0 && free.is_some_and(|free| free < floor.saturating_add(size)) +} + +/// Holds back a buffer of `size` bytes about to be made in the PC's memory +/// (shared with the card, or upload memory: either is locked in RAM as long +/// as it lives) while less than the floor ([`ram_floor`]) would be left +/// free: for up to [`ram_wait_most`] ms each, at most [`ram_wait_share`] ms +/// of every second for all threads, in steps of 10 ms. Then it is made, +/// room or not: the throttle only slows the making, it never refuses. +/// +/// Why: as the world streams in, the layer makes gigabytes of such buffers +/// in seconds (on the RTX 3050 laptop with 16 GB, the memory shared with +/// the card went from 0.7 to 5.3 GB in 20 s of one measured run), faster than +/// Windows writes what it takes from others to the page file (2.5 GB were +/// waiting to be written then). Free RAM fell under 300 MB for seconds and +/// the PC paged the game itself in and out (28,000 pages a second). Each +/// buffer that waits gives the system time to write those pages out. A +/// frame there takes a second or two anyway. +pub(crate) fn ram_gate(size: u64) { + let floor = ram_floor(); + if floor == 0 || !ram_held(ram_free_now(), size, floor) { + return; + } + let (most, share) = (ram_wait_most(), ram_wait_share()); + let begun = now_ms(); + let mut waited = false; + loop { + let free = ram_free_now(); + if !ram_held(free, size, floor) { + break; + } + if let Some(free) = free { + RAM_GATE[5].fetch_min(free >> 20, Ordering::Relaxed); + } + let now = now_ms(); + if now >= begun + most { + RAM_GATE[3].fetch_add(1, Ordering::Relaxed); + break; + } + // The second's share, for all threads together. + let second = now / 1000; + if RAM_SHARE[0].swap(second, Ordering::Relaxed) != second { + RAM_SHARE[1].store(0, Ordering::Relaxed); ``` Thanks, @⁠nidscode. Packing the time window and charge into one atomic update addresses the race I raised. The rollover test also covers callers that arrive with an older timestamp. I’ve started the fresh CI run for `fc74f10`. Could you keep #96 focused on the RAM throttle and move `VICTORY_RAM_KEEP_ALIVE` to a separate PR? That change borrows the entire mapped image as a Rust slice, including ranges that could be unreadable, and writes to an address supplied through a safe public API. The heartbeat can also be accessed by the title and multiple host threads. That needs its own checks for readable and writable ranges, pointer lifetime and concurrent access.
github-bot force-pushed github-bot/gh-96 from fc74f101f2 to d5c5d61f4d 2026-11-27 02:57:01 +00:00 Compare
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-27 02:59 UTC · original · edited 2026-11-27 03:03 UTC

Thanks, @⁠nidscode. I checked d5c5d61 and confirmed that the heartbeat changes are out. The two throttle tests and the window-budget test passed locally, and Windows CI passed on that head.

I found one more input-handling issue before this is ready. The RAM floor still shifts a parsed u64 by 20, which can truncate it, and both waits add an unrestricted duration to begun. Please check the MiB conversion and validate the wait values before using them in deadline arithmetic. Could you also update the PR description and the submission-wait comment for the current head? The 16 GB runs in #100 show that individually bounded waits can still delay a world load long enough to trip the watchdog.

**@⁠TaynanGT** on GitHub · 2026-11-27 02:59 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/96#issuecomment-7208603034) · edited 2026-11-27 03:03 UTC Thanks, @⁠nidscode. I checked `d5c5d61` and confirmed that the heartbeat changes are out. The two throttle tests and the window-budget test passed locally, and [Windows CI](https://github.com/TaynanGT/Vice-Tay/actions/runs/45931039307) passed on that head. I found one more input-handling issue before this is ready. The RAM floor still shifts a parsed `u64` by 20, which can truncate it, and both waits add an unrestricted duration to `begun`. Please check the MiB conversion and validate the wait values before using them in deadline arithmetic. Could you also update the PR description and the submission-wait comment for the current head? The 16 GB runs in #100 show that individually bounded waits can still delay a world load long enough to trip the watchdog.
Author
Owner

@⁠TaynanGT on GitHub · 2026-11-27 04:18 UTC · original

Thanks for the watchdog-on load counts, @⁠nidscode. Draft #147 carries your throttle with the checked MiB conversion and bounded elapsed-time waits. Four targeted tests and Clippy passed. I’m keeping the guarded 0-of-6 result visible as the baseline for any future hardware retest.

**@⁠TaynanGT** on GitHub · 2026-11-27 04:18 UTC · [original](https://github.com/TaynanGT/Vice-Tay/pull/96#issuecomment-7209691390) Thanks for the watchdog-on load counts, @⁠nidscode. [Draft #147](https://git.gtahub.st/github/TaynanGT--Vice-Tay/pulls/147) carries your throttle with the checked MiB conversion and bounded elapsed-time waits. Four targeted tests and Clippy passed. I’m keeping the guarded 0-of-6 result visible as the baseline for any future hardware retest.
This pull request has changes conflicting with the target branch.
  • crates/victory-gpu/src/host.rs
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/96/head:github-bot/gh-96'
git switch 'github-bot/gh-96'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-96'
git switch 'github-bot/gh-96'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-96'
git switch 'github-bot/gh-96'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-96'
git switch 'main'
git merge --squash 'github-bot/gh-96'
git switch 'main'
git merge --ff-only 'github-bot/gh-96'
git switch 'main'
git merge 'github-bot/gh-96'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.