Skip to content

D3D12.X: evict top texture mips under local VRAM budget - #3098

Open
O5-7 wants to merge 1 commit into
xcl-dev:mainfrom
O5-7:vram/ws5-budget-eviction
Open

O5-7 wants to merge 1 commit into
xcl-dev:mainfrom
O5-7:vram/ws5-budget-eviction

Conversation

@O5-7

@O5-7 O5-7 commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Implements opt-in automatic top-mip VRAM budget eviction (XCL_TEXTURE_BUDGET_EVICT=1) on top of the Workstream 5 SRV-tracking and tile-class foundation already in main. Default behavior with XCL_TEXTURE_BUDGET_EVICT unset is unchanged.

Part of #2688

What is in it

  • crates/xcl/src/hle/d3d12x/console_heap.rs: expose ViewSlotLease::device(&self) -> &ID3D12Device.
  • crates/xcl/src/hle/d3d12x/real.rs: add unhooked native_create_srv and native_copy_descriptors_simple helpers for quiescent SRV descriptor clamping, apply resident_min_mip clamp on new SRV creation in dev_create_srv_x, and update note_srv last-touch tracking when srv_tracking_enabled().
  • crates/xcl/src/hle/d3d12x/vram.rs:
    • Add XCL_TEXTURE_BUDGET_PCT (default 85, clamped 50..=98), XCL_TEXTURE_BUDGET_MB override, Levels::evictable_chain, TilePool::mark_heap_pinned, Pages::unmap_range, clamp_srv_min_lod, default_srv_desc, resident_min_mip, heap-draining candidate selection (pick_evict_candidates_by_heap), and quiescent evict_under_budget executed periodically in before_execute using with_exact_tracked_srv_mutations (failing closed if any descriptor generation or raw word changed or gained an untracked SRV before mutation).
    • Track Target::last_touch and Target::min_resident_mip, isolate evictable top mips from packed tails and pinned aliases, update resident_texels and EVICT_STATS (TexelStats::evicted_mips / evicted_tiles), and add unit + GPU verification tests (clamp_srv_min_lod_raises_clamp_without_lowering_existing, heap_draining_eviction_empties_coldest_heaps_first_and_skips_pinned, gpu_unmap_top_mip_with_srv_min_lod_clamp_samples_resident_mip).
  • crates/xcl/src/host.rs: append ; evicted {} mips ({} MB) to XCL_ACTIVITY=1 texture residency: logging when evictions occur.

Tested

  • Hardware / toolchain: NVIDIA GeForce RTX 5080 (driver 32.0.15.9579), AMD Ryzen 7 9700X, Windows 11 Pro 10.0.26100, rustc 1.100.0 (0ef1bc386 2026-11-09).
  • cargo test -p xcl --lib vram::tests -- --nocapture --test-threads=1: 65 passed, 0 failed, 1 ignored (churn_update_tile_mappings_timing), 0 skipped.
  • cargo test -p xcl --lib console_heap::tests -- --nocapture --test-threads=1: 15 passed, 0 failed, 0 ignored, 0 skipped.
  • cargo build --release -p xcl: clean build with 0 new warnings (26 pre-existing warnings on main).
  • Paired 60 s default retail smoke (title: 9cc6a39e, run with XCL_PREPARE=0 per 8617577b, XCL_TEXTURE_* unset): 60f1a222 matched main e429936c cleanly (944 vs 895 frames shown, 13703 vs 13711 MB peak commit, 0 crashes, 0 device removals).
  • Active-eviction 60 s retail smoke (XCL_PREPARE=0 XCL_TEXTURE_BUDGET_EVICT=1 XCL_TEXTURE_BUDGET_MB=4096): exit: 0x0, 923 frames shown (PresentX 923), 13773 MB peak commit, 0 crashes, 0 device removals; logged D3D12.X: texture budget eviction: evicted 71 mip groups (22 MB) at 6046 / 4096 MB local VRAM and texture residency: 514 sampled (508 with SRV); texels 275.0M resident / 314.0M srv-sampled / 314.0M virtual (87% resident); evicted 71 mips (22 MB).

Regression run

xcl-smoke v1
commit: e429936c10a5b8aa09470ff99dfc8c8d3d8c56fd
gpu: NVIDIA GeForce RTX 5080
title: 9cc6a39e
seconds: 60
exit: 0x0
frames shown: 895 (PresentX 895)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 13711 MB
xcl-smoke v1
commit: 60f1a2225d5e34d4d69b96abcae5a0b8d8b0262d
gpu: NVIDIA GeForce RTX 5080
title: 9cc6a39e
seconds: 60
exit: 0x0
frames shown: 944 (PresentX 944)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 13703 MB

Not tested

  • Full cargo test --workspace at 60f1a222 (only vram::tests and console_heap::tests ran after final edits; benches/runtime.rs on base main e429936c fails to compile due to upstream Config.input_profile visibility).
  • Extended world traversal under XCL_TEXTURE_BUDGET_EVICT=1 to confirm multi-heap reclamation after 2 s cooling during longer sessions.
  • AMD, Intel, or Linux/Wine GPUs.

AI use

  • Implemented quiescent budget eviction on top of main's SRV-lease primitives, resolved test/lock ordering issues, ran tests, release build, and smokes (default and XCL_TEXTURE_BUDGET_EVICT=1), and drafted this description with Antigravity (Gemini 4 Neon).

