runtime, d3d12: memory leak fixes from one sweep (RT-LEAK-SWEEP) #2569

Closed
adrianmjim wants to merge 376 commits from upstream-pr/2569 into main
adrianmjim commented 2026-11-28 09:48:55 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-28T09:48:55Z.


Claimed in the coordination issue as: RT-UPLOAD-ARENA-REWIND, RT-PSO-BYTECODE-INTERN, RT-SPARE-LIST-EPOCHS, RT-SLOT-RECORDS-BUCKETS, RT-REHYDRATE-SCRATCH-TICKET, RT-FSSM-ARENA-SHARE, RT-TITLE-BUFFER-FALLBACK, RT-SLOT70-DEVICE-CYCLE, RT-MEM-PROBE-WINDOWS, RT-ZERO-IMAGES-RETRY, RT-TITLE-TEXTURE-GONE-RANGES, RT-SHADOW-GPU-RELEASED-RANGES, RT-SLOT70-OWNED-RETIRE (https://github.com/ProjectLeonida/mandy/issues/1608#issuecomment-7235789024); RS-HOST-LIST-ALLOCATOR-PEAK, RS-XTASKQUEUE-POOL-TRIM, RS-TEXTURE-READ-TRIM, RS-SNAPSHOT-POOL-TRIM, RS-EXACT-SPARE-CAP, RS-GRAPHICS-STATE-INTERN, RS-EARLY-START-AGE, RS-XMEM-FREE-DEFAULT, RS-THIN-UPLOAD-DROP, RS-APU-SCRATCH, RS-REPLACED-DRAIN (https://github.com/ProjectLeonida/mandy/issues/1608#issuecomment-7236879810); RT-GEOMETRY-VIEWS-CONTAIN, RT-DRAW-VIEWS-UNCHANGED (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7237948341); RS-ARENA-ONE-COPY, RS-SHADER-CONTAINER-FREE, RS-DSTORAGE-SCRATCH, RT-DEVICE-LOST-DRAIN (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7238735045); RT-SESSION-CACHE-UNCHANGED (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7240509497); RT-SHARED-PIPELINE-LAYOUTS (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7243840161); RS-HOST-LIST-SCRATCH-TRIM, RS-PIPELINE-LIBRARY-FINGERPRINT, RT-ZERO-IMAGES-RELEASE, RT-DSTORAGE-CPP-SCRATCH (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7244436564)
Depends on: none. It conflicts with #1521 (both add a release at the same spot in ~Device; keep both), #2267 (runtime/CMakeLists.txt, runtime/test/d3d12_existing_heap_test.cpp) #2085 (runtime/shims/d3d12_geometry_views.h, runtime/test/geometry_views_test.cpp), #2480 (runtime/src/command_list.h) and #1756 (save_session_pipeline_cache in runtime/shims/d3d12_vulkan_device.cpp and the end of runtime/test/pipeline_cache_store_test.cpp: whichever lands second passes state->cache_origin in the checkpoint and calls record_session_seed only when the save succeeded; a bool does not convert to CacheOrigin, so a wrong merge does not compile).

What and why

Thirty-six fixes for memory that the two runtimes never give back, or keep longer than they need. Twenty are in the C++ runtime (runtime/: the D3D12 → Vulkan layer and the console D3D12 proxy), the thirteen below and seven more further down. Sixteen are in the Rust runtime (d3d12/). They were claimed one by one (links above) and were meant to be separate pull requests. GitHub only lets this account have one open pull request in this repository, so they come together here.

The fixes stay apart in the history, which makes them easy to review or revert one at a time. Each one is its own commit (or a few), merged into this branch with its own merge commit, and comes with its own test that fails on main and passes here. Each one also still exists on its own branch, adrianmjim/leonida:leaks/<name>, so any of them can become a separate pull request on request, or be dropped from this one.

# Item Change
1 RT-UPLOAD-ARENA-REWIND d3d12: upload memory comes back at its command allocator's Reset
2 RT-PSO-BYTECODE-INTERN d3d12_xs: PSO streams with equal shader bytecode share one copy
3 RT-SPARE-LIST-EPOCHS d3d12: an idle list-cut spare drops its recording and holds back no retired title window
4 RT-SLOT-RECORDS-BUCKETS d3d12: a slot-record bucket goes with the last half it holds
5 RT-REHYDRATE-SCRATCH-TICKET d3d12: a shim's scratch stays alive until the submission that used it has completed
6 RT-FSSM-ARENA-SHARE d3d12: the PSOs of one program share its code-base copy in the arena
7 RT-TITLE-BUFFER-FALLBACK d3d12: a title vertex or index view makes and keeps only a buffer that covers it
8 RT-SLOT70-DEVICE-CYCLE d3d12: an image made for slot-70 views holds no device reference, so a released device goes
9 RT-MEM-PROBE-WINDOWS mem probe: on native Windows a vmmap line shows the process's memory by kind
10 RT-ZERO-IMAGES-RETRY d3d12: a shape whose shared zero image could not be made is tried again, after a wait that doubles at each failure
11 RT-TITLE-TEXTURE-GONE-RANGES d3d12: a title texture destroyed inside the registry leaves the async refresh's indexes too
12 RT-SHADOW-GPU-RELEASED-RANGES d3d12: LEONIDA_SHADOW_GPU=1 alone keeps no released ranges for the console heap pass
13 RT-SLOT70-OWNED-RETIRE d3d12: a slot-70 image a newer texture covers, or whose pages went, is retired once no view names it

RT-SLOT70-OWNED-RETIRE is off by default (LEONIDA_TITLE_IMAGE_RETIRE=1 turns it on): a second review found cases where retiring an image too early could show wrong pixels. LEONIDA_UPLOAD_REWIND=0 turns RT-UPLOAD-ARENA-REWIND off. The other fixes have no switch.

A short description of each fix follows, to keep this text under GitHub's size limit. The full description, and what the fix's test checks, are in the commit messages on its branch, https://github.com/adrianmjim/leonida/commits/leaks/<name>:

1. RT-UPLOAD-ARENA-REWIND: d3d12: upload memory comes back at its command allocator's Reset

Console list slot 148 (AllocateUploadMemory) carved memory from an arena of persistently mapped UPLOAD buffers in runtime/shims/d3d12_xs_device.cpp that only ever advanced; only destroy_upload_state gave it back, when the device proxy went, so a title that uploads every frame grew it by one buffer each time the newest was full. Chunks now belong to an allocator: the allocator proxy's Reset (slot 8) rewinds them, a chunk idle for 8 of its allocator's Resets is given back, and the proxy's last release frees them. LEONIDA_UPLOAD_REWIND=0 keeps the one shared arena that only grows, as before; LEONIDA_UPLOAD_LOG=1 names each chunk given back.

2. RT-PSO-BYTECODE-INTERN: d3d12_xs: PSO streams with equal shader bytecode share one copy

PsoStreamRecord::capture (runtime/shims/d3d12_xs_pso_stream.cpp, copy_pointed_data) copied every shader stage's bytecode into the record's own blobs in both compile modes (including LEONIDA_PIPELINE_COMPILE=on-demand), so each slot 86 PSO kept a private copy of every container it was made from. copy_pointed_data now takes the bytecode from a process-wide table keyed by size and DXBC checksum, takes a candidate only when all its bytes are equal, and holds weak references only, so a container is freed with the last PSO that uses it. No switch is added, because what each PSO's stream holds and reads does not change.

3. RT-SPARE-LIST-EPOCHS: d3d12: an idle list-cut spare drops its recording and holds back no retired title window

A retired title window waits for every command list whose recording began before its retirement, and the list proxy's spare real lists (restart_recording in runtime/shims/d3d12_xs_device.cpp) kept their last recording's stamp until the proxy was released, holding back every window retired after it. restart_recording now drops each new spare's recording through rt::d3d12::drop_recording, so a dropped list carries no stamp until its next Reset, and a window still without a ticket after 30 s is logged once. There is no switch; without LEONIDA_VULKAN_DEVICE the spares are kept as before, and a closed list the title neither resets nor releases still holds back later windows.

4. RT-SLOT-RECORDS-BUCKETS: d3d12: a slot-record bucket goes with the last half it holds

The two indexes in runtime/src/console_heap_slot_records.h never erased a bucket, so for the main resource heap, which lives as long as the session, the bucket count grew with every (span class, granule) ever written, not with the live slots, and never went down. Each bucket now counts the halves it holds (Bucket::live), and set() lets the last half to leave a bucket erase it with its stale entries, so the buckets held are at most twice the halves recorded. There is no LEONIDA_*=0 switch: nothing a lookup returns changes, only memory that nothing reads anymore is freed.

5. RT-REHYDRATE-SCRATCH-TICKET: d3d12: a shim's scratch stays alive until the submission that used it has completed

When the title passes ScratchAccelerationStructureData = 0, rehydrate_scratch (shims/xbox_bvh_builder.cpp) hands its DEFAULT scratch buffer to the list with rt::d3d12::hold_until_reset; in the default synchronous submit mode (LEONIDA_SUBMIT_ASYNC unset) the list released it at its Reset while the build could still run, and ~Resource returned its arena range at once. A list now records those objects (kept_) and ExecuteCommandLists passes them to VulkanQueue::execute as a keep callback, so the scratch lives until the first queue call after its submission has completed. There is no switch to bring back the old behaviour, since that behaviour was a use-after-free.

6. RT-FSSM-ARENA-SHARE: d3d12: the PSOs of one program share its code-base copy in the arena

A PSO whose shader reads its code base copies that program into the fixed-size GPU address arena (create_compute and create_graphics in runtime/shims/d3d12_vulkan_device.cpp), and every PSO made its own copy, so N PSOs of one program held N copies of the same bytes until they were released. The device now keeps one copy per program (DeviceState::code_copies), keyed by the program's SHA-256; later PSOs take a reference and the last one returns the copy from ~PipelineState. LEONIDA_SHARE_CODE_BASE=0 gives every PSO a copy of its own, as before, and a compute index entry without a uses_code_base key is still copied. Not in this pull request: 2,426 of the 2,689 compute shaders in the main index have no uses_code_base key yet, so they are still copied; that is a translator change.

7. RT-TITLE-BUFFER-FALLBACK: d3d12: a title vertex or index view makes and keeps only a buffer that covers it

When make_title_buffer (runtime/shims/d3d12_vulkan_device.cpp) could neither import nor shadow the title's pages, create_at_host_address still returned an ordinary DEFAULT buffer that resolved nothing; it was kept in title_buffers_ until the device went and counted against LEONIDA_TITLE_BUFFERS_MB, and each rebind made another until the cap was used up. Now make_title_buffer gets E_OUTOFMEMORY instead (ordinary_fallback is false), keeps a buffer only when the context knows a buffer at the view's address (1 byte with LEONIDA_TITLE_BUFFER_COVERAGE=0), and after a refusal tries no range for a second, a refused range waiting twice as long each time, up to 64 s. No switch.

8. RT-SLOT70-DEVICE-CYCLE: d3d12: an image made for slot-70 views holds no device reference, so a released device goes

The images make_title_texture makes for slot-70 views held a device reference (attach_device) while the device's registry (state_.title_textures) and retired_title_textures_ held the images, and ~Device released neither, so a released device and its Vulkan objects were never destroyed. Each image now drops its device reference right after it is made, and ~Device releases the registry's images and the retired ones after vkDeviceWaitIdle (release_title_images). This is teardown only: during a session the refresh pass releases retired images, and a title never releases its device.

9. RT-MEM-PROBE-WINDOWS: mem probe: on native Windows a vmmap line shows the process's memory by kind

LEONIDA_MEM_PROBE=<seconds> (runtime/src/mem_probe.h) reads /proc/<pid>/smaps for its process-memory line, so on native Windows it only printed no /proc entry names gta6rt and could not say where 20+ GB of commit go. When proc_dir() finds no /proc entry, sample() now prints a vmmap line: private commit and working set from GetProcessMemoryInfo, committed bytes by kind (title, pe-private, pe-image, pe-section, vk-mapped) from a VirtualQuery walk, and the largest private allocations. It is a diagnostic only, with no LEONIDA_*=0 switch: with LEONIDA_MEM_PROBE unset nothing runs, and under Wine with a /proc entry the smaps line is unchanged.

10. RT-ZERO-IMAGES-RETRY: d3d12: a shape whose shared zero image could not be made is tried again, after a wait that doubles at each failure

When the shared zeroed image for a sampled BC texture's shape (DeviceState::zero_sampled_image) could not be made, for example under VRAM pressure, the shape was stored as nullptr in zero_images, so every later slot 133 placement of that shape took memory of its own for the rest of the session. The failure is now remembered in zero_image_retry and tried again after 1 s, doubling at each failure up to 64 s, and a shape that gets its image leaves the map. Only a shape whose image would pass the 256 MiB limit stays null for good; there is no switch.

11. RT-TITLE-TEXTURE-GONE-RANGES: d3d12: a title texture destroyed inside the registry leaves the async refresh's indexes too

With LEONIDA_TEXTURE_REFRESH_ASYNC=1, drain_titles_gone erased a destroyed slot-133 texture's registry entry but left its key in texture_ranges and mapped_title_textures, so the mapped list kept the TitleTexture alive and the next refresh pass's title_textures.at() threw std::out_of_range, ending the process (0xC0000409). drain_titles_gone now erases the range key with the registry entry and also erases a mapped entry that has no resource. The async pass's apply lambda uses find() and skips keys with no entry.

12. RT-SHADOW-GPU-RELEASED-RANGES: d3d12: LEONIDA_SHADOW_GPU=1 alone keeps no released ranges for the console heap pass

With LEONIDA_SHADOW_GPU=1 and LEONIDA_CONSOLE_HEAP_GPU unset, every arena release, destroyed title-window or geometry block, released slot-133 import and removed alias range added entries that only the console heap pass takes, so they piled up for as long as the process ran. In runtime/shims/d3d12_vulkan_device.cpp the pushes in backing() and title_block_gone now ask heap_pass_enabled(), the alias table records removals only when the pass runs, arena_release no longer calls backing(..., false) twice, and ~Device releases heap_gpu before the VkDevice goes. With LEONIDA_CONSOLE_HEAP_GPU=1 nothing changes apart from the duplicate range being gone.

13. RT-SLOT70-OWNED-RETIRE: d3d12: a slot-70 image a newer texture covers, or whose pages went, is retired once no view names it

Owned slot-70 images from make_title_texture were released (retire_title_texture) only when the same address got a slot-133 registration or another description, so a streaming title kept the image and bindless index of every address it ever named for the device's life. retire_idle_owned_images now retires an image superseded by a newer overlapping texture and not named since, or whose pages are gone, after LEONIDA_TITLE_IMAGE_IDLE_MS (2000 ms by default), with up to LEONIDA_TITLE_IMAGE_CHECKS (128) candidates a pass. Retirement is off by default (LEONIDA_TITLE_IMAGE_RETIRE=1 turns it on), because a descriptor the title wrote once would then sample the fallback. No in-game numbers back the claim that this fixes the bindless filling seen during the story load.

Two more runtime fixes (runtime/)

From a third pass over the same runtime, claimed in #2570, which continues #1608 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7237948341). Same rules as above: each is its own merge with
its own test that fails on main and passes here, and it still exists on its own branch.

# Item Change
25 RT-GEOMETRY-VIEWS-CONTAIN d3d12: a geometry range inside a live view is answered from that view, not copied again
26 RT-DRAW-VIEWS-UNCHANGED d3d12: draws that bind the same views again share one views block

RT-GEOMETRY-VIEWS-CONTAIN only acts with LEONIDA_GEOMETRY_MB set (off by default) and has its own switch,
LEONIDA_GEOMETRY_CONTAINED=0. It retires nothing for disuse or on a remap (the reason #2350 was reverted by #2370).

25. RT-GEOMETRY-VIEWS-CONTAIN: d3d12: a geometry range inside a live view is answered from that view, not copied again

GeometryViews::resolve (runtime/shims/d3d12_geometry_views.h) looked up only its exact (source, bytes) key, so with LEONIDA_GEOMETRY_MB set a range inside a live geometry copy got a copy of its own, all charged to the cap. An index of the outermost live views by source now answers a range inside a filled live view with that view's address plus its offset, and the range is retired with its view; this also fixes a lost update where a filled view over a tile with a file read in flight skipped its other written tiles for good. Nothing is retired for disuse, and LEONIDA_GEOMETRY_CONTAINED=0 restores the old behaviour.

26. RT-DRAW-VIEWS-UNCHANGED: d3d12: draws that bind the same views again share one views block

GraphicsCommandList (runtime/shims/d3d12_com.cpp) marked its DrawViews block stale in set_vertex_buffers and OMSetRenderTargets without comparing with what is already bound, so a title that rebinds the same vertex buffer before each draw got one make_shared<DrawViews> per draw (about 728 bytes), kept by the recorded draws until the list's Reset. Now set_vertex_buffers marks it stale only for a slot whose view changes, and OMSetRenderTargets only when the target count or a copied target view differs. What each draw records is unchanged.

Tested at 9fc3ad427 (all 26 fixes, with main 33db04a70 merged):

  • Full ctest, -j 3: 521 of 524 pass; the three that fail are the same as on plain main here (d3d12_texture_tiles, pipeline_cache_seed, d3d12_clear). d3d12_compile_pool failed once in an earlier full run and about 1 time in 3 alone; this branch does not touch the compile pool or its test.
  • Under LEONIDA_VK_VALIDATION=1: xs_proxy_mock, geometry_views, d3d12_geometry_views, d3d12_title_va, d3d12_title_va_shadow, d3d12_draw, d3d12_draw_views_sharing and d3d12_existing_heap pass 8/8, no validation errors.

The Rust runtime (d3d12/)

Eleven more fixes from the same sweep, in the Rust runtime this time, claimed in #1608 as well
(https://github.com/ProjectLeonida/mandy/issues/1608#issuecomment-7236879810). They were meant to follow the runtime ones
one pull request at a time and come here for the same reason. A twelfth, RS-XASYNC-CANCEL-UAF, was withdrawn: zmasi's
earlier D3D12-HLE-XASYNC-CALLBACK-AND-CANCEL-LIFETIME covers it. As above, each fix is its own merge with its own test that
fails on main and passes here, and still exists on its own branch, adrianmjim/leonida:leaks/rs-<name>.

# Item Change
14 RS-HOST-LIST-ALLOCATOR-PEAK leonida-gpu: submitted lists hold no host list until reset, idle ones are trimmed
15 RS-XTASKQUEUE-POOL-TRIM leonida-hle: the XTaskQueue thread pool starts few workers in a burst and trims idle ones
16 RS-TEXTURE-READ-TRIM leonida-gpu: a texture refresh thread keeps at most 16 MiB of read buffer between textures
17 RS-SNAPSHOT-POOL-TRIM leonida-gpu: snapshot buffers no snapshot took for the idle time leave the pool
18 RS-EXACT-SPARE-CAP leonida-gpu: spare buffers of view copies are capped at 64 MiB and go when idle
19 RS-GRAPHICS-STATE-INTERN leonida-gpu: title pipelines of one graphics state share it
20 RS-EARLY-START-AGE leonida-gpu: the early pipeline list keeps the last two runs
21 RS-XMEM-FREE-DEFAULT leonida-hle: XMemFreeDefault tells the GPU side of freed 32-bit memory
22 RS-THIN-UPLOAD-DROP leonida-gpu: thin lists give back uploads a reset or release leaves behind
23 RS-APU-SCRATCH leonida-hle: XApu decodes each packet into memory the connection keeps
24 RS-REPLACED-DRAIN leonida-gpu: replaced host copies go with LEONIDA_TEXTURE_SWEEP=0 too

None of them changes what the title sees. RS-EARLY-START-AGE keeps the last 2 runs (LEONIDA_EARLY_RUNS, 0 = every run
as before) and RS-TEXTURE-READ-TRIM keeps 16 MiB a thread (LEONIDA_TEXTURE_READ_KEEP_MB).

14. RS-HOST-LIST-ALLOCATOR-PEAK: leonida-gpu: submitted lists hold no host list until reset, idle ones are trimmed

leonida-gpu host command lists keep their command allocators at peak size, every submitted title list (with LEONIDA_THIN=1, every back list) got a new host list at once that sat unused until the title's next reset, and the idle pool (IDLE, list.rs) kept up to 512 lists that nothing trimmed. A submission now takes the host list and leaves the title list none, and reset takes one from the pool. Once a second the sweep lets go of the oldest half of the idle lists nobody took since the last sweep, through retire, so they are freed on the reaper thread.

15. RS-XTASKQUEUE-POOL-TRIM: leonida-hle: the XTaskQueue thread pool starts few workers in a burst and trims idle ones

the XTaskQueue thread pool (d3d12/crates/leonida-hle/src/modules/xasync.rs, Pool), which also runs every XAsync completion on the process queue, starts about one thread per callback in a burst of short callbacks and never lets a worker go. So it keeps its peak thread count, each thread with its stack and the title's per-thread state. Fix: start a worker only when none is idle or coming, chain the next start while tasks wait, hand each task to the worker that went idle last, and let workers idle for 30 s leave down to 4. Test: 256 short callbacks start at most 32 workers, and 16 workers left idle drop to the one kept while a callback still comes every 10 ms. The tests do not compile on main (no constructor or worker count); with a test-only shim that adds both, they fail there (55 to 255 workers in the burst; 16 or 17 that never leave). No game files.

Test: pool_workers_stay_few_in_a_burst_of_short_callbacks, pool_workers_left_idle_leave_under_a_trickle_of_callbacks.

16. RS-TEXTURE-READ-TRIM: leonida-gpu: a texture refresh thread keeps at most 16 MiB of read buffer between textures

In leonida-gpu, each thread's texture read buffer (texture.rs READ, with_read) only grows, so the submitting thread and each shadow::wide_each helper keep room for the largest texture they ever read for the whole run. A thread now keeps at most LEONIDA_TEXTURE_READ_KEEP_MB (16 unless set) of its own; larger reads take a buffer from a process-wide pool and give it back, and the once-a-second sweep (texture::let_go_idle) hands buffers idle for host::ram_idle_ms to the reaper thread. Nothing the title sees changes.

17. RS-SNAPSHOT-POOL-TRIM: leonida-gpu: snapshot buffers no snapshot took for the idle time leave the pool

leonida-gpu's snapshot pool (shadow.rs POOL/give_back) keeps up to 512 MiB, or its largest buffer, of committed PC memory for the rest of the run, with no trim. Fix: stamp each pooled buffer when it is given back, take out those idle for host::ram_idle_ms in shadow::let_go_idle, and hand them to host::retire so the reaper thread frees them. Test: shadow::snapshot_pool_tests::buffers_the_pool_kept_for_the_idle_time_go (fails with d44285197's behaviour, passes with the fix). No game files.

Test: shadow::snapshot_pool_tests::buffers_the_pool_kept_for_the_idle_time_go.

18. RS-EXACT-SPARE-CAP: leonida-gpu: spare buffers of view copies are capped at 64 MiB and go when idle

leonida-gpu's EXACT_SPARE (shadow.rs exact()) keeps up to 1,024 spare view-copy buffers (each 64 KiB to 64 MiB of committed PC memory) forever, reused only on an exact width match. Fix: also cap the spares at 64 MiB (counted in 64 KiB blocks, evicting the oldest), release what leaves outside the lock, and retire those parked for host::ram_idle_ms from shadow::let_go_idle. Test: shadow::exact_spare_tests::spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle (fails with d44285197's rule, passes with the fix). No game files.

Test: shadow::exact_spare_tests::spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle.

19. RS-GRAPHICS-STATE-INTERN: leonida-gpu: title pipelines of one graphics state share it

every title pipeline created from a stream keeps its own heap copy of the full graphics state for the session (make.rs Pending.graphics: Box, pipeline.rs create_stream), ~84,000 copies of ~5,700 distinct states. Fix: Pending holds Arc, interned by a hash of describe() in a weak table, so equal states share one copy and are freed with their last pipeline. Test: two pipelines from the same synthetic stream must share one state and one with another topology must not; fails on main (two boxes), passes with the fix. No game files.

Test: pipelines_of_one_graphics_state_share_it.

20. RS-EARLY-START-AGE: leonida-gpu: the early pipeline list keeps the last two runs

early-pipelines.txt (d3d12/crates/leonida-gpu/src/pipeline/library.rs) holds every run ever and, since EARLY_MAX is above the title's pipeline count, is never trimmed, so every pipeline drawn with in any earlier run is started at creation at every load and its host PSO stays alive for the session. Each line now holds key run, and a save keeps only the keys requested in the last 2 runs (LEONIDA_EARLY_RUNS, 0 = every run as before). A process that requests nothing writes the list back unchanged, and old lists without runs still load.

21. RS-XMEM-FREE-DEFAULT: leonida-hle: XMemFreeDefault tells the GPU side of freed 32-bit memory

XMemFreeDefault's 32-bit path (d3d12/crates/leonida-hle/src/modules/xmem.rs) frees with the host VirtualFree directly. XMemAllocDefault's 32-bit path told the GPU side about that memory through XMemVirtualAlloc, but leonida_gpu::title_memory_freed never runs for the free, so the guarded, absent and foreign blocks, views and write-combined regions noted for the range survive and can be taken for true of the next memory at that address. The fix frees through title_virtual_free(address, 0, MEM_RELEASE), the title's own VirtualFree, which tells the GPU side first. A new unit test fails on main (the free never reaches the GPU side) and passes with the fix. No game files.

Test: free_default_tells_the_gpu_side_of_32bit_memory.

22. RS-THIN-UPLOAD-DROP: leonida-gpu: thin lists give back uploads a reset or release leaves behind

with LEONIDA_THIN=1, a title list reset or released while it records clears its words that were not handed over yet in Front::leave (d3d12/crates/leonida-gpu/src/list/thin.rs) without dropping the Box they name, so their 64 KiB upload arena blocks stay taken for good. The fix drops those uploads in leave(). The CPU unit test fails on main (the upload is never given back) and passes with the fix. No game files.

Test: uploads_of_words_never_handed_over_are_given_back.

23. RS-APU-SCRATCH: leonida-hle: XApu decodes each packet into memory the connection keeps

XApu's process() (d3d12/crates/leonida-hle/src/modules/apu.rs) allocates and zeroes a 46 KB Vec for every Opus packet, about 50 a second per playing stream, under the connection lock. The fix keeps one buffer in the connection's State. A unit test with a test-only counting allocator fails on main (10 large allocations for 10 packets) and passes with the fix (0). Processor time, not footprint. No game files.

Test: packets_decode_without_memory_of_their_own.

24. RS-REPLACED-DRAIN: leonida-gpu: replaced host copies go with LEONIDA_TEXTURE_SWEEP=0 too

with LEONIDA_TEXTURE_SWEEP=0, let_go_idle (d3d12/crates/leonida-gpu/src/resource.rs) returns before it drains REPLACED, so every host copy want_level replaces by one with more levels stays on the card for good although nothing can use it. The fix moves the drain above the switch; idle copies are still kept with the sweep off. The test runs a child process with the sweep off and checks that a replaced copy goes after four frames and a second: it fails on main and passes with the fix. No game files.

Test: replaced_copies_go_with_the_sweep_off.

Tested (leaks/all with the eleven merged; one conflict in shadow.rs, where two fixes add their call to the same
sweep, both kept; each fix's test is named in its details above):

  • cargo test --locked --offline -p leonida-hle --lib: 186 passed, 0 failed.
  • cargo test --locked --offline -p leonida-gpu --lib -- --test-threads=4: 493 passed, 4 failed, 46 ignored. The four
    (views_off_their_elements_get_a_copy_of_their_bytes, batch_tables, host_list_budget_starts_empty_at_each_submission,
    warp_batch_charges_every_execution) fail the same way on plain main on this machine (RX 7900 XT, AMD 32.0.32029.2010).
  • Each fix's test was first run on main d44285197 without the fix and failed there (the commit messages say how).
  • The C++ runtime of this head, rebuilt and run whole: 521 of 524 ctest pass at 9fc3ad427 (see the section above).
  • Recomputed in a second session on the same machine at 9fc3ad427: the same results (leonida-gpu --lib 493 passed with the same 4 failures; leonida-hle 186 passed). Plain main 33db04a70: leonida-gpu --lib 479 passed with the same 4 failures, leonida-hle 181 passed.

Four more fixes

From a fourth pass, three in the Rust runtime and one in the C++ runtime, claimed in #2570
(https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7238735045). Same rules as above: each is its own merge with
its own test that fails on main and passes here, and it still exists on its own branch, adrianmjim/leonida:leaks/<name>.
None of them has a switch.

# Item Change
27 RS-ARENA-ONE-COPY leonida-gpu: an arena of memory by address is in the PC's memory once
28 RS-SHADER-CONTAINER-FREE leonida-gpu: a translated shader lets its container go
29 RS-DSTORAGE-SCRATCH leonida-hle: DirectStorage workers reuse their request buffers
30 RT-DEVICE-LOST-DRAIN vulkan: after a device loss, released objects are destroyed at once
27. RS-ARENA-ONE-COPY: leonida-gpu: an arena of memory by address is in the PC's memory once

memory.rs held each 64 MiB arena twice in the PC's memory, as the arena itself (upload::reserve) and as the CPU side of its copy on the card (shadow::by_address) with the same bytes; with LEONIDA_BVH_BUILDER=1 that is up to 48 arenas, about 3 GiB. Memory::another() now makes the copy with shadow::by_address_opened, which opens the arena as a host heap so the arena itself is the CPU side, and bring()/take() resend exactly the changed dword runs; if the host does not open the memory, the copy is made as before. There is no switch, and a dword changed and changed back within one send window now goes up over what the builder stored there.

28. RS-SHADER-CONTAINER-FREE: leonida-gpu: a translated shader lets its container go

d3d12/crates/leonida-gpu/src/pipeline.rs kept every distinct shader container in the static SHADERS table (container: bytes.to_vec()) for the whole process, although after translation only small derived facts are read from it. Those facts are now kept in Translated and a new Facts, and after a successful translation Shader::translated lets the container go, except for a shader that stores while LEONIDA_PICKED_WRITES is on, until crate::picked has read its programs. Shaders that never translate or fail to translate keep their container, and nothing the title can see changes, so there is no switch.

29. RS-DSTORAGE-SCRATCH: leonida-hle: DirectStorage workers reuse their request buffers

d3d12/crates/leonida-hle/src/modules/dstorage.rs allocated new zero-filled buffers (read_source, the zlib output, into_pages) for every compressed request and freed them at its end, and staging_bytes counted only the compressed source, so the other buffers were outside LEONIDA_DSTORAGE_STAGING_MB. Each worker now keeps a Scratch it reuses, holding at most 16 MiB (SCRATCH_KEPT) between requests, and staging_bytes counts every buffer a request holds. What workers keep between requests is outside the staging limit, and the bytes written to destinations are the same as before.

30. RT-DEVICE-LOST-DRAIN: vulkan: after a device loss, released objects are destroyed at once

After a device loss, nothing drained the Vulkan layer's deferred deletion queue (runtime/src/vulkan_backend.h) until the context was destroyed, so every image, buffer, VkDeviceMemory, framebuffer and image-memory range the title released after the loss stayed allocated for the rest of the process. On a lost device VulkanContext::defer_destroy now destroys the object at once, and the first such call also destroys what was queued before (DeferredDeletionQueue::drain_lost); bindless slots and image views still wait until teardown. There is no switch, and completed_retire_ticket() deliberately still answers 0 after the loss, so the other ticket-gated frees still stop there.

Tested at eb145de6f (all 30 fixes, with main d48a957bb merged):

  • The four merged without a conflict, but the leonida-hle tests no longer built: RS-APU-SCRATCH and RS-DSTORAGE-SCRATCH each installed a counting #[global_allocator] in their tests, and a binary has one. The merge fix eb145de6f moves it to leonida-hle/src/test_alloc.rs, which tells both counters of each block. Test code only.
  • New tests, each first run on main without its fix, where it fails (the commit messages say how): memory::tests::an_arena_is_in_the_pcs_memory_once, pipeline::tests::translated_shaders_let_their_containers_go, modules::dstorage::tests::{compressed_requests_reuse_the_workers_buffers, staging_counts_every_buffer_a_request_holds} and vk_deferred_destroy_lost (ctest). All pass here, and vk_deferred_destroy_lost also passes under LEONIDA_VK_VALIDATION=1.
  • cargo test --workspace --no-fail-fast in d3d12/: leonida-gpu 496 passed with the same 4 failures as main, leonida-hle 189 passed. The other failures are the three described under "Latest main merge" below, in code that is the same as on main.
  • Full ctest, -j 8: 3 of 526 fail, the same three as on main (d3d12_texture_tiles, pipeline_cache_seed, d3d12_clear).
  • python -I scripts/check_no_game_data.py passes on every file these four change. The game was not run with them.

One more runtime fix

From a fifth pass, claimed in #2570 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7240509497). Same rules as above: its own merge, its own test that fails on main and
passes here, and its own branch, adrianmjim/leonida:leaks/session-cache-unchanged.

# Item Change
31 RT-SESSION-CACHE-UNCHANGED d3d12: a session file written beside the offline seed is loaded alone
31. RT-SESSION-CACHE-UNCHANGED: d3d12: a session file written beside the offline seed is loaded alone

With the offline seed loaded, pipeline_cache.session.bin is the driver's union of the seed and what sessions added (on the
RX 7900 XT a 1.88 GB seed and a 1.88–1.89 GB session file). Every launch still created a driver cache from the seed, then a
second one from the session file, and merged them. In the in-game sessions below, the mem probe's vmmap line shows private
commit going from 8.1 to 9.95 GB and back to 8.3 GB between 10 and 20 s. Now, whenever the session file is written beside this
device's seed, a small record pipeline_cache.session.seed (written after it, through the same temp-file + MoveFileEx
helper) notes the seed's size and last-write time and the session file's size. On the next launch, when the record matches the
current seed and session file and the session file's header fits the device, the cache is created from the session file alone:
pipeline_cache.bin is only stat'ed and nothing is merged. Everything else takes today's path: no record, a changed seed, a
session file of another size, a driver that declines the blob, LEONIDA_SESSION_CACHE_DIRECT_SEED=0 or
LEONIDA_DIRECT_SESSION_CACHE=0. A write-back smaller than what the cache was created from drops the record, so the next launch
merges the seed again. Nothing is deleted except a stale record. The ~1.9 GB write at exit is unchanged on purpose. Documented
in docs/d3d12_vulkan.md.

Tested at 652f45345 (all 31 fixes; merging this fix's branch also brings in main 9c49bd533, 63 commits after d48a957bb, with no conflict):

  • New ctest d3d12_session_cache_seed (d3d12_compile_teardown_test --seed, a real device and a seed that holds a real pipeline; its rounds cover the relaunch, a touched seed, LEONIDA_PIPELINE_CACHE_BYTES=0, the switch at 0, no seed, and a seed with a session file but no record) and new unit checks in pipeline_cache_store (the record's format and every truncation, a changed seed or session file, the shrink rule). With main's device code the relaunch fails: 1 merge(s), caches created from [3652, 7252] bytes. With the fix: 0 merge(s), caches created from [7252] bytes, 2 of 2 compute build(s) a cache hit.
  • That test and its neighbours (pipeline_cache_store, heavy_pipeline_cache, d3d12_compute_journal, d3d12_pipeline_checkpoint, d3d12_compile_teardown*, plus mem_probe_vmmap) under LEONIDA_VK_VALIDATION=1: 8/8.
  • Full ctest, -j 8: of 527, the same three as on main fail (d3d12_texture_tiles, pipeline_cache_seed, d3d12_clear), plus the presentation tests (vk_present*, dxgi_*, d3d12_present, xbox_present), because the monitor was off during the run; they pass with it on, as in the runs above. gta6rt_no_tls_callbacks failed once because an incremental link left an old gta6rt.map; after a full relink it passes.
  • cargo test --workspace --no-fail-fast in d3d12/ and the 555 standalone tests/test_*.py: the same results as at eb145de6f (this fix touches neither). python -I scripts/check_no_game_data.py passes on every changed file.
  • In the game: PROVISIONAL (n=1 on the new path). gta6rt from this fix's branch (a580819a5, on main 9c49bd533), a fresh copy of the port with the 1.88 GB seed and a 1.88 GB session file, the same harness as the sessions below. The first launch took the old path (loaded 1883920688 bytes from pipeline_cache.bin, then merged 1884044916 bytes from pipeline_cache.session.bin) and its checkpoint wrote the record. The second took the new one (loaded 1884044916 bytes from pipeline_cache.session.bin, which holds the 1883920688-byte pipeline_cache.bin it was written beside; the seed was not loaded and nothing merged) and booted and ran normally. MEASURED with an outside sample every ~11 s over the first 120 s: peak working set minus working set reached 2,685–3,272 MiB in all 5 launches on the old path (both sessions below and three today), with a peak working set of 9,456–9,490 MiB; on the new path, 307 MiB and 8,398 MiB. Private commit at launch was not measured on this build (it has no vmmap line), and the 11 s samples of private bytes are too coarse to show a transient of a few seconds on either path.

652f45345 also answers a review: under Wine the process's commit charge does not count what it commits, so mem_probe_vmmap checks it on Windows only, like the private working set next to it.

And one more

From a sixth pass, claimed in #2570 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7243840161), with its own merge, its own test that fails on main and passes here, and its
own branch, adrianmjim/leonida:leaks/shared-pipeline-layouts.

# Item Change
32 RT-SHARED-PIPELINE-LAYOUTS d3d12: PSOs share one pipeline layout per shape, destroyed at device teardown
32. RT-SHARED-PIPELINE-LAYOUTS: d3d12: PSOs share one pipeline layout per shape, destroyed at device teardown

Every PSO made its own VkPipelineLayout (PipelineState::create_graphics / create_compute) and destroyed it with the PSO,
although the create info only differs by push-constant stages and whether set 0 is the bindless layout, so a session's ~50k PSOs
held ~50k identical layouts. MEASURED standalone on the RX 7900 XT (driver 26.11.2) with the runtime's bindless set layout:
~2.3 KB of process memory per layout with the bindless set (the driver copies the 29-binding set layout into each), ~0.2 KB
without; ASSUMED from that, ~117 MB for 54k PSOs (not measured in the game). Now DeviceState::pipeline_layout keeps one layout
per distinct create info: the key is the whole create info (flags, every set layout handle in order, every push range), and a
pNext chain is refused rather than shared. Layouts are made on first use under a mutex, with the map slot reserved first. PSOs
no longer destroy them; ~Device does, once, after the compiler cancel, vkDeviceWaitIdle, the drained deferred deletions and
the stopped pipeline workers, and before the bindless set layout and the VkDevice. The mem probe's device line adds
PSO pipeline layouts N.

Tested at 20ca6dcf5 (all 32 fixes, main 8b318bd40 merged; this fix's base d57b78a9c is already in it):

  • New ctests d3d12_shared_pipeline_layouts and _eager (LEONIDA_LAZY_PIPELINES=0, LEONIDA_LAZY_COMPUTE=0): 256 PSOs of 4 shapes (graphics and compute, each with and without set 0) made on 4 threads to race the first creation, a dispatch that pushes constants and binds sets with a shared layout, and a second device; they count creates and destroys through the hooked vkGetDeviceProcAddr. With main's device code they fail: 256 PSOs of 4 shapes made 256 pipeline layout(s). Here: 4 made and 4 destroyed per device, 0 live, 0 bad destroys.
  • These and their neighbours (pipeline_workers, d3d12_pipeline_workers*, d3d12_compute, d3d12_draw, d3d12_set0_compute, d3d12_mesh*, d3d12_compile_teardown*, vulkan_mesh_limits): 15/15. Under LEONIDA_VK_VALIDATION=1, the new two, d3d12_pipeline_workers* and d3d12_compute: 8/8, no VUID line.
  • Full ctest, -j 8: of 529, the same three as on main fail, and d3d12_mesh_heavy_cache failed once: it and d3d12_mesh run the same program, which rewrites the same %TEMP%\leonida_mesh_test\index.json, and its log reads cannot open ...\leonida_mesh_test\index.json (READ IN CODE: runtime/test/d3d12_mesh_test.cpp:128, unchanged here). It passes alone and with d3d12_mesh beside it, 13 of 13 runs.
  • Not measured in the game.

And one more in d3d12/

From a seventh pass, claimed in #2570 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7244436564), with its own merge, its own test that fails on main and passes here, and its
own branch, adrianmjim/leonida:leaks/rs-host-list-scratch-trim.

# Item Change
33 RS-HOST-LIST-SCRATCH-TRIM leonida-gpu: an idle host list lets go of an indirect scratch buffer past 1 MiB
33. RS-HOST-LIST-SCRATCH-TRIM: leonida-gpu: an idle host list lets go of an indirect scratch buffer past 1 MiB

HostList::indirect_scratch (d3d12/crates/leonida-gpu/src/host.rs) only grows its device-local buffer of clamped indirect
arguments, doubling it. list::recycle reset a host list and put it in the idle pool with that buffer still attached, and the pool
hands its lists to any title list, so one large ExecuteIndirect kept its buffer in the card's memory for the rest of the run, in
every idle list that had served one (up to 512). recycle now calls HostList::idle_trim right after the reset: a scratch larger
than 1 MiB (IDLE_INDIRECT_MOST) is taken out and handed to retire_resource, which drops it once the submissions still running
have finished. Smaller ones stay, so ordinary frames keep reusing theirs, and title-list resets are unchanged. The frame-rate line
counts what idle lists let go. It works with the Pool described under the latest main merge.

Tested at ca5aed779 (all 33 fixes, main 8b318bd40; this fix's base is the same main):

  • New test list::tests::an_idle_list_lets_go_of_a_large_indirect_scratch: grows a list's scratch to 2 MiB, recycles the list, takes it back from the pool and checks that the next request gets a fresh 64 KiB buffer, then that a 1 MiB buffer survives the same trip. On main it fails (the large buffer was let go: left 2097152, right 65536); here it passes, with list::tests 10/10.
  • cargo test --workspace --no-fail-fast in d3d12/: leonida-gpu 524 passed and leonida-hle 214 passed; the failures are the same 4 in leonida-gpu, 2 in leonida-shader and 1 in xtask as on main. runtime/ is unchanged by this fix. python -I scripts/check_no_game_data.py passes on both changed files. Not run in the game (the Rust runtime is not gta6rt).

Three more

From the same seventh pass, claimed in #2570 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7244436564): one in d3d12/, two in runtime/. Each has its own merge, its own
test that fails on main and passes here, and its own branch on the fork (leaks/rs-pipeline-library-fingerprint,
leaks/zero-images-release, leaks/dstorage-cpp-scratch).

# Item Change
34 RS-PIPELINE-LIBRARY-FINGERPRINT leonida-gpu: the host pipeline library is kept for one set of translated shaders
35 RT-ZERO-IMAGES-RELEASE d3d12: a shared zero image no placed texture shows any more is released
36 RT-DSTORAGE-CPP-SCRATCH dstorage: queue workers reuse their staging buffers
34. RS-PIPELINE-LIBRARY-FINGERPRINT: leonida-gpu: the host pipeline library is kept for one set of translated shaders

d3d12/crates/leonida-gpu/src/pipeline/library.rs opened host-pipelines.bin whatever translation its pipelines came from and saved it back whole, so entries of older translator generations, which can never load again, stayed and the file only grew (the library's own line reads 1,490 MB in memory in run 65). The fingerprint leonida warm already uses (known::fingerprint()) is now written beside it as host-pipelines.fingerprint; a missing or different one gives an empty library, and that run's first save writes over the old generation. A save that is cut short leaves no fingerprint, never a stale library under the current one. One SAVING mutex now covers a whole save: overlapping saves shared host-pipelines.tmp on main too, and with the fingerprint that could leave a half-written library under a valid one.

35. RT-ZERO-IMAGES-RELEASE: d3d12: a shared zero image no placed texture shows any more is released

Placed BC textures with no memory of their own yet show a shared all-zero image of their shape (DeviceState::zero_sampled_image), on a CUSTOM WRITE_BACK / L0 heap (host memory on a discrete GPU) under a 256 MiB cap, and those images were only released at device teardown, so a session streaming many shapes filled the cap for good. The device now counts each image's users (acquire_zero_image); when the last one is destroyed or gets memory of its own, the image leaves the map and the cap, and its Resource is released through the deferred-deletion queue. With several queues, a return carries the execute epoch and is released only once no replay in progress at it is left. Shapes left out for not fitting get another try (the comment RT-ZERO-IMAGES-RETRY left in zero_sampled_image is corrected in 962bc1601).

36. RT-DSTORAGE-CPP-SCRATCH: dstorage: queue workers reuse their staging buffers

Each compressed, swizzled or physical-page DirectStorage request in runtime/shims/dstorage.cpp allocated a new zero-filled buffer at every stage and freed it at the end, the C++ side of RS-DSTORAGE-SCRATCH. Each queue worker now keeps two sets of buffers (its own request's and its paired helper's), grown only when a request needs more, keeps at most 16 MiB between requests (the budget can_prepare already used), and no longer zero-fills bytes that are always written before they are read or the request fails and publishes nothing.

Tested at 962bc1601 (all 36 fixes, main 8b318bd40; the three branches' base is the same main):

  • New tests, each failing on main and passing here: pipeline::library::tests::{a_library_saved_for_other_shaders_is_not_opened, overlapping_saves_leave_one_whole_library_and_its_lists} (main: no fingerprint written; the second fails 3 of 3 with the lock made a no-op), ctest d3d12_zero_image_release (12 shapes placed and released, with a second queue running during the copy's replay; main: 12 images and 47,104 bytes still held; here 0 and 0) and, in dstorage, test_reused_buffers (100 requests of two streams, outputs compared byte for byte: 300 blocks of 128 KiB or more on main, 6 here), test_kept_buffers_cap and test_kept_buffers_pair_cap.
  • dstorage, d3d12_zero_image_retry and d3d12_zero_image_release: 3/3; the two zero-image tests under LEONIDA_VK_VALIDATION=1: 2/2, no VUID line.
  • Full ctest, -j 8: 3 of 530 fail, the same three as on main. cargo test --workspace --no-fail-fast: leonida-gpu 528 passed (pipeline::library 15/15) and leonida-hle 214, with the same failures as on main. python -I scripts/check_no_game_data.py passes on every changed file. Not run in the game.

Tested

On Windows 11 Pro 26300, MSVC 14.44, Ninja, RelWithDebInfo and Vulkan SDK 1.4.363.0, with an RX 7900 XT and 32 GB of RAM, while another gta6rt was running on the same GPU.

Latest main merge: leaks/all at 5fe777296, all 31 fixes then in this branch with main 8b318bd40 merged in (154 commits since 7daa4a4a5). One conflict, in d3d12/crates/leonida-gpu/src/list.rs: main's 7efbbdd39 (LEONIDA_ALLOCATOR_TRIM=1, off by default: idle host lists older than the limit are let go) and RS-HOST-LIST-ALLOCATOR-PEAK (the idle pool as a Pool, its untouched lists halved once a second) both changed the idle host-list pool. The Pool stays; an idle list keeps when it was put by, and with LEONIDA_ALLOCATOR_TRIM its stale oldest are taken out of the Pool (new Pool::take_oldest, with a unit test) and counted in ALLOCATOR_TRIMS[2] as on main, under the same condition. MEASURED on the same machine:

  • Build: gta6rt and every test target, after a full relink.
  • ctest, whole suite, -j 8: 3 of 527 fail, the same three as on main. pso_stream, xs_proxy_mock*, pipeline_cache_store, d3d12_session_cache_seed and mem_probe_vmmap under LEONIDA_VK_VALIDATION=1: 14/14.
  • cargo test --workspace --no-fail-fast in d3d12/: leonida-gpu 523 passed (with list::tests 9/9) and leonida-hle 214 passed; the failures are the same 4 in leonida-gpu, 2 in leonida-shader and 1 in xtask described further down, all on main too.
  • Python: of 585 standalone tests/test_*.py, the same 10 fail as at the merges before (listed below); tests/, tools/ and scripts/ are as on main.

Earlier main merges, each MEASURED the same way with no failure that is not also on main: d51ad23b7 (main 7daa4a4a5; one conflict in runtime/test/pso_stream_test.cpp, where #2476's test_later_subobject_versions and RT-PSO-BYTECODE-INTERN's three tests are all kept) and abdb93f0e (main d48a957bb, no conflict). The failures on main that show in every run: leonida-shader emit::valu_tests::{typed_d16_table_uav_roundtrip_uint_sint_and_float, rdna_forms_give_what_the_spelled_out_ones_give} and xtask policy::tests::repository_passes_policy (lower.rs over the size limit), both in code these fixes do not touch, and 10 standalone Python tests (tests/, tools/ and scripts/ are as on main): test_bc_feature_validation, test_bcpack_history_calib, test_build_runtime_fallback, test_make_game_pipelines, test_make_game_preflight, test_progress_dashboard, test_sampler_source_census, test_spirv_metal_set0_cli_errors, test_spirv_metal_set0_extra, test_tool_stdout_encoding.

leaks/all at 098342d02: the 13 fixes, with main 33db04a70 merged in. One conflict came from #958, which made release_child_reference the single path that drops a child proxy's last reference (the queue and fence pins use it too). The allocator's upload memory is now given back in that function, by the proxy's kind, so every path that drops an allocator's last reference frees it. The mock in xs_proxy_mock_test.cpp keeps the fields from both sides.

# Item Its test (ctest)
1 RT-UPLOAD-ARENA-REWIND xs_proxy_mock (check_upload_rewind), new xs_proxy_mock_upload_rewind_off
2 RT-PSO-BYTECODE-INTERN pso_stream
3 RT-SPARE-LIST-EPOCHS new xbox_list_cut_spares, command_list
4 RT-SLOT-RECORDS-BUCKETS console_heap_slot_records
5 RT-REHYDRATE-SCRATCH-TICKET xbox_bvh_builder, xbox_bvh_builder_check
6 RT-FSSM-ARENA-SHARE new d3d12_code_base_share, d3d12_code_base_per_pso
7 RT-TITLE-BUFFER-FALLBACK new d3d12_title_buffer_fallback
8 RT-SLOT70-DEVICE-CYCLE d3d12_existing_heap under LEONIDA_VK_VALIDATION=1
9 RT-MEM-PROBE-WINDOWS new mem_probe_vmmap
10 RT-ZERO-IMAGES-RETRY new d3d12_zero_image_retry
11 RT-TITLE-TEXTURE-GONE-RANGES d3d12_existing_heap (check_mapped_plane_gone_in_registry)
12 RT-SHADOW-GPU-RELEASED-RANGES new d3d12_shadow_gpu_releases, d3d12_console_heap_gpu_releases
13 RT-SLOT70-OWNED-RETIRE new d3d12_title_image_retire, d3d12_title_image_idle, xmem
  • Before the fixes. Each fix's test was first run on main d44285197 without that fix, and failed there (the commit messages say how). Between d44285197 and 33db04a70, main changed these files for the stub pipelines (bbc750655, 78159b886), which do not touch the paths these fixes change, and for #958, merged as described above.
  • These tests and the ones next to them, 41 in all (xs_proxy_mock*, pso_stream, command_list, xbox_list_cut_spares, console_heap_slot_records, xbox_bvh_builder*, d3d12_code_base_*, d3d12_title_buffer_fallback, d3d12_existing_heap*, mem_probe_vmmap, memory_breakdown, d3d12_zero_image_retry, d3d12_*_gpu_releases, d3d12_title_image_*, xmem*, allocator_proxy, device_proxy, title_texture_refresh, d3d12_title_va, d3d12_compute, d3d12_draw), with -j 4: 41/41 passed.
  • Under LEONIDA_VK_VALIDATION=1. d3d12_existing_heap, d3d12_title_image_retire, d3d12_title_image_idle, d3d12_zero_image_retry, d3d12_title_buffer_fallback, d3d12_shadow_gpu_releases, d3d12_code_base_share, allocator_proxy and xs_proxy_mock passed 9/9. There were no validation errors and no VUID-vkDestroyDevice-device-05137. On main, d3d12_existing_heap leaves 93 objects at vkDestroyDevice.
  • Full suite, with -j 4, run twice (before and after merging 33db04a70): 519/523 both times. Three tests failed both times, and they also fail on plain main on this machine; none of these fixes touches them:
    • d3d12_texture_tiles: the CopyTiles offset rounding on AMD (#964).
    • pipeline_cache_seed: the checker's device differs from the runtime's (#1833).
    • d3d12_clear: a NaN depth clear reads back 1.
    • The fourth failure was different each time: dxgi_waitable_latency in the first run and run_tiny_game_abort_exit_codes in the second. Each passes when run alone (the second 3/3), so they are timing-sensitive under -j.
  • Builds. gta6rt and every test target build and link.
  • Python checks. python -I scripts/check_no_game_data.py passes on every changed file, and python -m compileall -q make_game.py tools tests is clean. Of the 534 standalone tests/test_*.py, 7 fail, the same 7 with the same output as on main 33db04a70 (test_docs_cli_flags, test_docs_env_vars, test_docs_python_deps, test_docs_repo_paths, test_make_game_preflight, test_progress_dashboard, test_tool_stdout_encoding). test_docs_env_vars fails only on LEONIDA_CLWB_PATCH, which is not from this branch; the new switches are all documented.

In the game: PROVISIONAL (n=1 per arm). Two sessions of 720 s each, both stopped by the harness at the end: main d48a957bb alone, and this branch at 32d2020f7 (all 30 fixes; its runtime/ is the same as at eb145de6f, which only adds the test-only leonida-hle merge fix). Same build type, the same first-run-UI input, each started from the same copy of the pipeline caches, LEONIDA_TITLE_WATCHDOG=0 with its kick, LEONIDA_MEM_PROBE=10, and an outside sample of the process every ~11 s. Resizable BAR off. The character stands still in the world from about 420 s.

  • MEASURED (n=1): no regression. Both ran the full time with no fault and no device loss (PresentX 8,940 with main, 9,218 with the fixes, none failed).
  • MEASURED (n=1): private bytes at 424 s were 20,755 MiB with main and 20,786 MiB with the fixes, and at the end (714 s) 20,965 and 21,010 MiB. Slope from 450 to 720 s: +41.5 and +47.8 MiB/min. Dedicated video memory, flat from about 420 s: 8,544 and 8,659 MiB. The runtime's Vulkan allocations (mem probe), flat from 360 to 700 s: 8,405 and 8,494 MiB. With one run per arm and no prediction written beforehand, these are observations: there is no measurable difference in 12 minutes.
  • MEASURED in both arms: the growth in the world follows the graphics pipelines being built, about 19 a minute (+94 with main, +91 with the fixes, after 420 s). MEASURED standalone (a separate Vulkan program, no code from this repository, on the same GPU and driver, 22 real vertex + pixel shader pairs from the translated library with the runtime's bindless set layout and dynamic states): each first compile leaves the driver holding a median 2.4 MiB of private memory (0.4–19 MiB) after its shader modules are destroyed; vkDestroyPipeline gives none of it back, destroying all 22 gives back about 0.3 MiB each, and compiling and destroying at once still adds 2.4–3.9 MiB a compile. A pipeline made again from the pipeline cache costs 23–47 KiB and 0.1–0.4 ms. About 19 new pipelines a minute at ~2.4 MiB each is the ~45 MiB/min seen in both sessions (an inference from the two measurements, not measured inside the game). So this growth is the driver's, per compile, and not from these fixes; only compiling less (a pipeline already in the seed or the heavy cache) reduces it, and destroying cold pipelines would give back little.
  • READ IN CODE and MEASURED: these sessions do not exercise what most of the fixes target. The 14 Rust fixes are in d3d12/ and do not run in gta6rt. AllocateUploadMemory (list slot 148) was never called in either session (the runtime logs every list slot's first call), so RT-UPLOAD-ARENA-REWIND was not exercised, and an idle character does not churn PSOs or retire title windows.
  • An earlier pair of ~7 minute boots (main d44285197 against the first 13 fixes, without the watchdog variables) ended at the title's hang watchdog at about 400 s in both, also with no regression.

GPUs tested: AMD Radeon RX 7900 XT, 20 GB, desktop (profile M), AMD Software 26.11.2 (D3D12 driver 32.0.32029.2010, Vulkan driver 2.0.416), Windows 11 Pro 26300, 32 GB RAM

Second sweep in d3d12/ (25 more items)

Pushed at 26e00403c (with current main merged): fewer copies of each byte the title writes between the PC's memory and the card's, more title memory read in place, and more leaks. Claimed in #2570 (round 2); what each does, its switch and how it was tested are in this comment. Branches adrianmjim/leonida:unified/<name>: send-pool-trim, compare-ring, landed-cells-gate, small-leaks, placed-textures, texture-staging-release, descriptor-views, inplace-free, placement-bench, card-one-copy, inplace-blockers, page-pool-open, shadow-hot-paths, exact-waits, physical-reuse, title-alloc-watch (with xmem-combined). leonida-gpu 630 passed / 48 ignored, leonida-hle 243 passed / 2 ignored.

A third round (7 branches, 19006b0e6): landing in the submission, no forced sweep settle, detiling only what changed, more memory in place, GPU upload buffers, hot-path bookkeeping and a fix of in-place holds; see this comment. leonida-gpu 690 passed / 50 ignored.

A fourth round (7cc8e1879): card copies whose CPU side is title memory itself, in-place memory opened off the lookup path, a send ring, the compare measured and shared, list summaries at close, and a fix of double releases; see this comment. leonida-gpu 718 passed / 51 ignored.

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request. (Thirty-six leak fixes from one sweep, twenty in runtime/ and sixteen in d3d12/, and twenty-five more in d3d12/ from a second, together only because of the open pull request limit. Each one is its own merge here and its own branch on the fork.)
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a: no translator change)
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5538899796 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-28T09:48:55Z. --- Claimed in the coordination issue as: RT-UPLOAD-ARENA-REWIND, RT-PSO-BYTECODE-INTERN, RT-SPARE-LIST-EPOCHS, RT-SLOT-RECORDS-BUCKETS, RT-REHYDRATE-SCRATCH-TICKET, RT-FSSM-ARENA-SHARE, RT-TITLE-BUFFER-FALLBACK, RT-SLOT70-DEVICE-CYCLE, RT-MEM-PROBE-WINDOWS, RT-ZERO-IMAGES-RETRY, RT-TITLE-TEXTURE-GONE-RANGES, RT-SHADOW-GPU-RELEASED-RANGES, RT-SLOT70-OWNED-RETIRE (https://github.com/ProjectLeonida/mandy/issues/1608#issuecomment-7235789024); RS-HOST-LIST-ALLOCATOR-PEAK, RS-XTASKQUEUE-POOL-TRIM, RS-TEXTURE-READ-TRIM, RS-SNAPSHOT-POOL-TRIM, RS-EXACT-SPARE-CAP, RS-GRAPHICS-STATE-INTERN, RS-EARLY-START-AGE, RS-XMEM-FREE-DEFAULT, RS-THIN-UPLOAD-DROP, RS-APU-SCRATCH, RS-REPLACED-DRAIN (https://github.com/ProjectLeonida/mandy/issues/1608#issuecomment-7236879810); RT-GEOMETRY-VIEWS-CONTAIN, RT-DRAW-VIEWS-UNCHANGED (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7237948341); RS-ARENA-ONE-COPY, RS-SHADER-CONTAINER-FREE, RS-DSTORAGE-SCRATCH, RT-DEVICE-LOST-DRAIN (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7238735045); RT-SESSION-CACHE-UNCHANGED (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7240509497); RT-SHARED-PIPELINE-LAYOUTS (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7243840161); RS-HOST-LIST-SCRATCH-TRIM, RS-PIPELINE-LIBRARY-FINGERPRINT, RT-ZERO-IMAGES-RELEASE, RT-DSTORAGE-CPP-SCRATCH (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7244436564) Depends on: none. It conflicts with #1521 (both add a release at the same spot in `~Device`; keep both), #2267 (`runtime/CMakeLists.txt`, `runtime/test/d3d12_existing_heap_test.cpp`) #2085 (`runtime/shims/d3d12_geometry_views.h`, `runtime/test/geometry_views_test.cpp`), #2480 (`runtime/src/command_list.h`) and #1756 (`save_session_pipeline_cache` in `runtime/shims/d3d12_vulkan_device.cpp` and the end of `runtime/test/pipeline_cache_store_test.cpp`: whichever lands second passes `state->cache_origin` in the checkpoint and calls `record_session_seed` only when the save succeeded; a bool does not convert to `CacheOrigin`, so a wrong merge does not compile). ### What and why Thirty-six fixes for memory that the two runtimes never give back, or keep longer than they need. Twenty are in the C++ runtime (`runtime/`: the D3D12 → Vulkan layer and the console D3D12 proxy), the thirteen below and seven more further down. Sixteen are in the Rust runtime (`d3d12/`). They were claimed one by one (links above) and were meant to be separate pull requests. GitHub only lets this account have one open pull request in this repository, so they come together here. The fixes stay apart in the history, which makes them easy to review or revert one at a time. Each one is its own commit (or a few), merged into this branch with its own merge commit, and comes with its own test that fails on `main` and passes here. Each one also still exists on its own branch, `adrianmjim/leonida:leaks/<name>`, so any of them can become a separate pull request on request, or be dropped from this one. | # | Item | Change | |---|------|--------| | 1 | `RT-UPLOAD-ARENA-REWIND` | d3d12: upload memory comes back at its command allocator's Reset | | 2 | `RT-PSO-BYTECODE-INTERN` | d3d12_xs: PSO streams with equal shader bytecode share one copy | | 3 | `RT-SPARE-LIST-EPOCHS` | d3d12: an idle list-cut spare drops its recording and holds back no retired title window | | 4 | `RT-SLOT-RECORDS-BUCKETS` | d3d12: a slot-record bucket goes with the last half it holds | | 5 | `RT-REHYDRATE-SCRATCH-TICKET` | d3d12: a shim's scratch stays alive until the submission that used it has completed | | 6 | `RT-FSSM-ARENA-SHARE` | d3d12: the PSOs of one program share its code-base copy in the arena | | 7 | `RT-TITLE-BUFFER-FALLBACK` | d3d12: a title vertex or index view makes and keeps only a buffer that covers it | | 8 | `RT-SLOT70-DEVICE-CYCLE` | d3d12: an image made for slot-70 views holds no device reference, so a released device goes | | 9 | `RT-MEM-PROBE-WINDOWS` | mem probe: on native Windows a vmmap line shows the process's memory by kind | | 10 | `RT-ZERO-IMAGES-RETRY` | d3d12: a shape whose shared zero image could not be made is tried again, after a wait that doubles at each failure | | 11 | `RT-TITLE-TEXTURE-GONE-RANGES` | d3d12: a title texture destroyed inside the registry leaves the async refresh's indexes too | | 12 | `RT-SHADOW-GPU-RELEASED-RANGES` | d3d12: LEONIDA_SHADOW_GPU=1 alone keeps no released ranges for the console heap pass | | 13 | `RT-SLOT70-OWNED-RETIRE` | d3d12: a slot-70 image a newer texture covers, or whose pages went, is retired once no view names it | `RT-SLOT70-OWNED-RETIRE` is off by default (`LEONIDA_TITLE_IMAGE_RETIRE=1` turns it on): a second review found cases where retiring an image too early could show wrong pixels. `LEONIDA_UPLOAD_REWIND=0` turns `RT-UPLOAD-ARENA-REWIND` off. The other fixes have no switch. A short description of each fix follows, to keep this text under GitHub's size limit. The full description, and what the fix's test checks, are in the commit messages on its branch, `https://github.com/adrianmjim/leonida/commits/leaks/<name>`: <details> <summary><b>1. RT-UPLOAD-ARENA-REWIND</b>: d3d12: upload memory comes back at its command allocator's Reset</summary> Console list slot 148 (`AllocateUploadMemory`) carved memory from an arena of persistently mapped UPLOAD buffers in `runtime/shims/d3d12_xs_device.cpp` that only ever advanced; only `destroy_upload_state` gave it back, when the device proxy went, so a title that uploads every frame grew it by one buffer each time the newest was full. Chunks now belong to an allocator: the allocator proxy's Reset (slot 8) rewinds them, a chunk idle for 8 of its allocator's Resets is given back, and the proxy's last release frees them. `LEONIDA_UPLOAD_REWIND=0` keeps the one shared arena that only grows, as before; `LEONIDA_UPLOAD_LOG=1` names each chunk given back. </details> <details> <summary><b>2. RT-PSO-BYTECODE-INTERN</b>: d3d12_xs: PSO streams with equal shader bytecode share one copy</summary> `PsoStreamRecord::capture` (`runtime/shims/d3d12_xs_pso_stream.cpp`, `copy_pointed_data`) copied every shader stage's bytecode into the record's own blobs in both compile modes (including `LEONIDA_PIPELINE_COMPILE=on-demand`), so each slot 86 PSO kept a private copy of every container it was made from. `copy_pointed_data` now takes the bytecode from a process-wide table keyed by size and DXBC checksum, takes a candidate only when all its bytes are equal, and holds weak references only, so a container is freed with the last PSO that uses it. No switch is added, because what each PSO's stream holds and reads does not change. </details> <details> <summary><b>3. RT-SPARE-LIST-EPOCHS</b>: d3d12: an idle list-cut spare drops its recording and holds back no retired title window</summary> A retired title window waits for every command list whose recording began before its retirement, and the list proxy's spare real lists (`restart_recording` in `runtime/shims/d3d12_xs_device.cpp`) kept their last recording's stamp until the proxy was released, holding back every window retired after it. `restart_recording` now drops each new spare's recording through `rt::d3d12::drop_recording`, so a dropped list carries no stamp until its next Reset, and a window still without a ticket after 30 s is logged once. There is no switch; without `LEONIDA_VULKAN_DEVICE` the spares are kept as before, and a closed list the title neither resets nor releases still holds back later windows. </details> <details> <summary><b>4. RT-SLOT-RECORDS-BUCKETS</b>: d3d12: a slot-record bucket goes with the last half it holds</summary> The two indexes in `runtime/src/console_heap_slot_records.h` never erased a bucket, so for the main resource heap, which lives as long as the session, the bucket count grew with every (span class, granule) ever written, not with the live slots, and never went down. Each bucket now counts the halves it holds (`Bucket::live`), and `set()` lets the last half to leave a bucket erase it with its stale entries, so the buckets held are at most twice the halves recorded. There is no `LEONIDA_*=0` switch: nothing a lookup returns changes, only memory that nothing reads anymore is freed. </details> <details> <summary><b>5. RT-REHYDRATE-SCRATCH-TICKET</b>: d3d12: a shim's scratch stays alive until the submission that used it has completed</summary> When the title passes `ScratchAccelerationStructureData = 0`, `rehydrate_scratch` (`shims/xbox_bvh_builder.cpp`) hands its DEFAULT scratch buffer to the list with `rt::d3d12::hold_until_reset`; in the default synchronous submit mode (`LEONIDA_SUBMIT_ASYNC` unset) the list released it at its `Reset` while the build could still run, and `~Resource` returned its arena range at once. A list now records those objects (`kept_`) and `ExecuteCommandLists` passes them to `VulkanQueue::execute` as a `keep` callback, so the scratch lives until the first queue call after its submission has completed. There is no switch to bring back the old behaviour, since that behaviour was a use-after-free. </details> <details> <summary><b>6. RT-FSSM-ARENA-SHARE</b>: d3d12: the PSOs of one program share its code-base copy in the arena</summary> A PSO whose shader reads its code base copies that program into the fixed-size GPU address arena (`create_compute` and `create_graphics` in `runtime/shims/d3d12_vulkan_device.cpp`), and every PSO made its own copy, so N PSOs of one program held N copies of the same bytes until they were released. The device now keeps one copy per program (`DeviceState::code_copies`), keyed by the program's SHA-256; later PSOs take a reference and the last one returns the copy from `~PipelineState`. `LEONIDA_SHARE_CODE_BASE=0` gives every PSO a copy of its own, as before, and a compute index entry without a `uses_code_base` key is still copied. Not in this pull request: 2,426 of the 2,689 compute shaders in the main index have no `uses_code_base` key yet, so they are still copied; that is a translator change. </details> <details> <summary><b>7. RT-TITLE-BUFFER-FALLBACK</b>: d3d12: a title vertex or index view makes and keeps only a buffer that covers it</summary> When `make_title_buffer` (`runtime/shims/d3d12_vulkan_device.cpp`) could neither import nor shadow the title's pages, `create_at_host_address` still returned an ordinary DEFAULT buffer that resolved nothing; it was kept in `title_buffers_` until the device went and counted against `LEONIDA_TITLE_BUFFERS_MB`, and each rebind made another until the cap was used up. Now `make_title_buffer` gets `E_OUTOFMEMORY` instead (`ordinary_fallback` is `false`), keeps a buffer only when the context knows a buffer at the view's address (1 byte with `LEONIDA_TITLE_BUFFER_COVERAGE=0`), and after a refusal tries no range for a second, a refused range waiting twice as long each time, up to 64 s. No switch. </details> <details> <summary><b>8. RT-SLOT70-DEVICE-CYCLE</b>: d3d12: an image made for slot-70 views holds no device reference, so a released device goes</summary> The images `make_title_texture` makes for slot-70 views held a device reference (`attach_device`) while the device's registry (`state_.title_textures`) and `retired_title_textures_` held the images, and `~Device` released neither, so a released device and its Vulkan objects were never destroyed. Each image now drops its device reference right after it is made, and `~Device` releases the registry's images and the retired ones after `vkDeviceWaitIdle` (`release_title_images`). This is teardown only: during a session the refresh pass releases retired images, and a title never releases its device. </details> <details> <summary><b>9. RT-MEM-PROBE-WINDOWS</b>: mem probe: on native Windows a vmmap line shows the process's memory by kind</summary> `LEONIDA_MEM_PROBE=<seconds>` (`runtime/src/mem_probe.h`) reads `/proc/<pid>/smaps` for its process-memory line, so on native Windows it only printed `no /proc entry names gta6rt` and could not say where 20+ GB of commit go. When `proc_dir()` finds no `/proc` entry, `sample()` now prints a `vmmap` line: private commit and working set from `GetProcessMemoryInfo`, committed bytes by kind (title, pe-private, pe-image, pe-section, vk-mapped) from a `VirtualQuery` walk, and the largest private allocations. It is a diagnostic only, with no `LEONIDA_*=0` switch: with `LEONIDA_MEM_PROBE` unset nothing runs, and under Wine with a `/proc` entry the smaps line is unchanged. </details> <details> <summary><b>10. RT-ZERO-IMAGES-RETRY</b>: d3d12: a shape whose shared zero image could not be made is tried again, after a wait that doubles at each failure</summary> When the shared zeroed image for a sampled BC texture's shape (`DeviceState::zero_sampled_image`) could not be made, for example under VRAM pressure, the shape was stored as nullptr in `zero_images`, so every later slot 133 placement of that shape took memory of its own for the rest of the session. The failure is now remembered in `zero_image_retry` and tried again after 1 s, doubling at each failure up to 64 s, and a shape that gets its image leaves the map. Only a shape whose image would pass the 256 MiB limit stays null for good; there is no switch. </details> <details> <summary><b>11. RT-TITLE-TEXTURE-GONE-RANGES</b>: d3d12: a title texture destroyed inside the registry leaves the async refresh's indexes too</summary> With `LEONIDA_TEXTURE_REFRESH_ASYNC=1`, `drain_titles_gone` erased a destroyed slot-133 texture's registry entry but left its key in `texture_ranges` and `mapped_title_textures`, so the mapped list kept the `TitleTexture` alive and the next refresh pass's `title_textures.at()` threw `std::out_of_range`, ending the process (0xC0000409). `drain_titles_gone` now erases the range key with the registry entry and also erases a mapped entry that has no resource. The async pass's apply lambda uses `find()` and skips keys with no entry. </details> <details> <summary><b>12. RT-SHADOW-GPU-RELEASED-RANGES</b>: d3d12: LEONIDA_SHADOW_GPU=1 alone keeps no released ranges for the console heap pass</summary> With `LEONIDA_SHADOW_GPU=1` and `LEONIDA_CONSOLE_HEAP_GPU` unset, every arena release, destroyed title-window or geometry block, released slot-133 import and removed alias range added entries that only the console heap pass takes, so they piled up for as long as the process ran. In `runtime/shims/d3d12_vulkan_device.cpp` the pushes in `backing()` and `title_block_gone` now ask `heap_pass_enabled()`, the alias table records removals only when the pass runs, `arena_release` no longer calls `backing(..., false)` twice, and `~Device` releases `heap_gpu` before the VkDevice goes. With `LEONIDA_CONSOLE_HEAP_GPU=1` nothing changes apart from the duplicate range being gone. </details> <details> <summary><b>13. RT-SLOT70-OWNED-RETIRE</b>: d3d12: a slot-70 image a newer texture covers, or whose pages went, is retired once no view names it</summary> Owned slot-70 images from `make_title_texture` were released (`retire_title_texture`) only when the same address got a slot-133 registration or another description, so a streaming title kept the image and bindless index of every address it ever named for the device's life. `retire_idle_owned_images` now retires an image superseded by a newer overlapping texture and not named since, or whose pages are gone, after `LEONIDA_TITLE_IMAGE_IDLE_MS` (2000 ms by default), with up to `LEONIDA_TITLE_IMAGE_CHECKS` (128) candidates a pass. Retirement is **off by default** (`LEONIDA_TITLE_IMAGE_RETIRE=1` turns it on), because a descriptor the title wrote once would then sample the fallback. No in-game numbers back the claim that this fixes the bindless filling seen during the story load. </details> ### Two more runtime fixes (`runtime/`) From a third pass over the same runtime, claimed in #2570, which continues #1608 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7237948341). Same rules as above: each is its own merge with its own test that fails on `main` and passes here, and it still exists on its own branch. | # | Item | Change | |---|------|--------| | 25 | `RT-GEOMETRY-VIEWS-CONTAIN` | d3d12: a geometry range inside a live view is answered from that view, not copied again | | 26 | `RT-DRAW-VIEWS-UNCHANGED` | d3d12: draws that bind the same views again share one views block | `RT-GEOMETRY-VIEWS-CONTAIN` only acts with `LEONIDA_GEOMETRY_MB` set (off by default) and has its own switch, `LEONIDA_GEOMETRY_CONTAINED=0`. It retires nothing for disuse or on a remap (the reason #2350 was reverted by #2370). <details> <summary><b>25. RT-GEOMETRY-VIEWS-CONTAIN</b>: d3d12: a geometry range inside a live view is answered from that view, not copied again</summary> `GeometryViews::resolve` (`runtime/shims/d3d12_geometry_views.h`) looked up only its exact (source, bytes) key, so with `LEONIDA_GEOMETRY_MB` set a range inside a live geometry copy got a copy of its own, all charged to the cap. An index of the outermost live views by source now answers a range inside a filled live view with that view's address plus its offset, and the range is retired with its view; this also fixes a lost update where a filled view over a tile with a file read in flight skipped its other written tiles for good. Nothing is retired for disuse, and `LEONIDA_GEOMETRY_CONTAINED=0` restores the old behaviour. </details> <details> <summary><b>26. RT-DRAW-VIEWS-UNCHANGED</b>: d3d12: draws that bind the same views again share one views block</summary> `GraphicsCommandList` (`runtime/shims/d3d12_com.cpp`) marked its `DrawViews` block stale in `set_vertex_buffers` and `OMSetRenderTargets` without comparing with what is already bound, so a title that rebinds the same vertex buffer before each draw got one `make_shared<DrawViews>` per draw (about 728 bytes), kept by the recorded draws until the list's Reset. Now `set_vertex_buffers` marks it stale only for a slot whose view changes, and `OMSetRenderTargets` only when the target count or a copied target view differs. What each draw records is unchanged. </details> **Tested** at `9fc3ad427` (all 26 fixes, with `main` `33db04a70` merged): - Full ctest, `-j 3`: 521 of 524 pass; the three that fail are the same as on plain `main` here (`d3d12_texture_tiles`, `pipeline_cache_seed`, `d3d12_clear`). `d3d12_compile_pool` failed once in an earlier full run and about 1 time in 3 alone; this branch does not touch the compile pool or its test. - Under `LEONIDA_VK_VALIDATION=1`: `xs_proxy_mock`, `geometry_views`, `d3d12_geometry_views`, `d3d12_title_va`, `d3d12_title_va_shadow`, `d3d12_draw`, `d3d12_draw_views_sharing` and `d3d12_existing_heap` pass 8/8, no validation errors. ### The Rust runtime (`d3d12/`) Eleven more fixes from the same sweep, in the Rust runtime this time, claimed in #1608 as well (https://github.com/ProjectLeonida/mandy/issues/1608#issuecomment-7236879810). They were meant to follow the runtime ones one pull request at a time and come here for the same reason. A twelfth, `RS-XASYNC-CANCEL-UAF`, was withdrawn: zmasi's earlier D3D12-HLE-XASYNC-CALLBACK-AND-CANCEL-LIFETIME covers it. As above, each fix is its own merge with its own test that fails on `main` and passes here, and still exists on its own branch, `adrianmjim/leonida:leaks/rs-<name>`. | # | Item | Change | |---|------|--------| | 14 | `RS-HOST-LIST-ALLOCATOR-PEAK` | leonida-gpu: submitted lists hold no host list until reset, idle ones are trimmed | | 15 | `RS-XTASKQUEUE-POOL-TRIM` | leonida-hle: the XTaskQueue thread pool starts few workers in a burst and trims idle ones | | 16 | `RS-TEXTURE-READ-TRIM` | leonida-gpu: a texture refresh thread keeps at most 16 MiB of read buffer between textures | | 17 | `RS-SNAPSHOT-POOL-TRIM` | leonida-gpu: snapshot buffers no snapshot took for the idle time leave the pool | | 18 | `RS-EXACT-SPARE-CAP` | leonida-gpu: spare buffers of view copies are capped at 64 MiB and go when idle | | 19 | `RS-GRAPHICS-STATE-INTERN` | leonida-gpu: title pipelines of one graphics state share it | | 20 | `RS-EARLY-START-AGE` | leonida-gpu: the early pipeline list keeps the last two runs | | 21 | `RS-XMEM-FREE-DEFAULT` | leonida-hle: XMemFreeDefault tells the GPU side of freed 32-bit memory | | 22 | `RS-THIN-UPLOAD-DROP` | leonida-gpu: thin lists give back uploads a reset or release leaves behind | | 23 | `RS-APU-SCRATCH` | leonida-hle: XApu decodes each packet into memory the connection keeps | | 24 | `RS-REPLACED-DRAIN` | leonida-gpu: replaced host copies go with LEONIDA_TEXTURE_SWEEP=0 too | None of them changes what the title sees. `RS-EARLY-START-AGE` keeps the last 2 runs (`LEONIDA_EARLY_RUNS`, 0 = every run as before) and `RS-TEXTURE-READ-TRIM` keeps 16 MiB a thread (`LEONIDA_TEXTURE_READ_KEEP_MB`). <details> <summary><b>14. RS-HOST-LIST-ALLOCATOR-PEAK</b>: leonida-gpu: submitted lists hold no host list until reset, idle ones are trimmed</summary> leonida-gpu host command lists keep their command allocators at peak size, every submitted title list (with `LEONIDA_THIN=1`, every back list) got a new host list at once that sat unused until the title's next reset, and the idle pool (`IDLE`, `list.rs`) kept up to 512 lists that nothing trimmed. A submission now takes the host list and leaves the title list none, and reset takes one from the pool. Once a second the sweep lets go of the oldest half of the idle lists nobody took since the last sweep, through retire, so they are freed on the reaper thread. </details> <details> <summary><b>15. RS-XTASKQUEUE-POOL-TRIM</b>: leonida-hle: the XTaskQueue thread pool starts few workers in a burst and trims idle ones</summary> the XTaskQueue thread pool (d3d12/crates/leonida-hle/src/modules/xasync.rs, Pool), which also runs every XAsync completion on the process queue, starts about one thread per callback in a burst of short callbacks and never lets a worker go. So it keeps its peak thread count, each thread with its stack and the title's per-thread state. Fix: start a worker only when none is idle or coming, chain the next start while tasks wait, hand each task to the worker that went idle last, and let workers idle for 30 s leave down to 4. Test: 256 short callbacks start at most 32 workers, and 16 workers left idle drop to the one kept while a callback still comes every 10 ms. The tests do not compile on main (no constructor or worker count); with a test-only shim that adds both, they fail there (55 to 255 workers in the burst; 16 or 17 that never leave). No game files. Test: `pool_workers_stay_few_in_a_burst_of_short_callbacks`, `pool_workers_left_idle_leave_under_a_trickle_of_callbacks`. </details> <details> <summary><b>16. RS-TEXTURE-READ-TRIM</b>: leonida-gpu: a texture refresh thread keeps at most 16 MiB of read buffer between textures</summary> In leonida-gpu, each thread's texture read buffer (`texture.rs` `READ`, `with_read`) only grows, so the submitting thread and each `shadow::wide_each` helper keep room for the largest texture they ever read for the whole run. A thread now keeps at most `LEONIDA_TEXTURE_READ_KEEP_MB` (16 unless set) of its own; larger reads take a buffer from a process-wide pool and give it back, and the once-a-second sweep (`texture::let_go_idle`) hands buffers idle for `host::ram_idle_ms` to the reaper thread. Nothing the title sees changes. </details> <details> <summary><b>17. RS-SNAPSHOT-POOL-TRIM</b>: leonida-gpu: snapshot buffers no snapshot took for the idle time leave the pool</summary> leonida-gpu's snapshot pool (shadow.rs POOL/give_back) keeps up to 512 MiB, or its largest buffer, of committed PC memory for the rest of the run, with no trim. Fix: stamp each pooled buffer when it is given back, take out those idle for host::ram_idle_ms in shadow::let_go_idle, and hand them to host::retire so the reaper thread frees them. Test: shadow::snapshot_pool_tests::buffers_the_pool_kept_for_the_idle_time_go (fails with d44285197's behaviour, passes with the fix). No game files. Test: `shadow::snapshot_pool_tests::buffers_the_pool_kept_for_the_idle_time_go`. </details> <details> <summary><b>18. RS-EXACT-SPARE-CAP</b>: leonida-gpu: spare buffers of view copies are capped at 64 MiB and go when idle</summary> leonida-gpu's EXACT_SPARE (shadow.rs exact()) keeps up to 1,024 spare view-copy buffers (each 64 KiB to 64 MiB of committed PC memory) forever, reused only on an exact width match. Fix: also cap the spares at 64 MiB (counted in 64 KiB blocks, evicting the oldest), release what leaves outside the lock, and retire those parked for host::ram_idle_ms from shadow::let_go_idle. Test: shadow::exact_spare_tests::spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle (fails with d44285197's rule, passes with the fix). No game files. Test: `shadow::exact_spare_tests::spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle`. </details> <details> <summary><b>19. RS-GRAPHICS-STATE-INTERN</b>: leonida-gpu: title pipelines of one graphics state share it</summary> every title pipeline created from a stream keeps its own heap copy of the full graphics state for the session (make.rs Pending.graphics: Box, pipeline.rs create_stream), ~84,000 copies of ~5,700 distinct states. Fix: Pending holds Arc<GraphicsState>, interned by a hash of describe() in a weak table, so equal states share one copy and are freed with their last pipeline. Test: two pipelines from the same synthetic stream must share one state and one with another topology must not; fails on main (two boxes), passes with the fix. No game files. Test: `pipelines_of_one_graphics_state_share_it`. </details> <details> <summary><b>20. RS-EARLY-START-AGE</b>: leonida-gpu: the early pipeline list keeps the last two runs</summary> `early-pipelines.txt` (`d3d12/crates/leonida-gpu/src/pipeline/library.rs`) holds every run ever and, since `EARLY_MAX` is above the title's pipeline count, is never trimmed, so every pipeline drawn with in any earlier run is started at creation at every load and its host PSO stays alive for the session. Each line now holds `key run`, and a save keeps only the keys requested in the last 2 runs (`LEONIDA_EARLY_RUNS`, 0 = every run as before). A process that requests nothing writes the list back unchanged, and old lists without runs still load. </details> <details> <summary><b>21. RS-XMEM-FREE-DEFAULT</b>: leonida-hle: XMemFreeDefault tells the GPU side of freed 32-bit memory</summary> XMemFreeDefault's 32-bit path (d3d12/crates/leonida-hle/src/modules/xmem.rs) frees with the host VirtualFree directly. XMemAllocDefault's 32-bit path told the GPU side about that memory through XMemVirtualAlloc, but leonida_gpu::title_memory_freed never runs for the free, so the guarded, absent and foreign blocks, views and write-combined regions noted for the range survive and can be taken for true of the next memory at that address. The fix frees through title_virtual_free(address, 0, MEM_RELEASE), the title's own VirtualFree, which tells the GPU side first. A new unit test fails on main (the free never reaches the GPU side) and passes with the fix. No game files. Test: `free_default_tells_the_gpu_side_of_32bit_memory`. </details> <details> <summary><b>22. RS-THIN-UPLOAD-DROP</b>: leonida-gpu: thin lists give back uploads a reset or release leaves behind</summary> with LEONIDA_THIN=1, a title list reset or released while it records clears its words that were not handed over yet in Front::leave (d3d12/crates/leonida-gpu/src/list/thin.rs) without dropping the Box<Upload> they name, so their 64 KiB upload arena blocks stay taken for good. The fix drops those uploads in leave(). The CPU unit test fails on main (the upload is never given back) and passes with the fix. No game files. Test: `uploads_of_words_never_handed_over_are_given_back`. </details> <details> <summary><b>23. RS-APU-SCRATCH</b>: leonida-hle: XApu decodes each packet into memory the connection keeps</summary> XApu's process() (d3d12/crates/leonida-hle/src/modules/apu.rs) allocates and zeroes a 46 KB Vec<f32> for every Opus packet, about 50 a second per playing stream, under the connection lock. The fix keeps one buffer in the connection's State. A unit test with a test-only counting allocator fails on main (10 large allocations for 10 packets) and passes with the fix (0). Processor time, not footprint. No game files. Test: `packets_decode_without_memory_of_their_own`. </details> <details> <summary><b>24. RS-REPLACED-DRAIN</b>: leonida-gpu: replaced host copies go with LEONIDA_TEXTURE_SWEEP=0 too</summary> with LEONIDA_TEXTURE_SWEEP=0, let_go_idle (d3d12/crates/leonida-gpu/src/resource.rs) returns before it drains REPLACED, so every host copy want_level replaces by one with more levels stays on the card for good although nothing can use it. The fix moves the drain above the switch; idle copies are still kept with the sweep off. The test runs a child process with the sweep off and checks that a replaced copy goes after four frames and a second: it fails on main and passes with the fix. No game files. Test: `replaced_copies_go_with_the_sweep_off`. </details> **Tested** (`leaks/all` with the eleven merged; one conflict in `shadow.rs`, where two fixes add their call to the same sweep, both kept; each fix's test is named in its details above): - `cargo test --locked --offline -p leonida-hle --lib`: 186 passed, 0 failed. - `cargo test --locked --offline -p leonida-gpu --lib -- --test-threads=4`: 493 passed, 4 failed, 46 ignored. The four (`views_off_their_elements_get_a_copy_of_their_bytes`, `batch_tables`, `host_list_budget_starts_empty_at_each_submission`, `warp_batch_charges_every_execution`) fail the same way on plain `main` on this machine (RX 7900 XT, AMD 32.0.32029.2010). - Each fix's test was first run on `main` `d44285197` without the fix and failed there (the commit messages say how). - The C++ runtime of this head, rebuilt and run whole: 521 of 524 ctest pass at `9fc3ad427` (see the section above). - Recomputed in a second session on the same machine at `9fc3ad427`: the same results (`leonida-gpu --lib` 493 passed with the same 4 failures; `leonida-hle` 186 passed). Plain `main` `33db04a70`: `leonida-gpu --lib` 479 passed with the same 4 failures, `leonida-hle` 181 passed. ### Four more fixes From a fourth pass, three in the Rust runtime and one in the C++ runtime, claimed in #2570 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7238735045). Same rules as above: each is its own merge with its own test that fails on `main` and passes here, and it still exists on its own branch, `adrianmjim/leonida:leaks/<name>`. None of them has a switch. | # | Item | Change | |---|------|--------| | 27 | `RS-ARENA-ONE-COPY` | leonida-gpu: an arena of memory by address is in the PC's memory once | | 28 | `RS-SHADER-CONTAINER-FREE` | leonida-gpu: a translated shader lets its container go | | 29 | `RS-DSTORAGE-SCRATCH` | leonida-hle: DirectStorage workers reuse their request buffers | | 30 | `RT-DEVICE-LOST-DRAIN` | vulkan: after a device loss, released objects are destroyed at once | <details> <summary><b>27. RS-ARENA-ONE-COPY</b>: leonida-gpu: an arena of memory by address is in the PC's memory once</summary> `memory.rs` held each 64 MiB arena twice in the PC's memory, as the arena itself (`upload::reserve`) and as the CPU side of its copy on the card (`shadow::by_address`) with the same bytes; with `LEONIDA_BVH_BUILDER=1` that is up to 48 arenas, about 3 GiB. `Memory::another()` now makes the copy with `shadow::by_address_opened`, which opens the arena as a host heap so the arena itself is the CPU side, and `bring()`/`take()` resend exactly the changed dword runs; if the host does not open the memory, the copy is made as before. There is no switch, and a dword changed and changed back within one send window now goes up over what the builder stored there. </details> <details> <summary><b>28. RS-SHADER-CONTAINER-FREE</b>: leonida-gpu: a translated shader lets its container go</summary> `d3d12/crates/leonida-gpu/src/pipeline.rs` kept every distinct shader container in the static `SHADERS` table (`container: bytes.to_vec()`) for the whole process, although after translation only small derived facts are read from it. Those facts are now kept in `Translated` and a new `Facts`, and after a successful translation `Shader::translated` lets the container go, except for a shader that stores while `LEONIDA_PICKED_WRITES` is on, until `crate::picked` has read its programs. Shaders that never translate or fail to translate keep their container, and nothing the title can see changes, so there is no switch. </details> <details> <summary><b>29. RS-DSTORAGE-SCRATCH</b>: leonida-hle: DirectStorage workers reuse their request buffers</summary> `d3d12/crates/leonida-hle/src/modules/dstorage.rs` allocated new zero-filled buffers (`read_source`, the zlib output, `into_pages`) for every compressed request and freed them at its end, and `staging_bytes` counted only the compressed source, so the other buffers were outside `LEONIDA_DSTORAGE_STAGING_MB`. Each worker now keeps a `Scratch` it reuses, holding at most 16 MiB (`SCRATCH_KEPT`) between requests, and `staging_bytes` counts every buffer a request holds. What workers keep between requests is outside the staging limit, and the bytes written to destinations are the same as before. </details> <details> <summary><b>30. RT-DEVICE-LOST-DRAIN</b>: vulkan: after a device loss, released objects are destroyed at once</summary> After a device loss, nothing drained the Vulkan layer's deferred deletion queue (`runtime/src/vulkan_backend.h`) until the context was destroyed, so every image, buffer, `VkDeviceMemory`, framebuffer and image-memory range the title released after the loss stayed allocated for the rest of the process. On a lost device `VulkanContext::defer_destroy` now destroys the object at once, and the first such call also destroys what was queued before (`DeferredDeletionQueue::drain_lost`); bindless slots and image views still wait until teardown. There is no switch, and `completed_retire_ticket()` deliberately still answers 0 after the loss, so the other ticket-gated frees still stop there. </details> **Tested** at `eb145de6f` (all 30 fixes, with `main` `d48a957bb` merged): - The four merged without a conflict, but the `leonida-hle` tests no longer built: `RS-APU-SCRATCH` and `RS-DSTORAGE-SCRATCH` each installed a counting `#[global_allocator]` in their tests, and a binary has one. The merge fix `eb145de6f` moves it to `leonida-hle/src/test_alloc.rs`, which tells both counters of each block. Test code only. - New tests, each first run on `main` without its fix, where it fails (the commit messages say how): `memory::tests::an_arena_is_in_the_pcs_memory_once`, `pipeline::tests::translated_shaders_let_their_containers_go`, `modules::dstorage::tests::{compressed_requests_reuse_the_workers_buffers, staging_counts_every_buffer_a_request_holds}` and `vk_deferred_destroy_lost` (ctest). All pass here, and `vk_deferred_destroy_lost` also passes under `LEONIDA_VK_VALIDATION=1`. - `cargo test --workspace --no-fail-fast` in `d3d12/`: `leonida-gpu` 496 passed with the same 4 failures as `main`, `leonida-hle` 189 passed. The other failures are the three described under "Latest `main` merge" below, in code that is the same as on `main`. - Full ctest, `-j 8`: 3 of 526 fail, the same three as on `main` (`d3d12_texture_tiles`, `pipeline_cache_seed`, `d3d12_clear`). - `python -I scripts/check_no_game_data.py` passes on every file these four change. The game was not run with them. ### One more runtime fix From a fifth pass, claimed in #2570 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7240509497). Same rules as above: its own merge, its own test that fails on `main` and passes here, and its own branch, `adrianmjim/leonida:leaks/session-cache-unchanged`. | # | Item | Change | |---|------|--------| | 31 | `RT-SESSION-CACHE-UNCHANGED` | d3d12: a session file written beside the offline seed is loaded alone | <details> <summary><b>31. RT-SESSION-CACHE-UNCHANGED</b>: d3d12: a session file written beside the offline seed is loaded alone</summary> With the offline seed loaded, `pipeline_cache.session.bin` is the driver's union of the seed and what sessions added (on the RX 7900 XT a 1.88 GB seed and a 1.88–1.89 GB session file). Every launch still created a driver cache from the seed, then a second one from the session file, and merged them. In the in-game sessions below, the mem probe's vmmap line shows private commit going from 8.1 to 9.95 GB and back to 8.3 GB between 10 and 20 s. Now, whenever the session file is written beside this device's seed, a small record `pipeline_cache.session.seed` (written after it, through the same temp-file + `MoveFileEx` helper) notes the seed's size and last-write time and the session file's size. On the next launch, when the record matches the current seed and session file and the session file's header fits the device, the cache is created from the session file alone: `pipeline_cache.bin` is only stat'ed and nothing is merged. Everything else takes today's path: no record, a changed seed, a session file of another size, a driver that declines the blob, `LEONIDA_SESSION_CACHE_DIRECT_SEED=0` or `LEONIDA_DIRECT_SESSION_CACHE=0`. A write-back smaller than what the cache was created from drops the record, so the next launch merges the seed again. Nothing is deleted except a stale record. The ~1.9 GB write at exit is unchanged on purpose. Documented in `docs/d3d12_vulkan.md`. </details> **Tested** at `652f45345` (all 31 fixes; merging this fix's branch also brings in `main` `9c49bd533`, 63 commits after `d48a957bb`, with no conflict): - New ctest `d3d12_session_cache_seed` (`d3d12_compile_teardown_test --seed`, a real device and a seed that holds a real pipeline; its rounds cover the relaunch, a touched seed, `LEONIDA_PIPELINE_CACHE_BYTES=0`, the switch at 0, no seed, and a seed with a session file but no record) and new unit checks in `pipeline_cache_store` (the record's format and every truncation, a changed seed or session file, the shrink rule). With `main`'s device code the relaunch fails: `1 merge(s), caches created from [3652, 7252] bytes`. With the fix: `0 merge(s), caches created from [7252] bytes, 2 of 2 compute build(s) a cache hit`. - That test and its neighbours (`pipeline_cache_store`, `heavy_pipeline_cache`, `d3d12_compute_journal`, `d3d12_pipeline_checkpoint`, `d3d12_compile_teardown*`, plus `mem_probe_vmmap`) under `LEONIDA_VK_VALIDATION=1`: 8/8. - Full ctest, `-j 8`: of 527, the same three as on `main` fail (`d3d12_texture_tiles`, `pipeline_cache_seed`, `d3d12_clear`), plus the presentation tests (`vk_present*`, `dxgi_*`, `d3d12_present`, `xbox_present`), because the monitor was off during the run; they pass with it on, as in the runs above. `gta6rt_no_tls_callbacks` failed once because an incremental link left an old `gta6rt.map`; after a full relink it passes. - `cargo test --workspace --no-fail-fast` in `d3d12/` and the 555 standalone `tests/test_*.py`: the same results as at `eb145de6f` (this fix touches neither). `python -I scripts/check_no_game_data.py` passes on every changed file. - **In the game: PROVISIONAL (n=1 on the new path).** `gta6rt` from this fix's branch (`a580819a5`, on `main` `9c49bd533`), a fresh copy of the port with the 1.88 GB seed and a 1.88 GB session file, the same harness as the sessions below. The first launch took the old path (`loaded 1883920688 bytes from pipeline_cache.bin`, then `merged 1884044916 bytes from pipeline_cache.session.bin`) and its checkpoint wrote the record. The second took the new one (`loaded 1884044916 bytes from pipeline_cache.session.bin, which holds the 1883920688-byte pipeline_cache.bin it was written beside; the seed was not loaded and nothing merged`) and booted and ran normally. MEASURED with an outside sample every ~11 s over the first 120 s: peak working set minus working set reached 2,685–3,272 MiB in all 5 launches on the old path (both sessions below and three today), with a peak working set of 9,456–9,490 MiB; on the new path, 307 MiB and 8,398 MiB. Private commit at launch was not measured on this build (it has no vmmap line), and the 11 s samples of private bytes are too coarse to show a transient of a few seconds on either path. `652f45345` also answers a review: under Wine the process's commit charge does not count what it commits, so `mem_probe_vmmap` checks it on Windows only, like the private working set next to it. ### And one more From a sixth pass, claimed in #2570 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7243840161), with its own merge, its own test that fails on `main` and passes here, and its own branch, `adrianmjim/leonida:leaks/shared-pipeline-layouts`. | # | Item | Change | |---|------|--------| | 32 | `RT-SHARED-PIPELINE-LAYOUTS` | d3d12: PSOs share one pipeline layout per shape, destroyed at device teardown | <details> <summary><b>32. RT-SHARED-PIPELINE-LAYOUTS</b>: d3d12: PSOs share one pipeline layout per shape, destroyed at device teardown</summary> Every PSO made its own `VkPipelineLayout` (`PipelineState::create_graphics` / `create_compute`) and destroyed it with the PSO, although the create info only differs by push-constant stages and whether set 0 is the bindless layout, so a session's ~50k PSOs held ~50k identical layouts. MEASURED standalone on the RX 7900 XT (driver 26.11.2) with the runtime's bindless set layout: ~2.3 KB of process memory per layout with the bindless set (the driver copies the 29-binding set layout into each), ~0.2 KB without; ASSUMED from that, ~117 MB for 54k PSOs (not measured in the game). Now `DeviceState::pipeline_layout` keeps one layout per distinct create info: the key is the whole create info (flags, every set layout handle in order, every push range), and a `pNext` chain is refused rather than shared. Layouts are made on first use under a mutex, with the map slot reserved first. PSOs no longer destroy them; `~Device` does, once, after the compiler cancel, `vkDeviceWaitIdle`, the drained deferred deletions and the stopped pipeline workers, and before the bindless set layout and the `VkDevice`. The mem probe's device line adds `PSO pipeline layouts N`. </details> **Tested** at `20ca6dcf5` (all 32 fixes, `main` `8b318bd40` merged; this fix's base `d57b78a9c` is already in it): - New ctests `d3d12_shared_pipeline_layouts` and `_eager` (`LEONIDA_LAZY_PIPELINES=0`, `LEONIDA_LAZY_COMPUTE=0`): 256 PSOs of 4 shapes (graphics and compute, each with and without set 0) made on 4 threads to race the first creation, a dispatch that pushes constants and binds sets with a shared layout, and a second device; they count creates and destroys through the hooked `vkGetDeviceProcAddr`. With `main`'s device code they fail: `256 PSOs of 4 shapes made 256 pipeline layout(s)`. Here: 4 made and 4 destroyed per device, 0 live, 0 bad destroys. - These and their neighbours (`pipeline_workers`, `d3d12_pipeline_workers*`, `d3d12_compute`, `d3d12_draw`, `d3d12_set0_compute`, `d3d12_mesh*`, `d3d12_compile_teardown*`, `vulkan_mesh_limits`): 15/15. Under `LEONIDA_VK_VALIDATION=1`, the new two, `d3d12_pipeline_workers*` and `d3d12_compute`: 8/8, no `VUID` line. - Full ctest, `-j 8`: of 529, the same three as on `main` fail, and `d3d12_mesh_heavy_cache` failed once: it and `d3d12_mesh` run the same program, which rewrites the same `%TEMP%\leonida_mesh_test\index.json`, and its log reads `cannot open ...\leonida_mesh_test\index.json` (READ IN CODE: `runtime/test/d3d12_mesh_test.cpp:128`, unchanged here). It passes alone and with `d3d12_mesh` beside it, 13 of 13 runs. - Not measured in the game. ### And one more in `d3d12/` From a seventh pass, claimed in #2570 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7244436564), with its own merge, its own test that fails on `main` and passes here, and its own branch, `adrianmjim/leonida:leaks/rs-host-list-scratch-trim`. | # | Item | Change | |---|------|--------| | 33 | `RS-HOST-LIST-SCRATCH-TRIM` | leonida-gpu: an idle host list lets go of an indirect scratch buffer past 1 MiB | <details> <summary><b>33. RS-HOST-LIST-SCRATCH-TRIM</b>: leonida-gpu: an idle host list lets go of an indirect scratch buffer past 1 MiB</summary> `HostList::indirect_scratch` (`d3d12/crates/leonida-gpu/src/host.rs`) only grows its device-local buffer of clamped indirect arguments, doubling it. `list::recycle` reset a host list and put it in the idle pool with that buffer still attached, and the pool hands its lists to any title list, so one large `ExecuteIndirect` kept its buffer in the card's memory for the rest of the run, in every idle list that had served one (up to 512). `recycle` now calls `HostList::idle_trim` right after the reset: a scratch larger than 1 MiB (`IDLE_INDIRECT_MOST`) is taken out and handed to `retire_resource`, which drops it once the submissions still running have finished. Smaller ones stay, so ordinary frames keep reusing theirs, and title-list resets are unchanged. The frame-rate line counts what idle lists let go. It works with the `Pool` described under the latest `main` merge. </details> **Tested** at `ca5aed779` (all 33 fixes, `main` `8b318bd40`; this fix's base is the same `main`): - New test `list::tests::an_idle_list_lets_go_of_a_large_indirect_scratch`: grows a list's scratch to 2 MiB, recycles the list, takes it back from the pool and checks that the next request gets a fresh 64 KiB buffer, then that a 1 MiB buffer survives the same trip. On `main` it fails (`the large buffer was let go`: left 2097152, right 65536); here it passes, with `list::tests` 10/10. - `cargo test --workspace --no-fail-fast` in `d3d12/`: `leonida-gpu` 524 passed and `leonida-hle` 214 passed; the failures are the same 4 in `leonida-gpu`, 2 in `leonida-shader` and 1 in `xtask` as on `main`. `runtime/` is unchanged by this fix. `python -I scripts/check_no_game_data.py` passes on both changed files. Not run in the game (the Rust runtime is not `gta6rt`). ### Three more From the same seventh pass, claimed in #2570 (https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7244436564): one in `d3d12/`, two in `runtime/`. Each has its own merge, its own test that fails on `main` and passes here, and its own branch on the fork (`leaks/rs-pipeline-library-fingerprint`, `leaks/zero-images-release`, `leaks/dstorage-cpp-scratch`). | # | Item | Change | |---|------|--------| | 34 | `RS-PIPELINE-LIBRARY-FINGERPRINT` | leonida-gpu: the host pipeline library is kept for one set of translated shaders | | 35 | `RT-ZERO-IMAGES-RELEASE` | d3d12: a shared zero image no placed texture shows any more is released | | 36 | `RT-DSTORAGE-CPP-SCRATCH` | dstorage: queue workers reuse their staging buffers | <details> <summary><b>34. RS-PIPELINE-LIBRARY-FINGERPRINT</b>: leonida-gpu: the host pipeline library is kept for one set of translated shaders</summary> `d3d12/crates/leonida-gpu/src/pipeline/library.rs` opened `host-pipelines.bin` whatever translation its pipelines came from and saved it back whole, so entries of older translator generations, which can never load again, stayed and the file only grew (the library's own line reads 1,490 MB in memory in run 65). The fingerprint `leonida warm` already uses (`known::fingerprint()`) is now written beside it as `host-pipelines.fingerprint`; a missing or different one gives an empty library, and that run's first save writes over the old generation. A save that is cut short leaves no fingerprint, never a stale library under the current one. One `SAVING` mutex now covers a whole save: overlapping saves shared `host-pipelines.tmp` on `main` too, and with the fingerprint that could leave a half-written library under a valid one. </details> <details> <summary><b>35. RT-ZERO-IMAGES-RELEASE</b>: d3d12: a shared zero image no placed texture shows any more is released</summary> Placed BC textures with no memory of their own yet show a shared all-zero image of their shape (`DeviceState::zero_sampled_image`), on a CUSTOM WRITE_BACK / L0 heap (host memory on a discrete GPU) under a 256 MiB cap, and those images were only released at device teardown, so a session streaming many shapes filled the cap for good. The device now counts each image's users (`acquire_zero_image`); when the last one is destroyed or gets memory of its own, the image leaves the map and the cap, and its `Resource` is released through the deferred-deletion queue. With several queues, a return carries the execute epoch and is released only once no replay in progress at it is left. Shapes left out for not fitting get another try (the comment `RT-ZERO-IMAGES-RETRY` left in `zero_sampled_image` is corrected in `962bc1601`). </details> <details> <summary><b>36. RT-DSTORAGE-CPP-SCRATCH</b>: dstorage: queue workers reuse their staging buffers</summary> Each compressed, swizzled or physical-page DirectStorage request in `runtime/shims/dstorage.cpp` allocated a new zero-filled buffer at every stage and freed it at the end, the C++ side of `RS-DSTORAGE-SCRATCH`. Each queue worker now keeps two sets of buffers (its own request's and its paired helper's), grown only when a request needs more, keeps at most 16 MiB between requests (the budget `can_prepare` already used), and no longer zero-fills bytes that are always written before they are read or the request fails and publishes nothing. </details> **Tested** at `962bc1601` (all 36 fixes, `main` `8b318bd40`; the three branches' base is the same `main`): - New tests, each failing on `main` and passing here: `pipeline::library::tests::{a_library_saved_for_other_shaders_is_not_opened, overlapping_saves_leave_one_whole_library_and_its_lists}` (`main`: `no fingerprint written`; the second fails 3 of 3 with the lock made a no-op), ctest `d3d12_zero_image_release` (12 shapes placed and released, with a second queue running during the copy's replay; `main`: 12 images and 47,104 bytes still held; here 0 and 0) and, in `dstorage`, `test_reused_buffers` (100 requests of two streams, outputs compared byte for byte: 300 blocks of 128 KiB or more on `main`, 6 here), `test_kept_buffers_cap` and `test_kept_buffers_pair_cap`. - `dstorage`, `d3d12_zero_image_retry` and `d3d12_zero_image_release`: 3/3; the two zero-image tests under `LEONIDA_VK_VALIDATION=1`: 2/2, no `VUID` line. - Full ctest, `-j 8`: 3 of 530 fail, the same three as on `main`. `cargo test --workspace --no-fail-fast`: `leonida-gpu` 528 passed (`pipeline::library` 15/15) and `leonida-hle` 214, with the same failures as on `main`. `python -I scripts/check_no_game_data.py` passes on every changed file. Not run in the game. ### Tested On Windows 11 Pro 26300, MSVC 14.44, Ninja, RelWithDebInfo and Vulkan SDK 1.4.363.0, with an RX 7900 XT and 32 GB of RAM, while another `gta6rt` was running on the same GPU. **Latest `main` merge: `leaks/all` at `5fe777296`**, all 31 fixes then in this branch with `main` `8b318bd40` merged in (154 commits since `7daa4a4a5`). One conflict, in `d3d12/crates/leonida-gpu/src/list.rs`: `main`'s `7efbbdd39` (`LEONIDA_ALLOCATOR_TRIM=1`, off by default: idle host lists older than the limit are let go) and `RS-HOST-LIST-ALLOCATOR-PEAK` (the idle pool as a `Pool`, its untouched lists halved once a second) both changed the idle host-list pool. The `Pool` stays; an idle list keeps when it was put by, and with `LEONIDA_ALLOCATOR_TRIM` its stale oldest are taken out of the `Pool` (new `Pool::take_oldest`, with a unit test) and counted in `ALLOCATOR_TRIMS[2]` as on `main`, under the same condition. MEASURED on the same machine: - **Build:** `gta6rt` and every test target, after a full relink. - **ctest, whole suite, `-j 8`:** 3 of 527 fail, the same three as on `main`. `pso_stream`, `xs_proxy_mock*`, `pipeline_cache_store`, `d3d12_session_cache_seed` and `mem_probe_vmmap` under `LEONIDA_VK_VALIDATION=1`: 14/14. - **`cargo test --workspace --no-fail-fast`** in `d3d12/`: `leonida-gpu` 523 passed (with `list::tests` 9/9) and `leonida-hle` 214 passed; the failures are the same 4 in `leonida-gpu`, 2 in `leonida-shader` and 1 in `xtask` described further down, all on `main` too. - **Python:** of 585 standalone `tests/test_*.py`, the same 10 fail as at the merges before (listed below); `tests/`, `tools/` and `scripts/` are as on `main`. Earlier `main` merges, each MEASURED the same way with no failure that is not also on `main`: `d51ad23b7` (`main` `7daa4a4a5`; one conflict in `runtime/test/pso_stream_test.cpp`, where #2476's `test_later_subobject_versions` and `RT-PSO-BYTECODE-INTERN`'s three tests are all kept) and `abdb93f0e` (`main` `d48a957bb`, no conflict). The failures on `main` that show in every run: `leonida-shader` `emit::valu_tests::{typed_d16_table_uav_roundtrip_uint_sint_and_float, rdna_forms_give_what_the_spelled_out_ones_give}` and `xtask` `policy::tests::repository_passes_policy` (`lower.rs` over the size limit), both in code these fixes do not touch, and 10 standalone Python tests (`tests/`, `tools/` and `scripts/` are as on `main`): `test_bc_feature_validation`, `test_bcpack_history_calib`, `test_build_runtime_fallback`, `test_make_game_pipelines`, `test_make_game_preflight`, `test_progress_dashboard`, `test_sampler_source_census`, `test_spirv_metal_set0_cli_errors`, `test_spirv_metal_set0_extra`, `test_tool_stdout_encoding`. `leaks/all` at `098342d02`: the 13 fixes, with `main` `33db04a70` merged in. One conflict came from #958, which made `release_child_reference` the single path that drops a child proxy's last reference (the queue and fence pins use it too). The allocator's upload memory is now given back in that function, by the proxy's `kind`, so every path that drops an allocator's last reference frees it. The mock in `xs_proxy_mock_test.cpp` keeps the fields from both sides. | # | Item | Its test (ctest) | |---|------|------------------| | 1 | `RT-UPLOAD-ARENA-REWIND` | `xs_proxy_mock` (`check_upload_rewind`), new `xs_proxy_mock_upload_rewind_off` | | 2 | `RT-PSO-BYTECODE-INTERN` | `pso_stream` | | 3 | `RT-SPARE-LIST-EPOCHS` | new `xbox_list_cut_spares`, `command_list` | | 4 | `RT-SLOT-RECORDS-BUCKETS` | `console_heap_slot_records` | | 5 | `RT-REHYDRATE-SCRATCH-TICKET` | `xbox_bvh_builder`, `xbox_bvh_builder_check` | | 6 | `RT-FSSM-ARENA-SHARE` | new `d3d12_code_base_share`, `d3d12_code_base_per_pso` | | 7 | `RT-TITLE-BUFFER-FALLBACK` | new `d3d12_title_buffer_fallback` | | 8 | `RT-SLOT70-DEVICE-CYCLE` | `d3d12_existing_heap` under `LEONIDA_VK_VALIDATION=1` | | 9 | `RT-MEM-PROBE-WINDOWS` | new `mem_probe_vmmap` | | 10 | `RT-ZERO-IMAGES-RETRY` | new `d3d12_zero_image_retry` | | 11 | `RT-TITLE-TEXTURE-GONE-RANGES` | `d3d12_existing_heap` (`check_mapped_plane_gone_in_registry`) | | 12 | `RT-SHADOW-GPU-RELEASED-RANGES` | new `d3d12_shadow_gpu_releases`, `d3d12_console_heap_gpu_releases` | | 13 | `RT-SLOT70-OWNED-RETIRE` | new `d3d12_title_image_retire`, `d3d12_title_image_idle`, `xmem` | - **Before the fixes.** Each fix's test was first run on `main` `d44285197` without that fix, and failed there (the commit messages say how). Between `d44285197` and `33db04a70`, `main` changed these files for the stub pipelines (`bbc750655`, `78159b886`), which do not touch the paths these fixes change, and for #958, merged as described above. - **These tests and the ones next to them**, 41 in all (`xs_proxy_mock*`, `pso_stream`, `command_list`, `xbox_list_cut_spares`, `console_heap_slot_records`, `xbox_bvh_builder*`, `d3d12_code_base_*`, `d3d12_title_buffer_fallback`, `d3d12_existing_heap*`, `mem_probe_vmmap`, `memory_breakdown`, `d3d12_zero_image_retry`, `d3d12_*_gpu_releases`, `d3d12_title_image_*`, `xmem*`, `allocator_proxy`, `device_proxy`, `title_texture_refresh`, `d3d12_title_va`, `d3d12_compute`, `d3d12_draw`), with `-j 4`: 41/41 passed. - **Under `LEONIDA_VK_VALIDATION=1`.** `d3d12_existing_heap`, `d3d12_title_image_retire`, `d3d12_title_image_idle`, `d3d12_zero_image_retry`, `d3d12_title_buffer_fallback`, `d3d12_shadow_gpu_releases`, `d3d12_code_base_share`, `allocator_proxy` and `xs_proxy_mock` passed 9/9. There were no validation errors and no `VUID-vkDestroyDevice-device-05137`. On `main`, `d3d12_existing_heap` leaves 93 objects at `vkDestroyDevice`. - **Full suite**, with `-j 4`, run twice (before and after merging `33db04a70`): 519/523 both times. Three tests failed both times, and they also fail on plain `main` on this machine; none of these fixes touches them: - `d3d12_texture_tiles`: the CopyTiles offset rounding on AMD (#964). - `pipeline_cache_seed`: the checker's device differs from the runtime's (#1833). - `d3d12_clear`: a NaN depth clear reads back 1. - The fourth failure was different each time: `dxgi_waitable_latency` in the first run and `run_tiny_game_abort_exit_codes` in the second. Each passes when run alone (the second 3/3), so they are timing-sensitive under `-j`. - **Builds.** `gta6rt` and every test target build and link. - **Python checks.** `python -I scripts/check_no_game_data.py` passes on every changed file, and `python -m compileall -q make_game.py tools tests` is clean. Of the 534 standalone `tests/test_*.py`, 7 fail, the same 7 with the same output as on `main` `33db04a70` (`test_docs_cli_flags`, `test_docs_env_vars`, `test_docs_python_deps`, `test_docs_repo_paths`, `test_make_game_preflight`, `test_progress_dashboard`, `test_tool_stdout_encoding`). `test_docs_env_vars` fails only on `LEONIDA_CLWB_PATCH`, which is not from this branch; the new switches are all documented. **In the game: PROVISIONAL (n=1 per arm).** Two sessions of 720 s each, both stopped by the harness at the end: `main` `d48a957bb` alone, and this branch at `32d2020f7` (all 30 fixes; its `runtime/` is the same as at `eb145de6f`, which only adds the test-only `leonida-hle` merge fix). Same build type, the same first-run-UI input, each started from the same copy of the pipeline caches, `LEONIDA_TITLE_WATCHDOG=0` with its kick, `LEONIDA_MEM_PROBE=10`, and an outside sample of the process every ~11 s. Resizable BAR off. The character stands still in the world from about 420 s. - MEASURED (n=1): no regression. Both ran the full time with no fault and no device loss (PresentX 8,940 with `main`, 9,218 with the fixes, none failed). - MEASURED (n=1): private bytes at 424 s were 20,755 MiB with `main` and 20,786 MiB with the fixes, and at the end (714 s) 20,965 and 21,010 MiB. Slope from 450 to 720 s: +41.5 and +47.8 MiB/min. Dedicated video memory, flat from about 420 s: 8,544 and 8,659 MiB. The runtime's Vulkan allocations (mem probe), flat from 360 to 700 s: 8,405 and 8,494 MiB. With one run per arm and no prediction written beforehand, these are observations: there is no measurable difference in 12 minutes. - MEASURED in both arms: the growth in the world follows the graphics pipelines being built, about 19 a minute (+94 with `main`, +91 with the fixes, after 420 s). MEASURED standalone (a separate Vulkan program, no code from this repository, on the same GPU and driver, 22 real vertex + pixel shader pairs from the translated library with the runtime's bindless set layout and dynamic states): each first compile leaves the driver holding a median 2.4 MiB of private memory (0.4–19 MiB) after its shader modules are destroyed; `vkDestroyPipeline` gives none of it back, destroying all 22 gives back about 0.3 MiB each, and compiling and destroying at once still adds 2.4–3.9 MiB a compile. A pipeline made again from the pipeline cache costs 23–47 KiB and 0.1–0.4 ms. About 19 new pipelines a minute at ~2.4 MiB each is the ~45 MiB/min seen in both sessions (an inference from the two measurements, not measured inside the game). So this growth is the driver's, per compile, and not from these fixes; only compiling less (a pipeline already in the seed or the heavy cache) reduces it, and destroying cold pipelines would give back little. - READ IN CODE and MEASURED: these sessions do not exercise what most of the fixes target. The 14 Rust fixes are in `d3d12/` and do not run in `gta6rt`. `AllocateUploadMemory` (list slot 148) was never called in either session (the runtime logs every list slot's first call), so `RT-UPLOAD-ARENA-REWIND` was not exercised, and an idle character does not churn PSOs or retire title windows. - An earlier pair of ~7 minute boots (`main` `d44285197` against the first 13 fixes, without the watchdog variables) ended at the title's hang watchdog at about 400 s in both, also with no regression. GPUs tested: AMD Radeon RX 7900 XT, 20 GB, desktop (profile M), AMD Software 26.11.2 (D3D12 driver 32.0.32029.2010, Vulkan driver 2.0.416), Windows 11 Pro 26300, 32 GB RAM ### Second sweep in `d3d12/` (25 more items) Pushed at `26e00403c` (with current `main` merged): fewer copies of each byte the title writes between the PC's memory and the card's, more title memory read in place, and more leaks. Claimed in [#2570](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7254924718) ([round 2](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7254925059)); what each does, its switch and how it was tested are in [this comment](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7255200827). Branches `adrianmjim/leonida:unified/<name>`: `send-pool-trim`, `compare-ring`, `landed-cells-gate`, `small-leaks`, `placed-textures`, `texture-staging-release`, `descriptor-views`, `inplace-free`, `placement-bench`, `card-one-copy`, `inplace-blockers`, `page-pool-open`, `shadow-hot-paths`, `exact-waits`, `physical-reuse`, `title-alloc-watch` (with `xmem-combined`). `leonida-gpu` 630 passed / 48 ignored, `leonida-hle` 243 passed / 2 ignored. A third round (7 branches, `19006b0e6`): landing in the submission, no forced sweep settle, detiling only what changed, more memory in place, GPU upload buffers, hot-path bookkeeping and a fix of in-place holds; see [this comment](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7256073326). `leonida-gpu` 690 passed / 50 ignored. A fourth round (`7cc8e1879`): card copies whose CPU side is title memory itself, in-place memory opened off the lookup path, a send ring, the compare measured and shared, list summaries at close, and a fix of double releases; see [this comment](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7257387207). `leonida-gpu` 718 passed / 51 ignored. ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [ ] One topic; follow-up work goes in a new pull request. (Thirty-six leak fixes from one sweep, twenty in `runtime/` and sixteen in `d3d12/`, and twenty-five more in `d3d12/` from a second, together only because of the open pull request limit. Each one is its own merge here and its own branch on the fork.) - [x] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. (n/a: no translator change)
Copilot commented 2026-11-28 09:54:28 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-28T09:54:28Z.

Code review location: runtime/test/d3d12_title_buffer_fallback_test.cpp; line 123

@@ -0,0 +1,268 @@
+// A vertex or index view that names the title's own memory gets a buffer made over those pages (make_title_buffer,
+// TitleVaAliases::want_buffer), the way slot 133 makes one: the pages imported, or a shadow copied from them. When
+// neither can be made, slot 133's last resort is an ordinary DEFAULT buffer, which has neither the title's VA nor its
+// bytes. A view must not keep such a buffer: it does not cover the view, so the next IASetVertexBuffers of the same
+// view would make another, each holding device memory and a device reference until the device goes, until
+// LEONIDA_TITLE_BUFFERS_MB is used up and no new title view is resolved for the rest of the session. Nor is such a
+// buffer made only to be let go: it would take device-local memory at every try, under the pressure that refused the
+// shadow.
+//   - The arena is filled first (LEONIDA_ARENA_MB=16, filled with 64 KiB buffers, so no slice is left for a shadow)
+//     and host-visible allocations are refused (the test wraps vkAllocateMemory behind the instance-proc pointer it
+//     hands the layer), with LEONIDA_SLOT133_IMPORT=0: no import and no shadow can be made, but a device-local DEFAULT
+//     buffer could.
+//   - The same 2 MiB view of title memory bound 16 times, as vertex and index views, keeps no buffer (every buffer
+//     made over title memory holds a device reference, and the device's count does not grow) and is tried once: one
+//     buffer of its size is created, the shadow's, and no device-local memory of its size is allocated.
+//   - A second, 512 KiB view bound right after that refusal is not tried: after a refusal no range is tried for a
+//     second, whichever range it is.
+//   - After that second the first view is tried again, once, and refused again. 1.5 s later the second view is tried,
+//     but the first is not: a range refused again waits twice as long. After that it is tried once more.
+// Needs a device-local memory type that is not host-visible (skipped otherwise). Synthetic data only. Set
+// LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
+#include "vk_test_device.h"
+#include "../shims/d3d12_com.h"
+#include "../src/title_va_alias.h"
+
+#include <atomic>
+#include <cstdio>
+#include <cstring>
+#include <vector>
+
+#define EXPECT(condition) do { \
+    if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
+} while (0)
+
+namespace {
+
+template<class T>
+struct Ref {
+    T* p = nullptr;
+    Ref() = default;
+    Ref(const Ref&) = delete;  // a copy would release the same interface twice
+    Ref& operator=(const Ref&) = delete;
+    ~Ref() { reset(); }
+    void reset() {
+        if (p) p->Release();
+        p = nullptr;
+    }
+    T* operator->() const { return p; }
+};
+
+constexpr UINT large_bytes = 2u << 20, small_bytes = 512u << 10;  // the two views; no other buffer has these sizes
+
+// The Vulkan calls the layer makes, seen through the function pointers it loads.
+PFN_vkGetInstanceProcAddr real_instance_proc = nullptr;
+PFN_vkGetDeviceProcAddr real_device_proc = nullptr;
+PFN_vkAllocateMemory real_allocate = nullptr;
+PFN_vkCreateBuffer real_create_buffer = nullptr;
+VkPhysicalDeviceMemoryProperties memory{};
+std::atomic<bool> refuse_host_visible{false};
+std::atomic<unsigned> large_buffers{0}, small_buffers{0};  // buffers of each view's size created
+std::atomic<unsigned> device_allocations{0};  // device-local allocations of at least the smaller view's size, made
+                                              // while host-visible ones are refused
+
+VKAPI_ATTR VkResult VKAPI_CALL allocate(VkDevice device, const VkMemoryAllocateInfo* info,
+                                        const VkAllocationCallbacks* allocator, VkDeviceMemory* out) {
+    if (refuse_host_visible.load() && info->memoryTypeIndex < memory.memoryTypeCount) {
+        const VkMemoryPropertyFlags flags = memory.memoryTypes[info->memoryTypeIndex].propertyFlags;
+        if (flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) return VK_ERROR_OUT_OF_DEVICE_MEMORY;
+        if ((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && info->allocationSize >= small_bytes) ++device_allocations;
+    }
+    return real_allocate(device, info, allocator, out);
+}
+
+VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice device, const VkBufferCreateInfo* info,
+                                             const VkAllocationCallbacks* allocator, VkBuffer* buffer) {
+    if (info->size == large_bytes) ++large_buffers;
+    if (info->size == small_bytes) ++small_buffers;
+    return real_create_buffer(device, info, allocator, buffer);
+}
+
+VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) {
+    if (std::strcmp(name, "vkAllocateMemory") == 0) {
+        real_allocate = reinterpret_cast<PFN_vkAllocateMemory>(real_device_proc(device, name));
+        return real_allocate ? reinterpret_cast<PFN_vkVoidFunction>(&allocate) : nullptr;
+    }
+    if (std::strcmp(name, "vkCreateBuffer") == 0) {
+        real_create_buffer = reinterpret_cast<PFN_vkCreateBuffer>(real_device_proc(device, name));
+        return real_create_buffer ? reinterpret_cast<PFN_vkVoidFunction>(&create_buffer) : nullptr;
+    }
+    return real_device_proc(device, name);
+}
+
+VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) {
+    if (std::strcmp(name, "vkGetDeviceProcAddr") == 0) {
+        real_device_proc = reinterpret_cast<PFN_vkGetDeviceProcAddr>(real_instance_proc(instance, name));
+        return real_device_proc ? reinterpret_cast<PFN_vkVoidFunction>(&device_proc) : nullptr;
+    }
+    return real_instance_proc(instance, name);
+}
+
+D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) {
+    D3D12_RESOURCE_DESC desc{};
+    desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+    desc.Width = bytes;
+    desc.Height = 1;
+    desc.DepthOrArraySize = 1;
+    desc.MipLevels = 1;
+    desc.SampleDesc.Count = 1;
+    desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+    return desc;
+}
+
+// The device's reference count: every buffer the device keeps over title memory holds one.
+ULONG references(ID3D12Device* device) {
+    device->AddRef();
+    return device->Release();
+}
+
+}  // namespace
+
+int main() {
+    vktest::Device vk;
+    if (!vk.create()) return 77;

vktest::Device leaves buffer device addresses disabled unless requested (vk_test_device.h:135,437–438), but line 154 advertises the feature as enabled to the runtime. Arena creation then uses device-address allocations and queries without enabling the required Vulkan feature, causing validation errors or driver-dependent behavior before the fallback assertions run. Request the feature before device creation and skip this arena-dependent test if it is unavailable.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4726480218 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480218). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-28T09:54:28Z. **Code review location:** `runtime/test/d3d12_title_buffer_fallback_test.cpp`; line 123 ~~~~diff @@ -0,0 +1,268 @@ +// A vertex or index view that names the title's own memory gets a buffer made over those pages (make_title_buffer, +// TitleVaAliases::want_buffer), the way slot 133 makes one: the pages imported, or a shadow copied from them. When +// neither can be made, slot 133's last resort is an ordinary DEFAULT buffer, which has neither the title's VA nor its +// bytes. A view must not keep such a buffer: it does not cover the view, so the next IASetVertexBuffers of the same +// view would make another, each holding device memory and a device reference until the device goes, until +// LEONIDA_TITLE_BUFFERS_MB is used up and no new title view is resolved for the rest of the session. Nor is such a +// buffer made only to be let go: it would take device-local memory at every try, under the pressure that refused the +// shadow. +// - The arena is filled first (LEONIDA_ARENA_MB=16, filled with 64 KiB buffers, so no slice is left for a shadow) +// and host-visible allocations are refused (the test wraps vkAllocateMemory behind the instance-proc pointer it +// hands the layer), with LEONIDA_SLOT133_IMPORT=0: no import and no shadow can be made, but a device-local DEFAULT +// buffer could. +// - The same 2 MiB view of title memory bound 16 times, as vertex and index views, keeps no buffer (every buffer +// made over title memory holds a device reference, and the device's count does not grow) and is tried once: one +// buffer of its size is created, the shadow's, and no device-local memory of its size is allocated. +// - A second, 512 KiB view bound right after that refusal is not tried: after a refusal no range is tried for a +// second, whichever range it is. +// - After that second the first view is tried again, once, and refused again. 1.5 s later the second view is tried, +// but the first is not: a range refused again waits twice as long. After that it is tried once more. +// Needs a device-local memory type that is not host-visible (skipped otherwise). Synthetic data only. Set +// LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../src/title_va_alias.h" + +#include <atomic> +#include <cstdio> +#include <cstring> +#include <vector> + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template<class T> +struct Ref { + T* p = nullptr; + Ref() = default; + Ref(const Ref&) = delete; // a copy would release the same interface twice + Ref& operator=(const Ref&) = delete; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +constexpr UINT large_bytes = 2u << 20, small_bytes = 512u << 10; // the two views; no other buffer has these sizes + +// The Vulkan calls the layer makes, seen through the function pointers it loads. +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetDeviceProcAddr real_device_proc = nullptr; +PFN_vkAllocateMemory real_allocate = nullptr; +PFN_vkCreateBuffer real_create_buffer = nullptr; +VkPhysicalDeviceMemoryProperties memory{}; +std::atomic<bool> refuse_host_visible{false}; +std::atomic<unsigned> large_buffers{0}, small_buffers{0}; // buffers of each view's size created +std::atomic<unsigned> device_allocations{0}; // device-local allocations of at least the smaller view's size, made + // while host-visible ones are refused + +VKAPI_ATTR VkResult VKAPI_CALL allocate(VkDevice device, const VkMemoryAllocateInfo* info, + const VkAllocationCallbacks* allocator, VkDeviceMemory* out) { + if (refuse_host_visible.load() && info->memoryTypeIndex < memory.memoryTypeCount) { + const VkMemoryPropertyFlags flags = memory.memoryTypes[info->memoryTypeIndex].propertyFlags; + if (flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) return VK_ERROR_OUT_OF_DEVICE_MEMORY; + if ((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && info->allocationSize >= small_bytes) ++device_allocations; + } + return real_allocate(device, info, allocator, out); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice device, const VkBufferCreateInfo* info, + const VkAllocationCallbacks* allocator, VkBuffer* buffer) { + if (info->size == large_bytes) ++large_buffers; + if (info->size == small_bytes) ++small_buffers; + return real_create_buffer(device, info, allocator, buffer); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) { + if (std::strcmp(name, "vkAllocateMemory") == 0) { + real_allocate = reinterpret_cast<PFN_vkAllocateMemory>(real_device_proc(device, name)); + return real_allocate ? reinterpret_cast<PFN_vkVoidFunction>(&allocate) : nullptr; + } + if (std::strcmp(name, "vkCreateBuffer") == 0) { + real_create_buffer = reinterpret_cast<PFN_vkCreateBuffer>(real_device_proc(device, name)); + return real_create_buffer ? reinterpret_cast<PFN_vkVoidFunction>(&create_buffer) : nullptr; + } + return real_device_proc(device, name); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetDeviceProcAddr") == 0) { + real_device_proc = reinterpret_cast<PFN_vkGetDeviceProcAddr>(real_instance_proc(instance, name)); + return real_device_proc ? reinterpret_cast<PFN_vkVoidFunction>(&device_proc) : nullptr; + } + return real_instance_proc(instance, name); +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +// The device's reference count: every buffer the device keeps over title memory holds one. +ULONG references(ID3D12Device* device) { + device->AddRef(); + return device->Release(); +} + +} // namespace + +int main() { + vktest::Device vk; + if (!vk.create()) return 77; ~~~~ --- `vktest::Device` leaves buffer device addresses disabled unless requested (`vk_test_device.h:135,437–438`), but line 154 advertises the feature as enabled to the runtime. Arena creation then uses device-address allocations and queries without enabling the required Vulkan feature, causing validation errors or driver-dependent behavior before the fallback assertions run. Request the feature before device creation and skip this arena-dependent test if it is unavailable.
Copilot commented 2026-11-28 09:54:28 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-28T09:54:28Z.

Code review location: runtime/test/xbox_bvh_builder_test.cpp; line 604

@@ -522,6 +542,88 @@ int main(int argc, char** argv) {
                 : "the batch's first element (its own scratch region) is written for check-build");
     }
 
+    // ---- the shim's scratch outlives a Reset of the list until the submission that used it has completed ----
+    // D3D12 lets the title Reset a list as soon as ExecuteCommandLists returns (only its allocator waits for the GPU),
+    // and the title rehydrates with ScratchAccelerationStructureData = 0. The scratch the shim made for the build must
+    // not go back to the arena before the build has run: the next DEFAULT buffer of its size would get its range and
+    // be zeroed by the CPU while the GPU still uses it. A list released right after the call makes the same promise.
+    {
+        Ref<ID3D12CommandAllocator> next_allocator, other_allocator;
+        Ref<ID3D12GraphicsCommandList4> other_list;
+        Ref<ID3D12Resource> kept_as, kept_rb;
+        if (FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
+                                                       IID_PPV_ARGS(next_allocator.put()))) ||
+            FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
+                                                       IID_PPV_ARGS(other_allocator.put()))) ||
+            FAILED(hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, other_allocator.p, nullptr,
+                                                  IID_PPV_ARGS(other_list.put()))) ||
+            FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav,
+                               kept_as.put())) ||
+            FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes,
+                               D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, kept_rb.put())))
+            return fail("kept-scratch lists or buffers", hr);
+        if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for kept scratch");
+        D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC kept_desc = zero_scratch_desc;
+        kept_desc.DestAccelerationStructureData = kept_as->GetGPUVirtualAddress();
+        check(rehydrate(builder, list.p, 1, &kept_desc, &source) == S_OK,
+              "a rehydrate without the title's scratch is recorded for the Reset check");
+        // The build's scratch is the one buffer the shim made for this call (one element: its region starts there).
+        UINT64 scratch_va = 0;
+        std::vector<leonida::Command> commands;
+        if (rt::d3d12::recorded_commands(list.p, commands))
+            for (const auto& command : commands)
+                if (const auto* build = std::get_if<leonida::BuildAccelerationStructure>(&command))
+                    scratch_va = build->scratch_va;
+        const UINT64 scratch_bytes = (blas_info.ScratchDataSizeInBytes + 255) / 256 * 256;
+        // Static, so a release that comes after this block (the queue's worker, or the teardown after a failed step
+        // returns early) still finds the object.
+        static Sentinel reset_sentinel, release_sentinel;
+        check(scratch_va && rt::d3d12::hold_until_reset(list.p, &reset_sentinel) &&
+                  rt::d3d12::hold_until_reset(other_list.p, &release_sentinel),
+              "the build has the shim's scratch, and both lists hold a sentinel");
+        list->ResourceBarrier(1, &barrier);
+        list->CopyBufferRegion(kept_rb.p, 0, kept_as.p, 0, blas_info.ResultDataMaxSizeInBytes);
+        if (FAILED(list->Close()) || FAILED(other_list->Close())) return fail("Close for kept scratch");
+        ID3D12CommandList* lists[] = {list.p, other_list.p};
+        queue->ExecuteCommandLists(2, lists);
+        // At once, before any Signal: the one list is Reset on another allocator, the other released.
+        if (FAILED(list->Reset(next_allocator.p, nullptr))) return fail("Reset right after ExecuteCommandLists");
+        other_list->Release();
+        other_list.p = nullptr;
+        Ref<ID3D12Resource> probe;
+        if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_bytes, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
+                               uav, probe.put())))
+            return fail("probe buffer", hr);
+        const UINT64 probe_va = probe->GetGPUVirtualAddress();
+        std::printf("scratch VA 0x%llx, a DEFAULT buffer of its 0x%llx bytes made after the Reset at VA 0x%llx\n",
+                    static_cast<unsigned long long>(scratch_va), static_cast<unsigned long long>(scratch_bytes),
+                    static_cast<unsigned long long>(probe_va));
+        check(probe_va + scratch_bytes <= scratch_va || scratch_va + scratch_bytes <= probe_va,
+              "a DEFAULT buffer made right after the Reset does not get the range of the scratch the submission uses");
+        check(reset_sentinel.refs.load() > 1, "an object a list holds outlives the list's Reset after the call");
+        check(release_sentinel.refs.load() > 1, "and the list's release after the call");

These assertions can fail with correct lifetime handling if the GPU finishes the build before ExecuteCommandLists returns: execute_sync drains completed pins before returning, so resetting/releasing the lists can leave both sentinels at one reference and make the scratch range reusable. Keep completion deterministically blocked until after these checks, then allow completion and verify release. Avoid an unresolved D3D12 queue wait that sends the batch through the pre-existing CPU-held-batch path instead of exercising the new synchronous pinning.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4726480227 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480227). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-28T09:54:28Z. **Code review location:** `runtime/test/xbox_bvh_builder_test.cpp`; line 604 ~~~~diff @@ -522,6 +542,88 @@ int main(int argc, char** argv) { : "the batch's first element (its own scratch region) is written for check-build"); } + // ---- the shim's scratch outlives a Reset of the list until the submission that used it has completed ---- + // D3D12 lets the title Reset a list as soon as ExecuteCommandLists returns (only its allocator waits for the GPU), + // and the title rehydrates with ScratchAccelerationStructureData = 0. The scratch the shim made for the build must + // not go back to the arena before the build has run: the next DEFAULT buffer of its size would get its range and + // be zeroed by the CPU while the GPU still uses it. A list released right after the call makes the same promise. + { + Ref<ID3D12CommandAllocator> next_allocator, other_allocator; + Ref<ID3D12GraphicsCommandList4> other_list; + Ref<ID3D12Resource> kept_as, kept_rb; + if (FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(next_allocator.put()))) || + FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(other_allocator.put()))) || + FAILED(hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, other_allocator.p, nullptr, + IID_PPV_ARGS(other_list.put()))) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, + kept_as.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, kept_rb.put()))) + return fail("kept-scratch lists or buffers", hr); + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for kept scratch"); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC kept_desc = zero_scratch_desc; + kept_desc.DestAccelerationStructureData = kept_as->GetGPUVirtualAddress(); + check(rehydrate(builder, list.p, 1, &kept_desc, &source) == S_OK, + "a rehydrate without the title's scratch is recorded for the Reset check"); + // The build's scratch is the one buffer the shim made for this call (one element: its region starts there). + UINT64 scratch_va = 0; + std::vector<leonida::Command> commands; + if (rt::d3d12::recorded_commands(list.p, commands)) + for (const auto& command : commands) + if (const auto* build = std::get_if<leonida::BuildAccelerationStructure>(&command)) + scratch_va = build->scratch_va; + const UINT64 scratch_bytes = (blas_info.ScratchDataSizeInBytes + 255) / 256 * 256; + // Static, so a release that comes after this block (the queue's worker, or the teardown after a failed step + // returns early) still finds the object. + static Sentinel reset_sentinel, release_sentinel; + check(scratch_va && rt::d3d12::hold_until_reset(list.p, &reset_sentinel) && + rt::d3d12::hold_until_reset(other_list.p, &release_sentinel), + "the build has the shim's scratch, and both lists hold a sentinel"); + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(kept_rb.p, 0, kept_as.p, 0, blas_info.ResultDataMaxSizeInBytes); + if (FAILED(list->Close()) || FAILED(other_list->Close())) return fail("Close for kept scratch"); + ID3D12CommandList* lists[] = {list.p, other_list.p}; + queue->ExecuteCommandLists(2, lists); + // At once, before any Signal: the one list is Reset on another allocator, the other released. + if (FAILED(list->Reset(next_allocator.p, nullptr))) return fail("Reset right after ExecuteCommandLists"); + other_list->Release(); + other_list.p = nullptr; + Ref<ID3D12Resource> probe; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_bytes, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + uav, probe.put()))) + return fail("probe buffer", hr); + const UINT64 probe_va = probe->GetGPUVirtualAddress(); + std::printf("scratch VA 0x%llx, a DEFAULT buffer of its 0x%llx bytes made after the Reset at VA 0x%llx\n", + static_cast<unsigned long long>(scratch_va), static_cast<unsigned long long>(scratch_bytes), + static_cast<unsigned long long>(probe_va)); + check(probe_va + scratch_bytes <= scratch_va || scratch_va + scratch_bytes <= probe_va, + "a DEFAULT buffer made right after the Reset does not get the range of the scratch the submission uses"); + check(reset_sentinel.refs.load() > 1, "an object a list holds outlives the list's Reset after the call"); + check(release_sentinel.refs.load() > 1, "and the list's release after the call"); ~~~~ --- These assertions can fail with correct lifetime handling if the GPU finishes the build before `ExecuteCommandLists` returns: `execute_sync` drains completed pins before returning, so resetting/releasing the lists can leave both sentinels at one reference and make the scratch range reusable. Keep completion deterministically blocked until after these checks, then allow completion and verify release. Avoid an unresolved D3D12 queue wait that sends the batch through the pre-existing CPU-held-batch path instead of exercising the new synchronous pinning.
copilot-pull-request-reviewer[bot] commented 2026-11-28 09:54:29 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-28T09:54:29Z.

Review: COMMENTED


The tests need deterministic GPU completion control and explicit Vulkan buffer-device-address enablement to avoid false failures, validation errors, and driver-dependent behavior.

3 open issues
What changed in this PR

This PR addresses thirteen memory-retention and resource-lifetime issues in the runtime’s D3D12-to-Vulkan layer and Xbox ABI proxies. It also adds native Windows memory diagnostics.

Changes:

  • Reclaims upload memory and stale bookkeeping, shares shader copies, and ties scratch lifetime to GPU completion.
  • Improves allocation retries and texture cleanup, with additional slot-70 image retirement remaining opt-in.
  • Adds synthetic regression tests and documents lifetime guarantees, diagnostics, and switches.
File Description
runtime/​test/​xs_proxy_mock_test.cpp Tests allocator-owned upload reuse and cleanup.
runtime/​test/​xmem_test.cpp Checks release notifications identify the freed range.
runtime/​test/​xbox_list_cut_spares_test.cpp Tests idle spare lists release recordings and references.
runtime/​test/​xbox_bvh_builder_test.cpp Checks scratch retention through GPU completion.
runtime/​test/​pso_stream_test.cpp Tests bytecode sharing, collisions, and concurrent captures.
runtime/​test/​mem_probe_vmmap_test.cpp Tests Windows memory classification and reporting.
runtime/​test/​d3d12_zero_image_retry_test.cpp Tests shared-image retries and backoff.
runtime/​test/​d3d12_title_buffer_fallback_test.cpp Tests failed title-buffer allocation and retry throttling.
runtime/​test/​d3d12_shadow_gpu_releases_test.cpp Checks released-range cleanup in GPU copy modes.
runtime/​test/​d3d12_code_base_share_test.cpp Tests shared shader arena copies and release.
runtime/​test/​console_heap_slot_records_test.cpp Checks bucket counts follow live records.
runtime/​test/​command_list_test.cpp Tests epoch cleanup when recordings are dropped.
runtime/​src/​vulkan_backend.h Retains shim-owned objects until submissions complete.
runtime/​src/​title_va_alias.h Exposes pending removal counts for tests.
runtime/​src/​title_texture_refresh.h Exposes texture range-index size for tests.
runtime/​src/​title_texture_memory.h Adds texture-page commitment checks.
runtime/​src/​mem_probe.h Adds native Windows process-memory reporting.
runtime/​src/​console_heap_slot_records.h Removes buckets when their last live record leaves.
runtime/​src/​command_list.h Allows closed lists to drop their recordings.
runtime/​src/​command_list_epochs.h Supports recordings without an active epoch stamp.
runtime/​shims/​xmem.cpp Reports reservation ranges for whole-allocation releases.
runtime/​shims/​d3d12_xs_pso_stream.h Documents shared shader-bytecode ownership.
runtime/​shims/​d3d12_xs_pso_stream.cpp Interns identical shader bytecode across records.
runtime/​shims/​d3d12_xs_device.cpp Rewinds allocator uploads and drops idle spare recordings.
runtime/​shims/​d3d12_com.h Declares lifetime helpers and diagnostic test hooks.
runtime/​shims/​d3d12_com.cpp Tracks shim-owned objects and releases dropped recordings.
runtime/​README.md Documents memory controls and diagnostics.
runtime/​CMakeLists.txt Registers new regression tests and variants.
docs/​d3d12_xs_console_abi.md Documents spare-list recording cleanup.
docs/​d3d12_vulkan.md Explains sharing, reclamation, and texture-retirement limits.
docs/​d3d12_command_objects.md Documents allocator-owned upload lifetimes.

Review effort: Balanced

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6097138101 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6097138101). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-28T09:54:29Z. **Review:** COMMENTED --- <!-- ccr-overview-v2 --> ### 🟡 Changes recommended The tests need deterministic GPU completion control and explicit Vulkan buffer-device-address enablement to avoid false failures, validation errors, and driver-dependent behavior. <details open> <summary><strong>3 open issues</strong></summary> - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Enable buffer device address feature before arena creation](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480218) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Block GPU completion until synchronous pinning assertions finish](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480227) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Enable buffer device address feature before running the test](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480242) · New </details> <details> <summary><strong>What changed in this PR</strong></summary> This PR addresses thirteen memory-retention and resource-lifetime issues in the runtime’s D3D12-to-Vulkan layer and Xbox ABI proxies. It also adds native Windows memory diagnostics. **Changes:** - Reclaims upload memory and stale bookkeeping, shares shader copies, and ties scratch lifetime to GPU completion. - Improves allocation retries and texture cleanup, with additional slot-70 image retirement remaining opt-in. - Adds synthetic regression tests and documents lifetime guarantees, diagnostics, and switches. | File | Description | | ---- | ----------- | | runtime/​test/​xs_proxy_mock_test.cpp | Tests allocator-owned upload reuse and cleanup. | | runtime/​test/​xmem_test.cpp | Checks release notifications identify the freed range. | | runtime/​test/​xbox_list_cut_spares_test.cpp | Tests idle spare lists release recordings and references. | | runtime/​test/​xbox_bvh_builder_test.cpp | Checks scratch retention through GPU completion. | | runtime/​test/​pso_stream_test.cpp | Tests bytecode sharing, collisions, and concurrent captures. | | runtime/​test/​mem_probe_vmmap_test.cpp | Tests Windows memory classification and reporting. | | runtime/​test/​d3d12_zero_image_retry_test.cpp | Tests shared-image retries and backoff. | | runtime/​test/​d3d12_title_buffer_fallback_test.cpp | Tests failed title-buffer allocation and retry throttling. | | runtime/​test/​d3d12_shadow_gpu_releases_test.cpp | Checks released-range cleanup in GPU copy modes. | | runtime/​test/​d3d12_code_base_share_test.cpp | Tests shared shader arena copies and release. | | runtime/​test/​console_heap_slot_records_test.cpp | Checks bucket counts follow live records. | | runtime/​test/​command_list_test.cpp | Tests epoch cleanup when recordings are dropped. | | runtime/​src/​vulkan_backend.h | Retains shim-owned objects until submissions complete. | | runtime/​src/​title_va_alias.h | Exposes pending removal counts for tests. | | runtime/​src/​title_texture_refresh.h | Exposes texture range-index size for tests. | | runtime/​src/​title_texture_memory.h | Adds texture-page commitment checks. | | runtime/​src/​mem_probe.h | Adds native Windows process-memory reporting. | | runtime/​src/​console_heap_slot_records.h | Removes buckets when their last live record leaves. | | runtime/​src/​command_list.h | Allows closed lists to drop their recordings. | | runtime/​src/​command_list_epochs.h | Supports recordings without an active epoch stamp. | | runtime/​shims/​xmem.cpp | Reports reservation ranges for whole-allocation releases. | | runtime/​shims/​d3d12_xs_pso_stream.h | Documents shared shader-bytecode ownership. | | runtime/​shims/​d3d12_xs_pso_stream.cpp | Interns identical shader bytecode across records. | | runtime/​shims/​d3d12_xs_device.cpp | Rewinds allocator uploads and drops idle spare recordings. | | runtime/​shims/​d3d12_com.h | Declares lifetime helpers and diagnostic test hooks. | | runtime/​shims/​d3d12_com.cpp | Tracks shim-owned objects and releases dropped recordings. | | runtime/​README.md | Documents memory controls and diagnostics. | | runtime/​CMakeLists.txt | Registers new regression tests and variants. | | docs/​d3d12_xs_console_abi.md | Documents spare-list recording cleanup. | | docs/​d3d12_vulkan.md | Explains sharing, reclamation, and texture-retirement limits. | | docs/​d3d12_command_objects.md | Documents allocator-owned upload lifetimes. | </details> <sub>Review effort: Balanced</sub>
Copilot commented 2026-11-28 09:54:29 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-28T09:54:29Z.

Code review location: runtime/test/xbox_list_cut_spares_test.cpp; line 52

@@ -0,0 +1,160 @@
+// The spare real lists a list-value cut leaves behind (d3d12_xs_device.cpp restart_recording), on a Vulkan device
+// and the queue and list proxies. No game data.
+// A recording cut three times leaves three spare real lists when the title resets its list; later recordings cut at
+// most once reuse only the last of them, and the other two stay closed and idle until the list is released. A title
+// window the layer retires is freed only once every command list whose recording began before the retirement is gone
+// (src/command_list_epochs.h), and a list holds the root signatures and pipeline states its recording set until its
+// next Reset. The idle spares must therefore drop their recordings when they become spares: they can never be
+// executed again before a cut resets them. Without that, the oldest live recording stays the first one's, and the
+// root signature it set stays referenced by the two idle spares.
+#include "vk_test_device.h"
+#include "d3d12_test_shaders.h"
+#include "../shims/d3d12_com.h"
+#include "../shims/d3d12_xs_device.h"
+#include "../src/command_list_epochs.h"
+
+#include <cstdint>
+#include <cstdio>
+
+#define CHECK(x)                                                                                                       \
+    do {                                                                                                               \
+        if (!(x)) {                                                                                                    \
+            std::fprintf(stderr, "line %d: %s\n", __LINE__, #x);                                                       \
+            return 1;                                                                                                  \
+        }                                                                                                              \
+    } while (0)
+
+using namespace d3d12test;
+namespace xs = rt::d3d12_xs;
+namespace epochs = leonida::command_list_epochs;
+
+namespace {
+using Create = HRESULT(WINAPI *)(void *, const void *, ID3D12CommandAllocator *, ID3D12PipelineState *, const IID *,
+                                 void **);
+// Console list slots on the newer layout (an undetected one reads the same): wait64(address, comparison, reference,
+// flags) and SetComputeRootSignature (PC slot 29).
+using WaitFn = std::uint64_t(WINAPI *)(void *, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t);
+using RootSignatureFn = std::uint64_t(WINAPI *)(void *, std::uint64_t);
+constexpr unsigned kConsoleWait64 = 74, kConsoleSetComputeRootSignature = 33;
+constexpr std::uint64_t kGreaterEqual = 7;  // memory >= reference, in D3D12_COMPARISON_FUNC order
+
+ULONG references(IUnknown *object) {
+    object->AddRef();
+    return object->Release();
+}
+}  // namespace
+
+int main() {
+    xs::set_list_values_enabled(true);
+    vktest::Device gpu;
+    auto status = gpu.initialize();
+    if (status == vktest::DeviceStatus::unavailable) return 77;
+    CHECK(status == vktest::DeviceStatus::ready);

vktest::Device leaves buffer device addresses disabled unless requested (vk_test_device.h:135,437–438), but line 60 advertises the feature as enabled to the runtime. This makes the test use device-address allocations and queries without enabling the required Vulkan feature, causing validation errors or driver-dependent behavior. Request the feature before initialization and skip this test if it is unavailable.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4726480242 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480242). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-28T09:54:29Z. **Code review location:** `runtime/test/xbox_list_cut_spares_test.cpp`; line 52 ~~~~diff @@ -0,0 +1,160 @@ +// The spare real lists a list-value cut leaves behind (d3d12_xs_device.cpp restart_recording), on a Vulkan device +// and the queue and list proxies. No game data. +// A recording cut three times leaves three spare real lists when the title resets its list; later recordings cut at +// most once reuse only the last of them, and the other two stay closed and idle until the list is released. A title +// window the layer retires is freed only once every command list whose recording began before the retirement is gone +// (src/command_list_epochs.h), and a list holds the root signatures and pipeline states its recording set until its +// next Reset. The idle spares must therefore drop their recordings when they become spares: they can never be +// executed again before a cut resets them. Without that, the oldest live recording stays the first one's, and the +// root signature it set stays referenced by the two idle spares. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/command_list_epochs.h" + +#include <cstdint> +#include <cstdio> + +#define CHECK(x) \ + do { \ + if (!(x)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); \ + return 1; \ + } \ + } while (0) + +using namespace d3d12test; +namespace xs = rt::d3d12_xs; +namespace epochs = leonida::command_list_epochs; + +namespace { +using Create = HRESULT(WINAPI *)(void *, const void *, ID3D12CommandAllocator *, ID3D12PipelineState *, const IID *, + void **); +// Console list slots on the newer layout (an undetected one reads the same): wait64(address, comparison, reference, +// flags) and SetComputeRootSignature (PC slot 29). +using WaitFn = std::uint64_t(WINAPI *)(void *, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); +using RootSignatureFn = std::uint64_t(WINAPI *)(void *, std::uint64_t); +constexpr unsigned kConsoleWait64 = 74, kConsoleSetComputeRootSignature = 33; +constexpr std::uint64_t kGreaterEqual = 7; // memory >= reference, in D3D12_COMPARISON_FUNC order + +ULONG references(IUnknown *object) { + object->AddRef(); + return object->Release(); +} +} // namespace + +int main() { + xs::set_list_values_enabled(true); + vktest::Device gpu; + auto status = gpu.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + CHECK(status == vktest::DeviceStatus::ready); ~~~~ --- `vktest::Device` leaves buffer device addresses disabled unless requested (`vk_test_device.h:135,437–438`), but line 60 advertises the feature as enabled to the runtime. This makes the test use device-address allocations and queries without enabling the required Vulkan feature, causing validation errors or driver-dependent behavior. Request the feature before initialization and skip this test if it is unavailable.
lixonik commented 2026-11-28 10:16:27 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-28T10:16:27Z.

Review: COMMENTED


Reviewed and verified at head f4cc2b33f (Windows 11, MSVC 19.44, Ninja Release, Rust 1.98.1, LEONIDA_VK_VALIDATION=1).

Verification

  • C++ runtime (
    untime/):
    built all 13 added/modified test targets plus gta6rt:
    • ctest (LEONIDA_VK_VALIDATION=1): 13/13 passed (xs_proxy_mock, pso_stream, command_list, xmem, xbox_bvh_builder, d3d12_shadow_gpu_releases, d3d12_existing_heap, d3d12_zero_image_retry, d3d12_title_buffer_fallback, xbox_list_cut_spares, d3d12_code_base_share, mem_probe_vmmap, console_heap_slot_records), 0 Vulkan validation errors on NVIDIA GeForce RTX 5070.
    • python -I scripts/check_no_game_data.py: clean.
  • Rust (d3d12/):
    • cargo test -p leonida-hle -p leonida: 188/188 passed (0 failed, 2 ignored).
    • cargo test -p leonida-gpu --lib: 493 passed, 4 failed (46 ignored). Re-tested the 4 failures (descriptor::host::tests::views_off_their_elements_get_a_copy_of_their_bytes, indirect::tests::batch_tables, indirect::tests::host_list_budget_starts_empty_at_each_submission, indirect::tests::warp_batch_charges_every_execution) on clean main (33db04a70) with --test-threads=1: all 4 fail identically on clean main (pre-existing on this host), while all 14 new leonida-gpu tests introduced by this PR pass.

Review notes

  1. Needs rebase/merge with main (blocking merge): two content conflicts against main (33db04a70) in runtime/shims/d3d12_xs_device.cpp and runtime/test/xs_proxy_mock_test.cpp due to recent main commits 10eb17825, 038980a38, and 53ed711b8.
  2. Note on Copilot's BDA comments (false positive): vktest::Device unconditionally sets enable12.bufferDeviceAddress = VK_TRUE at runtime/test/vk_test_device.h:459, and both d3d12_title_buffer_fallback_test and xbox_list_cut_spares_test run with 0 validation errors under VK_LAYER_KHRONOS_validation on RTX 5070.
  3. Minor test robustness note (
    untime/test/xbox_bvh_builder_test.cpp:603-604):
    the assertions reset_sentinel.refs.load() > 1 / release_sentinel.refs.load() > 1 passed here, though as noted in the inline review, if the GPU completes the BLAS build before execute_sync drains completed pins on return, those assertions could become timing-sensitive on faster drivers.

Overall the 24 leak fixes (shared code-base arena copies, PSO bytecode interning, command-list drop/epoch release, slot-record bucket pruning, owned title-image retirement, thin-upload drop, idle pool trimming, etc.) are well-scoped and clean; happy to approve once rebased cleanly onto main.

GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, VK_LAYER_KHRONOS_validation 1.4.363).

AI-assisted (Antigravity, Gemini).

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6097209190 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6097209190). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-28T10:16:27Z. **Review:** COMMENTED --- Reviewed and verified at head `f4cc2b33f` (Windows 11, MSVC 19.44, Ninja Release, Rust 1.98.1, `LEONIDA_VK_VALIDATION=1`). ### Verification - **C++ runtime ( untime/):** built all 13 added/modified test targets plus `gta6rt`: - `ctest` (`LEONIDA_VK_VALIDATION=1`): **13/13 passed** (`xs_proxy_mock`, `pso_stream`, `command_list`, `xmem`, `xbox_bvh_builder`, `d3d12_shadow_gpu_releases`, `d3d12_existing_heap`, `d3d12_zero_image_retry`, `d3d12_title_buffer_fallback`, `xbox_list_cut_spares`, `d3d12_code_base_share`, `mem_probe_vmmap`, `console_heap_slot_records`), **0 Vulkan validation errors** on NVIDIA GeForce RTX 5070. - `python -I scripts/check_no_game_data.py`: clean. - **Rust (d3d12/):** - `cargo test -p leonida-hle -p leonida`: **188/188 passed** (0 failed, 2 ignored). - `cargo test -p leonida-gpu --lib`: **493 passed, 4 failed** (46 ignored). Re-tested the 4 failures (`descriptor::host::tests::views_off_their_elements_get_a_copy_of_their_bytes`, `indirect::tests::batch_tables`, `indirect::tests::host_list_budget_starts_empty_at_each_submission`, `indirect::tests::warp_batch_charges_every_execution`) on clean `main` (`33db04a70`) with `--test-threads=1`: **all 4 fail identically on clean `main`** (pre-existing on this host), while all 14 new `leonida-gpu` tests introduced by this PR pass. ### Review notes 1. **Needs rebase/merge with `main` (blocking merge):** two content conflicts against `main` (`33db04a70`) in `runtime/shims/d3d12_xs_device.cpp` and `runtime/test/xs_proxy_mock_test.cpp` due to recent `main` commits `10eb17825`, `038980a38`, and `53ed711b8`. 2. **Note on Copilot's BDA comments (false positive):** `vktest::Device` unconditionally sets `enable12.bufferDeviceAddress = VK_TRUE` at `runtime/test/vk_test_device.h:459`, and both `d3d12_title_buffer_fallback_test` and `xbox_list_cut_spares_test` run with 0 validation errors under `VK_LAYER_KHRONOS_validation` on RTX 5070. 3. **Minor test robustness note ( untime/test/xbox_bvh_builder_test.cpp:603-604):** the assertions `reset_sentinel.refs.load() > 1` / `release_sentinel.refs.load() > 1` passed here, though as noted in the inline review, if the GPU completes the BLAS build before `execute_sync` drains completed pins on return, those assertions could become timing-sensitive on faster drivers. Overall the 24 leak fixes (shared code-base arena copies, PSO bytecode interning, command-list drop/epoch release, slot-record bucket pruning, owned title-image retirement, thin-upload drop, idle pool trimming, etc.) are well-scoped and clean; happy to approve once rebased cleanly onto `main`. GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, `VK_LAYER_KHRONOS_validation` 1.4.363). AI-assisted (Antigravity, Gemini).
lixonik commented 2026-11-28 10:30:46 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-28T10:30:46Z.

Review: APPROVED


Re-verified after the main merge in 098342d02 (Windows 11, MSVC 19.44, Ninja Release, LEONIDA_VK_VALIDATION=1).

Verification at 098342d02

  • Reviewed the merge resolution in runtime/shims/d3d12_xs_device.cpp, runtime/test/pso_stream_test.cpp, and runtime/test/xs_proxy_mock_test.cpp: cleanly preserves both main's release_child_reference / test_view_instancing_is_captured / queue-fence ownership assertions and this PR's upload_allocator_gone / bytecode-interning / mapped-upload additions.
  • Rebuilt xs_proxy_mock_test, pso_stream_test, d3d12_existing_heap_test, xbox_list_cut_spares_test, and gta6rt.
  • ctest (LEONIDA_VK_VALIDATION=1): 4/4 passed (0 validation errors), in addition to the full 13/13 C++ + Rust leonida-hle/leonida/new leonida-gpu verification at f4cc2b33f.

GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, VK_LAYER_KHRONOS_validation 1.4.363).

AI-assisted (Antigravity, Gemini).

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6097249062 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6097249062). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-28T10:30:46Z. **Review:** APPROVED --- Re-verified after the `main` merge in `098342d02` (Windows 11, MSVC 19.44, Ninja Release, `LEONIDA_VK_VALIDATION=1`). ### Verification at `098342d02` - Reviewed the merge resolution in `runtime/shims/d3d12_xs_device.cpp`, `runtime/test/pso_stream_test.cpp`, and `runtime/test/xs_proxy_mock_test.cpp`: cleanly preserves both `main`'s `release_child_reference` / `test_view_instancing_is_captured` / queue-fence ownership assertions and this PR's `upload_allocator_gone` / bytecode-interning / mapped-upload additions. - Rebuilt `xs_proxy_mock_test`, `pso_stream_test`, `d3d12_existing_heap_test`, `xbox_list_cut_spares_test`, and `gta6rt`. - `ctest` (`LEONIDA_VK_VALIDATION=1`): **4/4 passed** (0 validation errors), in addition to the full 13/13 C++ + Rust `leonida-hle`/`leonida`/new `leonida-gpu` verification at `f4cc2b33f`. GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, `VK_LAYER_KHRONOS_validation` 1.4.363). AI-assisted (Antigravity, Gemini).
GrahamboJangles commented 2026-11-28 11:17:28 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by GrahamboJangles on 2026-11-28T11:17:28Z.

Review: COMMENTED


Reviewer pass over the sweep as a whole (nightly review; verified against current main b0c572464).

Claims check out. All 24 RT-*/RS-* item IDs link to exactly one claiming: line each in #1608 (by this branch's author), and the two geometry items (RT-GEOMETRY-VIEWS-CONTAIN, RT-DRAW-VIEWS-UNCHANGED) to #2570. No open PR duplicates any of the 26 IDs (gh pr list --search per ID).

Conflict notes check out. #1521, #2267 and #2085 are all still open, and the file overlaps are real: runtime/shims/d3d12_vulkan_device.cpp + runtime/test/d3d12_draw_test.cpp with #1521; runtime/CMakeLists.txt, runtime/README.md, runtime/test/d3d12_existing_heap_test.cpp with #2267; runtime/shims/d3d12_geometry_views.h + runtime/test/geometry_views_test.cpp with #2085. GitHub says mergeable but UNSTABLE — that matches: landing order against those three needs to be settled before merge.

Tree checks (local merge against fresh main b0c572464).

  • Automatic merge is clean; git diff gives 51 files, +5543/−294 — same as GitHub's stats.
  • git diff --check: no whitespace findings. scripts/check_no_game_data.py over all 51 changed files: clean.
  • Docs tests: current main already fails four of them (test_docs_env_vars on LEONIDA_CLWB_PATCH at runtime/src/cpu_emulation.h:366; test_docs_cli_flags on 56 flags in d3d12/docs/*; test_docs_python_deps on port_ctl.py vs AGENTS.md; test_docs_repo_paths on 14 backticked paths). On the merged tree the failure lists are byte-identical, so this PR adds zero new docs-test failures — the red ones stay red and belong to #2550/#2551/#2552 and to whoever landed the CLWB patch without documenting it.
  • Sampled commit structure matches the PR body's promise: each fix is its own commit with its own test and quantified before/after (e.g. 5fa9c200f RT-UPLOAD-ARENA-REWIND: 25 chunks → 1 over 200 mock frames, plus a --upload-rewind-off ctest for the switch; b179a98a0 RS-HOST-LIST-ALLOCATOR-PEAK: a_submitted_list_keeps_no_host_list_until_its_reset asserts held(&lists) == 0 after submit rounds). Commit messages state mechanism, fix, and test scope, including honest hedges (RT-SLOT70-OWNED-RETIRE opt-in after a second review found early-retire pixel risk; RT-MEM-PROBE-WINDOWS's test says it does not build on d44285197).

What I could not verify here: the native C++/Rust test suites — no CI has run on leaks/all (gh pr checks 2569: no checks reported, likely because the head is a fork), and these tests need the runtime build environment. Green tests are on the maintainers' side until CI runs them on Linux.

Two protocol gaps to close before merge:

  1. AGENTS.md:133 requires the PR to say it was AI-assisted, what was tested, and on which GPU and driver — the body has no such statement for any of the 26 fixes.
  2. Given no CI signal on this PR and three open conflicting PRs, per-fix branches adrianmjim/leonida:leaks/<name> are exactly the right fallback if the bundle has to be split; a line about intended landing order (vs #1521/#2267/#2085) would settle the UNSTABLE state.

No approval given from this pass: the native tests are unrun, so this is verification-of-claims, not a substitute for a CI-green bundle.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6097434581 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6097434581). Originally posted by [GrahamboJangles](https://github.com/GrahamboJangles) on 2026-11-28T11:17:28Z. **Review:** COMMENTED --- Reviewer pass over the sweep as a whole (nightly review; verified against current `main` `b0c572464`). **Claims check out.** All 24 `RT-*`/`RS-*` item IDs link to exactly one `claiming:` line each in #1608 (by this branch's author), and the two geometry items (`RT-GEOMETRY-VIEWS-CONTAIN`, `RT-DRAW-VIEWS-UNCHANGED`) to #2570. No open PR duplicates any of the 26 IDs (`gh pr list --search` per ID). **Conflict notes check out.** #1521, #2267 and #2085 are all still open, and the file overlaps are real: `runtime/shims/d3d12_vulkan_device.cpp` + `runtime/test/d3d12_draw_test.cpp` with #1521; `runtime/CMakeLists.txt`, `runtime/README.md`, `runtime/test/d3d12_existing_heap_test.cpp` with #2267; `runtime/shims/d3d12_geometry_views.h` + `runtime/test/geometry_views_test.cpp` with #2085. GitHub says mergeable but `UNSTABLE` — that matches: landing order against those three needs to be settled before merge. **Tree checks (local merge against fresh main `b0c572464`).** - Automatic merge is clean; `git diff` gives 51 files, +5543/−294 — same as GitHub's stats. - `git diff --check`: no whitespace findings. `scripts/check_no_game_data.py` over all 51 changed files: clean. - Docs tests: current `main` already fails four of them (`test_docs_env_vars` on `LEONIDA_CLWB_PATCH` at `runtime/src/cpu_emulation.h:366`; `test_docs_cli_flags` on 56 flags in `d3d12/docs/*`; `test_docs_python_deps` on `port_ctl.py` vs AGENTS.md; `test_docs_repo_paths` on 14 backticked paths). On the merged tree the failure lists are byte-identical, so this PR adds **zero** new docs-test failures — the red ones stay red and belong to #2550/#2551/#2552 and to whoever landed the CLWB patch without documenting it. - Sampled commit structure matches the PR body's promise: each fix is its own commit with its own test and quantified before/after (e.g. `5fa9c200f` RT-UPLOAD-ARENA-REWIND: 25 chunks → 1 over 200 mock frames, plus a `--upload-rewind-off` ctest for the switch; `b179a98a0` RS-HOST-LIST-ALLOCATOR-PEAK: `a_submitted_list_keeps_no_host_list_until_its_reset` asserts `held(&lists) == 0` after submit rounds). Commit messages state mechanism, fix, and test scope, including honest hedges (RT-SLOT70-OWNED-RETIRE opt-in after a second review found early-retire pixel risk; RT-MEM-PROBE-WINDOWS's test says it does not build on `d44285197`). **What I could not verify here:** the native C++/Rust test suites — no CI has run on `leaks/all` (`gh pr checks 2569`: no checks reported, likely because the head is a fork), and these tests need the runtime build environment. Green tests are on the maintainers' side until CI runs them on Linux. **Two protocol gaps to close before merge:** 1. AGENTS.md:133 requires the PR to say it was AI-assisted, what was tested, and on which GPU and driver — the body has no such statement for any of the 26 fixes. 2. Given no CI signal on this PR and three open conflicting PRs, per-fix branches `adrianmjim/leonida:leaks/<name>` are exactly the right fallback if the bundle has to be split; a line about intended landing order (vs #1521/#2267/#2085) would settle the `UNSTABLE` state. No approval given from this pass: the native tests are unrun, so this is verification-of-claims, not a substitute for a CI-green bundle.
zmasi commented 2026-11-28 12:02:29 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-11-28T12:02:29Z.


VERIFY-2569-D3D12 — verified the Rust d3d12/ crates (leonida-gpu, leonida-hle, leonida) and standalone console_heap_slot_records_test at head 9fc3ad427c merged cleanly with main 030d2039e on Windows 11 Pro (build 26200), NVIDIA GeForce RTX 3090 (driver 610.88) + MSVC 19.44, synthetic unit/GPU test inputs only.

Red (main 030d2039e) -> Green (030d2039e + 9fc3ad427c)

  • Red on main:
    • cargo test --manifest-path d3d12/Cargo.toml -p leonida-gpu --lib list::tests::a_submitted_list_keeps_no_host_list_until_its_reset -- --exact --test-threads=1 -> FAILED (round 0: submitted lists keep host lists alive, left: 64, right: 0).
    • cargo test --manifest-path d3d12/Cargo.toml -p leonida-gpu --lib pipeline::tests::pipelines_of_one_graphics_state_share_it -- --exact --test-threads=1 -> FAILED (distinct GraphicsState pointers allocated for identical stream states).
  • Green on merged PR:
    • leonida-gpu targeted D3D12 + host suites:
      • list::tests:: -> 6 passed; 0 failed
      • list::thin::tests:: -> 4 passed; 0 failed
      • pipeline::tests:: -> 3 passed; 0 failed
      • pipeline::library::tests:: -> 11 passed; 0 failed
      • resource::tests:: (--test-threads=1, including LEONIDA_TEXTURE_SWEEP=0 child-process D3D12 run in replaced_copies_go_with_the_sweep_off) -> 18 passed; 0 failed
      • shadow::snapshot_pool_tests:: (1/1), shadow::exact_spare_tests:: (1/1), and texture::read_buffer_tests:: (2/2) -> all passed
    • cargo test --manifest-path d3d12/Cargo.toml -p leonida-hle --lib -- --test-threads=4 -> 186 passed; 0 failed; 2 ignored (including xasync worker-linger/burst/rendezvous tests, xmem::tests::free_default_tells_the_gpu_side_of_32bit_memory, and apu::tests::packets_decode_without_memory_of_their_own).
    • cargo check --manifest-path d3d12/Cargo.toml -p leonida --bin leonida -> clean.
    • Standalone C++ unit test runtime/test/console_heap_slot_records_test.cpp (cl.exe /std:c++20 /W4 /permissive- /utf-8 /EHsc) -> 0 warnings, exit 0 (400 differential rounds, console_heap_slot_records_test: ok).
    • python -I tests/test_docs_links.py -> 17 OK.

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7238951156 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7238951156). Originally posted by [zmasi](https://github.com/zmasi) on 2026-11-28T12:02:29Z. --- `VERIFY-2569-D3D12` — verified the Rust `d3d12/` crates (`leonida-gpu`, `leonida-hle`, `leonida`) and standalone `console_heap_slot_records_test` at head `9fc3ad427c` merged cleanly with `main` `030d2039e` on Windows 11 Pro (build 26200), NVIDIA GeForce RTX 3090 (driver 610.88) + MSVC `19.44`, synthetic unit/GPU test inputs only. ### Red (`main` `030d2039e`) -> Green (`030d2039e` + `9fc3ad427c`) - **Red on `main`**: - `cargo test --manifest-path d3d12/Cargo.toml -p leonida-gpu --lib list::tests::a_submitted_list_keeps_no_host_list_until_its_reset -- --exact --test-threads=1` -> **FAILED** (`round 0: submitted lists keep host lists alive`, `left: 64, right: 0`). - `cargo test --manifest-path d3d12/Cargo.toml -p leonida-gpu --lib pipeline::tests::pipelines_of_one_graphics_state_share_it -- --exact --test-threads=1` -> **FAILED** (distinct `GraphicsState` pointers allocated for identical stream states). - **Green on merged PR**: - `leonida-gpu` targeted D3D12 + host suites: - `list::tests::` -> **6 passed; 0 failed** - `list::thin::tests::` -> **4 passed; 0 failed** - `pipeline::tests::` -> **3 passed; 0 failed** - `pipeline::library::tests::` -> **11 passed; 0 failed** - `resource::tests::` (`--test-threads=1`, including `LEONIDA_TEXTURE_SWEEP=0` child-process D3D12 run in `replaced_copies_go_with_the_sweep_off`) -> **18 passed; 0 failed** - `shadow::snapshot_pool_tests::` (`1/1`), `shadow::exact_spare_tests::` (`1/1`), and `texture::read_buffer_tests::` (`2/2`) -> **all passed** - `cargo test --manifest-path d3d12/Cargo.toml -p leonida-hle --lib -- --test-threads=4` -> **186 passed; 0 failed; 2 ignored** (including `xasync` worker-linger/burst/rendezvous tests, `xmem::tests::free_default_tells_the_gpu_side_of_32bit_memory`, and `apu::tests::packets_decode_without_memory_of_their_own`). - `cargo check --manifest-path d3d12/Cargo.toml -p leonida --bin leonida` -> **clean**. - Standalone C++ unit test `runtime/test/console_heap_slot_records_test.cpp` (`cl.exe /std:c++20 /W4 /permissive- /utf-8 /EHsc`) -> **0 warnings**, exit **`0`** (`400` differential rounds, `console_heap_slot_records_test: ok`). - `python -I tests/test_docs_links.py` -> **17 OK**. AI-assisted.
lixonik commented 2026-11-28 13:42:44 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-28T13:42:44Z.

Review: APPROVED


Re-verified updated head abdb93f0e (covering the two newly added leak fixes RT-GEOMETRY-VIEWS-CONTAIN and RT-DRAW-VIEWS-UNCHANGED, plus the clean main d48a957bb merge).

Code audit (098342d02..abdb93f0e):

  • RT-GEOMETRY-VIEWS-CONTAIN (runtime/shims/d3d12_geometry_views.h, d3d12_vulkan_device.cpp): outer_ index + contained_ tracking cleanly serve inner ranges from ready outer views, kListsPending defers command-list epoch stamping until on_retire completes, and copy_title_range opts out with contain = false.
  • RT-DRAW-VIEWS-UNCHANGED (runtime/shims/d3d12_com.cpp, runtime/src/command_list.h): OMSetRenderTargets and set_vertex_buffers mark draw_views_stale_ only on actual bound view changes.

Verification at abdb93f0e (Windows 11, MSVC 19.44, Ninja Release, LEONIDA_VK_VALIDATION=1):

  • Built geometry_views_test and d3d12_draw_test.
  • ctest -R '^(geometry_views|d3d12_draw|d3d12_draw_views_sharing)$': 3/3 passed (0 validation errors).
  • python -I scripts/check_no_game_data.py: passed.

GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, VK_LAYER_KHRONOS_validation 1.4.363).

AI-assisted (Antigravity, Gemini).

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6098098882 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6098098882). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-28T13:42:44Z. **Review:** APPROVED --- Re-verified updated head `abdb93f0e` (covering the two newly added leak fixes `RT-GEOMETRY-VIEWS-CONTAIN` and `RT-DRAW-VIEWS-UNCHANGED`, plus the clean `main` `d48a957bb` merge). Code audit (`098342d02..abdb93f0e`): - `RT-GEOMETRY-VIEWS-CONTAIN` (`runtime/shims/d3d12_geometry_views.h`, `d3d12_vulkan_device.cpp`): `outer_` index + `contained_` tracking cleanly serve inner ranges from ready outer views, `kListsPending` defers command-list epoch stamping until `on_retire` completes, and `copy_title_range` opts out with `contain = false`. - `RT-DRAW-VIEWS-UNCHANGED` (`runtime/shims/d3d12_com.cpp`, `runtime/src/command_list.h`): `OMSetRenderTargets` and `set_vertex_buffers` mark `draw_views_stale_` only on actual bound view changes. Verification at `abdb93f0e` (Windows 11, MSVC 19.44, Ninja Release, `LEONIDA_VK_VALIDATION=1`): - Built `geometry_views_test` and `d3d12_draw_test`. - `ctest -R '^(geometry_views|d3d12_draw|d3d12_draw_views_sharing)$'`: **3/3 passed** (0 validation errors). - `python -I scripts/check_no_game_data.py`: passed. GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, `VK_LAYER_KHRONOS_validation` 1.4.363). AI-assisted (Antigravity, Gemini).
Tauwni commented 2026-11-28 14:24:11 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Tauwni on 2026-11-28T14:24:11Z.


Under Wine the new mem_probe_vmmap fails at the commit-charge check. Apple M3, macOS 26.5.1, Wine 11.0, Windows cross-build, head eb145de6f merged onto main ec740bcc3; fails 3/3 runs (MEASURED, also 3/3 at the previous head 87497c87a):

pe-private 3 -> 67 MiB, private commit 41555 -> 41555 MiB, private working set 0 MiB
line 123: counters_after.private_commit >= counters_before.private_commit + 64 * kMiB

The region walk sees the 64 MiB (pe-private 3 -> 67), but the private commit Wine reports does not move after the VirtualAlloc + memset, and stays around 41 GiB. live() already keeps the private working set check off under Wine (line 125, if (!wine && ...)); the same guard on line 123 would make the test pass there, if the counter is meant to be Windows-only. EXPECT returns at the first failure, so I don't know yet whether the checks after line 123 pass under Wine. I have only run Wine on macOS, not on Linux.

The three xmem tests also fail under Wine here, but they fail the same way on main, so not because of this pull request.

Not checked by a second agent or human yet.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7240641808 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7240641808). Originally posted by [Tauwni](https://github.com/Tauwni) on 2026-11-28T14:24:11Z. --- Under Wine the new `mem_probe_vmmap` fails at the commit-charge check. Apple M3, macOS 26.5.1, Wine 11.0, Windows cross-build, head `eb145de6f` merged onto `main` `ec740bcc3`; fails 3/3 runs (MEASURED, also 3/3 at the previous head `87497c87a`): ``` pe-private 3 -> 67 MiB, private commit 41555 -> 41555 MiB, private working set 0 MiB line 123: counters_after.private_commit >= counters_before.private_commit + 64 * kMiB ``` The region walk sees the 64 MiB (`pe-private 3 -> 67`), but the private commit Wine reports does not move after the `VirtualAlloc` + `memset`, and stays around 41 GiB. `live()` already keeps the private working set check off under Wine (line 125, `if (!wine && ...)`); the same guard on line 123 would make the test pass there, if the counter is meant to be Windows-only. `EXPECT` returns at the first failure, so I don't know yet whether the checks after line 123 pass under Wine. I have only run Wine on macOS, not on Linux. The three `xmem` tests also fail under Wine here, but they fail the same way on `main`, so not because of this pull request. Not checked by a second agent or human yet. AI-assisted (Claude Code).
lixonik commented 2026-11-28 14:36:02 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-28T14:36:02Z.

Review: APPROVED


Re-verified updated head eb145de6f covering the newly added fixes (RT-DEVICE-LOST-DRAIN, RS-ARENA-ONE-COPY, RS-SHADER-CONTAINER-FREE, RS-DSTORAGE-SCRATCH, and the shared leonida-hle test allocator).

Code audit (abdb93f0e..eb145de6f):

  • RT-DEVICE-LOST-DRAIN (runtime/src/vulkan_backend.h): kept_after_loss preserves bindless_slot and image_view ordering until teardown, drain_lost compacts kept items in-place safely in the ring buffer and destroys the rest outside mutex_, defer_destroy drains pre-loss items once via lost_queue_drained_.exchange(true, acq_rel), and execute_now re-checks is_device_lost() after taking tracker_mutex_ before bindless_prepare_.
  • Rust additions (leonida-hle/src/test_alloc.rs, dstorage.rs, apu.rs; leonida-gpu/src/memory.rs, shadow.rs, pipeline.rs, pipeline/host.rs): cleanly unify the test counting allocator, reuse per-worker DirectStorage scratch buffers within the 16 MiB bound, drop translated shader containers once metadata is captured, and avoid double-copying opened arenas.

Verification at eb145de6f (Windows 11, MSVC 19.44, Ninja Release, LEONIDA_VK_VALIDATION=1):

  • C++: built vk_deferred_destroy_lost_test; ctest -R '^vk_deferred_destroy_lost$': 1/1 passed (0.23 s, 0 validation errors).
  • Rust (d3d12/):
    • cargo test -p leonida-hle --lib -- --test-threads=1: 189 passed, 0 failed, 2 ignored (including packets_decode_without_memory_of_their_own, compressed_requests_reuse_the_workers_buffers, and staging_counts_every_buffer_a_request_holds).
    • cargo test -p leonida-gpu --lib memory:: -- --test-threads=1: 4 passed, 0 failed (including an_arena_is_in_the_pcs_memory_once and an_arena_sends_up_only_the_dwords_the_title_changed).
    • cargo test -p leonida-gpu --lib shadow:: -- --test-threads=1: 58 passed, 0 failed, 1 ignored.
    • cargo test -p leonida-gpu --lib pipeline:: -- --test-threads=1: 37 passed, 1 failed, 7 ignored -- pipeline::tests::translated_shaders_let_their_containers_go passed; the sole failure is the untouched pipeline::host::tests::depth_bounds_pipeline_loads_and_filters_draws (root_signature returning E_INVALIDARG on this host's inbox d3d12.dll).
  • python -I scripts/check_no_game_data.py: passed.

GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, VK_LAYER_KHRONOS_validation 1.4.363).

AI-assisted (Antigravity, Gemini).

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6098416927 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6098416927). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-28T14:36:02Z. **Review:** APPROVED --- Re-verified updated head `eb145de6f` covering the newly added fixes (`RT-DEVICE-LOST-DRAIN`, `RS-ARENA-ONE-COPY`, `RS-SHADER-CONTAINER-FREE`, `RS-DSTORAGE-SCRATCH`, and the shared `leonida-hle` test allocator). Code audit (`abdb93f0e..eb145de6f`): - `RT-DEVICE-LOST-DRAIN` (`runtime/src/vulkan_backend.h`): `kept_after_loss` preserves `bindless_slot` and `image_view` ordering until teardown, `drain_lost` compacts kept items in-place safely in the ring buffer and destroys the rest outside `mutex_`, `defer_destroy` drains pre-loss items once via `lost_queue_drained_.exchange(true, acq_rel)`, and `execute_now` re-checks `is_device_lost()` after taking `tracker_mutex_` before `bindless_prepare_`. - Rust additions (`leonida-hle/src/test_alloc.rs`, `dstorage.rs`, `apu.rs`; `leonida-gpu/src/memory.rs`, `shadow.rs`, `pipeline.rs`, `pipeline/host.rs`): cleanly unify the test counting allocator, reuse per-worker DirectStorage scratch buffers within the 16 MiB bound, drop translated shader containers once metadata is captured, and avoid double-copying opened arenas. Verification at `eb145de6f` (Windows 11, MSVC 19.44, Ninja Release, `LEONIDA_VK_VALIDATION=1`): - **C++:** built `vk_deferred_destroy_lost_test`; `ctest -R '^vk_deferred_destroy_lost$'`: **1/1 passed** (0.23 s, 0 validation errors). - **Rust (`d3d12/`):** - `cargo test -p leonida-hle --lib -- --test-threads=1`: **189 passed, 0 failed, 2 ignored** (including `packets_decode_without_memory_of_their_own`, `compressed_requests_reuse_the_workers_buffers`, and `staging_counts_every_buffer_a_request_holds`). - `cargo test -p leonida-gpu --lib memory:: -- --test-threads=1`: **4 passed, 0 failed** (including `an_arena_is_in_the_pcs_memory_once` and `an_arena_sends_up_only_the_dwords_the_title_changed`). - `cargo test -p leonida-gpu --lib shadow:: -- --test-threads=1`: **58 passed, 0 failed, 1 ignored**. - `cargo test -p leonida-gpu --lib pipeline:: -- --test-threads=1`: **37 passed, 1 failed, 7 ignored** -- `pipeline::tests::translated_shaders_let_their_containers_go` **passed**; the sole failure is the untouched `pipeline::host::tests::depth_bounds_pipeline_loads_and_filters_draws` (`root_signature` returning `E_INVALIDARG` on this host's inbox `d3d12.dll`). - `python -I scripts/check_no_game_data.py`: passed. GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341, `VK_LAYER_KHRONOS_validation` 1.4.363). AI-assisted (Antigravity, Gemini).
adrianmjim commented 2026-11-28 18:06:06 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-28T18:06:06Z.


Thanks. Taken as you suggest: in 652f45345 the commit charge check (private_commit grows by the 64 MiB) runs on Windows only, like the private working set check next to it, since Wine's counter does not count what the process commits. The checks after it (largest private allocations, the title range, the pagefile-backed section, the vk-mapped range) read only the region walk, which your output shows sees the block, but I have not run them under Wine. Still passes on Windows 11 (RX 7900 XT).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7243530192 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7243530192). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-28T18:06:06Z. --- Thanks. Taken as you suggest: in `652f45345` the commit charge check (`private_commit` grows by the 64 MiB) runs on Windows only, like the private working set check next to it, since Wine's counter does not count what the process commits. The checks after it (largest private allocations, the title range, the pagefile-backed section, the vk-mapped range) read only the region walk, which your output shows sees the block, but I have not run them under Wine. Still passes on Windows 11 (RX 7900 XT).
adrianmjim commented 2026-11-28 18:06:07 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-28T18:06:07Z.

Code review location: runtime/test/d3d12_title_buffer_fallback_test.cpp; line 123

@@ -0,0 +1,268 @@
+// A vertex or index view that names the title's own memory gets a buffer made over those pages (make_title_buffer,
+// TitleVaAliases::want_buffer), the way slot 133 makes one: the pages imported, or a shadow copied from them. When
+// neither can be made, slot 133's last resort is an ordinary DEFAULT buffer, which has neither the title's VA nor its
+// bytes. A view must not keep such a buffer: it does not cover the view, so the next IASetVertexBuffers of the same
+// view would make another, each holding device memory and a device reference until the device goes, until
+// LEONIDA_TITLE_BUFFERS_MB is used up and no new title view is resolved for the rest of the session. Nor is such a
+// buffer made only to be let go: it would take device-local memory at every try, under the pressure that refused the
+// shadow.
+//   - The arena is filled first (LEONIDA_ARENA_MB=16, filled with 64 KiB buffers, so no slice is left for a shadow)
+//     and host-visible allocations are refused (the test wraps vkAllocateMemory behind the instance-proc pointer it
+//     hands the layer), with LEONIDA_SLOT133_IMPORT=0: no import and no shadow can be made, but a device-local DEFAULT
+//     buffer could.
+//   - The same 2 MiB view of title memory bound 16 times, as vertex and index views, keeps no buffer (every buffer
+//     made over title memory holds a device reference, and the device's count does not grow) and is tried once: one
+//     buffer of its size is created, the shadow's, and no device-local memory of its size is allocated.
+//   - A second, 512 KiB view bound right after that refusal is not tried: after a refusal no range is tried for a
+//     second, whichever range it is.
+//   - After that second the first view is tried again, once, and refused again. 1.5 s later the second view is tried,
+//     but the first is not: a range refused again waits twice as long. After that it is tried once more.
+// Needs a device-local memory type that is not host-visible (skipped otherwise). Synthetic data only. Set
+// LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation.
+#include "vk_test_device.h"
+#include "../shims/d3d12_com.h"
+#include "../src/title_va_alias.h"
+
+#include <atomic>
+#include <cstdio>
+#include <cstring>
+#include <vector>
+
+#define EXPECT(condition) do { \
+    if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
+} while (0)
+
+namespace {
+
+template<class T>
+struct Ref {
+    T* p = nullptr;
+    Ref() = default;
+    Ref(const Ref&) = delete;  // a copy would release the same interface twice
+    Ref& operator=(const Ref&) = delete;
+    ~Ref() { reset(); }
+    void reset() {
+        if (p) p->Release();
+        p = nullptr;
+    }
+    T* operator->() const { return p; }
+};
+
+constexpr UINT large_bytes = 2u << 20, small_bytes = 512u << 10;  // the two views; no other buffer has these sizes
+
+// The Vulkan calls the layer makes, seen through the function pointers it loads.
+PFN_vkGetInstanceProcAddr real_instance_proc = nullptr;
+PFN_vkGetDeviceProcAddr real_device_proc = nullptr;
+PFN_vkAllocateMemory real_allocate = nullptr;
+PFN_vkCreateBuffer real_create_buffer = nullptr;
+VkPhysicalDeviceMemoryProperties memory{};
+std::atomic<bool> refuse_host_visible{false};
+std::atomic<unsigned> large_buffers{0}, small_buffers{0};  // buffers of each view's size created
+std::atomic<unsigned> device_allocations{0};  // device-local allocations of at least the smaller view's size, made
+                                              // while host-visible ones are refused
+
+VKAPI_ATTR VkResult VKAPI_CALL allocate(VkDevice device, const VkMemoryAllocateInfo* info,
+                                        const VkAllocationCallbacks* allocator, VkDeviceMemory* out) {
+    if (refuse_host_visible.load() && info->memoryTypeIndex < memory.memoryTypeCount) {
+        const VkMemoryPropertyFlags flags = memory.memoryTypes[info->memoryTypeIndex].propertyFlags;
+        if (flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) return VK_ERROR_OUT_OF_DEVICE_MEMORY;
+        if ((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && info->allocationSize >= small_bytes) ++device_allocations;
+    }
+    return real_allocate(device, info, allocator, out);
+}
+
+VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice device, const VkBufferCreateInfo* info,
+                                             const VkAllocationCallbacks* allocator, VkBuffer* buffer) {
+    if (info->size == large_bytes) ++large_buffers;
+    if (info->size == small_bytes) ++small_buffers;
+    return real_create_buffer(device, info, allocator, buffer);
+}
+
+VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) {
+    if (std::strcmp(name, "vkAllocateMemory") == 0) {
+        real_allocate = reinterpret_cast<PFN_vkAllocateMemory>(real_device_proc(device, name));
+        return real_allocate ? reinterpret_cast<PFN_vkVoidFunction>(&allocate) : nullptr;
+    }
+    if (std::strcmp(name, "vkCreateBuffer") == 0) {
+        real_create_buffer = reinterpret_cast<PFN_vkCreateBuffer>(real_device_proc(device, name));
+        return real_create_buffer ? reinterpret_cast<PFN_vkVoidFunction>(&create_buffer) : nullptr;
+    }
+    return real_device_proc(device, name);
+}
+
+VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) {
+    if (std::strcmp(name, "vkGetDeviceProcAddr") == 0) {
+        real_device_proc = reinterpret_cast<PFN_vkGetDeviceProcAddr>(real_instance_proc(instance, name));
+        return real_device_proc ? reinterpret_cast<PFN_vkVoidFunction>(&device_proc) : nullptr;
+    }
+    return real_instance_proc(instance, name);
+}
+
+D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) {
+    D3D12_RESOURCE_DESC desc{};
+    desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+    desc.Width = bytes;
+    desc.Height = 1;
+    desc.DepthOrArraySize = 1;
+    desc.MipLevels = 1;
+    desc.SampleDesc.Count = 1;
+    desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+    return desc;
+}
+
+// The device's reference count: every buffer the device keeps over title memory holds one.
+ULONG references(ID3D12Device* device) {
+    device->AddRef();
+    return device->Release();
+}
+
+}  // namespace
+
+int main() {
+    vktest::Device vk;
+    if (!vk.create()) return 77;

vktest::Device creates the device with bufferDeviceAddress on whatever was requested: vk_test_device.h:459 sets enable12.bufferDeviceAddress = VK_TRUE after the request-gated line 438, and lines 378-379 refuse (the test then skips) a device without the feature. request_buffer_device_address only decides whether the helper's own buffer()/device_address() use device addresses (lines 842, 863). So info.buffer_device_address = true matches the device the test made; that has been so since ec64fd309. The test also passes under LEONIDA_VK_VALIDATION=1 with no validation message.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4728232952 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728232952). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-28T18:06:07Z. **Code review location:** `runtime/test/d3d12_title_buffer_fallback_test.cpp`; line 123 ~~~~diff @@ -0,0 +1,268 @@ +// A vertex or index view that names the title's own memory gets a buffer made over those pages (make_title_buffer, +// TitleVaAliases::want_buffer), the way slot 133 makes one: the pages imported, or a shadow copied from them. When +// neither can be made, slot 133's last resort is an ordinary DEFAULT buffer, which has neither the title's VA nor its +// bytes. A view must not keep such a buffer: it does not cover the view, so the next IASetVertexBuffers of the same +// view would make another, each holding device memory and a device reference until the device goes, until +// LEONIDA_TITLE_BUFFERS_MB is used up and no new title view is resolved for the rest of the session. Nor is such a +// buffer made only to be let go: it would take device-local memory at every try, under the pressure that refused the +// shadow. +// - The arena is filled first (LEONIDA_ARENA_MB=16, filled with 64 KiB buffers, so no slice is left for a shadow) +// and host-visible allocations are refused (the test wraps vkAllocateMemory behind the instance-proc pointer it +// hands the layer), with LEONIDA_SLOT133_IMPORT=0: no import and no shadow can be made, but a device-local DEFAULT +// buffer could. +// - The same 2 MiB view of title memory bound 16 times, as vertex and index views, keeps no buffer (every buffer +// made over title memory holds a device reference, and the device's count does not grow) and is tried once: one +// buffer of its size is created, the shadow's, and no device-local memory of its size is allocated. +// - A second, 512 KiB view bound right after that refusal is not tried: after a refusal no range is tried for a +// second, whichever range it is. +// - After that second the first view is tried again, once, and refused again. 1.5 s later the second view is tried, +// but the first is not: a range refused again waits twice as long. After that it is tried once more. +// Needs a device-local memory type that is not host-visible (skipped otherwise). Synthetic data only. Set +// LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../src/title_va_alias.h" + +#include <atomic> +#include <cstdio> +#include <cstring> +#include <vector> + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +template<class T> +struct Ref { + T* p = nullptr; + Ref() = default; + Ref(const Ref&) = delete; // a copy would release the same interface twice + Ref& operator=(const Ref&) = delete; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +constexpr UINT large_bytes = 2u << 20, small_bytes = 512u << 10; // the two views; no other buffer has these sizes + +// The Vulkan calls the layer makes, seen through the function pointers it loads. +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetDeviceProcAddr real_device_proc = nullptr; +PFN_vkAllocateMemory real_allocate = nullptr; +PFN_vkCreateBuffer real_create_buffer = nullptr; +VkPhysicalDeviceMemoryProperties memory{}; +std::atomic<bool> refuse_host_visible{false}; +std::atomic<unsigned> large_buffers{0}, small_buffers{0}; // buffers of each view's size created +std::atomic<unsigned> device_allocations{0}; // device-local allocations of at least the smaller view's size, made + // while host-visible ones are refused + +VKAPI_ATTR VkResult VKAPI_CALL allocate(VkDevice device, const VkMemoryAllocateInfo* info, + const VkAllocationCallbacks* allocator, VkDeviceMemory* out) { + if (refuse_host_visible.load() && info->memoryTypeIndex < memory.memoryTypeCount) { + const VkMemoryPropertyFlags flags = memory.memoryTypes[info->memoryTypeIndex].propertyFlags; + if (flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) return VK_ERROR_OUT_OF_DEVICE_MEMORY; + if ((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && info->allocationSize >= small_bytes) ++device_allocations; + } + return real_allocate(device, info, allocator, out); +} + +VKAPI_ATTR VkResult VKAPI_CALL create_buffer(VkDevice device, const VkBufferCreateInfo* info, + const VkAllocationCallbacks* allocator, VkBuffer* buffer) { + if (info->size == large_bytes) ++large_buffers; + if (info->size == small_bytes) ++small_buffers; + return real_create_buffer(device, info, allocator, buffer); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice device, const char* name) { + if (std::strcmp(name, "vkAllocateMemory") == 0) { + real_allocate = reinterpret_cast<PFN_vkAllocateMemory>(real_device_proc(device, name)); + return real_allocate ? reinterpret_cast<PFN_vkVoidFunction>(&allocate) : nullptr; + } + if (std::strcmp(name, "vkCreateBuffer") == 0) { + real_create_buffer = reinterpret_cast<PFN_vkCreateBuffer>(real_device_proc(device, name)); + return real_create_buffer ? reinterpret_cast<PFN_vkVoidFunction>(&create_buffer) : nullptr; + } + return real_device_proc(device, name); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetDeviceProcAddr") == 0) { + real_device_proc = reinterpret_cast<PFN_vkGetDeviceProcAddr>(real_instance_proc(instance, name)); + return real_device_proc ? reinterpret_cast<PFN_vkVoidFunction>(&device_proc) : nullptr; + } + return real_instance_proc(instance, name); +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +// The device's reference count: every buffer the device keeps over title memory holds one. +ULONG references(ID3D12Device* device) { + device->AddRef(); + return device->Release(); +} + +} // namespace + +int main() { + vktest::Device vk; + if (!vk.create()) return 77; ~~~~ --- `vktest::Device` creates the device with `bufferDeviceAddress` on whatever was requested: `vk_test_device.h:459` sets `enable12.bufferDeviceAddress = VK_TRUE` after the request-gated line 438, and lines 378-379 refuse (the test then skips) a device without the feature. `request_buffer_device_address` only decides whether the helper's own `buffer()`/`device_address()` use device addresses (lines 842, 863). So `info.buffer_device_address = true` matches the device the test made; that has been so since ec64fd309. The test also passes under `LEONIDA_VK_VALIDATION=1` with no validation message.
adrianmjim commented 2026-11-28 18:06:10 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-28T18:06:10Z.

Code review location: runtime/test/xbox_list_cut_spares_test.cpp; line 52

@@ -0,0 +1,160 @@
+// The spare real lists a list-value cut leaves behind (d3d12_xs_device.cpp restart_recording), on a Vulkan device
+// and the queue and list proxies. No game data.
+// A recording cut three times leaves three spare real lists when the title resets its list; later recordings cut at
+// most once reuse only the last of them, and the other two stay closed and idle until the list is released. A title
+// window the layer retires is freed only once every command list whose recording began before the retirement is gone
+// (src/command_list_epochs.h), and a list holds the root signatures and pipeline states its recording set until its
+// next Reset. The idle spares must therefore drop their recordings when they become spares: they can never be
+// executed again before a cut resets them. Without that, the oldest live recording stays the first one's, and the
+// root signature it set stays referenced by the two idle spares.
+#include "vk_test_device.h"
+#include "d3d12_test_shaders.h"
+#include "../shims/d3d12_com.h"
+#include "../shims/d3d12_xs_device.h"
+#include "../src/command_list_epochs.h"
+
+#include <cstdint>
+#include <cstdio>
+
+#define CHECK(x)                                                                                                       \
+    do {                                                                                                               \
+        if (!(x)) {                                                                                                    \
+            std::fprintf(stderr, "line %d: %s\n", __LINE__, #x);                                                       \
+            return 1;                                                                                                  \
+        }                                                                                                              \
+    } while (0)
+
+using namespace d3d12test;
+namespace xs = rt::d3d12_xs;
+namespace epochs = leonida::command_list_epochs;
+
+namespace {
+using Create = HRESULT(WINAPI *)(void *, const void *, ID3D12CommandAllocator *, ID3D12PipelineState *, const IID *,
+                                 void **);
+// Console list slots on the newer layout (an undetected one reads the same): wait64(address, comparison, reference,
+// flags) and SetComputeRootSignature (PC slot 29).
+using WaitFn = std::uint64_t(WINAPI *)(void *, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t);
+using RootSignatureFn = std::uint64_t(WINAPI *)(void *, std::uint64_t);
+constexpr unsigned kConsoleWait64 = 74, kConsoleSetComputeRootSignature = 33;
+constexpr std::uint64_t kGreaterEqual = 7;  // memory >= reference, in D3D12_COMPARISON_FUNC order
+
+ULONG references(IUnknown *object) {
+    object->AddRef();
+    return object->Release();
+}
+}  // namespace
+
+int main() {
+    xs::set_list_values_enabled(true);
+    vktest::Device gpu;
+    auto status = gpu.initialize();
+    if (status == vktest::DeviceStatus::unavailable) return 77;
+    CHECK(status == vktest::DeviceStatus::ready);

Same as the thread on d3d12_title_buffer_fallback_test.cpp: initialize() goes through the same device creation, which always enables bufferDeviceAddress (vk_test_device.h:459) and refuses a device without it (378-379), so the runtime's device-address allocations are legal here.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4728233080 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728233080). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-28T18:06:10Z. **Code review location:** `runtime/test/xbox_list_cut_spares_test.cpp`; line 52 ~~~~diff @@ -0,0 +1,160 @@ +// The spare real lists a list-value cut leaves behind (d3d12_xs_device.cpp restart_recording), on a Vulkan device +// and the queue and list proxies. No game data. +// A recording cut three times leaves three spare real lists when the title resets its list; later recordings cut at +// most once reuse only the last of them, and the other two stay closed and idle until the list is released. A title +// window the layer retires is freed only once every command list whose recording began before the retirement is gone +// (src/command_list_epochs.h), and a list holds the root signatures and pipeline states its recording set until its +// next Reset. The idle spares must therefore drop their recordings when they become spares: they can never be +// executed again before a cut resets them. Without that, the oldest live recording stays the first one's, and the +// root signature it set stays referenced by the two idle spares. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/command_list_epochs.h" + +#include <cstdint> +#include <cstdio> + +#define CHECK(x) \ + do { \ + if (!(x)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); \ + return 1; \ + } \ + } while (0) + +using namespace d3d12test; +namespace xs = rt::d3d12_xs; +namespace epochs = leonida::command_list_epochs; + +namespace { +using Create = HRESULT(WINAPI *)(void *, const void *, ID3D12CommandAllocator *, ID3D12PipelineState *, const IID *, + void **); +// Console list slots on the newer layout (an undetected one reads the same): wait64(address, comparison, reference, +// flags) and SetComputeRootSignature (PC slot 29). +using WaitFn = std::uint64_t(WINAPI *)(void *, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); +using RootSignatureFn = std::uint64_t(WINAPI *)(void *, std::uint64_t); +constexpr unsigned kConsoleWait64 = 74, kConsoleSetComputeRootSignature = 33; +constexpr std::uint64_t kGreaterEqual = 7; // memory >= reference, in D3D12_COMPARISON_FUNC order + +ULONG references(IUnknown *object) { + object->AddRef(); + return object->Release(); +} +} // namespace + +int main() { + xs::set_list_values_enabled(true); + vktest::Device gpu; + auto status = gpu.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + CHECK(status == vktest::DeviceStatus::ready); ~~~~ --- Same as the thread on `d3d12_title_buffer_fallback_test.cpp`: `initialize()` goes through the same device creation, which always enables `bufferDeviceAddress` (`vk_test_device.h:459`) and refuses a device without it (378-379), so the runtime's device-address allocations are legal here.
adrianmjim commented 2026-11-28 18:06:11 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-28T18:06:11Z.

Code review location: runtime/test/xbox_bvh_builder_test.cpp; line 604

@@ -522,6 +542,88 @@ int main(int argc, char** argv) {
                 : "the batch's first element (its own scratch region) is written for check-build");
     }
 
+    // ---- the shim's scratch outlives a Reset of the list until the submission that used it has completed ----
+    // D3D12 lets the title Reset a list as soon as ExecuteCommandLists returns (only its allocator waits for the GPU),
+    // and the title rehydrates with ScratchAccelerationStructureData = 0. The scratch the shim made for the build must
+    // not go back to the arena before the build has run: the next DEFAULT buffer of its size would get its range and
+    // be zeroed by the CPU while the GPU still uses it. A list released right after the call makes the same promise.
+    {
+        Ref<ID3D12CommandAllocator> next_allocator, other_allocator;
+        Ref<ID3D12GraphicsCommandList4> other_list;
+        Ref<ID3D12Resource> kept_as, kept_rb;
+        if (FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
+                                                       IID_PPV_ARGS(next_allocator.put()))) ||
+            FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,
+                                                       IID_PPV_ARGS(other_allocator.put()))) ||
+            FAILED(hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, other_allocator.p, nullptr,
+                                                  IID_PPV_ARGS(other_list.put()))) ||
+            FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav,
+                               kept_as.put())) ||
+            FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes,
+                               D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, kept_rb.put())))
+            return fail("kept-scratch lists or buffers", hr);
+        if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for kept scratch");
+        D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC kept_desc = zero_scratch_desc;
+        kept_desc.DestAccelerationStructureData = kept_as->GetGPUVirtualAddress();
+        check(rehydrate(builder, list.p, 1, &kept_desc, &source) == S_OK,
+              "a rehydrate without the title's scratch is recorded for the Reset check");
+        // The build's scratch is the one buffer the shim made for this call (one element: its region starts there).
+        UINT64 scratch_va = 0;
+        std::vector<leonida::Command> commands;
+        if (rt::d3d12::recorded_commands(list.p, commands))
+            for (const auto& command : commands)
+                if (const auto* build = std::get_if<leonida::BuildAccelerationStructure>(&command))
+                    scratch_va = build->scratch_va;
+        const UINT64 scratch_bytes = (blas_info.ScratchDataSizeInBytes + 255) / 256 * 256;
+        // Static, so a release that comes after this block (the queue's worker, or the teardown after a failed step
+        // returns early) still finds the object.
+        static Sentinel reset_sentinel, release_sentinel;
+        check(scratch_va && rt::d3d12::hold_until_reset(list.p, &reset_sentinel) &&
+                  rt::d3d12::hold_until_reset(other_list.p, &release_sentinel),
+              "the build has the shim's scratch, and both lists hold a sentinel");
+        list->ResourceBarrier(1, &barrier);
+        list->CopyBufferRegion(kept_rb.p, 0, kept_as.p, 0, blas_info.ResultDataMaxSizeInBytes);
+        if (FAILED(list->Close()) || FAILED(other_list->Close())) return fail("Close for kept scratch");
+        ID3D12CommandList* lists[] = {list.p, other_list.p};
+        queue->ExecuteCommandLists(2, lists);
+        // At once, before any Signal: the one list is Reset on another allocator, the other released.
+        if (FAILED(list->Reset(next_allocator.p, nullptr))) return fail("Reset right after ExecuteCommandLists");
+        other_list->Release();
+        other_list.p = nullptr;
+        Ref<ID3D12Resource> probe;
+        if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_bytes, D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
+                               uav, probe.put())))
+            return fail("probe buffer", hr);
+        const UINT64 probe_va = probe->GetGPUVirtualAddress();
+        std::printf("scratch VA 0x%llx, a DEFAULT buffer of its 0x%llx bytes made after the Reset at VA 0x%llx\n",
+                    static_cast<unsigned long long>(scratch_va), static_cast<unsigned long long>(scratch_bytes),
+                    static_cast<unsigned long long>(probe_va));
+        check(probe_va + scratch_bytes <= scratch_va || scratch_va + scratch_bytes <= probe_va,
+              "a DEFAULT buffer made right after the Reset does not get the range of the scratch the submission uses");
+        check(reset_sentinel.refs.load() > 1, "an object a list holds outlives the list's Reset after the call");
+        check(release_sentinel.refs.load() > 1, "and the list's release after the call");

Agreed, for the synchronous path (the default). execute_sync queues the keep under the ticket it just submitted (vulkan_backend.h:2836) and then calls drain_pins in the same call (2849), which releases every pin whose ticket is at or below the semaphore's current value. A build that completes between the submit and that query is therefore released before ExecuteCommandLists returns, so the checks at 601-604 can see both sentinels at one reference with correct lifetime handling. The window is a few microseconds (the test has passed in every run here and under validation on AMD and NVIDIA), but it is not deterministic. The runtime is right in that case; the test is what needs to change.

A deterministic version needs a way to keep the submission from completing without taking the queue's held path (a gated Wait makes the batch held, which exercises the pins instead of the keep under test), so it will come as a separate change.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4728233176 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728233176). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-28T18:06:11Z. **Code review location:** `runtime/test/xbox_bvh_builder_test.cpp`; line 604 ~~~~diff @@ -522,6 +542,88 @@ int main(int argc, char** argv) { : "the batch's first element (its own scratch region) is written for check-build"); } + // ---- the shim's scratch outlives a Reset of the list until the submission that used it has completed ---- + // D3D12 lets the title Reset a list as soon as ExecuteCommandLists returns (only its allocator waits for the GPU), + // and the title rehydrates with ScratchAccelerationStructureData = 0. The scratch the shim made for the build must + // not go back to the arena before the build has run: the next DEFAULT buffer of its size would get its range and + // be zeroed by the CPU while the GPU still uses it. A list released right after the call makes the same promise. + { + Ref<ID3D12CommandAllocator> next_allocator, other_allocator; + Ref<ID3D12GraphicsCommandList4> other_list; + Ref<ID3D12Resource> kept_as, kept_rb; + if (FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(next_allocator.put()))) || + FAILED(hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(other_allocator.put()))) || + FAILED(hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, other_allocator.p, nullptr, + IID_PPV_ARGS(other_list.put()))) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, + kept_as.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, kept_rb.put()))) + return fail("kept-scratch lists or buffers", hr); + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for kept scratch"); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC kept_desc = zero_scratch_desc; + kept_desc.DestAccelerationStructureData = kept_as->GetGPUVirtualAddress(); + check(rehydrate(builder, list.p, 1, &kept_desc, &source) == S_OK, + "a rehydrate without the title's scratch is recorded for the Reset check"); + // The build's scratch is the one buffer the shim made for this call (one element: its region starts there). + UINT64 scratch_va = 0; + std::vector<leonida::Command> commands; + if (rt::d3d12::recorded_commands(list.p, commands)) + for (const auto& command : commands) + if (const auto* build = std::get_if<leonida::BuildAccelerationStructure>(&command)) + scratch_va = build->scratch_va; + const UINT64 scratch_bytes = (blas_info.ScratchDataSizeInBytes + 255) / 256 * 256; + // Static, so a release that comes after this block (the queue's worker, or the teardown after a failed step + // returns early) still finds the object. + static Sentinel reset_sentinel, release_sentinel; + check(scratch_va && rt::d3d12::hold_until_reset(list.p, &reset_sentinel) && + rt::d3d12::hold_until_reset(other_list.p, &release_sentinel), + "the build has the shim's scratch, and both lists hold a sentinel"); + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(kept_rb.p, 0, kept_as.p, 0, blas_info.ResultDataMaxSizeInBytes); + if (FAILED(list->Close()) || FAILED(other_list->Close())) return fail("Close for kept scratch"); + ID3D12CommandList* lists[] = {list.p, other_list.p}; + queue->ExecuteCommandLists(2, lists); + // At once, before any Signal: the one list is Reset on another allocator, the other released. + if (FAILED(list->Reset(next_allocator.p, nullptr))) return fail("Reset right after ExecuteCommandLists"); + other_list->Release(); + other_list.p = nullptr; + Ref<ID3D12Resource> probe; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_bytes, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + uav, probe.put()))) + return fail("probe buffer", hr); + const UINT64 probe_va = probe->GetGPUVirtualAddress(); + std::printf("scratch VA 0x%llx, a DEFAULT buffer of its 0x%llx bytes made after the Reset at VA 0x%llx\n", + static_cast<unsigned long long>(scratch_va), static_cast<unsigned long long>(scratch_bytes), + static_cast<unsigned long long>(probe_va)); + check(probe_va + scratch_bytes <= scratch_va || scratch_va + scratch_bytes <= probe_va, + "a DEFAULT buffer made right after the Reset does not get the range of the scratch the submission uses"); + check(reset_sentinel.refs.load() > 1, "an object a list holds outlives the list's Reset after the call"); + check(release_sentinel.refs.load() > 1, "and the list's release after the call"); ~~~~ --- Agreed, for the synchronous path (the default). `execute_sync` queues the keep under the ticket it just submitted (`vulkan_backend.h:2836`) and then calls `drain_pins` in the same call (2849), which releases every pin whose ticket is at or below the semaphore's current value. A build that completes between the submit and that query is therefore released before `ExecuteCommandLists` returns, so the checks at 601-604 can see both sentinels at one reference with correct lifetime handling. The window is a few microseconds (the test has passed in every run here and under validation on AMD and NVIDIA), but it is not deterministic. The runtime is right in that case; the test is what needs to change. A deterministic version needs a way to keep the submission from completing without taking the queue's held path (a gated `Wait` makes the batch held, which exercises the pins instead of the keep under test), so it will come as a separate change.
copilot-pull-request-reviewer[bot] commented 2026-11-28 19:23:14 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-28T19:23:14Z.

Review: COMMENTED


Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6099736896 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6099736896). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-28T19:23:14Z. **Review:** COMMENTED --- Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level. An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. [Learn about Copilot code review billing](https://docs.github.com/en/copilot/concepts/agents/code-review#code-review-usage).
Copilot commented 2026-11-28 19:34:00 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-28T19:34:00Z.

Code review location: d3d12/crates/leonida-gpu/src/host/send.rs; line 243

@@ -232,10 +232,20 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us
         let mut to = to as *mut [u32; 2];
         for &(a, b) in ranges.iter().filter(|r| short(r)) {
             for offset in (a..b).step_by(4) {
-                // SAFETY: inside the copy's mapping (its CPU side, which
-                // the thread that asked, and waits, alone writes in these
-                // ranges) and inside the memory, which has room for every
-                // pair, a piece of work's behind the last one's.
+                // SAFETY: inside the copy's mapping (its CPU side) and
+                // inside the memory, which has room for every pair, a piece
+                // of work's behind the last one's. The thread that asked,
+                // and waits, alone writes in these ranges of a CPU side,
+                // but for a side that is memory of ours (`Shadow::opened`,
+                // an arena of `crate::memory`'s): there a recording thread
+                // may write a word while it is read here, or while
+                // `copy_all` below reads its run. Two plain accesses at
+                // once are a race the language leaves undefined. What the

The opened CPU side now aliases the arena that Memory::bring/take modify under the MEMORY mutex, but these read_unaligned reads and the copy_all copies do not acquire that synchronization. Concurrent recording and submission therefore cause a Rust data race; the old-or-new-byte behavior described here is not guaranteed under undefined behavior, and resending afterward cannot make it safe. Please synchronize opened-side reads with the arena writer, or collect a snapshot under that synchronization before handing it to the parallel send workers.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4728512319 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512319). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-28T19:34:00Z. **Code review location:** `d3d12/crates/leonida-gpu/src/host/send.rs`; line 243 ~~~~diff @@ -232,10 +232,20 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us let mut to = to as *mut [u32; 2]; for &(a, b) in ranges.iter().filter(|r| short(r)) { for offset in (a..b).step_by(4) { - // SAFETY: inside the copy's mapping (its CPU side, which - // the thread that asked, and waits, alone writes in these - // ranges) and inside the memory, which has room for every - // pair, a piece of work's behind the last one's. + // SAFETY: inside the copy's mapping (its CPU side) and + // inside the memory, which has room for every pair, a piece + // of work's behind the last one's. The thread that asked, + // and waits, alone writes in these ranges of a CPU side, + // but for a side that is memory of ours (`Shadow::opened`, + // an arena of `crate::memory`'s): there a recording thread + // may write a word while it is read here, or while + // `copy_all` below reads its run. Two plain accesses at + // once are a race the language leaves undefined. What the ~~~~ --- The opened CPU side now aliases the arena that `Memory::bring`/`take` modify under the `MEMORY` mutex, but these `read_unaligned` reads and the `copy_all` copies do not acquire that synchronization. Concurrent recording and submission therefore cause a Rust data race; the old-or-new-byte behavior described here is not guaranteed under undefined behavior, and resending afterward cannot make it safe. Please synchronize opened-side reads with the arena writer, or collect a snapshot under that synchronization before handing it to the parallel send workers.
Copilot commented 2026-11-28 19:34:01 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-28T19:34:01Z.

Code review location: runtime/src/vulkan_backend.h; line 2027

@@ -1971,13 +2009,21 @@ class VulkanContext {
     void defer_destroy(DeferredDeletionQueue::Kind kind, VkHandle handle) {
         const auto raw = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(handle));
         if (!raw) return;
-        std::lock_guard lock(submit_mutex_);
-        const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1;
-        deletion_queue_.push(safe_ticket, kind, raw);
+        defer_destroy(kind, raw);
     }
 
     void defer_destroy(DeferredDeletionQueue::Kind kind, std::uint64_t raw_handle) {
         if (!raw_handle && kind != DeferredDeletionQueue::Kind::bindless_slot) return;
+        // Once the device is lost no retire ticket completes again (completed_retire_ticket() answers 0 and acquire()
+        // returns before its drain), so a queued object would stay until the context goes and the queue would grow
+        // with everything the title releases. The lost device runs nothing more, and vkDestroy* and vkFreeMemory are
+        // valid on it: the object goes now, and the first time also everything queued before the loss. Bindless slots
+        // and image views still wait, in their order (DeferredDeletionQueue::kept_after_loss says why).
+        if (is_device_lost() && !DeferredDeletionQueue::kept_after_loss(kind)) {
+            if (!lost_queue_drained_.exchange(true, std::memory_order_acq_rel)) deletion_queue_.drain_lost(device_, vk);
+            DeferredDeletionQueue::destroy({0, raw_handle, kind}, device_, vk, nullptr, nullptr);
+            return;
+        }
         std::lock_guard lock(submit_mutex_);

A release can observe a live device, pause before acquiring submit_mutex_, and enqueue its object after another thread completes the one-time loss drain. Since retirement stops after loss and later releases skip that drain, the object remains allocated until teardown. Check for loss under the enqueue lock so non-retained objects cannot enter the queue after the drain, while keeping destruction outside that lock.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4728512338 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512338). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-28T19:34:01Z. **Code review location:** `runtime/src/vulkan_backend.h`; line 2027 ~~~~diff @@ -1971,13 +2009,21 @@ class VulkanContext { void defer_destroy(DeferredDeletionQueue::Kind kind, VkHandle handle) { const auto raw = static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(handle)); if (!raw) return; - std::lock_guard lock(submit_mutex_); - const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; - deletion_queue_.push(safe_ticket, kind, raw); + defer_destroy(kind, raw); } void defer_destroy(DeferredDeletionQueue::Kind kind, std::uint64_t raw_handle) { if (!raw_handle && kind != DeferredDeletionQueue::Kind::bindless_slot) return; + // Once the device is lost no retire ticket completes again (completed_retire_ticket() answers 0 and acquire() + // returns before its drain), so a queued object would stay until the context goes and the queue would grow + // with everything the title releases. The lost device runs nothing more, and vkDestroy* and vkFreeMemory are + // valid on it: the object goes now, and the first time also everything queued before the loss. Bindless slots + // and image views still wait, in their order (DeferredDeletionQueue::kept_after_loss says why). + if (is_device_lost() && !DeferredDeletionQueue::kept_after_loss(kind)) { + if (!lost_queue_drained_.exchange(true, std::memory_order_acq_rel)) deletion_queue_.drain_lost(device_, vk); + DeferredDeletionQueue::destroy({0, raw_handle, kind}, device_, vk, nullptr, nullptr); + return; + } std::lock_guard lock(submit_mutex_); ~~~~ --- A release can observe a live device, pause before acquiring `submit_mutex_`, and enqueue its object after another thread completes the one-time loss drain. Since retirement stops after loss and later releases skip that drain, the object remains allocated until teardown. Check for loss under the enqueue lock so non-retained objects cannot enter the queue after the drain, while keeping destruction outside that lock.
Copilot commented 2026-11-28 19:34:01 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-28T19:34:01Z.

Code review location: d3d12/crates/leonida-gpu/src/pipeline/library.rs; line 862

@@ -803,25 +804,97 @@ pub(crate) fn note_time(key: &str, ms: u64) {
     }
 }
 
-/// Title pipeline keys requested by draws or dispatches (this run and the last).
-static USED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
+/// Title pipeline keys requested by draws or dispatches (this run and the
+/// last, [`early_runs`]).
+static USED: Mutex<Option<Early>> = Mutex::new(None);
 static USED_CHANGED: AtomicBool = AtomicBool::new(false);
 
-fn used() -> std::sync::MutexGuard<'static, Option<HashSet<String>>> {
+/// How many runs' title pipelines the early list keeps: 2, those this run
+/// requested and those the run before did, so a pipeline is started early
+/// by the two runs after the last one that drew with it. The list held
+/// every run's: each pipeline drawn with in any earlier run was started at
+/// the title's creation of it, at every load, and kept as a host pipeline
+/// for the whole session whether this run drew with it or not. It grew
+/// with every place visited, and at `EARLY_MAX` it stopped taking new ones.
+/// `LEONIDA_EARLY_RUNS=<n>`: n runs; 0: every run's, as before.
+fn early_runs() -> u64 {
+    static RUNS: OnceLock<u64> = OnceLock::new();
+    *RUNS.get_or_init(|| {
+        std::env::var("LEONIDA_EARLY_RUNS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2)
+    })
+}
+
+/// The early list ([`EARLY_FILE`]): a key and the run that last requested
+/// it on each line. Runs are counted by the list itself: this one is one
+/// past the newest written down. A line with a key alone (a list written
+/// before runs were counted) is one of run 0.
+struct Early {
+    /// This run's number.
+    run: u64,
+    keys: HashMap<String, u64>,
+}
+
+impl Early {
+    fn read(text: &str) -> Early {
+        let mut keys: HashMap<String, u64> = HashMap::new();
+        for line in text.lines() {
+            let mut words = line.split_ascii_whitespace();
+            let Some(key) = words.next() else { continue };
+            let run = words.next().and_then(|r| r.parse().ok()).unwrap_or(0);
+            let last = keys.entry(key.to_owned()).or_insert(run);
+            *last = run.max(*last);
+        }
+        let run = keys.values().copied().max().unwrap_or(0).saturating_add(1);
+        Early { run, keys }
+    }
+
+    /// Whether a run on the list requested `key`.
+    fn has(&self, key: &str) -> bool {
+        self.keys.contains_key(key)
+    }
+
+    /// This run requested `key`; whether the list changed: a key new to it,
+    /// or one an earlier run requested last (its run is written again).
+    fn note(&mut self, key: &str) -> bool {
+        if let Some(last) = self.keys.get_mut(key) {
+            return std::mem::replace(last, self.run) != self.run;
+        }
+        self.keys.len() < EARLY_MAX && self.keys.insert(key.to_owned(), self.run).is_none()

When the early list already has EARLY_MAX keys and a run requests only new keys, every insertion is rejected and no entry gets the current run number. lines() therefore keeps aging from the previous run, retaining stale entries across repeated launches instead of admitting current pipelines. Track genuine requests independently of accepted entries and prune or evict old keys at capacity, while preserving the list when nothing was requested.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4728512358 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512358). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-28T19:34:01Z. **Code review location:** `d3d12/crates/leonida-gpu/src/pipeline/library.rs`; line 862 ~~~~diff @@ -803,25 +804,97 @@ pub(crate) fn note_time(key: &str, ms: u64) { } } -/// Title pipeline keys requested by draws or dispatches (this run and the last). -static USED: Mutex<Option<HashSet<String>>> = Mutex::new(None); +/// Title pipeline keys requested by draws or dispatches (this run and the +/// last, [`early_runs`]). +static USED: Mutex<Option<Early>> = Mutex::new(None); static USED_CHANGED: AtomicBool = AtomicBool::new(false); -fn used() -> std::sync::MutexGuard<'static, Option<HashSet<String>>> { +/// How many runs' title pipelines the early list keeps: 2, those this run +/// requested and those the run before did, so a pipeline is started early +/// by the two runs after the last one that drew with it. The list held +/// every run's: each pipeline drawn with in any earlier run was started at +/// the title's creation of it, at every load, and kept as a host pipeline +/// for the whole session whether this run drew with it or not. It grew +/// with every place visited, and at `EARLY_MAX` it stopped taking new ones. +/// `LEONIDA_EARLY_RUNS=<n>`: n runs; 0: every run's, as before. +fn early_runs() -> u64 { + static RUNS: OnceLock<u64> = OnceLock::new(); + *RUNS.get_or_init(|| { + std::env::var("LEONIDA_EARLY_RUNS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2) + }) +} + +/// The early list ([`EARLY_FILE`]): a key and the run that last requested +/// it on each line. Runs are counted by the list itself: this one is one +/// past the newest written down. A line with a key alone (a list written +/// before runs were counted) is one of run 0. +struct Early { + /// This run's number. + run: u64, + keys: HashMap<String, u64>, +} + +impl Early { + fn read(text: &str) -> Early { + let mut keys: HashMap<String, u64> = HashMap::new(); + for line in text.lines() { + let mut words = line.split_ascii_whitespace(); + let Some(key) = words.next() else { continue }; + let run = words.next().and_then(|r| r.parse().ok()).unwrap_or(0); + let last = keys.entry(key.to_owned()).or_insert(run); + *last = run.max(*last); + } + let run = keys.values().copied().max().unwrap_or(0).saturating_add(1); + Early { run, keys } + } + + /// Whether a run on the list requested `key`. + fn has(&self, key: &str) -> bool { + self.keys.contains_key(key) + } + + /// This run requested `key`; whether the list changed: a key new to it, + /// or one an earlier run requested last (its run is written again). + fn note(&mut self, key: &str) -> bool { + if let Some(last) = self.keys.get_mut(key) { + return std::mem::replace(last, self.run) != self.run; + } + self.keys.len() < EARLY_MAX && self.keys.insert(key.to_owned(), self.run).is_none() ~~~~ --- When the early list already has `EARLY_MAX` keys and a run requests only new keys, every insertion is rejected and no entry gets the current run number. `lines()` therefore keeps aging from the previous run, retaining stale entries across repeated launches instead of admitting current pipelines. Track genuine requests independently of accepted entries and prune or evict old keys at capacity, while preserving the list when nothing was requested.
Copilot commented 2026-11-28 19:34:01 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Copilot on 2026-11-28T19:34:01Z.

Code review location: runtime/src/pipeline_cache_store.h; line 149

@@ -73,4 +81,88 @@ inline bool header_matches(const void* data, std::size_t size, const cached_pso:
            std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0;
 }
 
+// Which pipeline_cache.bin a cache was created from: its size and last-write time (FILETIME, 100 ns ticks) when it
+// was loaded. The pipelines build stage writes a new seed through a rename, which gives it a new time; a seed copied
+// over with the same time and size is the same file in practice. Zero: no offline seed.
+struct SeedStamp {
+    std::uint64_t bytes = 0;
+    std::uint64_t write_time = 0;
+    bool operator==(const SeedStamp&) const = default;
+};
+
+// pipeline_cache.session.seed: the seed a session file was written beside, and that session file's size. Written
+// after the session file is published, so a session file published since (by a crash between the two, or an older
+// build that does not know of this file) has, in practice, another size.
+struct SessionSeed {
+    SeedStamp seed;
+    std::uint64_t session_bytes = 0;
+};
+
+inline constexpr std::string_view session_seed_magic = "leonida pipeline_cache.session.seed 1";
+
+// Four lines of text: the magic, then `seed_bytes N`, `seed_time N` and `session_bytes N`, in that order.
+inline std::string format_session_seed(const SessionSeed& recorded) {
+    return std::string(session_seed_magic) + "\nseed_bytes " + std::to_string(recorded.seed.bytes) + "\nseed_time " +
+           std::to_string(recorded.seed.write_time) + "\nsession_bytes " + std::to_string(recorded.session_bytes) +
+           "\n";
+}
+
+// The file's contents back, or nothing when they are not exactly what format_session_seed writes: a file cut short,
+// edited or from another version is not trusted, and the next launch loads the seed and merges as before.
+inline std::optional<SessionSeed> parse_session_seed(std::string_view text) {
+    const auto line = [&text](std::string_view& out) {
+        const auto end = text.find('\n');
+        if (end == std::string_view::npos) return false;
+        out = text.substr(0, end);
+        text.remove_prefix(end + 1);
+        return true;
+    };
+    const auto number = [&line](std::string_view key, std::uint64_t& out) {
+        std::string_view got;
+        if (!line(got) || got.size() <= key.size() + 1 || got.substr(0, key.size()) != key || got[key.size()] != ' ')
+            return false;
+        std::uint64_t value = 0;
+        for (const char c : got.substr(key.size() + 1)) {
+            if (c < '0' || c > '9') return false;
+            const auto digit = std::uint64_t(c - '0');
+            if (value > (std::numeric_limits<std::uint64_t>::max() - digit) / 10) return false;
+            value = value * 10 + digit;
+        }
+        out = value;
+        return true;
+    };
+    std::string_view magic;
+    SessionSeed recorded;
+    if (!line(magic) || magic != session_seed_magic || !number("seed_bytes", recorded.seed.bytes) ||
+        !number("seed_time", recorded.seed.write_time) || !number("session_bytes", recorded.session_bytes) ||
+        !text.empty())
+        return std::nullopt;
+    return recorded;
+}
+
+// Whether a session file of `session_bytes` holds every pipeline of the offline seed `seed` as it is now, so it can
+// be loaded instead of the seed and the merge: it was written beside exactly this seed and has not changed size since
+// (the driver's union, which is never smaller than the seed). Anything else, or no record, is the merge as before.
+inline bool session_holds_seed(const std::optional<SessionSeed>& recorded, const SeedStamp& seed,
+                               std::uint64_t session_bytes) {
+    return recorded && seed.bytes >= header_bytes && recorded->seed == seed &&
+           recorded->session_bytes == session_bytes && session_bytes >= seed.bytes;

A device-compatible session cache can replace this file with different contents but the same length, leaving the old seed record valid if the process crashes before updating or removing it. The next launch then skips the offline seed even if the replacement lacks its entries, and can carry that incomplete cache forward. Record and validate the session file's identity as well, such as its last-write stamp or a digest, rather than relying on its length.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4728512378 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512378). Originally posted by [Copilot](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-28T19:34:01Z. **Code review location:** `runtime/src/pipeline_cache_store.h`; line 149 ~~~~diff @@ -73,4 +81,88 @@ inline bool header_matches(const void* data, std::size_t size, const cached_pso: std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0; } +// Which pipeline_cache.bin a cache was created from: its size and last-write time (FILETIME, 100 ns ticks) when it +// was loaded. The pipelines build stage writes a new seed through a rename, which gives it a new time; a seed copied +// over with the same time and size is the same file in practice. Zero: no offline seed. +struct SeedStamp { + std::uint64_t bytes = 0; + std::uint64_t write_time = 0; + bool operator==(const SeedStamp&) const = default; +}; + +// pipeline_cache.session.seed: the seed a session file was written beside, and that session file's size. Written +// after the session file is published, so a session file published since (by a crash between the two, or an older +// build that does not know of this file) has, in practice, another size. +struct SessionSeed { + SeedStamp seed; + std::uint64_t session_bytes = 0; +}; + +inline constexpr std::string_view session_seed_magic = "leonida pipeline_cache.session.seed 1"; + +// Four lines of text: the magic, then `seed_bytes N`, `seed_time N` and `session_bytes N`, in that order. +inline std::string format_session_seed(const SessionSeed& recorded) { + return std::string(session_seed_magic) + "\nseed_bytes " + std::to_string(recorded.seed.bytes) + "\nseed_time " + + std::to_string(recorded.seed.write_time) + "\nsession_bytes " + std::to_string(recorded.session_bytes) + + "\n"; +} + +// The file's contents back, or nothing when they are not exactly what format_session_seed writes: a file cut short, +// edited or from another version is not trusted, and the next launch loads the seed and merges as before. +inline std::optional<SessionSeed> parse_session_seed(std::string_view text) { + const auto line = [&text](std::string_view& out) { + const auto end = text.find('\n'); + if (end == std::string_view::npos) return false; + out = text.substr(0, end); + text.remove_prefix(end + 1); + return true; + }; + const auto number = [&line](std::string_view key, std::uint64_t& out) { + std::string_view got; + if (!line(got) || got.size() <= key.size() + 1 || got.substr(0, key.size()) != key || got[key.size()] != ' ') + return false; + std::uint64_t value = 0; + for (const char c : got.substr(key.size() + 1)) { + if (c < '0' || c > '9') return false; + const auto digit = std::uint64_t(c - '0'); + if (value > (std::numeric_limits<std::uint64_t>::max() - digit) / 10) return false; + value = value * 10 + digit; + } + out = value; + return true; + }; + std::string_view magic; + SessionSeed recorded; + if (!line(magic) || magic != session_seed_magic || !number("seed_bytes", recorded.seed.bytes) || + !number("seed_time", recorded.seed.write_time) || !number("session_bytes", recorded.session_bytes) || + !text.empty()) + return std::nullopt; + return recorded; +} + +// Whether a session file of `session_bytes` holds every pipeline of the offline seed `seed` as it is now, so it can +// be loaded instead of the seed and the merge: it was written beside exactly this seed and has not changed size since +// (the driver's union, which is never smaller than the seed). Anything else, or no record, is the merge as before. +inline bool session_holds_seed(const std::optional<SessionSeed>& recorded, const SeedStamp& seed, + std::uint64_t session_bytes) { + return recorded && seed.bytes >= header_bytes && recorded->seed == seed && + recorded->session_bytes == session_bytes && session_bytes >= seed.bytes; ~~~~ --- A device-compatible session cache can replace this file with different contents but the same length, leaving the old seed record valid if the process crashes before updating or removing it. The next launch then skips the offline seed even if the replacement lacks its entries, and can carry that incomplete cache forward. Record and validate the session file's identity as well, such as its last-write stamp or a digest, rather than relying on its length.
copilot-pull-request-reviewer[bot] commented 2026-11-28 19:34:02 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-28T19:34:02Z.

Review: COMMENTED


Unsynchronized arena reads can cause Rust data races, while a device-loss enqueue race can leave released objects allocated until teardown.

4 open issues
3 resolved since last review

Review effort: Balanced

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6099772161 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6099772161). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-28T19:34:02Z. **Review:** COMMENTED --- <!-- ccr-overview-v2 --> ### 🟡 Changes recommended Unsynchronized arena reads can cause Rust data races, while a device-loss enqueue race can leave released objects allocated until teardown. <details open> <summary><strong>4 open issues</strong></summary> - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Opened-side arena reads race with concurrent writes](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512319) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Release can enqueue objects after the loss drain](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512338) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Full early list fails to admit newly requested keys](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512358) · New - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Same-length cache replacement leaves stale seed record valid](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512378) · New </details> <details> <summary><strong>3 resolved since last review</strong></summary> - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Enable buffer device address feature before running the test](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480242) - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Block GPU completion until synchronous pinning assertions finish](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480227) - <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Enable buffer device address feature before arena creation](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480218) </details> <sub>Review effort: Balanced</sub>
Maticcm commented 2026-11-28 21:17:07 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Maticcm on 2026-11-28T21:17:07Z.


Native Windows C++ runtime check of 962bc1601b37be431f7417840dfa6adc85408224, with the shared DirectStorage test also run on common ancestor 8b318bd4037e37a29bebda7417da0062d869f365. RTX 3080 desktop, 10 GiB, NVIDIA 630.20, Windows 11 build 26340, MSVC 19.50.35717 RelWithDebInfo and Vulkan SDK 1.4.363.1.

  • dstorage passed on both revisions. The head includes and executed the new paired-worker scratch-cap check.
  • d3d12_zero_image_release passed on the head on RTX 3080 with Khronos validation enabled, including the overlapping replay test.
  • mem_probe_vmmap passed on native Windows. Its live measurement showed private commit rise from 1 to 65 MiB with the 64 MiB allocation.

Overall 3/3 on the head and 1/1 on the ancestor, no CTest skips. Focused C++ synthetic checks only. AI-assisted (Codex).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7245906263 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7245906263). Originally posted by [Maticcm](https://github.com/Maticcm) on 2026-11-28T21:17:07Z. --- Native Windows C++ runtime check of `962bc1601b37be431f7417840dfa6adc85408224`, with the shared DirectStorage test also run on common ancestor `8b318bd4037e37a29bebda7417da0062d869f365`. RTX 3080 desktop, 10 GiB, NVIDIA 630.20, Windows 11 build 26340, MSVC 19.50.35717 RelWithDebInfo and Vulkan SDK 1.4.363.1. - `dstorage` passed on both revisions. The head includes and executed the new paired-worker scratch-cap check. - `d3d12_zero_image_release` passed on the head on RTX 3080 with Khronos validation enabled, including the overlapping replay test. - `mem_probe_vmmap` passed on native Windows. Its live measurement showed private commit rise from 1 to 65 MiB with the 64 MiB allocation. Overall 3/3 on the head and 1/1 on the ancestor, no CTest skips. Focused C++ synthetic checks only. AI-assisted (Codex).
lixonik commented 2026-11-28 21:17:49 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-28T21:17:49Z.

Review: COMMENTED


Focused follow-up on RS-PIPELINE-LIBRARY-FINGERPRINT at 962bc1601 merged locally with main aa918e5d9. Windows 10 22H2, Rust/MSVC, diag profile. The 15 library tests and one additional local file-lock fixture passed, including concurrent saves and fingerprint handling.

The extra fixture held the old cache file open without delete sharing and saved a synthetic blob for the new fingerprint. The implementation wrote the replacement to the waiting file. A read while the old file was locked correctly returned an empty library; after releasing the handle the new file was promoted and its bytes were read under the new fingerprint. This check only covers the Rust pipeline library lane of the sweep.

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6100124342 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6100124342). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-28T21:17:49Z. **Review:** COMMENTED --- Focused follow-up on RS-PIPELINE-LIBRARY-FINGERPRINT at `962bc1601` merged locally with `main` `aa918e5d9`. Windows 10 22H2, Rust/MSVC, `diag` profile. The 15 library tests and one additional local file-lock fixture passed, including concurrent saves and fingerprint handling. The extra fixture held the old cache file open without delete sharing and saved a synthetic blob for the new fingerprint. The implementation wrote the replacement to the waiting file. A read while the old file was locked correctly returned an empty library; after releasing the handle the new file was promoted and its bytes were read under the new fingerprint. This check only covers the Rust pipeline library lane of the sweep. AI-assisted.
zmasi commented 2026-11-28 21:39:03 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-11-28T21:39:03Z.


Native Windows 11 + NVIDIA GeForce RTX 3090 Verification (d3d12/ Rust Head 962bc1601b)

Verified the updated head 962bc1601b37be431f7417840dfa6adc85408224 merged cleanly onto origin/main (aa918e5d9f9e2f03e078d8f08854324890b5e176, git merge-tree --write-tree rc=0) on native Windows 11 (26200) + NVIDIA GeForce RTX 3090 (driver 610.88), covering the 6 Rust d3d12/ leak-remediation additions landed after 9fc3ad427c (RS-HOST-LIST-SCRATCH-TRIM, RS-PIPELINE-LIBRARY-FINGERPRINT, RS-ARENA-ONE-COPY, RS-SHADER-CONTAINER-FREE, RS-DSTORAGE-SCRATCH, and shared test_alloc counting allocator) alongside all earlier d3d12/ suites.

1. Red -> Green Hardware Reproduction (RS-ARENA-ONE-COPY on RTX 3090)

  • Red (origin/main aa918e5d9f): Probed Memory::another() across 3 consecutive 64 MiB arenas on RTX 3090 (ID3D12Device3::OpenExistingHeapFromAddress supported): each 64 MiB arena added 192 MiB of process commit (128 MiB beside its 64 MiB GPU side: 64 MiB upload::reserve + duplicate 64 MiB UPLOAD shared_buffer), failing grew < card + ARENA + ARENA / 2.
  • Green (origin/main + 962bc1601b): memory::tests::an_arena_is_in_the_pcs_memory_once passed (4/4 memory::tests green): each 64 MiB arena added 128 MiB total commit (64 MiB GPU side + 64 MiB CPU arena, 64 MiB less commit per arena), card_data() == at for all 3 arenas (by_address_opened via inplace::place_part), and an_arena_sends_up_only_the_dwords_the_title_changed confirmed dword-granular dirty-run uploads leave untouched GPU-written dwords intact.

2. d3d12/ Test Suites Executed (100% Green)

  • leonida-gpu (default & --features diagnostics, RTX 3090 D3D12):
    • memory::tests::*: 4/4 passed (an_arena_is_in_the_pcs_memory_once, an_arena_sends_up_only_the_dwords_the_title_changed, a_piece_takes_what_changed, a_packed_structure_is_known_by_its_header).
    • list::tests::*: 10/10 passed (an_idle_list_lets_go_of_a_large_indirect_scratch in both default and --features diagnostics, a_submitted_list_keeps_no_host_list_until_its_reset, idle_lists_nobody_takes_are_let_go, taking_out_the_oldest_keeps_the_pools_counts).
    • list::thin::tests::*: 4/4 passed (uploads_of_words_never_handed_over_are_given_back).
    • pipeline::tests::*: 4/4 passed (translated_shaders_let_their_containers_go, pipelines_of_one_graphics_state_share_it).
    • pipeline::library::tests::*: 15/15 passed (a_library_is_reused_only_for_the_same_shaders, a_library_saved_for_other_shaders_is_not_opened, a_save_writes_its_fingerprint_with_the_library, overlapping_saves_leave_one_whole_library_and_its_lists, the_early_list_keeps_the_last_two_runs).
    • resource::tests::replaced_copies_go_with_the_sweep_off (1/1), shadow::snapshot_pool_tests::* (1/1), shadow::exact_spare_tests::* (1/1), texture::read_buffer_tests::* (2/2): 5/5 passed.
  • leonida-hle (default with test_alloc & --features diagnostics):
    • modules::apu::tests::*: 3/3 passed (packets_decode_without_memory_of_their_own under shared test_alloc).
    • modules::dstorage::tests::*: 21/21 passed in default (compressed_requests_reuse_the_workers_buffers under shared test_alloc, a_worker_keeps_its_buffers_up_to_a_bound, staging_counts_every_buffer_a_request_holds) + 20/20 passed under --features diagnostics.
    • modules::xasync::tests::*: 15/15 passed (pool_workers_stay_few_in_a_burst_of_short_callbacks, pool_workers_left_idle_leave_under_a_trickle_of_callbacks, pool_callbacks_queued_together_may_wait_for_each_other).
    • modules::xmem::tests::*: 22/22 passed (free_default_tells_the_gpu_side_of_32bit_memory).
  • leonida & Docs/Policy:
    • cargo test --locked -p leonida: 40/40 passed (36 unit + 2 agility + 2 census).
    • tests/test_docs_*.py (56/56 OK) and scripts/check_no_game_data.py (rc=0).

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7246171846 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7246171846). Originally posted by [zmasi](https://github.com/zmasi) on 2026-11-28T21:39:03Z. --- ### Native Windows 11 + NVIDIA GeForce RTX 3090 Verification (`d3d12/` Rust Head `962bc1601b`) Verified the updated head `962bc1601b37be431f7417840dfa6adc85408224` merged cleanly onto `origin/main` (`aa918e5d9f9e2f03e078d8f08854324890b5e176`, `git merge-tree --write-tree` `rc=0`) on native **Windows 11 (`26200`) + NVIDIA GeForce RTX 3090 (driver `610.88`)**, covering the 6 Rust `d3d12/` leak-remediation additions landed after `9fc3ad427c` (`RS-HOST-LIST-SCRATCH-TRIM`, `RS-PIPELINE-LIBRARY-FINGERPRINT`, `RS-ARENA-ONE-COPY`, `RS-SHADER-CONTAINER-FREE`, `RS-DSTORAGE-SCRATCH`, and shared `test_alloc` counting allocator) alongside all earlier `d3d12/` suites. #### 1. Red -> Green Hardware Reproduction (`RS-ARENA-ONE-COPY` on RTX 3090) - **Red (`origin/main` `aa918e5d9f`)**: Probed `Memory::another()` across 3 consecutive 64 MiB arenas on RTX 3090 (`ID3D12Device3::OpenExistingHeapFromAddress` supported): each 64 MiB arena added **`192 MiB` of process commit** (`128 MiB` beside its `64 MiB` GPU side: `64 MiB` `upload::reserve` + duplicate `64 MiB` `UPLOAD` `shared_buffer`), failing `grew < card + ARENA + ARENA / 2`. - **Green (`origin/main + 962bc1601b`)**: `memory::tests::an_arena_is_in_the_pcs_memory_once` passed (`4/4` `memory::tests` green): each 64 MiB arena added **`128 MiB` total commit** (`64 MiB` GPU side + `64 MiB` CPU arena, **`64 MiB` less commit per arena**), `card_data() == at` for all 3 arenas (`by_address_opened` via `inplace::place_part`), and `an_arena_sends_up_only_the_dwords_the_title_changed` confirmed dword-granular dirty-run uploads leave untouched GPU-written dwords intact. #### 2. `d3d12/` Test Suites Executed (`100%` Green) - **`leonida-gpu` (`default` & `--features diagnostics`, RTX 3090 D3D12)**: - `memory::tests::*`: **`4/4` passed** (`an_arena_is_in_the_pcs_memory_once`, `an_arena_sends_up_only_the_dwords_the_title_changed`, `a_piece_takes_what_changed`, `a_packed_structure_is_known_by_its_header`). - `list::tests::*`: **`10/10` passed** (`an_idle_list_lets_go_of_a_large_indirect_scratch` in both default and `--features diagnostics`, `a_submitted_list_keeps_no_host_list_until_its_reset`, `idle_lists_nobody_takes_are_let_go`, `taking_out_the_oldest_keeps_the_pools_counts`). - `list::thin::tests::*`: **`4/4` passed** (`uploads_of_words_never_handed_over_are_given_back`). - `pipeline::tests::*`: **`4/4` passed** (`translated_shaders_let_their_containers_go`, `pipelines_of_one_graphics_state_share_it`). - `pipeline::library::tests::*`: **`15/15` passed** (`a_library_is_reused_only_for_the_same_shaders`, `a_library_saved_for_other_shaders_is_not_opened`, `a_save_writes_its_fingerprint_with_the_library`, `overlapping_saves_leave_one_whole_library_and_its_lists`, `the_early_list_keeps_the_last_two_runs`). - `resource::tests::replaced_copies_go_with_the_sweep_off` (`1/1`), `shadow::snapshot_pool_tests::*` (`1/1`), `shadow::exact_spare_tests::*` (`1/1`), `texture::read_buffer_tests::*` (`2/2`): **`5/5` passed**. - **`leonida-hle` (`default` with `test_alloc` & `--features diagnostics`)**: - `modules::apu::tests::*`: **`3/3` passed** (`packets_decode_without_memory_of_their_own` under shared `test_alloc`). - `modules::dstorage::tests::*`: **`21/21` passed** in default (`compressed_requests_reuse_the_workers_buffers` under shared `test_alloc`, `a_worker_keeps_its_buffers_up_to_a_bound`, `staging_counts_every_buffer_a_request_holds`) + **`20/20` passed** under `--features diagnostics`. - `modules::xasync::tests::*`: **`15/15` passed** (`pool_workers_stay_few_in_a_burst_of_short_callbacks`, `pool_workers_left_idle_leave_under_a_trickle_of_callbacks`, `pool_callbacks_queued_together_may_wait_for_each_other`). - `modules::xmem::tests::*`: **`22/22` passed** (`free_default_tells_the_gpu_side_of_32bit_memory`). - **`leonida` & Docs/Policy**: - `cargo test --locked -p leonida`: **`40/40` passed** (`36` unit + `2` `agility` + `2` `census`). - `tests/test_docs_*.py` (`56/56` `OK`) and `scripts/check_no_game_data.py` (`rc=0`). AI-assisted.
adrianmjim commented 2026-11-29 11:34:10 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-29T11:34:10Z.


Second sweep in d3d12/: the cost of the card's and the PC's memory being apart

Twenty-five more items in the Rust runtime, pushed to this pull request's branch (leaks/all) at 26e00403c, which also merges current main. Claimed in #2570 (round 1) and #2570 (round 2); the claims say what was wrong in each, with file and line. Each is its own merge here and its own branch adrianmjim/leonida:unified/<name>, each fix with a test that fails without it.

Branch Items What is now true
send-pool-trim RS-SEND-POOL-TRIM, RS-FETCH-SHRINK send memory made to within 1/8 of each send and given back when idle, released outside the lock (LEONIDA_SEND_TRIM=0); fetch buffers shrink after a window of small fetches (LEONIDA_FETCH_SHRINK=0)
compare-ring RS-COMPARE-RING the card compare's results are a ring: a submission sent ahead no longer drains the card for room (LEONIDA_COMPARE_RING=0)
landed-cells-gate RS-LANDED-CELLS-GATE landed cells are kept only in a run that can ask for them
small-leaks RS-WALLS-FILES-DROP, RS-VALUE-WAITS-RELEASE, RS-HEAP-SPANS-PRUNE the walls trace keeps no list of every file; a list released unsubmitted takes its value waits; a host heap that goes leaves PLACED_SPANS and GPU_RANGES (the branch's arena commits are taken back here: that part is D3D12-RT-FG-ARENA-VA-STORM)
placed-textures RS-PLACED-SWEEP-GONE-COPIES, RS-PLACED-EVICT the look by age skips gone copies; placed textures nothing names and without a host copy are released
texture-staging-release RS-TEXTURE-STAGING-RELEASE, RS-MOVIE-PLANE-STAGING a texture's staging bytes go once its copy is recorded (LEONIDA_STAGING_RELEASE=0); video planes get no staging and are copied when changed
descriptor-views RS-VIEW-TABLE-BOUND addressed view entries are bounded by a clock that never lets go of one a live slot names (LEONIDA_VIEW_ADDRESSED_MOST=0); resource views kept without padding words (LEONIDA_VIEW_NORMAL=0)
inplace-free RS-INPLACE-FREE, RS-PLACEHOLDER-RELEASE the title's VirtualFree of memory in place succeeds once the heap is gone; a split placeholder reservation is released whole
placement-bench RS-PLACEMENT-BENCH-AMD an ignored device test measures placements; the RX 7900 XT table is in d3d12/docs/findings.md
card-one-copy RS-SEND-DIRECT a byte the title wrote into a copy on the card is copied once on the CPU: long runs go up straight out of the copy's CPU side (LEONIDA_SEND_DIRECT=0)
inplace-blockers RS-INPLACE-PROTECT VirtualProtect of memory in place, slots over freed memory, fixed-address reservations over a pending release (LEONIDA_INPLACE_PROTECT, _SLOTS, _RESERVE); LEONIDA_INPLACE stays off
page-pool-open RS-SECTION-MB-DEFAULT, RS-SECTION-COMMIT physical pages in sections of 16 MiB by default (LEONIDA_SECTION_MB=0); committed sections at first touch, off by default (LEONIDA_SECTION_COMMIT=1)
shadow-hot-paths RS-SNAPSHOT-DECLARED, RS-CARDED-INDEX snapshots hold only declared pieces; card copies found by address; pending ranges searched
exact-waits RS-EXACT-WAIT value and blocking fence waits under the relay end when the flights that matter have landed (LEONIDA_EXACT_WAIT=0)
physical-reuse RS-PHYSICAL-REUSE freed physical pages given out again, zeroed; numbers below 2^25 reused; waiting pages discarded (LEONIDA_PHYSICAL_REUSE=0, LEONIDA_PHYSICAL_DISCARD=0)
title-alloc-watch RS-TITLE-ALLOC-WATCH, RS-WORKING-SET-STATS large XMemAllocDefault blocks and CreateHeap heaps are write-watched; XMemGetWorkingSetStatistics reports the title's own use
xmem-combined (merge) physical-reuse and title-alloc-watch merged with page-pool-open's sections, and a test of reuse with committed sections

Measured on the RX 7900 XT without the game (host::placement, details in findings.md): the card reads the PC's memory at 23 to 28 GB/s from upload, custom L0 write-back and memory opened with OpenExistingHeapFromAddress alike, so sending straight out of a write-back CPU side or reading title memory in place costs the card nothing over the upload ring here, and saves the CPU a copy. Resizable BAR is off on this PC, so D3D12_HEAP_TYPE_GPU_UPLOAD was not measured yet.

Tested

cargo test -p leonida-gpu --lib -- --test-threads=4: 630 passed, 0 failed, 48 ignored (548 on the first sweep's head). cargo test -p leonida-hle --lib: 243 passed, 0 failed, 2 ignored (219 before). cargo check --workspace --all-targets clean. Device tests on the RX 7900 XT and on WARP; synthetic inputs only, no game files. Not run with the game: the frame line has new counters (send memory held and spare, sends straight and their waits, settles for room in the compare's results) to measure each in a session. Two timing tests outside these changes (xasync pool workers, a dstorage 20 ms retry) fail now and then on a loaded machine.

GPU: AMD Radeon RX 7900 XT 20 GB, driver 32.0.32029.2010, Windows 11 Pro 26300.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7255200827 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7255200827). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-29T11:34:10Z. --- ### Second sweep in `d3d12/`: the cost of the card's and the PC's memory being apart Twenty-five more items in the Rust runtime, pushed to this pull request's branch (`leaks/all`) at `26e00403c`, which also merges current `main`. Claimed in [#2570 (round 1)](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7254924718) and [#2570 (round 2)](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7254925059); the claims say what was wrong in each, with file and line. Each is its own merge here and its own branch `adrianmjim/leonida:unified/<name>`, each fix with a test that fails without it. | Branch | Items | What is now true | |---|---|---| | `send-pool-trim` | `RS-SEND-POOL-TRIM`, `RS-FETCH-SHRINK` | send memory made to within 1/8 of each send and given back when idle, released outside the lock (`LEONIDA_SEND_TRIM=0`); fetch buffers shrink after a window of small fetches (`LEONIDA_FETCH_SHRINK=0`) | | `compare-ring` | `RS-COMPARE-RING` | the card compare's results are a ring: a submission sent ahead no longer drains the card for room (`LEONIDA_COMPARE_RING=0`) | | `landed-cells-gate` | `RS-LANDED-CELLS-GATE` | landed cells are kept only in a run that can ask for them | | `small-leaks` | `RS-WALLS-FILES-DROP`, `RS-VALUE-WAITS-RELEASE`, `RS-HEAP-SPANS-PRUNE` | the walls trace keeps no list of every file; a list released unsubmitted takes its value waits; a host heap that goes leaves `PLACED_SPANS` and `GPU_RANGES` (the branch's arena commits are taken back here: that part is `D3D12-RT-FG-ARENA-VA-STORM`) | | `placed-textures` | `RS-PLACED-SWEEP-GONE-COPIES`, `RS-PLACED-EVICT` | the look by age skips gone copies; placed textures nothing names and without a host copy are released | | `texture-staging-release` | `RS-TEXTURE-STAGING-RELEASE`, `RS-MOVIE-PLANE-STAGING` | a texture's staging bytes go once its copy is recorded (`LEONIDA_STAGING_RELEASE=0`); video planes get no staging and are copied when changed | | `descriptor-views` | `RS-VIEW-TABLE-BOUND` | addressed view entries are bounded by a clock that never lets go of one a live slot names (`LEONIDA_VIEW_ADDRESSED_MOST=0`); resource views kept without padding words (`LEONIDA_VIEW_NORMAL=0`) | | `inplace-free` | `RS-INPLACE-FREE`, `RS-PLACEHOLDER-RELEASE` | the title's `VirtualFree` of memory in place succeeds once the heap is gone; a split placeholder reservation is released whole | | `placement-bench` | `RS-PLACEMENT-BENCH-AMD` | an ignored device test measures placements; the RX 7900 XT table is in `d3d12/docs/findings.md` | | `card-one-copy` | `RS-SEND-DIRECT` | a byte the title wrote into a copy on the card is copied once on the CPU: long runs go up straight out of the copy's CPU side (`LEONIDA_SEND_DIRECT=0`) | | `inplace-blockers` | `RS-INPLACE-PROTECT` | `VirtualProtect` of memory in place, slots over freed memory, fixed-address reservations over a pending release (`LEONIDA_INPLACE_PROTECT`, `_SLOTS`, `_RESERVE`); `LEONIDA_INPLACE` stays off | | `page-pool-open` | `RS-SECTION-MB-DEFAULT`, `RS-SECTION-COMMIT` | physical pages in sections of 16 MiB by default (`LEONIDA_SECTION_MB=0`); committed sections at first touch, off by default (`LEONIDA_SECTION_COMMIT=1`) | | `shadow-hot-paths` | `RS-SNAPSHOT-DECLARED`, `RS-CARDED-INDEX` | snapshots hold only declared pieces; card copies found by address; pending ranges searched | | `exact-waits` | `RS-EXACT-WAIT` | value and blocking fence waits under the relay end when the flights that matter have landed (`LEONIDA_EXACT_WAIT=0`) | | `physical-reuse` | `RS-PHYSICAL-REUSE` | freed physical pages given out again, zeroed; numbers below 2^25 reused; waiting pages discarded (`LEONIDA_PHYSICAL_REUSE=0`, `LEONIDA_PHYSICAL_DISCARD=0`) | | `title-alloc-watch` | `RS-TITLE-ALLOC-WATCH`, `RS-WORKING-SET-STATS` | large `XMemAllocDefault` blocks and `CreateHeap` heaps are write-watched; `XMemGetWorkingSetStatistics` reports the title's own use | | `xmem-combined` | (merge) | `physical-reuse` and `title-alloc-watch` merged with `page-pool-open`'s sections, and a test of reuse with committed sections | **Measured on the RX 7900 XT without the game** (`host::placement`, details in `findings.md`): the card reads the PC's memory at 23 to 28 GB/s from upload, custom L0 write-back and memory opened with `OpenExistingHeapFromAddress` alike, so sending straight out of a write-back CPU side or reading title memory in place costs the card nothing over the upload ring here, and saves the CPU a copy. Resizable BAR is off on this PC, so `D3D12_HEAP_TYPE_GPU_UPLOAD` was not measured yet. ### Tested `cargo test -p leonida-gpu --lib -- --test-threads=4`: 630 passed, 0 failed, 48 ignored (548 on the first sweep's head). `cargo test -p leonida-hle --lib`: 243 passed, 0 failed, 2 ignored (219 before). `cargo check --workspace --all-targets` clean. Device tests on the RX 7900 XT and on WARP; synthetic inputs only, no game files. Not run with the game: the frame line has new counters (send memory held and spare, sends straight and their waits, settles for room in the compare's results) to measure each in a session. Two timing tests outside these changes (`xasync` pool workers, a `dstorage` 20 ms retry) fail now and then on a loaded machine. GPU: AMD Radeon RX 7900 XT 20 GB, driver 32.0.32029.2010, Windows 11 Pro 26300.
adrianmjim commented 2026-11-29 12:48:07 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-29T12:48:07Z.


Third round in d3d12/ (pushed at 19006b0e6)

Seven more branches, claimed in #2570, each its own merge here and its own branch adrianmjim/leonida:unified/<name>, each fix with a test that fails without it.

Branch Item What is now true
land-same-submission RS-LAND-IN-SUBMISSION with the relay, what shaders wrote to card copies can come down in the submission that wrote it: the compare's flagged pieces are compacted on the card into a landing buffer and merged behind each plan's own send, no fetch list and no wait of its own (LEONIDA_LAND_IN_SUBMISSION=1, off by default)
settle-and-line RS-SWEEP-NO-SETTLE, RS-LINE-HOLDS the sweep no longer settles every flight every 1.5 s (LEONIDA_SWEEP_NO_SETTLE=0: as before); waits for landings look at steps outside the line's lock, what flights may write is kept counted one pass per flight, declared ranges merge by table (LEONIDA_LINE_COVER, LEONIDA_LINE_APART)
texture-detile-changed RS-TEXTURE-DETILE-CHANGED a write-watched texture is detiled and copied only in the subresources its written pages hold (LEONIDA_TEXTURE_PARTS); detiling straight from title memory (LEONIDA_TEXTURE_WATCHED_IN_PLACE=1, off); read-backs tiled straight out of the mapped buffer (LEONIDA_TEXBACK_MAPPED)
inplace-coverage RS-INPLACE-COVERAGE with LEONIDA_INPLACE: windows kept only in the PC's memory opened in place, runtime memory not copied as title memory (LEONIDA_INPLACE_OURS), committed sections of physical pages read in place (LEONIDA_INPLACE_SECTIONS)
rebar-paths RS-BAR-BUFFERS small buffers read often and never written can have their card side in GPU upload memory (LEONIDA_BAR_BUFFERS_MB=N, off); the log says whether resizable BAR is on and its window size
hot-path-bookkeeping RS-HOT-PATH-BOOKKEEPING no O(n) retain over HOST_WRITTEN_AT per release; diagnostics' copy maps lock per thread set
inplace-flake (fix of RS-INPLACE-FREE) a hold let go of is forgotten over memory the host freed: Windows gives the same addresses out again at once, and the old record made a later decommit of new memory there come out committed (found as a test failing 1 run in 5; 15 of 15 runs pass now)

Also: d17b3e2b3 (a closed section's record removed from Views.sections) is taken back in favour of zmasi's D3D12-GPU-INPLACE-VIEW-ALIAS-AND-SECTION-LIFETIME, which claimed it first. One switch name was changed during the merge: the landing in the submission first used LEONIDA_LAND_SAME, which land.rs already uses for something else.

Tested

cargo test -p leonida-gpu --lib -- --test-threads=4: 690 passed, 0 failed, 50 ignored (three runs in a row). cargo test -p leonida-hle --lib: 243 passed, 2 ignored. cargo check --workspace --all-targets, and leonida-gpu with diagnostics, clean. Device tests on the RX 7900 XT (driver 32.0.32029.2010) and WARP, synthetic inputs only; nothing run with the game. Resizable BAR is still off on this PC, so the GPU upload paths were tested on WARP only.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7256073326 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7256073326). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-29T12:48:07Z. --- ### Third round in `d3d12/` (pushed at `19006b0e6`) Seven more branches, claimed in [#2570](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7255807027), each its own merge here and its own branch `adrianmjim/leonida:unified/<name>`, each fix with a test that fails without it. | Branch | Item | What is now true | |---|---|---| | `land-same-submission` | `RS-LAND-IN-SUBMISSION` | with the relay, what shaders wrote to card copies can come down in the submission that wrote it: the compare's flagged pieces are compacted on the card into a landing buffer and merged behind each plan's own send, no fetch list and no wait of its own (`LEONIDA_LAND_IN_SUBMISSION=1`, off by default) | | `settle-and-line` | `RS-SWEEP-NO-SETTLE`, `RS-LINE-HOLDS` | the sweep no longer settles every flight every 1.5 s (`LEONIDA_SWEEP_NO_SETTLE=0`: as before); waits for landings look at steps outside the line's lock, what flights may write is kept counted one pass per flight, declared ranges merge by table (`LEONIDA_LINE_COVER`, `LEONIDA_LINE_APART`) | | `texture-detile-changed` | `RS-TEXTURE-DETILE-CHANGED` | a write-watched texture is detiled and copied only in the subresources its written pages hold (`LEONIDA_TEXTURE_PARTS`); detiling straight from title memory (`LEONIDA_TEXTURE_WATCHED_IN_PLACE=1`, off); read-backs tiled straight out of the mapped buffer (`LEONIDA_TEXBACK_MAPPED`) | | `inplace-coverage` | `RS-INPLACE-COVERAGE` | with `LEONIDA_INPLACE`: windows kept only in the PC's memory opened in place, runtime memory not copied as title memory (`LEONIDA_INPLACE_OURS`), committed sections of physical pages read in place (`LEONIDA_INPLACE_SECTIONS`) | | `rebar-paths` | `RS-BAR-BUFFERS` | small buffers read often and never written can have their card side in GPU upload memory (`LEONIDA_BAR_BUFFERS_MB=N`, off); the log says whether resizable BAR is on and its window size | | `hot-path-bookkeeping` | `RS-HOT-PATH-BOOKKEEPING` | no O(n) retain over `HOST_WRITTEN_AT` per release; diagnostics' copy maps lock per thread set | | `inplace-flake` | (fix of `RS-INPLACE-FREE`) | a hold let go of is forgotten over memory the host freed: Windows gives the same addresses out again at once, and the old record made a later decommit of new memory there come out committed (found as a test failing 1 run in 5; 15 of 15 runs pass now) | Also: `d17b3e2b3` (a closed section's record removed from `Views.sections`) is taken back in favour of zmasi's `D3D12-GPU-INPLACE-VIEW-ALIAS-AND-SECTION-LIFETIME`, which claimed it first. One switch name was changed during the merge: the landing in the submission first used `LEONIDA_LAND_SAME`, which `land.rs` already uses for something else. ### Tested `cargo test -p leonida-gpu --lib -- --test-threads=4`: 690 passed, 0 failed, 50 ignored (three runs in a row). `cargo test -p leonida-hle --lib`: 243 passed, 2 ignored. `cargo check --workspace --all-targets`, and `leonida-gpu` with `diagnostics`, clean. Device tests on the RX 7900 XT (driver 32.0.32029.2010) and WARP, synthetic inputs only; nothing run with the game. Resizable BAR is still off on this PC, so the GPU upload paths were tested on WARP only.
adrianmjim commented 2026-11-29 14:32:49 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-29T14:32:49Z.


Fourth round in d3d12/ (pushed at 7cc8e1879)

Claimed in #2570. Each is its own merge here and its own branch adrianmjim/leonida:unified/<name>, each fix with a test that fails without it.

Branch Item What is now true
card-from-title RS-CARD-FROM-TITLE a big title buffer's card copy can have its title memory, opened as a heap, as its CPU side: no staging buffer in RAM, and refreshes copy nothing on the CPU (the card copies the dirty runs straight out of title memory). A later write declaration gives it a CPU side of its own; a title free or protection under it lets go of the heap first (LEONIDA_CARD_FROM_TITLE=1, off by default)
inplace-async-open RS-INPLACE-ASYNC with LEONIDA_INPLACE, private title memory is opened by a thread of its own, the copy serving until then and switched at a safe point (LEONIDA_INPLACE_ASYNC); a page whose protection the title gave back is opened again (LEONIDA_INPLACE_AGAIN); XMemVirtualQuery reports what the title asked for (LEONIDA_INPLACE_QUERY); a reservation over a pending release does it first (LEONIDA_INPLACE_RELEASE_FIRST). LEONIDA_INPLACE stays off
send-ring RS-SEND-RING send memory is carved per submission from a ring of mapped upload buffers, space coming back in fence order (LEONIDA_SEND_RING)
compare-cost RS-COMPARE-COST the card's compare is measured (table in findings.md: about 1.7 us a declared MiB at 600 GB/s cold, 0.45 ms for 256 MiB); neighbouring declared ranges in one 64 KiB piece share one pass and one hash (LEONIDA_CARD_COMPARE_SHARE: 12,289 passes become 1 for 16,384 small views of a 256 MiB copy)
steps-at-close RS-CLOSE-SUMMARY what a submission needs of a list's steps is summarised at the list's close on its recording thread, so the submission walks it once (LEONIDA_CLOSE_SUMMARY=0: as before; =check compares both)
suite-stable (tests) tests release their title memory through the runtime's path, so let-go holds and pending releases of one test do not lie over the next test's memory
double-release (fix of RS-INPLACE-FREE) a second release of title memory whose first release is kept for a heap is refused as one of free memory (ERROR_INVALID_ADDRESS) and noted once: before, the note left over released whatever the host gave out at that address next (seen in the suite: a reservation released three times, then an access violation)

Tested

cargo test -p leonida-gpu --lib -- --test-threads=4: 718 passed, 0 failed, 51 ignored, five runs in a row. cargo test -p leonida-hle --lib: 245 passed, 2 ignored. cargo check --workspace --all-targets and leonida-gpu with diagnostics clean. Device tests on the RX 7900 XT (driver 32.0.32029.2010) and WARP, synthetic inputs only; nothing run with the game.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7257387207 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7257387207). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-29T14:32:49Z. --- ### Fourth round in `d3d12/` (pushed at `7cc8e1879`) Claimed in [#2570](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7256212954). Each is its own merge here and its own branch `adrianmjim/leonida:unified/<name>`, each fix with a test that fails without it. | Branch | Item | What is now true | |---|---|---| | `card-from-title` | `RS-CARD-FROM-TITLE` | a big title buffer's card copy can have its title memory, opened as a heap, as its CPU side: no staging buffer in RAM, and refreshes copy nothing on the CPU (the card copies the dirty runs straight out of title memory). A later write declaration gives it a CPU side of its own; a title free or protection under it lets go of the heap first (`LEONIDA_CARD_FROM_TITLE=1`, off by default) | | `inplace-async-open` | `RS-INPLACE-ASYNC` | with `LEONIDA_INPLACE`, private title memory is opened by a thread of its own, the copy serving until then and switched at a safe point (`LEONIDA_INPLACE_ASYNC`); a page whose protection the title gave back is opened again (`LEONIDA_INPLACE_AGAIN`); `XMemVirtualQuery` reports what the title asked for (`LEONIDA_INPLACE_QUERY`); a reservation over a pending release does it first (`LEONIDA_INPLACE_RELEASE_FIRST`). `LEONIDA_INPLACE` stays off | | `send-ring` | `RS-SEND-RING` | send memory is carved per submission from a ring of mapped upload buffers, space coming back in fence order (`LEONIDA_SEND_RING`) | | `compare-cost` | `RS-COMPARE-COST` | the card's compare is measured (table in `findings.md`: about 1.7 us a declared MiB at 600 GB/s cold, 0.45 ms for 256 MiB); neighbouring declared ranges in one 64 KiB piece share one pass and one hash (`LEONIDA_CARD_COMPARE_SHARE`: 12,289 passes become 1 for 16,384 small views of a 256 MiB copy) | | `steps-at-close` | `RS-CLOSE-SUMMARY` | what a submission needs of a list's steps is summarised at the list's close on its recording thread, so the submission walks it once (`LEONIDA_CLOSE_SUMMARY=0`: as before; `=check` compares both) | | `suite-stable` | (tests) | tests release their title memory through the runtime's path, so let-go holds and pending releases of one test do not lie over the next test's memory | | `double-release` | (fix of `RS-INPLACE-FREE`) | a second release of title memory whose first release is kept for a heap is refused as one of free memory (`ERROR_INVALID_ADDRESS`) and noted once: before, the note left over released whatever the host gave out at that address next (seen in the suite: a reservation released three times, then an access violation) | ### Tested `cargo test -p leonida-gpu --lib -- --test-threads=4`: 718 passed, 0 failed, 51 ignored, five runs in a row. `cargo test -p leonida-hle --lib`: 245 passed, 2 ignored. `cargo check --workspace --all-targets` and `leonida-gpu` with `diagnostics` clean. Device tests on the RX 7900 XT (driver 32.0.32029.2010) and WARP, synthetic inputs only; nothing run with the game.
adrianmjim commented 2026-11-29 15:16:56 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-29T15:16:56Z.


Fifth round in d3d12/ (pushed at 6737559d3)

Claimed in #2570. Each is its own merge here and its own branch adrianmjim/leonida:unified/<name>, each fix with a test that fails without it.

Branch Item What is now true
inplace-title-alloc RS-INPLACE-TITLE-ALLOC the title's own VirtualAlloc, VirtualAllocEx and VirtualProtectEx go through the runtime's glue, as VirtualFree and VirtualProtect did: a fixed-address reservation or commit into a release kept for a heap does that release first, and a protection of memory in place waits for its heap (LEONIDA_INPLACE_TITLE_ALLOC=0: bound to the host's calls, as before). XMemVirtualQuery tells a decommit kept committed and zeroed under a heap as reserved memory, within its own allocation, until the title commits it again (LEONIDA_INPLACE_QUERY_DECOMMITS). LEONIDA_INPLACE stays off
card-from-title-windows RS-CARD-FROM-TITLE-WINDOWS with LEONIDA_CARD_FROM_TITLE=1, card windows of title memory outside buffers have the title memory as their CPU side too: no second buffer in the PC's memory and no CPU copy of what the title wrote (LEONIDA_CARD_FROM_TITLE_WINDOWS=0: a side of their own)
spare-sampler-bounds RS-SPARE-TAKE-BOUND, RS-SAMPLER-ENTRIES-BOUND an allocation looks only at the freed runs it gives, longest first, when enough wait free of views; sampler entries of the view table go round the same clock as the addressed ones, never one a live slot names (LEONIDA_VIEW_SAMPLERS_BOUND=0: kept for the run)

Still not shimmed, for whoever has the import list: NtProtectVirtualMemory, NtAllocateVirtualMemory, VirtualAlloc2 and kernel32 VirtualQuery (nothing in the repository says whether the title imports them).

Tested

cargo test -p leonida-gpu --lib -- --test-threads=4: 731 passed, 0 failed, 51 ignored, three runs in a row. cargo test -p leonida-hle --lib: 250 passed, 2 ignored. cargo check --workspace --all-targets clean. Device tests on the RX 7900 XT (driver 32.0.32029.2010) and WARP, synthetic inputs only; nothing run with the game.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7257964946 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7257964946). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-29T15:16:56Z. --- ### Fifth round in `d3d12/` (pushed at `6737559d3`) Claimed in [#2570](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7257394728). Each is its own merge here and its own branch `adrianmjim/leonida:unified/<name>`, each fix with a test that fails without it. | Branch | Item | What is now true | |---|---|---| | `inplace-title-alloc` | `RS-INPLACE-TITLE-ALLOC` | the title's own `VirtualAlloc`, `VirtualAllocEx` and `VirtualProtectEx` go through the runtime's glue, as `VirtualFree` and `VirtualProtect` did: a fixed-address reservation or commit into a release kept for a heap does that release first, and a protection of memory in place waits for its heap (`LEONIDA_INPLACE_TITLE_ALLOC=0`: bound to the host's calls, as before). `XMemVirtualQuery` tells a decommit kept committed and zeroed under a heap as reserved memory, within its own allocation, until the title commits it again (`LEONIDA_INPLACE_QUERY_DECOMMITS`). `LEONIDA_INPLACE` stays off | | `card-from-title-windows` | `RS-CARD-FROM-TITLE-WINDOWS` | with `LEONIDA_CARD_FROM_TITLE=1`, card windows of title memory outside buffers have the title memory as their CPU side too: no second buffer in the PC's memory and no CPU copy of what the title wrote (`LEONIDA_CARD_FROM_TITLE_WINDOWS=0`: a side of their own) | | `spare-sampler-bounds` | `RS-SPARE-TAKE-BOUND`, `RS-SAMPLER-ENTRIES-BOUND` | an allocation looks only at the freed runs it gives, longest first, when enough wait free of views; sampler entries of the view table go round the same clock as the addressed ones, never one a live slot names (`LEONIDA_VIEW_SAMPLERS_BOUND=0`: kept for the run) | Still not shimmed, for whoever has the import list: `NtProtectVirtualMemory`, `NtAllocateVirtualMemory`, `VirtualAlloc2` and kernel32 `VirtualQuery` (nothing in the repository says whether the title imports them). ### Tested `cargo test -p leonida-gpu --lib -- --test-threads=4`: 731 passed, 0 failed, 51 ignored, three runs in a row. `cargo test -p leonida-hle --lib`: 250 passed, 2 ignored. `cargo check --workspace --all-targets` clean. Device tests on the RX 7900 XT (driver 32.0.32029.2010) and WARP, synthetic inputs only; nothing run with the game.
fiestorra commented 2026-11-29 17:38:55 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-11-29T17:38:55Z.


Mechanical note, no review: this branch conflicts with main (4364a4fa6) on a rebase, and the conflict is smaller than it sounds.

git merge-tree --write-tree origin/main refs/pull/2569/head reports 3 conflicted file(s):

  • d3d12/crates/leonida-gpu/src/texback.rs
  • d3d12/crates/leonida-gpu/src/texture.rs
  • runtime/shims/d3d12_vulkan_device.cpp

The last one is the file most pull requests trip over, so it may be worth rebasing after whatever else touches d3d12_vulkan_device.cpp lands.

So a rebase is all it needs - the change itself may well be fine, I have not looked at its content, only at whether git can apply it.

Written with an AI assistant.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7259855257 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7259855257). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-11-29T17:38:55Z. --- Mechanical note, no review: this branch **conflicts with `main`** (`4364a4fa6`) on a rebase, and the conflict is smaller than it sounds. `git merge-tree --write-tree origin/main refs/pull/2569/head` reports **3** conflicted file(s): - `d3d12/crates/leonida-gpu/src/texback.rs` - `d3d12/crates/leonida-gpu/src/texture.rs` - `runtime/shims/d3d12_vulkan_device.cpp` The last one is the file most pull requests trip over, so it may be worth rebasing after whatever else touches `d3d12_vulkan_device.cpp` lands. So a rebase is all it needs - the change itself may well be fine, I have not looked at its content, only at whether git can apply it. Written with an AI assistant.
adrianmjim commented 2026-11-29 20:39:41 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-29T20:39:41Z.


Thanks, @fiestorra. GitHub's own 'This branch has conflicts' banner had already broken the news, but it is reassuring to see git merge-tree agree with it. Current main is merged in now, conflicts resolved.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7262257703 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7262257703). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-29T20:39:41Z. --- Thanks, @fiestorra. GitHub's own 'This branch has conflicts' banner had already broken the news, but it is reassuring to see `git merge-tree` agree with it. Current `main` is merged in now, conflicts resolved.
MoonEyes commented 2026-11-29 21:54:25 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-11-29T21:54:25Z.


Tested ca6f10dfb merged (no commit) with main 060c47160: Windows 11, Rust toolchain from d3d12/rust-toolchain.toml, CPU only, no game run.

  • cargo test -p leonida -p leonida-gpu -p leonida-hle --locked: main 809 passed, 49 ignored; with this PR 1042 passed, 53 ignored, 0 failed.
  • cargo clippy -p leonida -p leonida-gpu -p leonida-hle --locked -- -D warnings: 10 findings on main and the same 10 with the PR (all in leonida-lua and leonida-shader); this PR adds none.
  • Merges cleanly with main, but merging it would force a rebase of #2566 (git merge-tree conflicts). Under the current merge freeze it should wait until #2566 lands, then be rebased.
  • Not covered: an in-game run. It touches the render path, so before merge it should also run in game for 300 s with no device loss, as this project now asks of render-path changes.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7263247046 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7263247046). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-11-29T21:54:25Z. --- Tested `ca6f10dfb` merged (no commit) with `main` `060c47160`: Windows 11, Rust toolchain from `d3d12/rust-toolchain.toml`, CPU only, no game run. - `cargo test -p leonida -p leonida-gpu -p leonida-hle --locked`: `main` 809 passed, 49 ignored; with this PR 1042 passed, 53 ignored, 0 failed. - `cargo clippy -p leonida -p leonida-gpu -p leonida-hle --locked -- -D warnings`: 10 findings on `main` and the same 10 with the PR (all in `leonida-lua` and `leonida-shader`); this PR adds none. - Merges cleanly with `main`, but merging it would force a rebase of #2566 (`git merge-tree` conflicts). Under the current merge freeze it should wait until #2566 lands, then be rebased. - Not covered: an in-game run. It touches the render path, so before merge it should also run in game for 300 s with no device loss, as this project now asks of render-path changes. AI-assisted (Claude Code).
adrianmjim commented 2026-11-29 22:09:15 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-29T22:09:15Z.


Sixth round in d3d12/ (pushed at 8f5f02d80), with current main merged

Claimed in #2570. This round comes from measuring the running title on an RX 7900 XT (the new section at the end of d3d12/docs/findings.md): there the frame is held by the submitting thread, and most of its time goes on keeping title memory and its host copies in step. Each item is its own merge and its own branch adrianmjim/leonida:unified/<name>, each fix with a test that fails without it.

Branch Item What is now true
placed-unmapped-release RS-PLACED-UNMAPPED-RELEASE host copies of placed textures whose title memory the title unmapped, and that no slot or list names, are let go by the sweep (LEONIDA_PLACED_UNMAPPED=0: kept to the card's idle time)
refresh-nothing-fast RS-REFRESH-NOTHING-FAST refreshes known to copy nothing are sorted out on the submitting thread before any worker is woken (LEONIDA_LOOK_FIRST), and a range whose end pages were written only beside it is known to copy nothing (LEONIDA_LOOK_PARTS)
heap-records-wait RS-HEAP-RECORDS-WAIT the pass ahead of a frame can look at the heap's written slots before the present (LEONIDA_HEAP_PRELOOK, off)
write-watch-ask RS-WRITE-WATCH-ASK write-watch askings are planned by allocation (LEONIDA_ASK_BY_ALLOCATION), view memory known as such is not asked (LEONIDA_VIEWS_UNASKED), and guards are set per view (LEONIDA_PROTECT_BY_VIEW); the 274 askings a frame the kernel refused are gone

In the running title (Series X, 2560x1440, the save restored before each start; the switches read at run time compared within one run with LEONIDA_AB, phases of 10 to 15 s interleaved so that the scene and the PC's load weigh on all of them alike):

  • RS-PLACED-UNMAPPED-RELEASE: the memory line's estimate of host copies of placed textures over title memory no longer mapped went from about 3,000 MB to 3 MB (25,502 placed textures released), host textures alive from 8.3 to 4.8 GB.
  • LEONIDA_LOOK_FIRST, LEONIDA_LOOK_PARTS and the three write-watch switches: every combination within -6 % to +3 % of the run's own phases with them off (frame medians 46 to 54 ms, about ±4 % between equal phases), so no frame time change is claimed; the write-watch askings take 3.0 ms a frame instead of 4.0 and none is refused.

Tested

cargo test -p leonida-gpu --lib -- --test-threads=4: 762 passed, 0 failed, 53 ignored (twice). cargo test -p leonida-hle --lib: 256 passed, 2 ignored. cargo check --workspace --all-targets and leonida-gpu with diagnostics clean. The merge with main (ca6f10dfb) also compiles runtime/shims/d3d12_vulkan_device.cpp, d3d12_com.cpp, dstorage.cpp, file_system.cpp, main.cpp and pe_loader.cpp with MSVC 19.44 against the pinned Vulkan-Headers; ctest was not run.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7263446466 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7263446466). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-29T22:09:15Z. --- ### Sixth round in `d3d12/` (pushed at `8f5f02d80`), with current `main` merged Claimed in [#2570](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7261774084). This round comes from measuring the running title on an RX 7900 XT (the new section at the end of `d3d12/docs/findings.md`): there the frame is held by the submitting thread, and most of its time goes on keeping title memory and its host copies in step. Each item is its own merge and its own branch `adrianmjim/leonida:unified/<name>`, each fix with a test that fails without it. | Branch | Item | What is now true | |---|---|---| | `placed-unmapped-release` | `RS-PLACED-UNMAPPED-RELEASE` | host copies of placed textures whose title memory the title unmapped, and that no slot or list names, are let go by the sweep (`LEONIDA_PLACED_UNMAPPED=0`: kept to the card's idle time) | | `refresh-nothing-fast` | `RS-REFRESH-NOTHING-FAST` | refreshes known to copy nothing are sorted out on the submitting thread before any worker is woken (`LEONIDA_LOOK_FIRST`), and a range whose end pages were written only beside it is known to copy nothing (`LEONIDA_LOOK_PARTS`) | | `heap-records-wait` | `RS-HEAP-RECORDS-WAIT` | the pass ahead of a frame can look at the heap's written slots before the present (`LEONIDA_HEAP_PRELOOK`, off) | | `write-watch-ask` | `RS-WRITE-WATCH-ASK` | write-watch askings are planned by allocation (`LEONIDA_ASK_BY_ALLOCATION`), view memory known as such is not asked (`LEONIDA_VIEWS_UNASKED`), and guards are set per view (`LEONIDA_PROTECT_BY_VIEW`); the 274 askings a frame the kernel refused are gone | **In the running title** (Series X, 2560x1440, the save restored before each start; the switches read at run time compared within one run with `LEONIDA_AB`, phases of 10 to 15 s interleaved so that the scene and the PC's load weigh on all of them alike): - `RS-PLACED-UNMAPPED-RELEASE`: the memory line's estimate of host copies of placed textures over title memory no longer mapped went from about 3,000 MB to 3 MB (25,502 placed textures released), host textures alive from 8.3 to 4.8 GB. - `LEONIDA_LOOK_FIRST`, `LEONIDA_LOOK_PARTS` and the three write-watch switches: every combination within -6 % to +3 % of the run's own phases with them off (frame medians 46 to 54 ms, about ±4 % between equal phases), so no frame time change is claimed; the write-watch askings take 3.0 ms a frame instead of 4.0 and none is refused. ### Tested `cargo test -p leonida-gpu --lib -- --test-threads=4`: 762 passed, 0 failed, 53 ignored (twice). `cargo test -p leonida-hle --lib`: 256 passed, 2 ignored. `cargo check --workspace --all-targets` and `leonida-gpu` with `diagnostics` clean. The merge with `main` (`ca6f10dfb`) also compiles `runtime/shims/d3d12_vulkan_device.cpp`, `d3d12_com.cpp`, `dstorage.cpp`, `file_system.cpp`, `main.cpp` and `pe_loader.cpp` with MSVC 19.44 against the pinned Vulkan-Headers; `ctest` was not run.
adrianmjim commented 2026-11-29 22:45:07 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-29T22:45:07Z.


RS-HOST-RS-SPLIT (claim), pushed at 208eaf7ea: with this pull request d3d12/crates/leonida-gpu/src/host.rs had grown to 813,049 bytes, past the 655,360-byte cap of xtask/src/policy.rs. Its tests (24 modules, refresh_tests left for D3D12-HOST-RS-SIZE) and five self-contained groups (the presenter, the plane pass, the buffer makers, the frame lines, the card compare) now live in host/*.rs, moved as they are; host.rs is 584,189 bytes. repository_passes_policy now names only emit/lower.rs (D3D12-SHADER-LOWER-SIZE); leonida-gpu --lib 762 passed / 53 ignored, the same test names as before.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7263920495 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7263920495). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-29T22:45:07Z. --- `RS-HOST-RS-SPLIT` ([claim](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7263458254)), pushed at `208eaf7ea`: with this pull request `d3d12/crates/leonida-gpu/src/host.rs` had grown to 813,049 bytes, past the 655,360-byte cap of `xtask/src/policy.rs`. Its tests (24 modules, `refresh_tests` left for `D3D12-HOST-RS-SIZE`) and five self-contained groups (the presenter, the plane pass, the buffer makers, the frame lines, the card compare) now live in `host/*.rs`, moved as they are; host.rs is 584,189 bytes. `repository_passes_policy` now names only `emit/lower.rs` (`D3D12-SHADER-LOWER-SIZE`); `leonida-gpu --lib` 762 passed / 53 ignored, the same test names as before.
adrianmjim commented 2026-11-30 10:47:43 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-30T10:47:43Z.


Seventh round in d3d12/ (pushed at 8164b315d)

Claimed in #2570. A timeline of the running title (LEONIDA_TIMELINE, RX 7900 XT, Series X 2560x1440) put about 600 list calls of 50 us or more a frame on the recording threads; the waits inside them were behind four locks that all eight recording threads share. Each item is its own merge and its own branch adrianmjim/leonida:unified/<name>, each fix with a test that fails without it, each behind a switch that is on by default (=0 is the lock as before).

Branch Switches What is now true
staging-lock-short LEONIDA_STAGING_SHORT the staging table's lock is held only to look up, put in or take out; a staging state is made with the table free, and a texture's release waits for a state being made of it
bake-lock-quick LEONIDA_BAKE_QUICK a bake draw with nothing to settle, upload or flip no longer waits for the bake lock, and never passes while another draw is at work under it
textures-queue-tabled-quick LEONIDA_QUEUE_MARKS, LEONIDA_SPANS_QUICK, LEONIDA_TABLED_INBOX recording threads no longer take a heap's texture queue to note what changes nothing, and a table's slot taken out while the queue is busy goes to an inbox applied by the next holder
indirect-sig-lockfree LEONIDA_SIG_TABLE an indirect execution's host command signature is found in a fixed table without a lock or an AddRef/Release; a refused packed signature keeps its root signature

In the running title (one LEONIDA_AB run, phases of 7 s, all 64 combinations once after the title was in game, the save restored before the start; each switch's effect by least squares over the 64 phases with a linear trend): every switch is within two standard errors of nothing (frame median -1.9 % to +2.1 %, s.e. 1.9 %; submitting thread -2.9 % to +1.7 %, s.e. 1.8 %), so no frame time change is claimed. The recording threads are not what holds this frame: the submitting thread still works about 33 ms of a 47 ms frame. The table is in the new section at the end of d3d12/docs/findings.md.

Tested

cargo test -p leonida-gpu --lib -- --test-threads=4: 786 passed, 0 failed, 53 ignored. cargo test -p leonida-hle --lib: 256 passed, 2 ignored. cargo check --workspace --all-targets and leonida-gpu with diagnostics clean. repository_passes_policy names only crates/leonida-shader/src/emit/lower.rs, as before this round.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7276088274 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7276088274). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-30T10:47:43Z. --- ### Seventh round in `d3d12/` (pushed at `8164b315d`) Claimed in [#2570](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7270883500). A timeline of the running title (`LEONIDA_TIMELINE`, RX 7900 XT, Series X 2560x1440) put about 600 list calls of 50 us or more a frame on the recording threads; the waits inside them were behind four locks that all eight recording threads share. Each item is its own merge and its own branch `adrianmjim/leonida:unified/<name>`, each fix with a test that fails without it, each behind a switch that is on by default (`=0` is the lock as before). | Branch | Switches | What is now true | |---|---|---| | `staging-lock-short` | `LEONIDA_STAGING_SHORT` | the staging table's lock is held only to look up, put in or take out; a staging state is made with the table free, and a texture's release waits for a state being made of it | | `bake-lock-quick` | `LEONIDA_BAKE_QUICK` | a bake draw with nothing to settle, upload or flip no longer waits for the bake lock, and never passes while another draw is at work under it | | `textures-queue-tabled-quick` | `LEONIDA_QUEUE_MARKS`, `LEONIDA_SPANS_QUICK`, `LEONIDA_TABLED_INBOX` | recording threads no longer take a heap's texture queue to note what changes nothing, and a table's slot taken out while the queue is busy goes to an inbox applied by the next holder | | `indirect-sig-lockfree` | `LEONIDA_SIG_TABLE` | an indirect execution's host command signature is found in a fixed table without a lock or an AddRef/Release; a refused packed signature keeps its root signature | **In the running title** (one `LEONIDA_AB` run, phases of 7 s, all 64 combinations once after the title was in game, the save restored before the start; each switch's effect by least squares over the 64 phases with a linear trend): every switch is within two standard errors of nothing (frame median -1.9 % to +2.1 %, s.e. 1.9 %; submitting thread -2.9 % to +1.7 %, s.e. 1.8 %), so no frame time change is claimed. The recording threads are not what holds this frame: the submitting thread still works about 33 ms of a 47 ms frame. The table is in the new section at the end of `d3d12/docs/findings.md`. ### Tested `cargo test -p leonida-gpu --lib -- --test-threads=4`: 786 passed, 0 failed, 53 ignored. `cargo test -p leonida-hle --lib`: 256 passed, 2 ignored. `cargo check --workspace --all-targets` and `leonida-gpu` with `diagnostics` clean. `repository_passes_policy` names only `crates/leonida-shader/src/emit/lower.rs`, as before this round.
adrianmjim commented 2026-11-30 14:38:22 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-30T14:38:22Z.


New round in this PR: RS-SAMPLER-UNWIND-FAULT and RS-SUBMIT-THREAD-COST (claim, status).

RS-SAMPLER-UNWIND-FAULT: LEONIDA_PROFILE no longer takes the title down. On an RX 7900 XT it faulted about 20 s into sampling. The fault was an access violation inside ntdll while walking a suspended thread's stack.

  • Cause: a frame in one of our code caves has no unwind data, so the walk took a garbage rbp for the next frame.
  • Fix: stacks::Unwinder now uses RtlVirtualUnwind2 with the thread's stack limits where ntdll has it (build 20348 and later). Before each step it also checks the image's tables, and it stops instead of faulting.
  • Cost and tests: a walk takes 2.3 us instead of 1.0. Ten child-process fault cases fail on the old walker and pass now. zmasi's two lines in crash::unwind_into are untouched.
  • In the title: a 30 s profile ran to the end.

What that profile showed. The title's busiest thread is waiting, not working:

  • 45 % of its samples are in a monitorx/mwaitx loop on a fence's GPU address, and 27 % in Sleep inside that loop.
  • Against two timelines, our part of that wait is short. The fence it waits for is set 0.2-0.6 ms after the card ends the flight before it, and the title leaves the loop 10-90 us later.
  • The wait is for the card itself: busy about 35 ms a frame, idle about 12 ms, and idle while the submitting thread prepares the next submission.

Four cuts on that thread, each behind a switch, measured in one LEONIDA_AB run in the world:

  • 67 phases of 7 s, with the 16 combinations about four times each;
  • least squares per switch with a time trend;
  • s.e. 1.9 % on the frame median and 1.2 % on the submitting thread.
Switch, on vs off Frame median Submitting thread Default
LEONIDA_PRELUDE_POOL: host list preludes made ahead on a thread of their own, not in CreateCommandAllocator in the middle of submissions -1.2 % -3.1 % on
LEONIDA_SPANS_ONE_WALK: stale parts of the heap pass's spans rebuilt in one blocked walk; 1 walk instead of 15 in the title -1.0 % +0.6 % on
LEONIDA_SMOOTH_YIELD: a present not held for pacing while submissions wait behind it +0.6 % +0.8 % off
LEONIDA_RELAY_PRIORITY: the relay thread above normal +1.6 % +1.4 % off

What the run settles:

  • Frame time: no switch moves it beyond two standard errors (median 46.4 ms).
  • The two that stay on: the prelude pool takes about 1 ms a frame off the submitting thread. The one walk does its job on a pass that runs beside the recording.
  • The two now off: they gained nothing, so they need =1.

What holds the frame now is the card's own work and its idle time while the title records. Details are in docs/findings.md.

Tests: leonida-gpu 794 passed, 53 ignored; leonida-hle 256 passed, 2 ignored; leonida-loader 73 passed. The policy check names only lower.rs, which was over the limit before.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7281692526 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7281692526). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-30T14:38:22Z. --- New round in this PR: `RS-SAMPLER-UNWIND-FAULT` and `RS-SUBMIT-THREAD-COST` ([claim](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7276097657), [status](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7280410218)). **`RS-SAMPLER-UNWIND-FAULT`: `LEONIDA_PROFILE` no longer takes the title down.** On an RX 7900 XT it faulted about 20 s into sampling. The fault was an access violation inside `ntdll` while walking a suspended thread's stack. - **Cause:** a frame in one of our code caves has no unwind data, so the walk took a garbage `rbp` for the next frame. - **Fix:** `stacks::Unwinder` now uses `RtlVirtualUnwind2` with the thread's stack limits where `ntdll` has it (build 20348 and later). Before each step it also checks the image's tables, and it stops instead of faulting. - **Cost and tests:** a walk takes 2.3 us instead of 1.0. Ten child-process fault cases fail on the old walker and pass now. zmasi's two lines in `crash::unwind_into` are untouched. - **In the title:** a 30 s profile ran to the end. **What that profile showed.** The title's busiest thread is waiting, not working: - 45 % of its samples are in a `monitorx`/`mwaitx` loop on a fence's GPU address, and 27 % in `Sleep` inside that loop. - Against two timelines, our part of that wait is short. The fence it waits for is set 0.2-0.6 ms after the card ends the flight before it, and the title leaves the loop 10-90 us later. - The wait is for the card itself: busy about 35 ms a frame, idle about 12 ms, and idle while the submitting thread prepares the next submission. **Four cuts on that thread, each behind a switch,** measured in one `LEONIDA_AB` run in the world: - 67 phases of 7 s, with the 16 combinations about four times each; - least squares per switch with a time trend; - s.e. 1.9 % on the frame median and 1.2 % on the submitting thread. | Switch, on vs off | Frame median | Submitting thread | Default | |---|---|---|---| | `LEONIDA_PRELUDE_POOL`: host list preludes made ahead on a thread of their own, not in `CreateCommandAllocator` in the middle of submissions | -1.2 % | **-3.1 %** | on | | `LEONIDA_SPANS_ONE_WALK`: stale parts of the heap pass's spans rebuilt in one blocked walk; 1 walk instead of 15 in the title | -1.0 % | +0.6 % | on | | `LEONIDA_SMOOTH_YIELD`: a present not held for pacing while submissions wait behind it | +0.6 % | +0.8 % | off | | `LEONIDA_RELAY_PRIORITY`: the relay thread above normal | +1.6 % | +1.4 % | off | **What the run settles:** - **Frame time:** no switch moves it beyond two standard errors (median 46.4 ms). - **The two that stay on:** the prelude pool takes about 1 ms a frame off the submitting thread. The one walk does its job on a pass that runs beside the recording. - **The two now off:** they gained nothing, so they need `=1`. What holds the frame now is the card's own work and its idle time while the title records. Details are in `docs/findings.md`. Tests: `leonida-gpu` 794 passed, 53 ignored; `leonida-hle` 256 passed, 2 ignored; `leonida-loader` 73 passed. The policy check names only `lower.rs`, which was over the limit before.
adrianmjim commented 2026-11-30 16:37:12 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-30T16:37:12Z.


New round in this PR: RS-CARD-OWN-WORK (claim). The card holds the frame on an RX 7900 XT: busy about 35 ms of 46. This round measured the runtime's own share of that on the card, and cut what it could.

Where the card's time goes. A LEONIDA_GPU_TIMING run in the world (every command between two stamps, so slower than a normal frame) gave about 41 ms a frame:

Commands ms a frame Commands a frame
title ExecuteIndirect 16.0 5161
title dispatches 15.7 3834
our batched clamps of indirect arguments 4.9 653
title mesh, draw, alias and indexed 5.0 843

Our lists over the card copies of title memory are not in that table. They are now timed on the card (LEONIDA_CARD_OWN_TIMES=1, diagnostics builds):

  • ranges sent up ahead of submissions: 1.2-1.3 ms a frame in about 13 lists;
  • hash passes after them: 0.07 ms;
  • the compare behind the lists: 0.6 ms in about 15 lists.

So the runtime's own card work is some 5-7 ms of the 35. The rest is the title's translated shaders.

Three changes, each behind a switch, measured in one LEONIDA_AB run in the world: 68 phases of 7 s, the 8 combinations about eight times each, least squares per switch with a time trend.

Switch, on vs off Frame median Card busy Submitting thread Default
LEONIDA_BATCH_TABLE_CARD: clamp passes read their job tables from card memory, copied there by the list's prelude, not over the bus from upload memory +0.0 % -0.6 % +1.7 % on
LEONIDA_COMPARE_JOIN: the compare goes in the same ExecuteCommandLists call as the submission's last lists, behind one global barrier list -1.4 % -1.2 % -0.8 % off
LEONIDA_CARD_OWN_TIMES: the timestamps above +2.8 % +0.9 % +2.2 % off
s.e. 1.9 % 0.9 % 1.2 %

What the run settles:

  • Frame time: no switch moves it beyond the noise (median 46.4 ms).
  • Batch tables in card memory: a second timing run, flipping the switch every 20 s, gave the clamps 4.2 ms a frame on against 4.7 ms off, about 660 passes either way. That is less than a standalone test promised (4.9 to 3.4 us a pass). The cost is about 114 table copies a frame in the preludes (2.9 MB) and a little on the submitting thread, which is not the limit. It stays on.
  • Compare join: about 0.4 ms of card time a frame, within the noise. It stays off until the title has run with it under the debug layer. A host copy that a title list wrote as unordered access is read by the joined compare in the same call, and that needs judging. This machine has no SDK layers; the tests say so instead of passing silently.
  • Own times: the stamps cost a little, so they are off by default and need =1.

What is left of our own card work is mostly the clamps, which need knowing what the title's culling programs write (the translator), and the ranges sent up, which are title CPU writes the card has to see. Details are in docs/findings.md.

Tests: leonida-gpu 803 passed, 53 ignored (869 with diagnostics); leonida-hle 256 passed, 2 ignored; leonida-loader 73 passed. The policy check names only lower.rs, which was over the limit before.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7284960967 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7284960967). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-30T16:37:12Z. --- New round in this PR: `RS-CARD-OWN-WORK` ([claim](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7281846399)). The card holds the frame on an RX 7900 XT: busy about 35 ms of 46. This round measured the runtime's own share of that on the card, and cut what it could. **Where the card's time goes.** A `LEONIDA_GPU_TIMING` run in the world (every command between two stamps, so slower than a normal frame) gave about 41 ms a frame: | Commands | ms a frame | Commands a frame | |---|---|---| | title `ExecuteIndirect` | 16.0 | 5161 | | title dispatches | 15.7 | 3834 | | our batched clamps of indirect arguments | 4.9 | 653 | | title mesh, draw, alias and indexed | 5.0 | 843 | Our lists over the card copies of title memory are not in that table. They are now timed on the card (`LEONIDA_CARD_OWN_TIMES=1`, diagnostics builds): - ranges sent up ahead of submissions: 1.2-1.3 ms a frame in about 13 lists; - hash passes after them: 0.07 ms; - the compare behind the lists: 0.6 ms in about 15 lists. So the runtime's own card work is some 5-7 ms of the 35. The rest is the title's translated shaders. **Three changes, each behind a switch,** measured in one `LEONIDA_AB` run in the world: 68 phases of 7 s, the 8 combinations about eight times each, least squares per switch with a time trend. | Switch, on vs off | Frame median | Card busy | Submitting thread | Default | |---|---|---|---|---| | `LEONIDA_BATCH_TABLE_CARD`: clamp passes read their job tables from card memory, copied there by the list's prelude, not over the bus from upload memory | +0.0 % | -0.6 % | +1.7 % | on | | `LEONIDA_COMPARE_JOIN`: the compare goes in the same `ExecuteCommandLists` call as the submission's last lists, behind one global barrier list | -1.4 % | -1.2 % | -0.8 % | off | | `LEONIDA_CARD_OWN_TIMES`: the timestamps above | +2.8 % | +0.9 % | +2.2 % | off | | s.e. | 1.9 % | 0.9 % | 1.2 % | | **What the run settles:** - **Frame time:** no switch moves it beyond the noise (median 46.4 ms). - **Batch tables in card memory:** a second timing run, flipping the switch every 20 s, gave the clamps 4.2 ms a frame on against 4.7 ms off, about 660 passes either way. That is less than a standalone test promised (4.9 to 3.4 us a pass). The cost is about 114 table copies a frame in the preludes (2.9 MB) and a little on the submitting thread, which is not the limit. It stays on. - **Compare join:** about 0.4 ms of card time a frame, within the noise. It stays off until the title has run with it under the debug layer. A host copy that a title list wrote as unordered access is read by the joined compare in the same call, and that needs judging. This machine has no SDK layers; the tests say so instead of passing silently. - **Own times:** the stamps cost a little, so they are off by default and need `=1`. What is left of our own card work is mostly the clamps, which need knowing what the title's culling programs write (the translator), and the ranges sent up, which are title CPU writes the card has to see. Details are in `docs/findings.md`. Tests: `leonida-gpu` 803 passed, 53 ignored (869 with diagnostics); `leonida-hle` 256 passed, 2 ignored; `leonida-loader` 73 passed. The policy check names only `lower.rs`, which was over the limit before.
KelboLive commented 2026-11-30 17:33:37 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by KelboLive on 2026-11-30T17:33:37Z.


Independent check on Windows (not the author), at abd996db7.

  • cargo test --locked -p leonida-gpu --lib (shared warm target): 803 passed, 0 failed, 53 ignored in 27.6 s — that includes the branch's added leak-sweep tests.

Environment: Ryzen 9 7950X3D, Windows 11 Pro 10.0.26200.9711, NVIDIA RTX 4070 Ti SUPER (driver 621.01), Rust 1.98.1 pinned.

This covers the GPU crate only; the runtime-side leak cases need a game run, which I did not do.

AI-assisted: yes (opencode).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7286496809 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7286496809). Originally posted by [KelboLive](https://github.com/KelboLive) on 2026-11-30T17:33:37Z. --- Independent check on Windows (not the author), at `abd996db7`. - `cargo test --locked -p leonida-gpu --lib` (shared warm target): **803 passed, 0 failed, 53 ignored** in 27.6 s — that includes the branch's added leak-sweep tests. Environment: Ryzen 9 7950X3D, Windows 11 Pro 10.0.26200.9711, NVIDIA RTX 4070 Ti SUPER (driver 621.01), Rust 1.98.1 pinned. This covers the GPU crate only; the runtime-side leak cases need a game run, which I did not do. AI-assisted: yes (opencode).
adrianmjim commented 2026-11-30 18:44:01 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-30T18:44:01Z.


New round in this PR: RS-ZERO-COPY-IN-TITLE (claim). These are the first runs in the title of the runtime's paths that read title memory where it is instead of keeping a copy of it. They were all off by default and had only been tested outside the game.

One run per configuration in the world, on an RX 7900 XT under Windows with ReBAR off. Each run is 270 s, with the save restored before each start.

Configuration Frame Private What it did in the title
base 48.6 ms 27.4 GB
LEONIDA_CARD_FROM_TITLE=1 49.0 ms 27.1 GB 13 copies with title memory as their CPU side, 13 MB saved
LEONIDA_INPLACE=1 49.0 ms 27.4 GB 7 windows in place (36 MB), 1,872 asks turned down
+ LEONIDA_SECTION_COMMIT=1 51.6 ms 27.5 GB 18 opened in their section, all let go; 1,838 turned down
LEONIDA_LAND_IN_SUBMISSION=1 49.5 ms 27.6 GB 1,392 pieces (49.7 MB) a frame landed in their own submission
LEONIDA_TEXTURE_WATCHED_IN_PLACE=1 50.9 ms 27.4 GB no fault

No configuration faulted. None moved the frame beyond what two starts of the same build differ by.

Why reading in place covers so little. The title's GPU memory outside buffers is its physical page pool. xmem maps that pool one 64 KiB view at a time, so a window that is contiguous to the title is made of scattered pages of a section, and a placed buffer cannot show it. A tiled buffer would be the console's own page table, so I asked the card (inplace/tiled.rs, behind LEONIDA_INPLACE_PROBE=1 and LEONIDA_INPLACE_PROBE_TILES=1, on a device of its own):

  • On a heap of ours, scattered tiles work in every respect: reads, CPU writes seen with no call in between, shader writes, aliased tiles, remap and unmap. They read at the same 27.5 GB/s as a placed buffer.
  • On a heap opened over a committed section, or over private memory, the first UpdateTileMappings removes the device with DXGI_ERROR_INVALID_CALL. Direct3D takes no tiles in a cross-adapter heap, and every heap opened on the process's memory is one (flags 0x421). WARP answers the same. The title's device survives the probe's removals.

So there is no tiled window over title memory on Windows. VKD3D-Proton has not been asked yet.

Landing in the submission is now decided once per plan, so LEONIDA_AB can flip it. One run of 67 phases gave:

on vs off change s.e.
Frame median +0.6 % 2.5 %
Card busy +1.1 % 1.5 %

The relay lands in 6.8 ms a frame instead of 10.2 and waits for no fetch, but the frame does not wait for the relay. It stays off.

Where the process's 27.4 GB of private memory goes. It is flat from about two minutes in the world, so there is no growth to chase.

  • Card memory counts too. On this driver both the card's memory and the PC memory shared with it count in private bytes about one for one. Moving a copy to the card saves no commit; only removing a duplicate does.
  • Card memory, 9.8 GB. Texture blocks take 4.4 GB, with about 1.7 GB free inside blocks that still hold a live texture; pool.rs lets a block go only once it is empty. There are also 210 MB of 64 KiB buffers that each hold about 100 bytes of hashes.
  • Shared memory, 8.0 GB. Windows take 3.8 GB, of which only 2.5 GB was ever copied.
  • Not useful: the line "private bytes grew N MB while lists were made" adds up changes across the whole process and does not measure what lists cost.

A finer window grid (LEONIDA_WINDOW_KB=256 LEONIDA_WINDOW_TAILS=1) takes windows from 3,820 to 2,219 MB and private memory from 27.4 to 26.1 GB. It stays off.

  • Why: where two windows hold the same bytes, a shader's write through one does not reliably reach the other before that other is read or sent up. This can happen through a read while the flight is in the air, a write and a read in one submission, the order two written copies land in, or the late merge. The 4 MiB grid has the same exposure where an ask crosses a cell line, only less often.
  • Checked in the title: LEONIDA_UPCOPY_CHECK=1 found no send putting an older value over a card write, at either grid.

What that check did find, at either grid. About nine title buffers of 1.1 to 2.5 MiB have a card copy that differs from its CPU side at rest. They are the same addresses at every check, written by shaders through a view no flight declared. A later send of a title write there would put the older bytes back over the shaders' bytes.

Also in this round: a fix for an intermittent test. the_pass_looks_only_at_slots_written_since_the_look_ahead read the process's frame once but stamped its slots at the frame of that moment, so the frame-waits test beside it could move it. The test now stamps its slots in its own frame; the runtime is unchanged.

Tests: leonida-gpu 813 passed, 54 ignored (880 with diagnostics); leonida-hle 256 passed, 2 ignored; leonida-loader 73 passed. The policy check names only lower.rs, which was over the limit before.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7288284592 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7288284592). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-30T18:44:01Z. --- New round in this PR: `RS-ZERO-COPY-IN-TITLE` ([claim](https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7285017897)). These are the first runs in the title of the runtime's paths that read title memory where it is instead of keeping a copy of it. They were all off by default and had only been tested outside the game. **One run per configuration** in the world, on an RX 7900 XT under Windows with ReBAR off. Each run is 270 s, with the save restored before each start. | Configuration | Frame | Private | What it did in the title | |---|---|---|---| | base | 48.6 ms | 27.4 GB | | | `LEONIDA_CARD_FROM_TITLE=1` | 49.0 ms | 27.1 GB | 13 copies with title memory as their CPU side, 13 MB saved | | `LEONIDA_INPLACE=1` | 49.0 ms | 27.4 GB | 7 windows in place (36 MB), 1,872 asks turned down | | `+ LEONIDA_SECTION_COMMIT=1` | 51.6 ms | 27.5 GB | 18 opened in their section, all let go; 1,838 turned down | | `LEONIDA_LAND_IN_SUBMISSION=1` | 49.5 ms | 27.6 GB | 1,392 pieces (49.7 MB) a frame landed in their own submission | | `LEONIDA_TEXTURE_WATCHED_IN_PLACE=1` | 50.9 ms | 27.4 GB | no fault | No configuration faulted. None moved the frame beyond what two starts of the same build differ by. **Why reading in place covers so little.** The title's GPU memory outside buffers is its physical page pool. `xmem` maps that pool one 64 KiB view at a time, so a window that is contiguous to the title is made of scattered pages of a section, and a placed buffer cannot show it. A tiled buffer would be the console's own page table, so I asked the card (`inplace/tiled.rs`, behind `LEONIDA_INPLACE_PROBE=1` and `LEONIDA_INPLACE_PROBE_TILES=1`, on a device of its own): - On a heap of ours, scattered tiles work in every respect: reads, CPU writes seen with no call in between, shader writes, aliased tiles, remap and unmap. They read at the same 27.5 GB/s as a placed buffer. - On a heap opened over a committed section, or over private memory, the first `UpdateTileMappings` removes the device with `DXGI_ERROR_INVALID_CALL`. Direct3D takes no tiles in a cross-adapter heap, and every heap opened on the process's memory is one (flags 0x421). WARP answers the same. The title's device survives the probe's removals. So there is no tiled window over title memory on Windows. VKD3D-Proton has not been asked yet. **Landing in the submission** is now decided once per plan, so `LEONIDA_AB` can flip it. One run of 67 phases gave: | on vs off | change | s.e. | |---|---|---| | Frame median | +0.6 % | 2.5 % | | Card busy | +1.1 % | 1.5 % | The relay lands in 6.8 ms a frame instead of 10.2 and waits for no fetch, but the frame does not wait for the relay. It stays off. **Where the process's 27.4 GB of private memory goes.** It is flat from about two minutes in the world, so there is no growth to chase. - **Card memory counts too.** On this driver both the card's memory and the PC memory shared with it count in private bytes about one for one. Moving a copy to the card saves no commit; only removing a duplicate does. - **Card memory, 9.8 GB.** Texture blocks take 4.4 GB, with about 1.7 GB free inside blocks that still hold a live texture; `pool.rs` lets a block go only once it is empty. There are also 210 MB of 64 KiB buffers that each hold about 100 bytes of hashes. - **Shared memory, 8.0 GB.** Windows take 3.8 GB, of which only 2.5 GB was ever copied. - **Not useful:** the line "private bytes grew N MB while lists were made" adds up changes across the whole process and does not measure what lists cost. **A finer window grid** (`LEONIDA_WINDOW_KB=256 LEONIDA_WINDOW_TAILS=1`) takes windows from 3,820 to 2,219 MB and private memory from 27.4 to 26.1 GB. It stays off. - **Why:** where two windows hold the same bytes, a shader's write through one does not reliably reach the other before that other is read or sent up. This can happen through a read while the flight is in the air, a write and a read in one submission, the order two written copies land in, or the late merge. The 4 MiB grid has the same exposure where an ask crosses a cell line, only less often. - **Checked in the title:** `LEONIDA_UPCOPY_CHECK=1` found no send putting an older value over a card write, at either grid. **What that check did find, at either grid.** About nine title buffers of 1.1 to 2.5 MiB have a card copy that differs from its CPU side at rest. They are the same addresses at every check, written by shaders through a view no flight declared. A later send of a title write there would put the older bytes back over the shaders' bytes. Also in this round: a fix for an intermittent test. `the_pass_looks_only_at_slots_written_since_the_look_ahead` read the process's frame once but stamped its slots at the frame of that moment, so the frame-waits test beside it could move it. The test now stamps its slots in its own frame; the runtime is unchanged. Tests: `leonida-gpu` 813 passed, 54 ignored (880 with diagnostics); `leonida-hle` 256 passed, 2 ignored; `leonida-loader` 73 passed. The policy check names only `lower.rs`, which was over the limit before.
adrianmjim commented 2026-11-30 21:30:52 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by adrianmjim on 2026-11-30T21:30:52Z.


Round 11: up to date with main, and what undoes shader writes in write-combined copies

The merge with main. leaks/all now contains origin/main at 8f41d7d01.

  • C++ runtime: this PR no longer touches runtime/. runtime/ and docs/d3d12_vulkan.md are taken from main as they are, so our old C++ leak fixes (RT-ZERO-IMAGES-RELEASE and the others) are dropped. The Rust runtime is the one that matters now.
  • Rust conflicts: resolved so that both sides survive:
    • draw.rs reads AHEAD_RECORDING through main's RwLock;
    • main's COPY_SCOPED line goes through host/lines.rs;
    • main's frame meter is in host/present.rs;
    • apu.rs uses main's lookup together with our reborrow;
    • findings.md keeps both sides' sections.
  • A fix found while merging: Resource::evict_placed. With LEONIDA_PLACED_SHARDS flipped while the title runs, a placed texture could be freed while still in its shard table.
    • It is now always taken out of the table under the write lock, and the stamp is checked again after.
    • Two tests cover it, one of them stepping between the removal and the recheck.
  • Tests: leonida-gpu 846 passed (938 with diagnostics), on an RX 7900 XT.

A correction to round 10. It said the up-copy check found no send putting an older value over a card write. That was wrong:

  • The lines "older values sent up to ..." come from the check's look at a send. Once in the world, every one of its summaries is nonzero.
  • The label "no shader was declared to write the buffer" also covers writes that LEONIDA_WC_NO_BACK keeps on the card, because those are never planned.

What wrote them (RS-UNDECLARED-SHADER-WRITES).

  • The tool: a diagnostics trace, LEONIDA_UNDECLARED_TRACE=1 with LEONIDA_UPCOPY_CHECK=1, off by default (host/undeclared.rs). For a copy the check flags, it says per submission whether its lists or its sends changed the bytes, which declarations the lists made there, and how many of the words a send changed had been changed by an earlier submission's lists. LEONIDA_UNDECLARED_WATCH=<addresses> watches chosen copies.
  • The runs: three, from one save, about 40 s in the world each.
  • All declared: every write into the flagged buffers is declared, through a UAV in a descriptor table. They are write-combined copies of 1 MiB or more, which the launcher's LEONIDA_WC_NO_BACK=1 leaves on the card.
  • Two buffers lose their shaders' writes every frame with that setting:
    • 0xd624f2660+0x177000: 1,203 words set by a compute pass, put back to 0 by the next submission's sends in 12 of 12 frames;
    • 0xd94cd7430+0x280000: the same in 9 of 15 frames.
    • With LEONIDA_WC_NO_BACK=0, no send touches those words in 24 of 24 frames. So the title does not write them; only whole-page sends undo them.
  • The rings next to them are the title's own rewrites, so sending them is right. Those are 0xdb5047000 / 0xdb515e500 / 0xdb5275a00 and 0xdba8a9c00 / 0xdbaaa9c00. The sends still go over the shaders' words with the write-back on, with the same value each time.
  • Cost of the write-back: leaving those copies on the card is worth about 21 ms a frame in these runs (66.7 against 88-90 ms, with both checks on).
  • Next: take back only the write-combined copies whose shader-written pages the title also writes.

Details are in d3d12/docs/findings.md, section "Shader writes that a send undoes, in write-combined title memory".

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7292513666 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7292513666). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-30T21:30:52Z. --- ### Round 11: up to date with main, and what undoes shader writes in write-combined copies **The merge with main.** `leaks/all` now contains `origin/main` at 8f41d7d01. - **C++ runtime:** this PR no longer touches `runtime/`. `runtime/` and `docs/d3d12_vulkan.md` are taken from main as they are, so our old C++ leak fixes (RT-ZERO-IMAGES-RELEASE and the others) are dropped. The Rust runtime is the one that matters now. - **Rust conflicts:** resolved so that both sides survive: - `draw.rs` reads `AHEAD_RECORDING` through main's `RwLock`; - main's `COPY_SCOPED` line goes through `host/lines.rs`; - main's frame meter is in `host/present.rs`; - `apu.rs` uses main's `lookup` together with our reborrow; - `findings.md` keeps both sides' sections. - **A fix found while merging:** `Resource::evict_placed`. With `LEONIDA_PLACED_SHARDS` flipped while the title runs, a placed texture could be freed while still in its shard table. - It is now always taken out of the table under the write lock, and the stamp is checked again after. - Two tests cover it, one of them stepping between the removal and the recheck. - **Tests:** `leonida-gpu` 846 passed (938 with diagnostics), on an RX 7900 XT. **A correction to round 10.** It said the up-copy check found no send putting an older value over a card write. That was wrong: - The lines "older values sent up to ..." come from the check's look **at a send**. Once in the world, every one of its summaries is nonzero. - The label "no shader was declared to write the buffer" also covers writes that `LEONIDA_WC_NO_BACK` keeps on the card, because those are never planned. **What wrote them (`RS-UNDECLARED-SHADER-WRITES`).** - **The tool:** a diagnostics trace, `LEONIDA_UNDECLARED_TRACE=1` with `LEONIDA_UPCOPY_CHECK=1`, off by default (`host/undeclared.rs`). For a copy the check flags, it says per submission whether its lists or its sends changed the bytes, which declarations the lists made there, and how many of the words a send changed had been changed by an earlier submission's lists. `LEONIDA_UNDECLARED_WATCH=<addresses>` watches chosen copies. - **The runs:** three, from one save, about 40 s in the world each. - **All declared:** every write into the flagged buffers is declared, through a UAV in a descriptor table. They are write-combined copies of 1 MiB or more, which the launcher's `LEONIDA_WC_NO_BACK=1` leaves on the card. - **Two buffers lose their shaders' writes every frame** with that setting: - 0xd624f2660+0x177000: 1,203 words set by a compute pass, put back to 0 by the next submission's sends in 12 of 12 frames; - 0xd94cd7430+0x280000: the same in 9 of 15 frames. - With `LEONIDA_WC_NO_BACK=0`, no send touches those words in 24 of 24 frames. So the title does not write them; only whole-page sends undo them. - **The rings next to them are the title's own rewrites,** so sending them is right. Those are 0xdb5047000 / 0xdb515e500 / 0xdb5275a00 and 0xdba8a9c00 / 0xdbaaa9c00. The sends still go over the shaders' words with the write-back on, with the same value each time. - **Cost of the write-back:** leaving those copies on the card is worth about 21 ms a frame in these runs (66.7 against 88-90 ms, with both checks on). - **Next:** take back only the write-combined copies whose shader-written pages the title also writes. Details are in `d3d12/docs/findings.md`, section "Shader writes that a send undoes, in write-combined title memory".
enlight3d commented 2026-12-01 14:38:25 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by enlight3d on 2026-12-01T14:38:25Z.


@adrianmjim, a question before anyone claims it: this pull request is closed, and the compares behind the submissions it worked on (its RS-COMPARE-COST part) are still a cost on cards held by the GPU: LEONIDA_OWN_STAMPS=1 measures them at about 0.57 ms a frame on an RTX 3090 and 1.86 ms a frame on an RTX 4070 Laptop (OreoFR's run), against a card busy about 98 % of the frame there. Do you plan to carry that part on in a new pull request? If not, I would claim it in #2570 and start from your findings, with credit. No rush: I will wait for your answer here before claiming.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7314586823 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7314586823). Originally posted by [enlight3d](https://github.com/enlight3d) on 2026-12-01T14:38:25Z. --- @adrianmjim, a question before anyone claims it: this pull request is closed, and the compares behind the submissions it worked on (its `RS-COMPARE-COST` part) are still a cost on cards held by the GPU: `LEONIDA_OWN_STAMPS=1` measures them at about 0.57 ms a frame on an RTX 3090 and 1.86 ms a frame on an RTX 4070 Laptop (OreoFR's run), against a card busy about 98 % of the frame there. Do you plan to carry that part on in a new pull request? If not, I would claim it in #2570 and start from your findings, with credit. No rush: I will wait for your answer here before claiming.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!2569
No description provided.