Skip to content

GPU: loose windows nothing has asked for go, with their memory (VICTORY_WINDOW_IDLE_SECS) - #3078

Open
Luislariosss wants to merge 1 commit into
Marvisak:mainfrom
Luislariosss:perf/loose-window-eviction
Open

Luislariosss wants to merge 1 commit into
Marvisak:mainfrom
Luislariosss:perf/loose-window-eviction

Conversation

@Luislariosss

Copy link
Copy Markdown
Contributor

Problem

Loose windows — host copies of title memory that belongs to no buffer — were never freed, so a long run kept every one it had ever made. One measured world run held 1,400 of them (6.4 GB) by its end, on a machine whose RAM is what limits it.

Change

crates/victory-gpu/src/shadow.rs tracks each window's last-asked time and the periodic line's sweep in crates/victory-gpu/src/host.rs frees windows idle for 30 s (VICTORY_WINDOW_IDLE_SECS, 0 keeps them all) — but only ones no view, list or heap still holds, since one of those would keep reading the old copy while a later ask made another of the same range. The page tables of crates/victory-gpu/src/memory.rs name every copy, so their references are counted and discounted (their lock is never held with the window map's: a rewrite takes both, in the other order), and the copies' generation is bumped so the tables are rebuilt without the gone ones. A window the title comes back to is copied again.

Measurement (Ryzen 5 9600X, RX 9060 XT 16 GB, 15 GB RAM)

A 902 s world run — the first on this machine to survive its whole planned length, and the farthest the title has gone:

  • 720 windows went idle and 3.4 GB came back; the live set stayed at 840 windows (3.6 GB) instead of growing without end
  • no allocation errors, no exceptions; free RAM ~1.4 GB at the end against ~0.6 GB at the same point before
  • a naive reference-count guard that ignored the page tables evicted only 11 windows (50 MB), the reason the tables' references are discounted

232 tests passing, 247 with --all-features, clippy clean in both. The new test covers the four cases: an idle window goes, a fresh one stays, one held by another reference stays, a gone one is made again.

Risk

A window the title comes back to is copied again, which costs an allocation and a copy — on this machine the recycled bytes far outweighed that. Windows still held by an external Arc keep their memory until that holder goes, by design.

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

Tested locally merged onto origin/main (63bcca4) on Windows 11 x64 (NVIDIA GeForce RTX 5090 + WARP):

  • Diff review: Tracking last-use timestamps on LOOSE windows and evicting idle windows (VICTORY_WINDOW_IDLE_SECS, default 30 s) only when Arc::strong_count == 2 + shared_refs (so no live view, list, or heap still holds a reference) while dropping evicted copies outside the locks cleanly bounds loose-window memory growth.
  • cargo test -p victory-gpu --features diagnostics shadow::tests -- --test-threads=1 (RTX 5090 & WARP): 10 passed, 0 failed on both (including idle_loose_windows_go_and_fresh_ones_stay).
  • cargo clippy -p victory-gpu --features diagnostics --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

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

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

Tested locally on Windows 11 x64 (rustc 1.98.1, NVIDIA GeForce RTX 5090 + WARP):

  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings (default and --all-features): clean.
  • RTX 5090: shadow::tests --test-threads=1 (10 passed), memory::tests --test-threads=1 --skip lists_share_a_table_and_copies_keep_their_views (7 passed).
  • WARP (--features diagnostics, VICTORY_D3D12_WARP=1): shadow::tests (10 passed), memory::tests (8 passed); cargo xtask policy: 191 files ok.

There is a CI failure plus three concurrency issues in evict_older_than that need attention before merge:

  1. CI failure in shadow::tests::idle_loose_windows_go_and_fresh_ones_stay (crates/victory-gpu/src/shadow.rs:1784):
    CI failed with assertion left == right failed: one window went (left: 2, right: 1). Because cargo test runs tests in parallel in the same process, calling evict_older_than(Duration::from_secs(1)) also evicts loose windows created >1 s earlier by other tests, bumping the process-global EVICTED[0] counter past 1. Using a threshold well above test runtime (e.g. Duration::from_secs(1800) against the 3600 s backdate) and asserting on the delta (after >= before + 1) fixes the flake.

  2. TOCTOU between memory::shared_refs and Arc::strong_count (shadow.rs:107-116):
    shared_refs(shadow) locks and unlocks SHARED before evict_older_than re-locks LOOSE and checks Arc::strong_count(shadow) == 2 + tables. If a heap is dropped (memory::release) or a page table is rewritten (Shared::rewrite) in that gap, the actual table reference count drops by 1 while tables stays stale—so a live external holder (list, view, or heap) makes strong_count == 2 + tables evaluate true, evicting a window that is still in use and allowing a subsequent loose() call to create a duplicate Shadow for the same title memory range.
    Note that Shared::rewrite already locks SHARED before LOOSE (memory::prepare -> Shared::rewrite -> shadow::all()), so holding SHARED across the LOOSE check (same SHARED -> LOOSE order) avoids the TOCTOU without inverting lock order.

  3. Arc<Layout> refcount blindspot when Meter::frame races Host::execute (host.rs:3481, memory.rs:216, 576, 638, 645):
    Host::present calls p.meter.frame(p.hwnd) (shadow::evict_idle()) without holding self.submitted. Meanwhile, a concurrent Host::execute holds a clone of Arc<Layout> (in memory::prepare, defer_missed, and defer_after), which does not increment Arc::strong_count(shadow) for entries inside Layout.copies. evict_older_than can therefore evict a window from LOOSE while an in-flight submission is still reading/writing it via Layout, allowing a concurrent loose() call to allocate a second Shadow for the same range before copy-back completes. Running evict_idle() under the submission lock (like resource::evict_unused()) or verifying Arc::strong_count(&table.layout) == 1 while holding SHARED closes this race.

  4. Timestamp not re-checked under LOOSE lock (shadow.rs:108-112):
    If another thread calls loose() on a candidate between collecting candidates and re-locking LOOSE (updating *used = now and dropping its temporary Arc), line 109 only checks Arc::ptr_eq(held, shadow) and does not re-check now.saturating_duration_since(*used) >= idle, evicting a freshly accessed window.

Minor note: when tables > 0, removing a window from LOOSE increments EVICTED immediately even though Shared.layout.copies retains the last Arc<Shadow> (and its 4 MiB D3D12 buffer) until a subsequent title-memory submission triggers Shared::rewrite.

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Needs work. CI is failing: shadow::tests::idle_loose_windows_go_and_fresh_ones_stay asserts EVICTED[0] == 1 and got 2. EVICTED and LOOSE are process-wide, and evict_older_than sweeps every loose window, including ones other tests running in parallel made. The test needs to check only its own key, or compare a before/after delta of the counter. It must not depend on global totals.

Before this can be reviewed for merging, also please:

  • Explain in a short code comment why freeing the copy is safe for submissions still in flight. changed() only has the page tables rebuilt later, and a GPU table built from the old layout may still name the evicted copy's GPU address. Say what keeps that buffer alive until the GPU is done with it.
  • Put the new 5-second tracing::info! line in Meter behind diagnostics like the other counters. loose_stats and EVICTED are documented as diagnostics.

The memory win in the description is worth having. The verdict changes once CI is green and the in-flight lifetime is shown.


Generated by Claude Code

…RY_WINDOW_IDLE_SECS)

