Skip to content

D3D12.X: scope resource_at by device and clean up on release (#248) - #292

Draft
heretic1321 wants to merge 1 commit into
xcl-dev:mainfrom
heretic1321:fix/title-texture-lifetime-248
Draft

heretic1321 wants to merge 1 commit into
xcl-dev:mainfrom
heretic1321:fix/title-texture-lifetime-248

Conversation

@heretic1321

@heretic1321 heretic1321 commented Nov 23, 2026 •

Copy link
Copy Markdown

Re-scoped onto upstream/main (47efa2e, head 8eb79c2), kept as draft. Part of #248.

Re-scope after #288, #866, and review feedback

  • Dropped #269 base and title_textures overlap-retirement: #288 landed on main using vram::Pages and already includes shadowed / retire_overlapping / unmap_superseded. Addressing live non-overlapping texture growth (@emirduran707's 9.8 GB RX 9060 XT table / @albertoglvn's 8 GB census) belongs to opt-in page budgets such as #640, not overlap retirement.
  • Dropped mid-device MADE_MAX / 2 s MADE_COOL eviction: per @qinrxx (points 1–2) and @Cattn, D3D12 descriptors hold no COM reference, so dropping a MADE resource while descriptors may still exist in reused heaps is unsafe.

What is in it

  • crates/xcl/src/hle/d3d12x/real.rs:
    • ResourceAtCache keys MADE by (device, va, desc) (previously (va, desc)).
    • resource_at returns an owned Option<ID3D12Resource> cloned while holding the MADE lock so dev_create_srv_at_x / dev_create_uav_at_x hold a live COM reference through descriptor creation (@Cattn's lifetime fix).
    • Hooks ID3D12Device::Release (dev_release). A cached resource is a COM child and holds the device, so the Release of the last outside reference returns 1 and a teardown placed after that call never runs (@WebIdentity1 reproduced this on two machines). The hook therefore tears the device's MADE entries down first when at most this caller's and real::init's process-lifetime reference remain (routing final ID3D12Resource::Release through #866's late_release while upload queues remain registered), then title_textures state for that device, and the device really reaches zero.
    • Calls vram::on_queue_release from q_release.
    • Unit test resource_at_tests::resource_at_cache_scopes_by_device_and_tears_down (holds gating, per-device isolation, idempotent teardown).
    • crates/xcl/src/hle/d3d12x/resource_lifetime_probe.rs: two on-device regression tests adapted from @WebIdentity1's reproducer — a raw COM-child teardown control and the production resource_at miss/hit/teardown path — both assert the cache is empty and the device reached 0. They skip without a GPU.
  • crates/xcl/src/hle/d3d12x/vram.rs:
    • Adds on_queue_release(queue) clearing released queues from every device's pages.waited map so reused queue pointers cannot skip mapping-fence waits.
  • crates/xcl/src/hle/d3d12x/title_textures.rs:
    • Adds Table::teardown / teardown(device) removing entries for a released device from by_res / by_va / shadowed / shadowed_by_va / LAST_CONTENT / QUEUES / WATCH_CACHE.
    • Adds Stats and stats() (active, shadowed, covered_bytes), plus unit test table_teardown_and_stats_are_scoped_by_device.
  • crates/xcl/src/host.rs:
    • Logs ; title textures {} ({} MB covered, {} shadowed) on the XCL_ACTIVITY memory: line.

Tested

  • Linux host (no Windows, no GPU), Rust 1.98.1, head 8eb79c2 on upstream/main 47efa2e:
    • AR_x86_64_pc_windows_msvc=llvm-ar cargo check --release --workspace --target x86_64-pc-windows-msvc — exit 0 (15.12s, 0 errors, 0 warnings).
    • AR_x86_64_pc_windows_msvc=llvm-ar cargo check --tests --workspace --target x86_64-pc-windows-msvc — exit 0 (8.95s, 0 errors, 0 warnings).
    • python3 scripts/pr_check.py --local verified all required sections and asset/model checks (failing only on the missing Windows xcl-smoke blocks for 8eb79c2).
  • @WebIdentity1 on e0e3910 — RTX 3090 driver 591.74, Windows 10 19045, Ryzen 7 7800X3D, Rust 1.98.1 MSVC, DXC 1.8.2502.11: cargo build --locked --workspace succeeds on main and the head; full suite 720 passed / 1 failed / 41 ignored on the head against 718 passed / 1 failed / 41 ignored on main (same pre-existing integer-CLAMP failure on both, four explicit skips each, the two added PR tests pass). Their cache-teardown finding reproduced on the RTX 3090 and on AMD integrated graphics; it is addressed by the release-hook change below.
  • Prior reports at bf8e16c (@grahamster2 RTX 3080, @qinrxx d3d12x:: tests) were on the #269-stacked version and do not cover this re-scoped commit 8eb79c2.

Regression run

  • Missing for head 8eb79c2 (draft; no Windows GPU host here).

Not tested

  • Windows MSVC link, cargo test --workspace execution, GPU tests, scripts/smoke.ps1 / retail title runs on 8eb79c2, and multi-device teardown in a real title. Both new probe tests and @WebIdentity1's numbers are on e0e3910; the release-hook fix and the probes have not been run on a GPU yet.

AI use

  • T3 Code / Antigravity, Orchestrator (Neon) / gemini-pro-orchestrator-neon: re-scoped onto upstream/main (47efa2e), fixed resource_at owned COM reference return and removed unsafe mid-device eviction per reviews, updated vram::on_queue_release for #288's per-device PAGES map, added unit tests, and ran Linux cargo check and scripts/pr_check.py --local.

Rebase note (47efa2e)

  • The pipeline-wait half of this branch overlapped what has since landed on main (wait_budget, resolve_within(&Pending, …), Pending::late) from the XCL_PSO_WAIT_MS work. Instead of keeping a second copy, resolve_for_draw now builds on main's resolve_within/wait_budget: this branch keeps the draw-specific 4 s default, the compute bypass, the standin_draws counter and the long-wait log, and drops the duplicated wait loop.
  • That rebase also silently took main's real.rs / title_textures.rs / vram.rs / host.rs and dropped this branch's half of the PR; it is restored in 8eb79c2, which is why the device-scoping and teardown work is back in the diff.
  • cargo check --release --workspace and --tests for x86_64-pc-windows-msvc on head 8eb79c2: 0 errors, 0 warnings.

@heretic1321
heretic1321 force-pushed the fix/title-texture-lifetime-248 branch from 86a9207 to bf8e16c Compare November 23, 2026 22:35
@heretic1321 heretic1321 changed the title D3D12.X: give title textures shared pages, reuse, and retirement (#248) D3D12.X: retire overwritten title textures, evict MADE, and clean up (#248) Nov 23, 2026
@grahamster2

grahamster2 commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Retail run of bf8e16c on a 10 GB NVIDIA card: the retail title (Series 1.0.2.1), RTX 3080, driver 610.88, warm caches, XCL_PRESS_A_AT=30,40,50,60,70,80,95,110, 180 s, two runs. All four heads are compared in #248 (comment).

run local VRAM 60 s → 120 s max VRAM first 0x8007000e end
1 6.9 → 11.4 GiB 12.3 GiB none AV write +0x2926872, 145 s
2 7.4 → (ended at 95 s, 9.3 GiB) 9.3 GiB none AV write +0x13936, 95 s
main (two runs) 7.5 → 17.6 / 17.9 GiB 19.8 GiB 127 s / 128 s AV +0x13936 128 s / 0x80000003 +0x193e00f 138 s

The access violation at +0x13936 is also one of main's endings, and this run ended at 9.3 GiB, well under the card. The title textures counter at the end: 19 330 active, 4 829 MB covered, 31 003 retired (run 1); 16 349 / 1 963 MB / 14 997 (run 2).

No device removal, and no new warning kinds compared with main. Correctness wasn't checked: the loading frames are a dark fade, and I can't look at them.

xcl-smoke, 60 s
xcl-smoke v1
commit: bf8e16cdc2faf0cf5a5994c381890a0c5170376e
gpu: NVIDIA GeForce RTX 3080
title: the retail title.Xbox.v1.0.2.1
seconds: 60
exit: 0x0
frames shown: 1482 (PresentX 1482)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14770 MB

Claude Code (Claude Opus 5.5) ran the tests and wrote this report. No game files attached.

@emirduran707

Copy link
Copy Markdown
Contributor

A data point for the retirement part of this PR, on current main (where #288 is in and #269 is closed, so this branch conflicts now).

RX 9060 XT 16 GB, 32 GB RAM, release, main a6f5f7a + #440 (video at speed) + #300 + #435, the same title, A pressed by hand, XCL_ACTIVITY=1. While the world streams in (from ~60 s), the tiled-texture pages (the target pages figure on the activity line, which since #288 counts targets and sampled textures on one shared book) keep growing, with no E_OUTOFMEMORY:

time process commit local VRAM tiled-texture pages
62 s 17.3 GB 7.9 GB 4.9 GB
82 s 23.4 GB 11.8 GB 7.9 GB
122 s 26.4 GB 13.3 GB 9.4 GB
142 s 27.8 GB 13.9 GB 9.8 GB

Pages are shared per address on main, so this is distinct addresses covered by resources the title has not released, which is what the retirement here addresses. Are you planning to rebase it onto main? I can run the same measurement on this card when it is.

AI use: Claude Code with Claude Opus 5.5 read the run's log and wrote this comment from my run.

@Cattn

Cattn commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

From a static review (no builds or runs) of bf8e16c:

resource_at returns a borrowed COM pointer, which the caller uses to create a descriptor after the cache lock is released. Another caller can retire the entry and drain the cache's reference after the two-second cooldown, leaving descriptor creation or submitted GPU work without a live resource if that was the final reference. This is a resource-lifetime bug, and I found no indication of malicious code.

Hold a COM reference through descriptor creation and defer GPU retirement until the relevant queue fences complete.

unsafe fn resource_at(this: *mut c_void, desc: *const u8, va: u64) -> *mut c_void {
if desc.is_null() || va == 0 || !crate::gpu::shader::readable(desc as usize, 0x38) {
return std::ptr::null_mut();
}
let expired = MADE.lock().unwrap().get_or_insert_with(ResourceAtCache::default).drain_expired(std::time::Instant::now());
for r in expired {
drop(windows::core::IUnknown::from_raw(r as *mut c_void));
}
// the PC part of the desc; the flags (@0x30) are its last dword, padding follows
let mut x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned();
x[0x34..].fill(0);
let key = (this as usize, va, x);
if let Some(&r) = MADE.lock().unwrap().get_or_insert_with(ResourceAtCache::default).made.get(&key) {
return r as *mut c_void;

const MADE_COOL: std::time::Duration = std::time::Duration::from_secs(2);
const MADE_MAX: usize = 65536;
static MADE: Mutex<Option<ResourceAtCache>> = Mutex::new(None);
impl ResourceAtCache {
fn retire(&mut self, res: usize, now: std::time::Instant) -> bool {
let Some(k) = self.by_res.remove(&res) else { return false };
self.made.remove(&k);
self.cooling.push_back((k.0, res, now));
true
}
fn drain_expired(&mut self, now: std::time::Instant) -> Vec<usize> {
let mut out = Vec::new();
while self.cooling.front().is_some_and(|&(_, _, at)| now.duration_since(at) >= MADE_COOL) {
out.push(self.cooling.pop_front().unwrap().1);
}
out
}

Review by Claude Code (Claude Opus 5.5) with a gpt-6.2-sol audit subagent; I checked each point against the code.

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

Review of bf8e16c (with 8111cf9 from #269 under it), on correctness and tests only. The diff was read against main 2997c9a.

What I ran: cargo test -p xcl --lib d3d12x:: -- --test-threads=4 on the PR head (base 63b9930): 84 passed, 0 failed, 1 ignored.

  • The two new tests pass (overlapping_placements_retire_old_release_and_teardown, resource_at_cache_retires_cools_caps_and_tears_down).
  • #269's four pass, including the GPU test title_textures_at_one_address_share_video_memory (RTX 5080, not skipped).
  • Not run: on main, because the PR doesn't merge (below); the workspace suite; the retail title.

0. State against main: this needs more than a rebase.

  • #269 was closed, and #288 landed instead with a different design: vram::Pages, one reserved resource per target, with tiles mapped onto shared 64 KiB pages.
  • main has no vram::Book, Space or place_title_texture. A merge of this branch into main conflicts in device_x.rs, title_textures.rs and vram.rs.
  • main's title_textures already retires overlapped entries when a newer placement covers their range (retire_range, title_textures.rs:141 on main). The Registry / by_end retirement and vram::detach_title_texture here cover the same ground, built on #269's types.
  • Not affected: real.rs (the resource_at cache, dev_release, q_release) and host.rs, which merge into main without conflicts.
  • That part could be a small PR of its own against main, with its unit test. Points 1–3 are about it.

1. Releasing a resource_at resource can leave descriptors pointing at freed memory.
resource_at makes a resource and writes an SRV/UAV for it into the title's descriptor (dev_create_srv_x(this, resource_at(..), &v, cpu)). D3D12 descriptors hold no reference, so MADE is the only thing keeping that resource alive, which is presumably why main never lets go of it. Here it is released 2 s after one of two things:

  • retired: a newer placement overlaps the old texture, and title_textures calls retire_resource_at(old_res);
  • evicted: MADE_MAX (65,536) entries are reached.

The title may still have descriptors over that resource in a heap it reuses, and does not need to make the view again: on the console the view reads the memory, which still exists. The GPU then reads through a descriptor of a destroyed resource. Is there something that shows the title's descriptors over a retired resource are rewritten within the 2 s?

2. The cap evicts the oldest entry made, not the least used.
insert evicts in creation order (order.pop_front()). A view made early and used every frame (a UI atlas, a lookup texture) is the first to go once 65,536 later ones exist. Its next resource_at makes a new resource, but the descriptors written before still point at the old one, the case in point 1. Least-recently-used order would make this rarer, but not safe.

3. Tests. resource_at_cache_retires_cools_caps_and_tears_down checks the bookkeeping with numbers in place of resources, which is fine for the data structure. Nothing covers what points 1 and 2 are about: a view by address still in use after its resource was retired or evicted. A GPU test that makes a view through device #70 / #71, makes 65,537 more (or overlaps the texture), waits past MADE_COOL and samples through the first descriptor would show it. On the debug layer it should report the destroyed resource.

Overlap with our work:

  • Our compute change for #232 touches pso_async.rs only: no overlap.
  • #267 adds a field to D3d12Stats and stats() in real.rs. This PR's real.rs changes are elsewhere in the file. I didn't merge the two together.

AI use: Claude Code (Claude Opus 5.5) built the PR head, ran the tests above, read the diff and wrote this review. I checked each point myself before posting.

@albertoglvn

Copy link
Copy Markdown

An 8 GB data point on how much the retirement here could free on the newer retail title (TitleID 7952987A). It's from a page census, not from a run of this branch, since it conflicts with main.

Machine: RTX 4060 Laptop 8 GB (7956 MiB), 15.2 GB RAM, Windows 11 26300, driver 621.24. Build: main f4ce27c + #495 + #496 + #640 with its budget off, plus a local patch that counts each 64 KiB page once, under the strongest of its holders (details in #640 (comment)). At 62 s:

pages held by MB
a GPU-written or GPU-owned texture 3200
else a CPU-filled texture whose T# is in a shader-visible view heap 1737
only CPU-filled textures with their T# in no shader-visible heap 1091 (827 of it under 2 s old)
all pages 6028

Pages are shared per address on main, so retiring an overwritten placement frees only the pages no other placement still holds. If the overwritten textures are among those whose T# is in no view heap, which I'd expect but didn't check, the last row is the most this can free here: about 1.1 GB, and less in practice, since most of it was under 2 s old.

On this machine that wouldn't move the end much. The out-of-memory stop comes when local plus non-local video memory fills the card plus Windows' shared GPU memory (#333 (comment)): 14.8 of about 15.7 GB at the refusal. On cards where the pages keep growing well past that, like emirduran707's table above, it may matter much more.

When this is rebased onto main, I can measure it here with the budgets logged at the refusal.

AI use: Claude Code (Claude Opus 5.5) wrote the census patch and this comment and read the logs; I ran the title.

Part of xcl-dev#248. Re-scoped onto upstream/main after xcl-dev#288 and xcl-dev#866: drops xcl-dev#269 overlap retirement (covered by xcl-dev#288) and unsafe mid-device MADE eviction (D3D12 descriptors hold no COM reference). Scopes real::MADE by device, returns an owned COM ID3D12Resource from resource_at held across descriptor creation, releases device-owned MADE entries and title_textures state on dev_release (routed through xcl-dev#866 late_release), clears released queues from vram::Pages::waited, and adds title-texture counts to XCL_ACTIVITY.

Assisted-by: T3 Code / Antigravity (gemini-pro-orchestrator-neon)
@heretic1321
heretic1321 force-pushed the fix/title-texture-lifetime-248 branch from bf8e16c to e0e3910 Compare November 24, 2026 09:46
@heretic1321 heretic1321 changed the title D3D12.X: retire overwritten title textures, evict MADE, and clean up (#248) D3D12.X: scope resource_at by device and clean up on release (#248) Nov 24, 2026
@heretic1321

Copy link
Copy Markdown
Author

Re-scoped cleanly onto upstream/main (6bac4b4) at e0e3910947bfeaf74fb38b52c0bafa0bae10aaa5 (0 errors, 0 warnings on AR_x86_64_pc_windows_msvc=llvm-ar cargo check --release --workspace and --tests; kept as draft until Windows/GPU tests run).

Thank you everyone for the thorough reviews and measurements:

  • D3D12.X: back kept-in-step title textures by shared VRAM pages (#248) #288 / D3D12.X: title textures on shared 64 KiB pages of video memory – video memory stays at what the title covers (#248) #269 state & live-page growth (@emirduran707, @albertoglvn, @grahamster2, @qinrxx): Dropped #269 and the title_textures overlap-retirement changes since #288 (vram::Pages, shadowed, retire_overlapping, unmap_superseded) is now on main. As @emirduran707's 9.8 GB RX 9060 XT table and @albertoglvn's 8 GB census show, the remaining target pages growth on main comes from live distinct addresses rather than overlaps (addressed by opt-in page budgets like #640), so this PR is re-scoped strictly to resource_at safety/scoping and release cleanup.
  • Borrowed pointer lifetime & unsafe mid-device MADE eviction (@Cattn, @qinrxx points 1–3):
    • Removed MADE_MAX creation-order eviction and the 2 s wall-clock MADE_COOL timer, since D3D12 descriptors hold no COM reference (@qinrxx).
    • Fixed resource_at COM lifetime (@Cattn): resource_at now clones and returns an owned Option<ID3D12Resource> while holding the MADE lock, and dev_create_srv_at_x / dev_create_uav_at_x hold that reference across dev_create_srv_x / dev_create_uav_x.
    • Device/queue cleanup: MADE is keyed by (device, va, desc); dev_release drains device-owned MADE entries (whose final ID3D12Resource::Release routes through #866's late_release while upload queues are still alive) before title_textures::teardown(Some(device)); q_release clears vram::Pages::waited via vram::on_queue_release.
    • XCL_ACTIVITY stats: logs title textures <active> (<covered> MB covered, <shadowed> shadowed) on the memory: line.

What is still needed before marking ready for review: Windows cargo test --workspace -- --test-threads=4 and a scripts/smoke.ps1 pair (main vs e0e3910).

pedro-anthony added a commit to pedro-anthony/xcl that referenced this pull request Nov 24, 2026
Conflicts resolved with upstream's versions where our side held older copies of PRs it has
since merged or superseded:
- title_textures.rs, vram.rs, device_x.rs: upstream's xcl-dev#248 (ad79932) and xcl-dev#283 replace our
  earlier merges of xcl-dev#248 / xcl-dev#269 (closed) / xcl-dev#292 (open, conflicts with main now). xcl-dev#242
  (R9G9B9E5 targets) is to be merged again on top.
- kernelx.rs unmap_away: upstream's condition (also keeps a home the caller committed).
- real.rs / host.rs: calls into xcl-dev#292's title_textures::teardown, vram::on_queue_release and
  title_textures::stats dropped (not in upstream's files); its MADE cache in real.rs stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@WebIdentity1

WebIdentity1 commented Nov 24, 2026 •

Copy link
Copy Markdown

Native Windows validation of e0e3910947bfeaf74fb38b52c0bafa0bae10aaa5, plus a reproduced cleanup gap.

Tested
RTX 3090 driver 591.74, Windows 10 19045, Ryzen 7 7800X3D, Rust 1.98.1 MSVC, DXC 1.8.2502.11, Agility 1.620.2. Unmodified source, debug builds, interactive desktop session:

cargo build --locked --workspace succeeds on both revisions.
cargo test --locked --workspace --no-fail-fast -- --test-threads=4 --show-output:

  • Parent main 6bac4b4419886acc940d479dcf8815d0b1804435:718 passed /1 failed /41 ignored.
  • PR head:720 passed /1 failed /41 ignored.
  • Same existing integer-CLAMP failure on both; four explicit skips each (two native-wave64, two missing debug layers). No timeout. The two added PR tests pass.

Cleanup finding
dev_release waits for native Release to return zero before dropping MADE. A cache-owned native resource keeps the device at one, so this cleanup does not run. A local GPU diagnostic calls production resource_at for a synthetic64KiB buffer, verifies cache miss/hit identity, and drops both returned references:

explicit cache teardown first: device Release=0, cache empty
new release hook alone:        device Release=1, cache retained

Reproduced independently on the RTX 3090 and AMD integrated Graphics (driver32.0.21030.2001): each targeted test0 passed /1 failed /0 ignored, no skips/timeouts. The failed assertion checks the retained cache entry; fixture cleanup occurs before asserting. A second real-COM-child probe reproduces the same dependency. Patch below adds only diagnostics and intentionally fails.

The old cache already retained resources; this finding limits the new cleanup claim. Device scoping and owned lookup results remain useful. An explicit owner/session teardown boundary would need to release cache-owned resources before the final device reference, while preserving descriptor lifetimes. real::init also intentionally holds a process-lifetime device reference.

Not tested
Retail title/smoke pair, actual texture descriptor execution, in-flight destruction, game-memory growth or gameplay. The production-entry probe uses the committed-buffer fallback outside UMA. Deliberately failing diagnostics are separate from the unmodified full-suite counts above.

AI use: Codex (GPT-6) wrote the diagnostics, ran the native tests and prepared this report. No competing runtime fix.

Reproducer patch against e0e3910
diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs
index ee3e961..d63a538 100644
--- a/crates/xcl/src/hle/d3d12x/real.rs
+++ b/crates/xcl/src/hle/d3d12x/real.rs
@@ -5848,3 +5848,7 @@ mod resource_at_tests {
         assert!(c.made.is_empty());
     }
 }
+
+#[cfg(test)]
+#[path = "resource_lifetime_probe.rs"]
+mod resource_lifetime_probe;
diff --git a/crates/xcl/src/hle/d3d12x/resource_lifetime_probe.rs b/crates/xcl/src/hle/d3d12x/resource_lifetime_probe.rs
new file mode 100644
index 0000000..bbe9052
--- /dev/null
+++ b/crates/xcl/src/hle/d3d12x/resource_lifetime_probe.rs
@@ -0,0 +1,103 @@
+//! Local PR292 diagnostic: real COM children, isolated from the process-wide title device.
+use super::*;
+
+#[test]
+fn native_cached_resource_device_teardown() {
+    unsafe {
+        let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
+        let sel = crate::gpu::adapter::Selector::from_env_or("auto");
+        let Some((adapter, desc)) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() else {
+            return crate::gpu::recomp::runner::skip_test("no GPU");
+        };
+        println!("adapter={}", crate::gpu::adapter::name(&desc));
+        for cached in [false, true] {
+            let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).unwrap();
+            let raw = dev.as_raw();
+            let add: RefFn = std::mem::transmute(*vt(raw).add(1));
+            let release: RefFn = std::mem::transmute(*vt(raw).add(2));
+            add(raw);
+            let before = release(raw);
+            let rd = D3D12_RESOURCE_DESC {
+                Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+                Width: 65536, Height: 1, DepthOrArraySize: 1, MipLevels: 1,
+                SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+                Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default()
+            };
+            let mut resource: Option<ID3D12Resource> = None;
+            dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rd, D3D12_RESOURCE_STATE_COMMON, None, &mut resource).unwrap();
+            let resource = resource.unwrap();
+            add(raw);
+            let with_child = release(raw);
+            // The same adoption/release hooks used for resources held by resource_at.
+            adopt(resource.as_raw(), Kind::Resource);
+            adopt(raw, Kind::Device);
+            assert_eq!(*vt(raw).add(2), dev_release as usize);
+            let key = (raw as usize, 0x10000, [0u8; 0x38]);
+            if cached {
+                MADE.lock().unwrap().get_or_insert_with(ResourceAtCache::default).insert(key, resource.into_raw() as usize);
+            } else {
+                drop(resource);
+                super::super::late_release::drain_known(true);
+            }
+            let raw = dev.into_raw(); // consume the only application-owned device reference
+            let remaining_refs = dev_release(raw);
+            let cache_retained = MADE.lock().unwrap().as_ref().is_some_and(|c| c.get(&key).is_some());
+            println!("cached={cached} device_refs_before_child={before} with_child={with_child} after_application_release={remaining_refs} cache_retained={cache_retained}");
+            // Clean up even when the intended teardown assertion fails; no queued GPU work exists.
+            if cache_retained {
+                teardown_resource_at(raw as usize);
+                super::super::late_release::drain_known(true);
+            }
+            assert!(!cache_retained, "cached resource prevents the device Release==0 cleanup from running");
+            if !cached { assert_eq!(remaining_refs, 0, "uncached control must reach the release hook"); }
+        }
+    }
+}
+
+/// The production cache entry point, using its committed-buffer fallback outside the UMA.
+/// This does not invoke a retail texture descriptor or submit GPU work.
+#[test]
+fn resource_at_device_teardown_path() {
+    unsafe {
+        let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
+        let sel = crate::gpu::adapter::Selector::from_env_or("auto");
+        let Some((adapter, desc)) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() else {
+            return crate::gpu::recomp::runner::skip_test("no GPU");
+        };
+        println!("adapter={}", crate::gpu::adapter::name(&desc));
+        let mut rd = [0u8; 0x38];
+        rd[0..4].copy_from_slice(&1u32.to_le_bytes()); // BUFFER
+        rd[16..24].copy_from_slice(&65536u64.to_le_bytes());
+        rd[24..28].copy_from_slice(&1u32.to_le_bytes());
+        rd[28..30].copy_from_slice(&1u16.to_le_bytes());
+        rd[30..32].copy_from_slice(&1u16.to_le_bytes());
+        rd[36..40].copy_from_slice(&1u32.to_le_bytes()); // sample count
+        rd[44..48].copy_from_slice(&1u32.to_le_bytes()); // ROW_MAJOR
+        for explicit_teardown in [true, false] {
+            let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).unwrap();
+            let raw = dev.as_raw();
+            adopt(raw, Kind::Device);
+            let first = resource_at(raw, rd.as_ptr(), 0x10000).expect("production cache miss creates a native resource");
+            let hit = resource_at(raw, rd.as_ptr(), 0x10000).expect("production cache hit returns an owned reference");
+            assert_eq!(first.as_raw(), hit.as_raw());
+            let key = (raw as usize, 0x10000, rd);
+            assert!(MADE.lock().unwrap().as_ref().is_some_and(|c| c.get(&key) == Some(first.as_raw() as usize)));
+            drop(first);
+            drop(hit);
+            if explicit_teardown {
+                teardown_resource_at(raw as usize);
+                super::super::late_release::drain_known(true);
+            }
+            let raw = dev.into_raw();
+            let remaining_refs = dev_release(raw);
+            let cache_retained = MADE.lock().unwrap().as_ref().is_some_and(|c| c.get(&key).is_some());
+            println!("resource_at explicit_teardown={explicit_teardown} after_application_release={remaining_refs} cache_retained={cache_retained}");
+            if cache_retained {
+                teardown_resource_at(raw as usize);
+                super::super::late_release::drain_known(true);
+            }
+            assert!(!cache_retained, "production resource_at cache still owns its resource after application device release");
+            if explicit_teardown { assert_eq!(remaining_refs, 0, "explicit teardown control releases the device"); }
+        }
+    }
+}

Run each probe in its own process with cargo test --locked -p xcl --lib native_cached_resource_device_teardown -- --test-threads=1 --show-output --nocapture and the same command with filter resource_at_device_teardown_path. Set XCL_ADAPTER=3090 or AMD.


Follow-up on the requested 8eb79c2 run (November24)

@heretic1321 I fetched the named commit directly from your fork: 8eb79c2ace0a5c5c9946ce91b9d38aac487a3be0. Both the PR head and fix/title-texture-lifetime-248 currently still point to e0e3910.

The fetched8eb tree differs from the described fix:

  • dev_release still forwards Release first and tears down only when n == 0. ResourceAtCache::holds and the new count-based branch are absent.
  • resource_lifetime_probe.rs is present but not declared as a module. On native Windows, each requested filter with -- --list reports 0 tests,0 benchmarks (exit0); that is test discovery, not passing GPU validation.
  • Adding only the missing test-module declaration locally makes cargo test --locked -p xcl --lib native_cached_resource_device_teardown -- --list fail compilation (exit101): E0425 cannot find function refs in this scope, at resource_lifetime_probe.rs:70. No GPU test executes. I preserved this four-line diagnostic patch and restored the original source afterward.

Please push/link the revision containing the intended release-hook change, its helpers and module declaration. I can then run the focused native checks and, if appropriate, the suite. Before accepting a count threshold, it also needs cases with more than one cached child and retained descriptor/device owners; the one-child probe alone does not establish descriptor lifetime safety.

One scope correction: these are two adapters in one Windows machine. We have no retail files here, so neither these filters nor a full workspace run can supply the required xcl-smoke retail pair.

AI use: Codex (GPT-6) inspected the exact Git objects and ran the Windows discovery/compile diagnostics. No runtime fix was fabricated from the prose description.

@heretic1321

Copy link
Copy Markdown
Author

@WebIdentity1 thank you — the full-suite counts, the four skips and the same pre-existing integer-CLAMP failure on both revisions make this the most useful run on the PR, and the teardown finding is correct: I reproduced the mechanism from the code (ID3D12Resource is a COM child and holds its device, so the app's last Release returns 1, not 0, and my if n == 0 teardown sat on the branch that could never run).

Fixed on 8eb79c2 rather than left as a diagnostic:

  • dev_release now tears the device's MADE entries down before forwarding when at most the caller's and real::init's process-lifetime reference are left (refs() = AddRef+Release, unchanged count), so the device really reaches 0 and the teardown is no longer unreachable. title_textures::teardown moves with it. Cached resources are rebuilt on their next lookup, and owner-cloned references keep their own COM ref, so nothing is freed under a live descriptor.
  • ResourceAtCache::holds gates the teardown, so the hook stops tearing down a device with no entries.
  • Your two probes are in the tree as crates/xcl/src/hle/d3d12x/resource_lifetime_probe.rs, adapted to pass instead of intentionally failing: both now assert Release returns 0 and the cache is empty. They skip without a GPU.

Since you have the hardware and I don't: could you run the same two filters on 8eb79c2 (native_cached_resource_device_teardown, resource_at_device_teardown_path), plus the full suite, against main? That would also cover the xcl-smoke pair this needs. The rebase onto 47efa2e also re-restored the real.rs/title_textures.rs/vram.rs/host.rs half of the PR that an earlier rebase had silently dropped, so the diff is now the intended one.

@Toons29

Toons29 commented Nov 25, 2026

Copy link
Copy Markdown

Regression run of e0e39109 on the retail title, for this PR's Regression run section. Both blocks are from scripts/smoke.ps1 as printed, not edited: main on 4178e888, this PR on its head commit with no uncommitted changes, same title and time.

xcl-smoke v1
commit: 4178e888c0b5be50a2887eda45cdb832763b68a4
gpu: AMD Radeon RX 9070
title: game.exe
seconds: 60
exit: 0x0
frames shown: 1618 (PresentX 1618)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 14831 MB
xcl-smoke v1
commit: e0e3910947bfeaf74fb38b52c0bafa0bae10aaa5
gpu: AMD Radeon RX 9070
title: game.exe
seconds: 60
exit: 0x0
frames shown: 1618 (PresentX 1618)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 14814 MB

Against the limits in CONTRIBUTING.md: 100 % of main's frames, 100 % of its peak commit, no crash, no device removal.

AMD Radeon RX 9070 (RDNA4, driver 32.0.32029.2010), Ryzen 7 7800X3D, 32 GB, Windows 11 build 26300, Rust 1.100.0, cargo build --release -p xcl, 60 s, XCL_NETWORK=0. This is a regression check only: it does not show whether the run reaches the code this PR changes.

AI use: Claude Code (Claude Opus 5.5) built both trees and ran scripts/smoke.ps1; I checked the blocks before posting.

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.

8 participants