Build automatic opt-in top-mip budget eviction (XCL_TEXTURE_BUDGET_EVICT=1)
on top of the Workstream 5 SRV-lease and tile-class foundation:
- Track last-touch timestamp and min_resident_mip per placed sampled 2D texture,
  and keep pinned aliases from mixing with future evictable heap packing.
- When DXGI local VRAM usage reaches XCL_TEXTURE_BUDGET_PCT (default 85%, or
  XCL_TEXTURE_BUDGET_MB override), select coldest evictable heaps first,
  re-clamp all tracked SRVs atomically under with_exact_tracked_srv_mutations
  (failing closed if any descriptor generation or raw word changed), update
  resident mip clamps before unmapping, and release top-mip tiles for cooling
  and 64 MiB heap reclamation.
- Also clamp new/copied SRVs on creation via resident_min_mip and log cumulative
  evictions in XCL_ACTIVITY=1.

Part of xcl-dev#2688

Assisted-by: Antigravity (Gemini 4 Neon)
@andrewDoing

Copy link
Copy Markdown
Contributor

I found a candidate-selection starvation case on head 60f1a222 with an exact-source Rust harness for pick_evict_candidates_by_heap and the downstream tracked-SRV check.

For a 64-tile target, heap A had 64 mapped tiles and no tracked SRV; heap B had 128 mapped tiles and a tracked SRV. The picker chose A, after which the tracked set for the selection was empty and the pass returned before unmapping. A second identical tick chose A again, leaving B untouched. Removing A selected B; marking both resources tracked preserved the intended preference for A.

Filtering the raw candidates against a snapshot of tracked resources before selection could avoid this starvation, while retaining the final quiescence and descriptor-generation revalidation. This is selection/control-flow evidence; I did not run actual GPU eviction, prove retail incidence, or measure reclamation.

AI use: OpenAI Codex with GPT-6.2 Astra built and ran the controls; Codex reviewed and prepared this report.

@andrewDoing

Copy link
Copy Markdown
Contributor

I checked a distinct SRV-range boundary on RTX 5070 / NVIDIA 616.92 at head 60f1a222 with a test-only native fixture. A two-mip texture had red mip 0 and green mip 1. The fixture used the production clamp helper, unmapped mip 0, then sampled through explicit SRVs after queue completion.

SRV view Before After clamp to mip 1 and unmap
Broad: most-detailed 0, 2 mips Red Green
Tail only: most-detailed 1, 1 mip Green Green
Top only: most-detailed 0, 1 mip Red Zero

Mip 1 remained resident in all cases, but it is outside the top-only view. The production all_clampable check appears to require a descriptor to exist without checking whether its exposed mip range intersects the surviving chain. A resource with any live SRV whose range ends before the proposed resident mip may need to be excluded, unless its view can be safely changed to expose a surviving level.

The fixture exercised the actual clamp helper, tile unmap, fence, and native sampling; candidate selection was source-reviewed rather than exercised end to end. No driver pressure, retail title, image-quality frequency, or performance was measured.

AI use: OpenAI Codex with GPT-6.2 Astra built and ran the fixture; Codex reviewed and prepared this report.

@DarkPanda69

Copy link
Copy Markdown

AMD run on an RX 9070 XT (with an RTX 3060 in the same PC): the three new tests pass, and nothing else in vram / console_heap changes.

Tested: at the PR head 60f1a22 against its merge-base, main e429936. Debug, Rust 1.100.0, Windows 11 Pro 26200, Ryzen 7 5800X. RX 9070 XT (RDNA4) driver 32.0.32029.2010; RTX 3060 driver 32.0.16.1088.

  • cargo test -p xcl --lib -- hle::d3d12x::vram::tests hle::d3d12x::console_heap::tests --test-threads=1 --nocapture, once with XCL_ADAPTER=Radeon and once with =3060: merge-base 77 passed, 0 failed, 1 ignored; PR 80 passed, 0 failed, 1 ignored, no SKIPPED, both times.
  • The only changes are clamp_srv_min_lod_raises_clamp_without_lowering_existing, heap_draining_eviction_empties_coldest_heaps_first_and_skips_pinned and gpu_unmap_top_mip_with_srv_min_lod_clamp_samples_resident_mip, all ok.
  • Which card ran the GPU test: gpu_unmap_top_mip_with_srv_min_lod_clamp_samples_resident_mip makes its device with D3D12CreateDevice(None, ..), which takes the first adapter and ignores XCL_ADAPTER. On this PC that's the RX 9070 XT, so both runs exercised the tiled tier-2 unmap and the min-LOD clamp on AMD. Neither run covers the RTX 3060's GPU.

Not tested: the whole suite, a title, XCL_TEXTURE_BUDGET_EVICT=1 outside the unit tests, the RTX 3060 for the GPU test (see above), Intel.

AI use: Claude Code (Claude Opus 5.5) ran the tests on this machine and wrote this report.

@JJAutoCompare

Copy link
Copy Markdown

Tested

Exact 60f1a2225d5e34d4d69b96abcae5a0b8d8b0262d on Windows 11 25H2 build 26200.9974, Ryzen 7 3800X, and Rust 1.100.1 MSVC debug. I reran the pinned libtest from a verified Git archive with one private test added. All 393 original files matched their Git blobs when the fixture was excluded.

I ran <libtest.exe> --exact <test> --nocapture --test-threads=1 separately for two tests under hle::d3d12x::vram::tests.

  • default_texture_srvs_preserve_view_fields_when_clamping_lod called default_srv_desc and clamp_srv_min_lod for a four-mip, three-slice 2D array and a five-mip 3D texture. Both started at zero. Higher requests raised ResourceMinLODClamp, and lower or repeated requests left it unchanged. Format, dimension, component mapping, mip range, and the array's slice and plane fields stayed intact. The default-descriptor helper returned None for the four-sample 2D input.
  • The stock scalar control clamp_srv_min_lod_raises_clamp_without_lowering_existing passed.

2 passed, 0 failed, 0 ignored, 0 runtime skips. Both native processes exited 0.

Not tested

GPU or device behavior, sampling, runtime eviction, allocator pressure, performance, retail titles, the base revision, and the full suite.

AI use

T3 Code through the Codex harness (gpt-6.2-sol) verified the archive, fixture and executable, ran the tests and wrote this report.

@fromthemoonx

Copy link
Copy Markdown

Full workspace suite on NVIDIA (listed under Not tested): no new failure. The 9 that fail are the ones current main e429936 fails here too (#3093). Each new test catches its part when that part is reverted.

Tested: 60f1a22 (its base is current main e429936, so head = merged). RTX 3060 12 GB (driver 610.88), Ryzen 7 5700X, Windows 11 Pro 26300, Rust 1.100.0 MSVC, debug, D3D12 debug layer installed.

result
cargo test --workspace --no-fail-fast -- --test-threads=4 2129 passed, 9 failed, 48 ignored; 25 SKIPPED lines. The 9 are main's: the 3 e2e title tests (post-Wait32/64 write failed (0x0)) and 6 split-wave64 GPU tests, all listed in #3093
the 3 new tests alone, 30 runs each; hle::d3d12x::vram:: (65 tests) at --test-threads=8, 30 runs 30 of 30 each (the GPU test ran, no SKIPPED); 30 of 30
e2e debug-layer messages (the title fails as on main) the same as on main: 3× error id 93, 1× error id 1046, 1× warning id 820, 2× warning id 926, 8× id 0; no texture budget eviction line, so the default path does not evict
scratch: clamp_srv_min_lod sets the clamp instead of raising it clamp_srv_min_lod_raises_clamp_without_lowering_existing fails (left: 1.0)
scratch: clamp_srv_min_lod leaves the clamp alone the same test fails (left: 0.5), and gpu_unmap_top_mip_with_srv_min_lod_clamp_samples_resident_mip fails: with mip 0 unmapped and SRV clamped to mip 1, sampling LOD 0 reads green, left: 0
scratch: !ev moved to the end of the heap sort key heap_draining_eviction_empties_coldest_heaps_first_and_skips_pinned fails (left: [1, 31, 30])

Not tested: XCL_TEXTURE_BUDGET_EVICT=1 in a title (no title here), a release build, AMD / Intel.

AI use: Claude Code (Claude Opus 5.5) ran the tests and the scratch mutations and wrote this report.

@Anon64

Anon64 commented Nov 28, 2026 •

Copy link
Copy Markdown

Test report for 60f1a222 on an RTX 3060 12 GB, against main e429936c. Same title (a newer retail game), 300 s, release, XCL_PREPARE=0 as in your runs, XCL_PRESS_A_AT for the menus.

Default (XCL_TEXTURE_BUDGET_EVICT unset): no regression.

xcl-smoke v1
commit: e429936c10a5b8aa09470ff99dfc8c8d3d8c56fd
gpu: NVIDIA GeForce RTX 3060
title: retail-1
seconds: 300
exit: 0x0
frames shown: 1794 (PresentX 1794)
presents per 2 s (last 3): 0 0 0
device removals: 0
crashes: 0
peak commit: 39048 MB
xcl-smoke v1
commit: 60f1a2225d5e34d4d69b96abcae5a0b8d8b0262d
gpu: NVIDIA GeForce RTX 3060
title: retail-1
seconds: 300
exit: 0x0
frames shown: 1744 (PresentX 1744)
presents per 2 s (last 3): 0 0 0
device removals: 0
crashes: 0
peak commit: 41198 MB

That's 97 % of main's frames and 106 % of its peak commit. Peak local video memory: 15 056 MB on main, 14 852 MB on the PR.

XCL_TEXTURE_BUDGET_EVICT=1: memory runs away on this card. Twice, my RAM watchdog (free < 4 GB) ended the run about 90 s in, before the smoke script got its summary. The second time xcl.exe held 51.4 GB. The log of that run, every 2 s near the end:

time process commit local video memory target-page pools
82.7 s 39 559 MB 22 005 MB 18 112 MB
84.7 s 41 931 MB 24 553 MB 20 608 MB
86.7 s 45 218 MB 27 524 MB 23 552 MB
88.8 s 50 399 MB 32 787 MB (of an 11 095 MB budget) 28 800 MB, 21 454 MB of it free

At 86.7 s the residency line says evicted 418 mips (401 MB), and it still says 418 at 88.8 s. So eviction frees a few hundred MB, while the target-page pools grow by 2.5–5 GB every 2 s, and most of that is free pool memory. A possible mechanism from reading vram.rs at 60f1a222 (not confirmed by a run). When a pinned (non-evictable) placement finds one of its pages already on heap h, mark_heap_pinned(h) flips the whole heap to the pinned class, free tiles included, and nothing flips it back short of the heap emptying. pick_heap only takes heaps of the requesting class, so the evictable class can't use those free tiles and take_batch makes a new 64 MiB heap. If pinned placements keep landing on pages of fresh evictable heaps (title placements that share addresses), every new heap gets pinned while it's still mostly free. That would match free pool memory growing much faster than eviction frees anything.

Edit, a run that checks that: the same head with one local change, mark_heap_pinned returning at once (so no heap changes class), XCL_TEXTURE_BUDGET_EVICT=1, the same 300 s run. It ran to the end:

xcl-smoke v1
commit: 92fc7f57f4b4b89581acbb502d09889309fdb75c
gpu: NVIDIA GeForce RTX 3060
title: retail-1
seconds: 300
exit: 0x0
frames shown: 1714 (PresentX 1714)
presents per 2 s (last 3): 0 0 0
device removals: 0
crashes: 0
peak commit: 44877 MB

(92fc7f57 is that local test commit on top of 60f1a222, not a commit of this PR.) At 299 s: target-page pools 9 472 MB, against 28 800 MB at 89 s with the flip; eviction had freed 9 091 mips (3 774 MB); local video memory peaked at 14 977 MB, about where main and the PR's default run peak, so still above the 11 GB budget. So the heap flip is what made the pools run away here. Skipping it is only a test, not a fix: a pinned tail can then sit on a heap that eviction drains. The default run never gets near this: its peak local video memory is 14.9 GB.

Edit, @thehollowedone's candidate (comment patch on 60f1a222, local commit 7e29ee63, not a commit of this PR): hle::d3d12x::vram::tests 66 passed, 0 failed, 1 ignored on the 3060. Same retail run, XCL_TEXTURE_BUDGET_EVICT=1, XCL_PREPARE=0, 300 s planned:

  • The pool runaway is gone: target-page pools grow with the pages in use and stop at 9 728 MB, only 421 MB of it free at 158 s (against 28 800 MB, 21 454 MB free, at 89 s with the relabel). Eviction had freed 548 mips (570 MB) by then.
  • The run still didn't finish: my RAM watchdog (free < 4 GB) ended it at ~159 s. Process commit was 52 748 MB, and D3D12.X: a memory line by owner, against DXGI's budget #2697's owner line puts 45 484 MB of it in "other" (UMA window 4 095, sparse CPU copy 3 168), so not the pools. Local video memory was 15 134 MB of an 11 256 MB budget. Commit climbed from 33.7 GB to 43.8 GB in about 16 s, and to 52.7 GB in the next 16 s, while the pools stayed at 9 728 MB. That growth is not eviction: the same build with XCL_TEXTURE_BUDGET_EVICT unset, same run, climbs the same way ("other" 27.3 GB at 122 s, 41.8 GB at 166 s, local video memory 15.0 GB) and my watchdog ended it at ~170 s too. So on this machine today the RAM runs out with or without eviction, in "other", not in anything D3D12.X: evict top texture mips under local VRAM budget #3098 owns. (My first runs above reached 300 s at 39–41 GB; I don't know yet what differs.)

So the candidate fixes the stranding this report was about, and eviction on doesn't add RAM growth of its own here.

RTX 3060 12 GB (driver 581.80), i9-14900KF, 64 GB RAM, Windows 11 26200. Not tested: the whole suite, AMD, a run longer than 300 s.

AI use: Claude Code (Claude Opus 5.5) ran the builds and tests, applied the candidate patch, read the logs and wrote this report.

@thehollowedone

thehollowedone commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to the RTX 3060 memory-growth report, checked against head 60f1a222.

The reported mark_heap_pinned path changes an evictable heap's allocation class when a pinned placement shares one page. Its remaining free tiles then cannot serve evictable requests, so take_batch can allocate another 64 MiB heap while that one has space. I tested a scoped correction: keep the heap's fresh-allocation class, record pinned occupancy separately for eviction priority, and clear that record when a fully cooled heap is reused. New pinned tiles still go to the pinned class; shared-page ownership remains governed by users in release_tiles, and a whole heap is reclaimed only after every tile is free.

A new allocator regression failed under the original relabeling behavior (0 passed, 1 failed) and passed with the candidate (1 passed, 0 failed). On the corrected candidate, cargo test --offline --locked -j 4 -p xcl --lib hle::d3d12x::vram::tests -- --test-threads=4 reported 66 passed, 0 failed, 1 ignored, 0 GPU skips on Windows 11 build 26300, RTX 3080 Ti 621.35, Ryzen 7 9800X3D, Rust 1.99.1 MSVC. git diff --check passed.

This covers the free-tile stranding mechanism. The candidate has not had a retail active-eviction run or paired smoke, and the top-only SRV range finding also remains to be resolved before merge.

Candidate diff and regression
diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs
index 6e4b19ac..9fb445e3 100644
--- a/crates/xcl/src/hle/d3d12x/vram.rs
+++ b/crates/xcl/src/hle/d3d12x/vram.rs
@@ -1215,6 +1215,8 @@ struct TilePool {
     /// Fresh-allocation packing class for heap `h`. Shared address pages may give either class
     /// live owners here, so this is never proof that a heap is safe to evict.
     heap_evictable: Vec<bool>,
+    /// A pinned allocation has occupied this heap since it was last empty.
+    heap_has_pinned: Vec<bool>,
     /// Total free tiles currently available across all heaps.
     free_total: usize,
     /// Tiles given back, reusable after `COOL`.
@@ -1227,6 +1229,7 @@ impl TilePool {
             free_by_heap: Vec::new(),
             dirty_sort: Vec::new(),
             heap_evictable: Vec::new(),
+            heap_has_pinned: Vec::new(),
             free_total: 0,
             cooling: std::collections::VecDeque::new(),
         }
@@ -1238,11 +1241,13 @@ impl TilePool {
             self.free_by_heap.resize_with(idx + 1, Vec::new);
             self.dirty_sort.resize(idx + 1, false);
             self.heap_evictable.resize(idx + 1, false);
+            self.heap_has_pinned.resize(idx + 1, false);
         }
         debug_assert!(self.free_by_heap[idx].is_empty());
         self.free_by_heap[idx] = (0..pool_pages).rev().collect();
         self.dirty_sort[idx] = false;
         self.heap_evictable[idx] = evictable;
+        self.heap_has_pinned[idx] = !evictable;
         self.free_total += pool_pages as usize;
     }
 
@@ -1266,6 +1271,7 @@ impl TilePool {
             self.free_by_heap[h].shrink_to_fit();
             self.dirty_sort[h] = false;
             self.heap_evictable[h] = false;
+            self.heap_has_pinned[h] = false;
             self.free_total -= full;
             reclaimed.push(h as u32);
         }
@@ -1374,6 +1380,10 @@ impl TilePool {
                 self.dirty_sort[h] = false;
             }
             let free = &mut self.free_by_heap[h];
+            if free.len() == pool_pages as usize {
+                // No prior owner remains in a fully cooled heap.
+                self.heap_has_pinned[h] = !evictable;
+            }
             let take = rem.min(free.len());
             for _ in 0..take {
                 let t = free.pop().unwrap();
@@ -1385,8 +1395,8 @@ impl TilePool {
     }
 
     fn mark_heap_pinned(&mut self, slot: u32) {
-        if let Some(flag) = self.heap_evictable.get_mut(slot as usize) {
-            *flag = false;
+        if let Some(flag) = self.heap_has_pinned.get_mut(slot as usize) {
+            *flag = true;
         }
     }
 }
@@ -2707,7 +2717,8 @@ unsafe fn evict_under_budget(dev: &ID3D12Device, dev_key: usize, now: std::time:
             let Some(lv) = t.levels.as_ref() else { continue };
             let Some((tiles, tail_mip)) = lv.evictable_chain() else { continue };
             let Some(heap) = evictable_heap(pages, lv) else { continue };
-            let heap_evictable = pages.pool.heap_evictable.get(heap as usize).copied().unwrap_or(false);
+            let heap_evictable = pages.pool.heap_evictable.get(heap as usize).copied().unwrap_or(false)
+                && !pages.pool.heap_has_pinned.get(heap as usize).copied().unwrap_or(true);
             let heap_free = pages.pool.free_by_heap.get(heap as usize).map_or(0, |v| v.len() as u32);
             raw_cands.push(HeapEvictCandidate {
                 res_key,
@@ -4328,6 +4339,36 @@ mod tests {
         assert_ne!(evictable[0].0, pinned[0].0, "allocation classes must not share a pool heap");
     }
 
+    #[test]
+    fn pinned_alias_does_not_strand_free_tiles_in_evictable_heap() {
+        const P: u32 = 64;
+        let now = Instant::now();
+        let mut pool = TilePool::new();
+        let next_slot = std::cell::Cell::new(0u32);
+        let mut alloc_slot = || {
+            let slot = next_slot.get();
+            next_slot.set(slot + 1);
+            Some(slot)
+        };
+
+        let first = pool.take_batch(1, None, true, now, P, &mut alloc_slot).unwrap();
+        let heap = first[0].0;
+        pool.mark_heap_pinned(heap); // a non-evictable placement shares the existing page
+        let pinned = pool.take_batch(1, None, false, now, P, &mut alloc_slot).unwrap();
+        assert_ne!(pinned[0].0, heap, "new pinned tiles still use a separate heap");
+        let rest = pool.take_batch(P as usize - 1, None, true, now, P, &mut alloc_slot).unwrap();
+        assert!(rest.iter().all(|&(h, _)| h == heap));
+        assert_eq!(next_slot.get(), 2, "a pinned alias must not strand the heap's free tiles");
+        assert!(pool.heap_evictable[heap as usize]);
+        assert!(pool.heap_has_pinned[heap as usize]);
+
+        pool.return_tiles(&first);
+        pool.return_tiles(&rest);
+        let reused = pool.take_batch(1, None, true, now, P, &mut alloc_slot).unwrap();
+        assert_eq!(reused[0].0, heap);
+        assert!(!pool.heap_has_pinned[heap as usize], "a fully free warm heap loses the old pin");
+    }
+
     #[test]
     fn tile_pool_keeps_one_warm_spare_for_each_allocation_class() {
         const P: u32 = 64;

AI use: Codex (GPT-6.2 Sol) traced the allocator, wrote and ran the candidate regression, and checked the diff; Codex (GPT-6.2 Astra) independently reviewed ownership and warm-heap reuse.
Update — tail residency, same head. With lazy level mapping, a top group can be mapped before the packed tail. Levels::evictable_chain currently returns that top group even when the tail group is unmapped; eviction could then clamp the view toward a mip with no tiles. A new two-group regression failed on the original predicate (0 passed, 1 failed: it returned Some((1, 1)) with the tail unmapped). Requiring the tail to be mapped before selecting the chain made that test pass; cargo test --offline --locked -j 4 -p xcl --lib hle::d3d12x::vram::tests -- --test-threads=4 reported 66 passed, 0 failed, 1 ignored, 0 GPU skips, and git diff --check passed.

This is a separate candidate guard, not a complete resolution of the top-only SRV issue. Descriptor changes and tile mappings still need their existing lifetime checks; I did not run an active retail eviction test for this update.

Tail-residency regression and candidate guard
diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs
index 6e4b19ac..ab93827a 100644
--- a/crates/xcl/src/hle/d3d12x/vram.rs
+++ b/crates/xcl/src/hle/d3d12x/vram.rs
@@ -885,6 +885,9 @@ impl Levels {
     /// Total tiles and packed-tail start mip if at least one evictable top group is mapped.
     fn evictable_chain(&self) -> Option<(u32, u32)> {
         let last = self.groups.len().checked_sub(1)?;
+        if !self.groups[last].3 {
+            return None;
+        }
         let mut tiles = 0u32;
         for g in &self.groups[..last] {
             if g.3 {
@@ -4145,6 +4148,15 @@ mod tests {
         assert_eq!(levels.group_tiles, expected, "cancelling a deferred unmap restores every group owner");
     }
 
+    #[test]
+    fn top_mips_are_not_evictable_until_the_tail_is_mapped() {
+        let mut levels = Levels::new(&[(0, 1)], Some((1, 1)), 2, 2).unwrap();
+        levels.groups[0].3 = true;
+        assert_eq!(levels.evictable_chain(), None);
+        levels.groups[1].3 = true;
+        assert_eq!(levels.evictable_chain(), Some((1, 1)));
+    }
+
     #[test]
     fn resource_release_takes_every_level_group_owner() {
         let mut levels = Levels::new(&[(0, 1), (1, 1)], Some((2, 1)), 3, 4).unwrap();

AI use for this update: Codex (GPT-6.2 Sol) traced, wrote, and ran the focused test; Codex (GPT-6.2 Astra) reviewed the lazy-map and descriptor paths.

@thehollowedone

Copy link
Copy Markdown
Contributor

One remaining correctness boundary for head 60f1a222, following the top-only SRV report: checking only views live at eviction cannot cover a top-only view created afterward.

Eviction unmaps and releases the top-level tiles. A later CreateShaderResourceView raises ResourceMinLODClamp to the saved floor, but a mip-0-only view has MostDetailedMip=0, MipLevels=1; mip 1 is outside its D3D12 view range. map_levels can bind replacement tiles without restoring their texels, and under budget pressure it skips levels below the saved floor. The normal upload path can skip unchanged CPU bytes, while GPU-write tracking retains submission provenance rather than the resulting texture contents. A CPU source is therefore not necessarily the current mip after GPU writes.

To preserve the resource's contents, eviction eligibility needs a guarantee that each discarded subresource can be restored before any later use requiring it, or a lifetime guarantee ruling that use out. A restore path would need authoritative versioned contents, mapping and upload even under continued pressure, and a queue wait before the first dependent submission. Until such a path exists for a resource, keeping its top mips resident is the correctness-preserving option. A live-view range guard still addresses views already present, but does not establish this future-use guarantee.

Suggested regression: upload red mip 0 and green mip 1, overwrite mip 0 with blue through a GPU copy, run the production eviction with only a broad SRV live, then create a mip-0-only SRV under sustained pressure. The sample must still be blue; if that source is not restorable, assert that eviction left mip 0 mapped.

This is a source-path finding and a test design; I have not run that late-view GPU regression. AI use: Codex (GPT-6.2 Sol) traced the source and checked the conclusion; Codex (GPT-6.2 Astra) independently reviewed the SRV and texture-lifetime paths.

@andrewDoing

Copy link
Copy Markdown
Contributor

I tested a narrow candidate for the top-only SRV finding on head 60f1a222. It checks the ranges of currently tracked views before ranking heaps, then repeats the range check in the existing descriptor-mutation pass. A broad view and a top-only view of the same resource together disqualify that resource.

With a 64-tile request, the existing picker initially preferred heap A (64 tiles). With both those views on A, the candidate picked heap B (128 eligible tiles). Removing A’s top-only view restored the preference for A. A zero-tile request selected neither. This uses synthetic candidate metadata and the production selection helpers.

Native RTX 5070, NVIDIA 616.92, two-mip reserved texture. The fixture exercised the new range predicate, native SRV rewrite, tile unmap when eligible, fence, and shader readback:

SRV Initial sample Candidate action Final sample
Mips 0–1 Red Evict mip 0 Green
Mip 1 only Green Evict mip 0 Green
Mip 0 only Red Keep mip 0 Red (stock fixture returned zero after eviction)

The focused VRAM module run with the fixture overlay completed 66 passed, 0 failed, 1 ignored (opt-in tile-mapping timing test). The native fixture made the eviction decision directly with the predicate. DXGI pressure and the full production eviction tick were outside this test.

This addresses the live-view and heap-selection cases. The later-created view finding still applies: a view may be created after eviction and require content previously written by the GPU. I would keep the opt-in restriction and treat a mapped tail and reliable restoration or lifetime guarantees as separate prerequisites before enabling this generally. The candidate is attached here for the author to use independently of the allocator changes.

Candidate and selection regression against 60f1a22
--- a/crates/xcl/src/hle/d3d12x/vram.rs
+++ b/crates/xcl/src/hle/d3d12x/vram.rs
@@ -1054,6 +1054,11 @@
     };
     let start = most_detailed.max(clamp_mip).min(end);
     start..end
+}
+
+fn view_reaches_resident_mips(mips: u32, tail: u32, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> bool {
+    let range = srv_mip_range(mips, desc);
+    range.start.max(tail) < range.end
 }
 
 fn srv_slice_range(res_slices: u32, dim: i32, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> std::ops::Range<u32> {
@@ -2686,6 +2691,21 @@
     None
 }
 
+fn retain_visible_candidates(
+    raw_cands: &mut Vec<HeapEvictCandidate>,
+    tail_by_res: &HashMap<usize, (u32, u32)>,
+    tracked: &TrackedSrvs,
+    dev_key: usize,
+) {
+    let mut eligible = std::collections::HashMap::<usize, bool>::new();
+    for entry in tracked.by_slot.values().filter(|entry| entry.device == dev_key) {
+        let Some(&(tail, mips)) = tail_by_res.get(&entry.resource) else { continue };
+        let allowed = view_reaches_resident_mips(mips, tail, entry.desc.as_ref());
+        *eligible.entry(entry.resource).or_insert(true) &= allowed;
+    }
+    raw_cands.retain(|c| eligible.get(&c.res_key) == Some(&true));
+}
+
 unsafe fn evict_under_budget(dev: &ID3D12Device, dev_key: usize, now: std::time::Instant) {
     let Some((usage, budget)) = local_vram_usage_and_budget(dev) else { return };
     let pct = budget_evict_pct();
@@ -2696,7 +2716,7 @@
     let want_bytes = usage.saturating_sub(budget.saturating_mul(low_pct) / 100);
     let target_tiles = (want_bytes / PAGE as u64).clamp(64, 8192);
     let mut raw_cands: Vec<HeapEvictCandidate> = Vec::new();
-    let mut tail_by_res: std::collections::HashMap<usize, u32> = std::collections::HashMap::new();
+    let mut tail_by_res: std::collections::HashMap<usize, (u32, u32)> = std::collections::HashMap::new();
     {
         let g = PAGES.lock().unwrap();
         let Some(Some(pages)) = g.get(&dev_key) else { return };
@@ -2717,11 +2737,17 @@
                 last_touch: t.last_touch,
                 tiles,
             });
-            tail_by_res.insert(res_key, tail_mip);
+            tail_by_res.insert(res_key, (tail_mip, lv.mips));
         }
     }
     if raw_cands.is_empty() {
         return;
+    }
+    // Filter before ranking so a resource with an unusable view cannot consume the tile target.
+    {
+        let g = TRACKED_SRVS.lock().unwrap();
+        let Some(tracked) = g.as_ref() else { return };
+        retain_visible_candidates(&mut raw_cands, &tail_by_res, tracked, dev_key);
     }
     let chosen = pick_evict_candidates_by_heap(&raw_cands, target_tiles);
     if chosen.is_empty() {
@@ -2754,8 +2780,10 @@
         let mut all_clampable: std::collections::HashMap<usize, bool> = std::collections::HashMap::new();
         for m in mutations {
             *surviving.entry(m.entry.resource).or_insert(0) += 1;
-            let clampable = tail_by_res.contains_key(&m.entry.resource)
-                && m.entry.desc.or_else(|| default_srv_desc(&m.resource.GetDesc())).is_some();
+            let desc = m.entry.desc.or_else(|| default_srv_desc(&m.resource.GetDesc()));
+            let clampable = tail_by_res.get(&m.entry.resource).is_some_and(|&(tail, mips)| {
+                desc.as_ref().is_some_and(|d| view_reaches_resident_mips(mips, tail, Some(d)))
+            });
             all_clampable
                 .entry(m.entry.resource)
                 .and_modify(|ok| *ok &= clampable)
@@ -2770,7 +2798,7 @@
             if surviving.get(&res_key).copied() != live_counts.get(&res_key).copied() {
                 continue;
             }
-            let Some(&tail_mip) = tail_by_res.get(&res_key) else { continue };
+            let Some(&(tail_mip, _)) = tail_by_res.get(&res_key) else { continue };
             let Some(mut d) = m.entry.desc.or_else(|| default_srv_desc(&m.resource.GetDesc())) else { continue };
             clamp_srv_min_lod(&mut d, tail_mip);
             super::real::native_create_srv(m.heap.device(), m.resource, &d, m.heap.pc_srv);
@@ -5278,6 +5306,41 @@
     }
 
     #[test]
+    fn top_only_view_does_not_starve_another_heap_under_eviction_pressure() {
+        let mut tracked = TrackedSrvs::default();
+        let mut broad = tracked_entry(1, 0x10);
+        broad.desc = None;
+        tracked.write(srv_slot(1, 0), Some(broad));
+        let mut top = tracked_entry(1, 0x20);
+        top.desc = Some(D3D12_SHADER_RESOURCE_VIEW_DESC {
+            ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
+            Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
+                Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() },
+            },
+            ..Default::default()
+        });
+        tracked.write(srv_slot(1, 1), Some(top));
+        let mut other = tracked_entry(2, 0x30);
+        other.desc = None;
+        tracked.write(srv_slot(2, 0), Some(other));
+        let now = Instant::now();
+        let candidates = vec![
+            HeapEvictCandidate { res_key: 1, heap: 1, heap_evictable: true, heap_free: 960, last_touch: now, tiles: 64 },
+            HeapEvictCandidate { res_key: 2, heap: 2, heap_evictable: true, heap_free: 896, last_touch: now, tiles: 128 },
+        ];
+        let tails = HashMap::from([(1, (1, 2)), (2, (1, 2))]);
+        assert_eq!(pick_evict_candidates_by_heap(&candidates, 64), [1]);
+        let mut eligible = candidates.clone();
+        retain_visible_candidates(&mut eligible, &tails, &tracked, 7);
+        assert_eq!(pick_evict_candidates_by_heap(&eligible, 64), [2]);
+        tracked.write(srv_slot(1, 1), None);
+        let mut eligible = candidates;
+        retain_visible_candidates(&mut eligible, &tails, &tracked, 7);
+        assert_eq!(pick_evict_candidates_by_heap(&eligible, 64), [1]);
+        assert!(pick_evict_candidates_by_heap(&eligible, 0).is_empty());
+    }
+
+    #[test]
     fn heap_draining_eviction_empties_coldest_heaps_first_and_skips_pinned() {
         let t0 = Instant::now();
         let cands = vec![

AI use: OpenAI Codex prepared the candidate, ran the selection and native readback controls, and wrote this report.

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

map_levels can restore an evicted top mip and lower Target.min_resident_mip, but existing live SRV descriptors remain clamped to the packed tail. Eviction rewrites them using clamp_srv_min_lod, which only raises ResourceMinLODClamp; the remapping path at lines 3128-3175 never rewrites those descriptors with a lower clamp. Sampling through an SRV created before eviction can therefore remain permanently restricted to lower-resolution mips after mip 0 is resident again.

Please make descriptor clamp state reversible when residency is restored, while preserving an application-specified original clamp. Add a GPU regression that creates an SRV, evicts mip 0, remaps mip 0 after budget recovery, and verifies that the same SRV samples mip 0 again.

Reviewed at 60f1a22 with Codex (GPT-5).

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Triage (#1607) – head 60f1a22

main has only the SRV-tracking groundwork for XCL_TEXTURE_BUDGET_EVICT; this PR adds the eviction itself. #2385 and #2968 address the same VRAM overrun differently: #2385 withholds top mips from new textures when memory is full, and #2968 drops a fixed number of levels. Problem found: vram.rs::evict_under_budget calls the new unmap_range, which unmaps the top mips at once on the mapping queue. It also rewrites the live SRV descriptors. It does not use the mark_unmap/held_unmaps guard that unmap_superseded uses, so title work already submitted on other queues can still sample the unmapped mips or read the rewritten descriptors. Off by default.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Review (head 60f1a22, diff read, not a merge-check; conflicts with main in vram.rs / real.rs):

  • Evicted mips almost never come back. Every caller of map_levels is behind XCL_TEXTURE_LEVEL_PAGES (title_textures.rs ~609, ~737, ~1691). With only XCL_TEXTURE_BUDGET_EVICT=1, which is how the PR's smoke ran, top mips are gone for good. With level pages on, they return only when the texture is written again. Even then existing SRVs keep their raised clamp (clamp_srv_min_lod only raises), as bmjask found.
  • Untracked views read zeros. track_srv skips views outside the shared heap (vram.rs ~389), and the "all views clamped" check (~2737-2778) counts only tracked views. Those views, and a view of only the top mip, read NULL tiles, which return zeros; andrewDoing measured this on an RTX 5070.
  • Synchronisation is partial. The quiescence check covers only submissions that use the shared view heap. The unmap and release (~2859-2860) come after it on a 2 s timer instead of mark_unmap / held_unmaps, so copy-queue work on those tiles isn't guarded (partly unverified).
  • Pool memory runs away. mark_heap_pinned (~1926) changes the class of a whole heap, against main's 3b5bc7b ("class is only a packing hint"); Anon64 measured pools reaching 28.8 GB and 51 GB of commit on an RTX 3060.
  • 869 lines with no reason given for not splitting. The red CI is main's benches/runtime.rs (input_profile private), not this PR.

Fine: off by default, and the default path matched main in both smokes. Render targets and UAVs are excluded (Flags == NONE), and SRV rewrites go through the unhooked native slots. Related approaches: #2385, #2968, #640, #782.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

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.

9 participants