Copies of windows were never freed, and a long run kept every one it had ever made: one held 1,400 of them (6.4 GB) by its end, on a machine whose RAM is the limit. A window now goes when no submission has asked for it for 30 s (VICTORY_WINDOW_IDLE_SECS, 0 keeps them all) — but only one no view, list or heap still holds, since one of those would keep reading the old copy while a later ask made another of the same range. The page tables of memory::Shared name every copy, so their references are discounted (their lock is never held with the map's: a rewrite takes both, in the other order), and changed() has them rebuilt without the gone ones. Measured over a 902 s world run, the first on this machine to survive its whole length: 720 windows went and 3.4 GB came back, the live set stayed at 840 (3.6 GB) instead of growing without end, no allocation errors, and the title went farther into its story than any run before. Test: an idle window goes, a fresh one stays, a held one stays, a gone one is made again.
@Luislariosss

Copy link
Copy Markdown
Contributor Author

Thanks @fuzeofficlal and the triage — all points are fixed in the new head:

  1. CI flake. The test checks only its own window and that EVICTED[0] grew, and sweeps with a 1800 s threshold against a 3600 s backdate, so windows other tests made in parallel are not touched.
  2. TOCTOU between the table count and strong_count. memory::with_shared_refs holds the page tables' lock while the loose windows' lock is taken inside it (tables, then windows: the order Shared::rewrite → shadow::all() already takes them), and the count, the check and the removal happen in that one critical section.
  3. Sweep racing an in-flight submission. evict_idle() no longer runs from Meter::frame. It runs in Host::execute right after resource::evict_unused(), under submitted, so no submission is in flight and no Arc<Layout> clone from prepare/defer_missed/defer_after is live; it looks at the windows at most every 5 s. A comment there says what keeps a gone copy's buffer alive: the page tables hold their own reference until prepare rewrites them for the next submission.
  4. Time stamp not re-checked. Idleness is read under the windows' lock in the same pass.

Also: the 5 s tracing::info! line and loose_stats are behind diagnostics. EVICTED counts windows when they leave the map; their bytes come back once the tables are rewritten without them (noted in the code).

cargo test -p victory-gpu --locked: 232 passed (three runs in a row); --all-features: 247 passed; cargo clippy --all-targets -- -D warnings clean with and without --all-features.

@Luislariosss
Luislariosss force-pushed the perf/loose-window-eviction branch from 4a8176a to 3e937d3 Compare November 26, 2026 11:27
@pickles976

Copy link
Copy Markdown

Local RTX 4060 Laptop / 16 GiB system RAM verification at 3e937d3 (clean production source).

  • shadow::tests::idle_loose_windows_go_and_fresh_ones_stay: 1 passed, 0 failed, real NVIDIA device initialized.
  • Linux, NVIDIA 590.48.1, Wine 11.0, DXVK dxgi.hideNvidiaGpu = False. Important qualification: vkd3d-proton 3.2.0 2576c0b4adfae4a+ is our diagnostic-relaxed build (assertions disabled and allocator/list vtable identity checks removed; null checks retained), not stock-runtime certification.
  • Same diagnostics release for both title runs, Series S, reported 1920x1080, 1280x720 window cap, scripted A at 15/25/35s. Identical saved data and shader/vkd3d cache seed restored before each. Planned 95s, unchanged 2048 MiB available-RAM floor, 6000 MiB GPU cutoff, 9 GiB cgroup memory limit and 512 MiB swap limit.
idle disabled (0) default idle (30)
Starting available RAM, MiB 11842.2 11880.7
Guard stop, seconds after launch (excludes build) 68.68 66.60
Available RAM at stop, MiB 1734.6 2016.8
Last logged live loose windows / decimal MB 418 / 1946 445 / 2059
Last logged retired windows / decimal MB 0 / 0 12 / 67

Both runs remained on loading artwork and were deliberately stopped by the RAM guard, not diagnosed as application OOM crashes. The default sweep does run and removes windows, but it does not relieve this machine's first-loading RAM limit sufficiently. The 67 MB counter means removal from the loose map, not a direct measurement of resident bytes returned: page tables may retain references. A single pair with differing load progress and OS file-cache residency does not establish a timing regression or a causal endpoint-memory delta.

This is compatible with the large benefit you measured later in a long world run; our limiting burst happens earlier. Local logs: 20261126T125419Z-{console.log,resources.csv} and 20261126T125548Z-{console.log,resources.csv}. No game content attached.

AI-assisted: omp / OpenAI Codex ran the checks and drafted this report.

@pickles976

Copy link
Copy Markdown

One additional bounded run on the same clean 3e937d3780d529a0bd08a8644ff1c20ee53372cd: VICTORY_WINDOW_IDLE_SECS=5, restored the same cache/data/vkd3d-cache seed, same title/input sequence and unchanged guards/environment described above. Fresh GPU release compilation confirmed after switching back from other PRs.

Earlier eviction does operate during loading: last diagnostic reported 46 windows/252MB gone idle, versus12/67MB with the default30s. Remaining loose windows:414/1887MB. These are removed-map capacity counters, not proof of equivalent resident RAM returned.

The run still stopped at the2048MiB available-RAM guard after71.69s (available RAM12327.8→1796.2MiB; GPU3216MiB; final cgroup7165.6MiB, anon2748.6MiB, shmem4101.1MiB). Loading-art transition at50s, no gameplay; three compute pipeline refusals remained. Local log prefix 20261126T130504Z. Different starting RAM/progress means the extra seconds are not a quantified performance or total-RAM improvement.

This narrows the result: lowering the existing threshold increases early retirement, but does not resolve this machine's loading RAM floor. No recommendation to change the default from this single sample, and no conclusion about later world-run savings. Related standalone #2971/#2972/#2974 checks and title results: #3012 (comment) . Same diagnostic-relaxed vkd3d caveat; AI-assisted verification using omp/OpenAI Codex.

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

All previous concurrency and CI items are resolved in 3e937d37 — approving to clear the earlier change request.

Re-verified on main (63bcca43) on Windows 11 x64 (RTX 5090 + WARP + VICTORY_D3D12_DEBUG=1):

  • Moving shadow::evict_idle() into Host::execute (crates/victory-gpu/src/host.rs:1171) under submitted, holding SHARED -> LOOSE across the ref-count, timestamp check, and removal via memory::with_shared_refs (crates/victory-gpu/src/memory.rs:232), and gating loose_stats / the 5 s log behind diagnostics cleanly address all three concurrency races and the triage notes.
  • cargo xtask policy (191 files ok) and cargo clippy --locked -p victory-gpu --all-targets -- -D warnings (default and --all-features) pass.
  • Three consecutive full parallel cargo test --locked -p victory-gpu --features diagnostics runs under WARP all passed (247/247 each), and shadow::tests:: + memory::tests:: passed under VICTORY_D3D12_DEBUG=1 on both RTX 5090 and WARP.
  • An additional lifecycle probe with a live Shared page table (refs_in_tables = 1) confirmed on both RTX 5090 and WARP under VICTORY_D3D12_DEBUG=1 that a held window stays, dropping the external ref lets evict_older_than evict it and bump generation(), the page table keeps the buffer alive until memory::prepare rewrites it, and the final Arc<Shadow> drops cleanly afterward with zero Debug Layer messages.

(Tiny non-blocking typo: crates/victory-gpu/src/shadow.rs:1105 and shadow.rs:1281 have UTF-8 mojibake in two comments — — and → instead of — and →.)

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants