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

Closed
github-bot wants to merge 376 commits from github-bot/gh-2569 into main AGit
Owner

@⁠adrianmjim on GitHub · 2026-11-28 09:48 UTC · original
leaks/all → main · +45518 −7041 · 107 files · 384 commits · closed without merging

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 (#1608); 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 (#1608); RT-GEOMETRY-VIEWS-CONTAIN, RT-DRAW-VIEWS-UNCHANGED (#2570); RS-ARENA-ONE-COPY, RS-SHADER-CONTAINER-FREE, RS-DSTORAGE-SCRATCH, RT-DEVICE-LOST-DRAIN (#2570); RT-SESSION-CACHE-UNCHANGED (#2570); RT-SHARED-PIPELINE-LAYOUTS (#2570); RS-HOST-LIST-SCRATCH-TRIM, RS-PIPELINE-LIBRARY-FINGERPRINT, RT-ZERO-IMAGES-RELEASE, RT-DSTORAGE-CPP-SCRATCH (#2570)
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 (#2570). 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
(#1608). 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
(#2570). 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 (#2570). 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 (#2570), 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 (#2570), 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 (#2570): 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)
**@⁠adrianmjim** on GitHub · 2026-11-28 09:48 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569) `leaks/all` → `main` · +45518 −7041 · 107 files · 384 commits · closed without merging 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608); 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608); RT-GEOMETRY-VIEWS-CONTAIN, RT-DRAW-VIEWS-UNCHANGED (https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570); RS-ARENA-ONE-COPY, RS-SHADER-CONTAINER-FREE, RS-DSTORAGE-SCRATCH, RT-DEVICE-LOST-DRAIN (https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570); RT-SESSION-CACHE-UNCHANGED (https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570); RT-SHARED-PIPELINE-LAYOUTS (https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570); RS-HOST-LIST-SCRATCH-TRIM, RS-PIPELINE-LIBRARY-FINGERPRINT, RT-ZERO-IMAGES-RELEASE, RT-DSTORAGE-CPP-SCRATCH (https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570) 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570). 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/1608). 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570). 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570). 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570), 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570), 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570): 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570) ([round 2](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570)); what each does, its switch and how it was tested are in [this comment](https://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569). 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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569). `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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569). `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)
make_title_texture made its image with create_committed, which attaches the device; the registry
(state_.title_textures) holds the image, and a retired image waits in retired_title_textures_ for
a refresh pass 3 s later, which only runs before a submission. A device released while such an
image existed was never destroyed and kept every Vulkan object it had: d3d12_existing_heap's
device without host image copies left 93 at vkDestroyDevice (VUID-vkDestroyDevice-device-05137).

The image now drops its device reference right after it is made, as the registry's reference
keeps it alive, and ~Device releases the registry's and the retired images after the GPU is idle
(release_title_images), before the deferred deletions are drained.

d3d12_existing_heap checks that the last Release of each device returns 0 and fails on
validation errors counted after vkDestroyDevice.
PsoStreamRecord::capture copied the bytecode of every stage into the
record's own blobs, so each slot 86 PSO kept a private copy of every
container it was made from, and a slot 55 PSO kept another one when
keep_pso_stream captured its stream again. The title makes some 50 000
slot 86 calls in its first boot from about 26 500 shaders
(docs/embedded_shaders.md), and the carved containers average 9.6 KB
on this machine, so most of them were kept many times over: an
estimated 0.65 to 1.0 GB of private bytes. Both compile modes copied:
keep_pso_stream by default, prepare_console_stream with
LEONIDA_PIPELINE_COMPILE=on-demand.

copy_pointed_data now takes the bytecode from a process-wide table
keyed by the size and the DXBC checksum (bytes 4..19, as key_shader
uses; FNV-1a over the bytes for a container without one). A candidate
is only taken when all of its bytes are equal, since hand-built
containers can share a checksum. The record holds a shared reference in
payloads_->shaders and its stream points at the shared bytes, which are
never written. The table holds weak references, swept every 1024 new
entries, so a container is freed with the last PSO that uses it; the
copy is made outside the table's lock and looked up again before it is
added. The stream bytes, the bytecode every consumer reads and the
containers a caller passes in (shared_native_graphics) are unchanged.

pso_stream_test: two streams with equal bytecode in different buffers,
10000 streams of one VS/PS pair, and records made and freed on 8
threads share one copy per container; bytecode with an equal checksum
but other bytes, and checksum-less bytecode that differs in one byte,
are not merged. On d44285197 5 of its 41 checks fail and the 10000
records grow private bytes by 202.9 MiB; with this change all pass and
they grow by 3.0 MiB.
The arena behind console list slot 148 (AllocateUploadMemory) only
advanced: upload_alloc moved chunk->used forward and made a new 8 MiB
UPLOAD buffer whenever nothing fitted, and the only release was
destroy_upload_state when the device went. A title that uploads every
frame (the XDXR builder asks count * 40 bytes per build) grew it by one
buffer each time the newest was full, in VRAM with Resizable BAR and in
host memory without, for as long as it ran.

Each allocator now has its own chunks, keyed by the real allocator the
list records into (ListProxy::allocator). The allocator proxy's Reset
(slot 8), which D3D12 allows only once the GPU has finished the lists
recorded into it, starts them from the front again when the real Reset
succeeds; a chunk that served nothing for 8 of these in a row is given
back, and the allocator proxy's release frees its chunks. A list's own
Reset gives nothing back, and one allocator's Reset leaves another's
memory alone. A freed chunk leaves the title VA table too under
LEONIDA_UPLOAD_ALIAS=1, as at the device's release, and the upload log
names it. upload_translate finds the chunk through a map ordered by CPU
base instead of walking every chunk.

LEONIDA_UPLOAD_REWIND=0 keeps the one arena all lists share, which only
grows, as before (runtime/README.md). An allocator the device hands out
unwrapped (a PC runtime's) never reaches the proxy's Reset, so its
chunks still only advance until the device goes.

xs_proxy_mock_test check_upload_rewind: 200 frames of {list Reset, 1 MiB,
Close, allocator Reset} on one allocator made 25 chunks and moved the
pointer 199 times before; now one chunk and the same pointer. Two
allocators, a failed allocator Reset, a list moved to another allocator,
an idle chunk given back and an allocator's release are covered too;
--upload-rewind-off (new ctest) checks the switch.
With LEONIDA_SHADOW_GPU=1 and LEONIDA_CONSOLE_HEAP_GPU unset, setup_console_heap_gpu makes heap_gpu for the
shadows' page copies and turns the alias table's removal list on, but only the pass takes released_ranges and that
list (console_heap_gpu_begin), and the pass runs only with LEONIDA_CONSOLE_HEAP_GPU=1. Every arena release (the
per-submission geometry upload leases among them), title block destroyed, slot-133 import released and alias range
removed added an entry nothing took, for as long as the process ran.

The pushes in backing() and title_block_gone now ask heap_pass_enabled() (heap_gpu and LEONIDA_CONSOLE_HEAP_GPU=1),
and the alias table records removals only when the pass runs.

arena_release called backing() twice for a release since 9f98dcc61. The second call erased nothing more: it only
repeated the slot change, the generation bump and the released range. It is gone, so a release is one range for
the pass and one slot change.

A device that owns its VkDevice (create_vulkan_device_standalone) faulted when released with either variable set:
the pass's pipeline and buffers went in ~DeviceState, after the VkDevice. ~Device now clears the context's prelude
and releases them first.

Test: d3d12_shadow_gpu_releases (new). LEONIDA_SHADOW_GPU=1 alone: 1,024 committed and 16 slot-133 buffers
released over 16 submissions leave nothing waiting (2,064 released ranges and 16 removed alias ranges on
d44285197). With --console-heap-gpu, 64 releases are 64 ranges (128 before), all taken by the next submission. The
accessors are console_heap_gpu_pending (d3d12_com.h) and TitleVaAliases::removals_pending.
Since #2465 a retired title window is freed only once every command list
whose recording began before the retirement is gone (src/
command_list_epochs.h). The list proxy's spare real lists never were:
restart_recording moves the cut parts and the last real list into the
spares closed and not reset, and cut_list reuses the newest spare first.
After a recording cut twice or more, later recordings that cut at most
once reset only the newest spare, so the others kept their last
recording's stamp until the list proxy was released, and every title
window retired after it kept its memory as long. The idle spares also
kept their commands and the pipeline states, root signatures and BVH
scratch those held.

A spare is not executed again before a cut resets it: a submission names
only the proxy's parts and current list, and the title's Reset ended the
recording they made. restart_recording now drops a spare's recording
through rt::d3d12::drop_recording: the layer list clears its commands,
releases what it held and resets its state, as Reset does, and stays
closed with no epoch stamp (CommandList::drop_recording, Stamp::drop). A
copy a held batch made earlier keeps its own stamp.

A retired window still without a ticket 30 s after its retirement is
logged once, with what it waits for, and the title memory report at
device release counts the retired windows not freed yet and how many
command-list epochs ago the oldest live list began.

Tests: xbox_list_cut_spares (new; a Vulkan device and the queue and list
proxies, no game data) records a list with three cuts, advances the epoch
as a retirement does, then records it eight times with at most one cut.
On d44285197 the oldest live recording stays at epoch 1 with the
retirement at 2, and the root signature the first recording set keeps 3
references; with the change the oldest is 2 and the references 1.
command_list checks CommandList::drop_recording and copies of a dropped
list.
A slot-133 texture destroyed while its thread holds title_texture_mutex (a slot-70 view overwrote the descriptor
that held its last reference, 5f549cf5f) only stops naming its resource, and drain_titles_gone erases the registry
entry once the lock is free. With LEONIDA_TEXTURE_REFRESH_ASYNC=1 the entry is also in texture_ranges
(index_texture) and, once mapped, in mapped_title_textures, and drain_titles_gone left both. The next refresh pass
that saw a title write or a map change over the texture's memory looked the key up with title_textures.at(), and
the std::out_of_range ended the process on the refresh worker. The mapped list also kept the TitleTexture alive.

drain_titles_gone now erases the range key with the registry entry, as title_texture_gone does outside the
registry, and the mapped entry when it has no resource (also when a texture made at the address since replaced the
registry entry). The async pass looks a key up with find() and skips one without an entry. The other places an
entry leaves the registry already erase its range key or replace it; a texture made for slot-70 views is never in
the mapped list.

Test: d3d12_mapped_plane_async (d3d12_existing_heap_test --mapped-plane-async) adds
check_mapped_plane_gone_in_registry: a mapped slot-133 plane released under the registry's lock, then a write over
its pages and a pass of the refresh worker. On d44285197 the process ends with 0xC0000409 (std::out_of_range from
the at() in refresh_title_textures, on the worker); now the registry is back to 0 entries, 0 range keys and 0
mapped textures. The accessors are title_texture_registry and release_in_title_registry (d3d12_com.h) and
TitleTextureRangeIndex::size.
The images the layer makes for slot-70 texture views of the title's
memory (owned TitleTextures) were retired only when their own address
got another description or a slot-133 texture. A title that streams
places its textures at ever new addresses of the same memory, so each
address named kept its image (in VRAM, then in host-visible memory),
its bindless index and its turn in every refresh pass for the device's
life.

place_title_view now records when a view last named an image, and the
refresh pass (retire_idle_owned_images) also retires one once a texture
made or registered after that view covers some of its bytes, or once
none of its pages has been committed since a title_memory_map change
over them, in both cases when no view has named it for
LEONIDA_TITLE_IMAGE_IDLE_MS (2000 by default). An image over exactly
the same bytes (the other view of a stream pool) is not covered, one
never filled does not go with its pages, and two textures over the same
bytes that views keep naming both stay. The image is released 3 s
later, as before; a later view makes it again with the same T#, so the
descriptors the title kept find it once it is filled.
LEONIDA_TITLE_IMAGE_RETIRE=0 keeps the images as before. The title
textures census line counts the retirements under a newer texture and
with their pages gone.

d3d12_title_image_retire (d3d12_existing_heap_test --title-image-retire,
with LEONIDA_TITLE_IMAGE_IDLE_MS=0): 16 textures named 4 KiB apart in
one committed MiB leave one image (64 KiB) and one bindless index,
where they left 16 (1024 KiB) and 16; a texture named again after its
image was retired reads its texels and its first T# finds it again;
decommitted pages and a slot-133 texture over its bytes retire the last
image. Tests read the registry through title_images and title_image
(d3d12_com.h).
The two indexes of src/console_heap_slot_records.h hold each V# half of a
console resource heap under (span class, granule), one unordered_map per
class. A half that moved or was cleared left a stale entry behind, and
nothing erased a bucket: push() cleaned only a bucket that was pushed
again until it held 32 keys, find() skipped stale entries, and only
reset(), at heap creation, emptied the maps. The main resource heap lives
as long as the session, and fix_vsharp records as waiting any non-image
word with w[2] != 0, so data the title keeps in a slot made a new bucket
whenever it changed. The bucket count was every (class, granule) the
session had written, not the live slots: two halves moved 200,001 times
held 600,003 buckets, 60.4 MiB of private bytes (measured with a scratch
program), with nothing recorded.

A bucket now counts the halves it holds. set() works out, per index, the
bucket a half leaves and the one it enters, and the last half to leave a
bucket erases it with its stale entries. The buckets held are at most
twice the halves recorded. Lookups name the same slots: they skipped
those entries already. The heap's slot-record log line gives the bucket
count after the halves recorded.

console_heap_slot_records_test: a new case moves two halves 200,001 times
and expects at most 4 buckets while they live and none once both slots
are cleared (on main: 600,003 both times). Every apply() of the model now
also compares touched() with a walk of every recorded half, and the
random case bounds the buckets by twice the halves recorded after each
round; both checks hold on main too.
LEONIDA_MEM_PROBE's smaps line reads /proc/<pid>/smaps through Wine's Z: drive. Native Windows has no such entry,
so there the line only said "no /proc entry names gta6rt", and the log had no breakdown of the process's own memory
on the platform most testers run.

Where no /proc entry is found, the probe now prints in its place

  [rt] mem-probe vmmap t=<s> (<ms>, <n> regions): private commit C MiB (peak P), working set W MiB (private V,
  peak Q); committed T MiB by kind: title A (n regions), pe-private B (n regions), pe-image C (n regions),
  pe-section D (n regions), vk-mapped E (n regions); reserved R MiB; largest private allocations MiB: 0x... N, ...

The counters come from GetProcessMemoryInfo with the PROCESS_MEMORY_COUNTERS_EX2 size (the private working set,
Windows 10 21H2 and later), falling back to the _EX size. The kinds come from a VirtualQuery walk over the user
address space with the smaps line's title and vk_mapped ranges; the rest of a committed region is named by its type.
A region is cut at the ranges' edges, so a reservation the title commits only part of counts in each kind it reaches.
The walk's time is in the line: 131 203 regions take about 75 ms here.

Diagnostic only: it runs on the probe's own thread, and with LEONIDA_MEM_PROBE unset nothing runs. Under Wine with a
/proc entry the smaps line is printed as before.

- src/mem_probe.h: VmTally (the classifier: regions and ranges in, committed bytes and region counts per kind out),
  process_counters, walk_address_space, vmmap_text and sample_vmmap; sample() prints the vmmap line when proc_dir()
  finds no /proc entry.
- runtime/README.md: LEONIDA_MEM_PROBE's row names the vmmap line.

Test: mem_probe_vmmap_test (CPU, Windows). Synthetic regions cut at unsorted, overlapping title ranges and a
vk_mapped range give the expected bytes and region counts per kind; the line's text; a walk of the test process sees
64 MiB it commits as pe-private and in the commit charge, or as title memory inside a title range, and a 16 MiB
section view as pe-section, or as vk-mapped inside a vk_mapped range; a 4 GiB reservation with 65 536 committed pages
is walked and timed. It does not build on d44285197, where the native sampler does not exist.
RehydrateRaytracingAccelerationStructureBatched2X makes its own scratch
buffer when the title passes ScratchAccelerationStructureData = 0 (the
retail title does) and hands it to the list with hold_until_reset. The
list released it at its Reset or release, which D3D12 allows as soon as
ExecuteCommandLists returns. In the default synchronous submit mode
nothing else held it, and a default-heap buffer's arena range is free
the moment the buffer is destroyed, so the next DEFAULT buffer of that
size could get the range, and be zeroed by the CPU, while the build
still ran.

ExecuteCommandLists now also gives the queue the objects its lists hold
through hold_until_reset (keep_lists), and a batch submitted at once
keeps them until its submission has completed; drain_pins releases them
as it releases the fences. Held batches and LEONIDA_SUBMIT_ASYNC already
kept them, with the lists' pipeline states (pin_lists). A list without
such objects costs one size check. The rehydrate is the only user of
hold_until_reset.

xbox_bvh_builder_test: a rehydrate without the title's scratch is
executed, the list is Reset at once on another allocator (a second list
is released), and a DEFAULT buffer of the scratch's size is made before
any Signal. On d44285197 it got the scratch's own VA and the sentinels
the lists held were already released (3 of 33 checks failed); now its
range is elsewhere, and the sentinels go once the submission has
completed.
A compute or graphics PSO whose shader reads its code base (s_getpc_b64 and
the constant tables in its own program) copies that program into the GPU
address arena, which has a fixed size (256 MiB by default, at most 4095 MiB).
Each 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, keyed by the SHA-256 the PSO found
the program's translation by (fssm_sha256, or fspx_code_sha256 for a kind-6
program), which is the hash of the bytes copied. The first PSO makes the
copy, the others take a reference, and the last one returns it to the arena
when that PSO is deleted: the same point a PSO's own copy was returned, after
any build of it a compile worker was running. Compute entries whose index has
no uses_code_base key are still copied, as before.

LEONIDA_SHARE_CODE_BASE=0 gives every PSO a copy of its own, as before
(runtime/README.md).

d3d12_code_base_share_test creates four compute PSOs of one program, others
of programs with and without a code base or with no uses_code_base key, and
two graphics PSOs whose pixel shader reads its code base. It checks the
arena's shader bytes and each PSO's code base VA and bytes through two
read-only test hooks (arena_shader_bytes, pipeline_code_base). Without the
sharing it fails: four PSOs of a 4004-byte program held 16016 bytes.
d3d12_code_base_per_pso runs it with LEONIDA_SHARE_CODE_BASE=0.
make_title_buffer makes a buffer over the title's pages the way slot
133 does: the pages imported, or a shadow copied from them. When both
fail (no import, the arena full, no host-visible memory left),
create_at_host_address still answers S_OK with an ordinary DEFAULT
buffer that has neither the title's VA nor its bytes. make_title_buffer
only checked FAILED(hr), so it kept that buffer until the device went
and counted it against LEONIDA_TITLE_BUFFERS_MB. The view stayed
uncovered, so the next IASetVertexBuffers or IASetIndexBuffer of the
same view made another one (each with its own memory, zero fill and
device reference), until the cap was used up; after that no new title
view was resolved for the rest of the session, even once the memory
was back.

A buffer is now kept and counted only when the context knows a buffer
at the view's address afterwards (knows_buffer_va over the backed
prefix, as the check before it). Otherwise it is released, and its
range is remembered for a second (refused_title_ranges_, by start,
pruned of expired entries at 256), so the binds in between return
without trying again. A range whose buffer could not be made at all is
remembered the same way.

d3d12_title_buffer_fallback_test fills a 16 MiB arena, refuses
host-visible allocations behind the instance-proc pointer it hands the
layer and runs with LEONIDA_SLOT133_IMPORT=0, then binds one 2 MiB
title view 16 times as vertex and index views. Before: 16 buffers
kept, 32 buffers of the view's size created. Now: none kept, 2 created
(by the first bind), and after the retry delay one more try, still
nothing kept.
A sampled BC texture placed on the title's memory waits for memory of
its own, and its views name one shared, zeroed image of its exact shape
(DeviceState::zero_sampled_image). When that image could not be made
(create_texture failed, as it does under VRAM pressure, or the image
lost its host-transfer usage after its memory was refused), the shape
was stored as null in zero_images for the device's life: every later
placement of it took memory of its own at once, for the rest of the
session, even after the pressure had passed.

Such a failure is now remembered in zero_image_retry with a time a
second later: placements of the shape before then do not try again
(each try makes an image and asks for its memory), and the first one
after it does. A shape whose image would pass the 256 MiB the shared
images may take still stays null: those images are never released, so
it stays past the limit.

d3d12_zero_image_retry_test refuses the next vkCreateImage of one BC1
shape behind the instance-proc pointer it hands the layer (the shared
image, made before the placement's own), on a device without host
image copies so that the shape takes a shared image at all. Before:
after the delay a third placement still had memory of its own (one
image of the shape made for it). Now it is shared (two made: the shared
image and its own).
The queue lets go of what a submission kept in the first of its calls
that finds the submission completed, after that call's own submission.
With LEONIDA_SUBMIT_ASYNC that call runs on the worker, so the fence of
its Signal can be reached before the release has run, and the test's
last check read the sentinels too early: it failed in 2 of 20 runs with
LEONIDA_SUBMIT_ASYNC=4. The test now signals and waits until both
sentinels are released, up to eight more Signals. The worker runs the
calls in order, so a release has finished by the time the next
Signal's fence is reached. The sentinels are static, so a late release,
or one at teardown after a failed step returned early, never touches a
frame that has ended.

execute_sync asks for the lists' kept objects only when the call
succeeded. A failed call submitted nothing of the lists, and on a lost
device the references would otherwise stay in pin_queue_ until the
queue is destroyed.

pin_lists and keep_lists take their references through one helper,
reference_lists.
The previous commit let go of the ordinary DEFAULT buffer that slot 133
answers with when a view's pages can be neither imported nor shadowed,
but every retry still made one: vkCreateBuffer, a dedicated
device-local allocation of up to 64 MiB (the arena being full is why
the shadow failed), a zero fill, then a deferred free. That happened
once a second for each refused range while the pressure lasted, under
memory_mutex(), where the title's own allocations wait.
create_at_host_address now takes ordinary_fallback (true by default,
so slot 133 keeps its stand-in); make_title_buffer passes false and
gets the shadow's HRESULT back instead. A buffer that does not cover
the view is still let go.

The retry was also per range: a title binding many views of one
refused pool made one full try per distinct start per second. Now,
after a refusal no range is tried for a second (title_buffer_retry_),
and a range refused again waits twice as long as its last wait, up to
64 s, so one that keeps failing does not take every second's try from
ranges that could get a buffer. Both checks come before the page walk,
so a held-back bind makes no VirtualQuery call.

d3d12_title_buffer_fallback_test now fills the arena with 64 KiB
buffers, counts device-local allocations of a view's size while
host-visible ones are refused, and binds a second view right after the
first is refused and again later. With the previous commit: 2
device-local allocations (one per view) and the second view tried at
once. Now: none, the second view held back for that second, and the
first view, refused a second time, waits 2 s.
title_memory_map::changed() with no range records [0, UINTPTR_MAX). On
Windows, xmem records one for each run of pages it commits for a
DirectStorage transfer, and one for every MEM_RELEASE. The refresh pass
took such a change for a change over every owned image. It then walked
the pages of each with VirtualQuery, under the registry lock, on the
title's submitting thread, nearly every pass of a streaming load. A
look costs about 0.5 us here, so 60,000 images would cost about 30 ms a
pass.

A change anywhere now marks no image: it says that something changed,
not where. title_free_impl records a whole release over the range that
allocation_extent finds before the free, so a released pool is still
found. It falls back to a change anywhere when the walk stopped early.
A pass visits at most LEONIDA_TITLE_IMAGE_CHECKS (128) of the images
that may be retired, from where the last pass stopped. A candidate not
reached keeps its mark.

A slot-133 texture covers owned images only with the layout of the
title's XG computer, or with the one its first slot-70 view gives it.
The guess from its description (Layout 0) can be larger than what the
title placed. The census line counts the images that a view named again
after a newer texture covered them. The test hooks are now
owned_title_images and owned_title_image, and the predicate is now
owned_image_retirement_on.

d3d12_title_image_retire adds four checks. A change anywhere with 13
images makes 0 looks (13 before). A change over 12 images makes 4 looks
a pass with LEONIDA_TITLE_IMAGE_CHECKS=4 (12 in one pass before). A
guessed slot-133 layout covers nothing until a view names the texture.
An image never filled stays when its pages go. The new
d3d12_title_image_idle (LEONIDA_TITLE_IMAGE_IDLE_MS=500) checks the
idle time for both reasons, and that a view of an image whose pages
went keeps it until a later change over them. xmem_test checks the
range a whole release records. All of them fail on d44285197.
The previous commit tried such a shape again a second after each
failure. A failure is not always transient: where the driver allows no
memory type for host-transfer images (the NVIDIA Pascal case
create_texture documents), the image loses host-transfer usage at
every try, so each BC shape there would cost two vkCreateImage calls, a
pool suballocation and bind, and a deferred free every second for the
whole session, where before it cost one try per shape per session.

zero_image_retry now keeps the last wait with the retry time. It is a
second after the first failure and doubles at each failure after it,
up to 64 s; a shape that gets its image is dropped from the map. A
shape that fails for good costs about one try a minute. One that
failed under pressure gets its image at the first placement after its
current wait, so at most 64 s after the memory is back.

d3d12_zero_image_retry_test now refuses the shape's image a second
time at the first retry. 1.5 s after that, a placement still has memory
of its own (refused twice, the shape waits 2 s); 1.5 s later one gets
the shared image. With the previous commit the placement 1.5 s after
the second refusal already took the shared image.
# Conflicts:
#	runtime/shims/d3d12_com.h
#	runtime/shims/d3d12_vulkan_device.cpp
LEONIDA_TITLE_IMAGE_RETIRE is off by default now; 1 turns it on. Retirement decides on a newer
texture over an image's bytes or on its pages going, and on no slot-70 view naming it for a while.
A title that samples such an image through a descriptor it wrote once (a heap it copies from, a
table it keeps) with no later view of the address would sample the fallback once the image goes,
and the census cannot see that. With the switch off nothing changes for the title; with it on, a
streaming session can show whether the images stay at the textures still there.

d3d12_title_image_retire and d3d12_title_image_idle run with the switch on. A negative
LEONIDA_TITLE_IMAGE_IDLE_MS counts as 0.
# Conflicts:
#	runtime/shims/d3d12_vulkan_device.cpp
# Conflicts:
#	runtime/shims/d3d12_com.cpp
XMemAllocDefault's 32-bit path goes through XMemVirtualAlloc, which tells
the GPU side of the new memory (title_memory_allocated). XMemFreeDefault
freed that memory with the host's VirtualFree directly, so
title_memory_freed never ran for it: the guarded, absent and foreign
blocks, the views and the write-combined regions noted for the range
survived the free and could be taken for true of the next memory at the
address.

It now frees through title_virtual_free, the title's own VirtualFree,
which tells the GPU side first. The new test frees a 32-bit block and
checks that the free reached the GPU side; a test-only record in
title_virtual_free shows which frees did.

No caller known to us sets the 32-bit attribute, so this may never run
with the title; it is a correctness fix more than a memory one
(sweep R1-06).
early-pipelines.txt was the union of every run ever: each run loaded it,
added the keys it requested and wrote the whole set back, so its comment
("this run and the last") was not true. Every title pipeline drawn with in
any earlier run was started at creation, at every load, and its host
pipeline stayed alive for the session whether this run drew with it or
not. EARLY_MAX (100,000) is above the title's 84,000 pipelines, and at the
cap the list stopped taking new keys instead of dropping old ones.

Each line now holds a key and the run that last requested it. The run is
counted by the list itself (one past the newest written down), and a save
keeps the keys requested in the last two runs. A process that requests no
pipeline writes the list back unchanged, so it does not age the others
out. A list without runs (written by an older build) still loads: its keys
count as run 0, are started early once more and then age like the others.
LEONIDA_EARLY_RUNS=<n> keeps n runs; 0 keeps every run's, as before.

leonida warm --used reads the same file, so it now takes the first word
of each line as the key.
want_level puts a host copy replaced by one with more levels in
REPLACED, so that a thread about to record its use still finds it alive
for a second and four frames. let_go_idle was the only place that let
those copies go, and it did that after the LEONIDA_TEXTURE_SWEEP=0 early
return: with the sweep off every replaced copy (its host texture and
twin) stayed on the card for good, although nothing could use it.

The drain now runs before the switch is looked at; the switch still
keeps every idle copy as before. The new test runs itself again in a
process of its own with the sweep off (the switch is read once), makes a
placed texture's copy from level 2, replaces it with one from level 0,
and checks that let_go_idle lets the old one go after four frames and a
second. It needs a host GPU, as its neighbours do.

Only runs with the non-default LEONIDA_TEXTURE_SWEEP=0 are affected
(sweep R3-07).
The read buffer of texture refreshes (texture.rs READ, with_read) is one per
thread and only grew. The threads that refresh write-watched, partly mapped
and unlocked-path textures (the submitting thread and the leonida-wide-N
helpers of shadow::wide_each) live for the run, so each kept the room of the
largest texture it ever read until the end: 22 MB for a 4096x4096 BC7
texture with its levels, 89 MB for one in RGBA8, on each of five threads on
a PC of 16 logical processors.

Room over LEONIDA_TEXTURE_READ_KEEP_MB (16 unless set) is now given back
when the read is over. The buffer grows by exactly what a texture asks for,
so that one under the limit keeps its room instead of leaving doubled room
over it (on d44285197 a read of 32 MiB after reads of 10 and 12 MiB left 40
MiB). A texture over the limit makes its room again at each read. The
buffer's contents were already "whatever the last texture left", so no
caller reads them before writing, and nothing the title sees changes.

Test: texture::read_buffer_tests::a_large_read_gives_its_room_back_when_it_is_over.
On d44285197 it fails with "40 MiB kept after a read of 32 MiB".
A command allocator keeps the memory of the most ever recorded into it
over its resets, and the pool of idle host lists hands its lists to any
title list, so every host list grows to the size of the largest
recording. At each submission, detach and detach_parts gave every title
list (with LEONIDA_THIN=1, every back list) a new host list at once,
which it kept, closed and unused, until the title reset it. So each
title list kept one grown allocator alive besides those in flight, and
the pool kept up to 512 more that nothing ever let go.

Now a submission takes the list's host list and leaves it none; reset
takes one from the pool (closed first, so its reset is the same as
before). Once a second the sweep lets go of the oldest half of the idle
lists nobody took since the last sweep, through retire, so the pool
follows what was needed lately and the allocators are freed on the
reaper thread.

Tests: a_submitted_list_keeps_no_host_list_until_its_reset (64 title
lists submitted four times hold no host list afterwards; it held 64
before) and idle_lists_nobody_takes_are_let_go (the pool goes from a
burst of 512 to the 8 a steady need takes).
The pool behind thread-pool ports started a thread whenever more tasks
waited than workers were idle, and created it while holding the pool's
lock. A worker that was starting did not count, and it could not take
the lock while tasks kept coming, so a burst of short callbacks started
about one thread per callback. Workers then waited for good, so the pool
kept its peak size, and every thread kept its stack and the title's
per-thread state.

Now a queued task starts a worker only when none is idle or starting,
and a worker that takes a task while others still wait, with none idle
or starting, starts the next before its task runs. A queued task always
has a worker coming, so a callback that blocks on another still never
starves it, but a burst of short callbacks is run by a few workers. The
thread is created after the lock is released. A worker that waits 30
seconds without a task leaves while at least four others are idle.

The new test queues 256 short callbacks on a pool of its own, then
checks how many workers started and that the idle ones leave. On
d44285197, with only a worker count added to the old pool for the test,
256 callbacks started 256 workers in one run and 42 in another, and none
of them ever left. With the change, 2 workers started in each of the
53 runs measured, 24 of them with 8 runs at once. A second test checks
that eight callbacks queued together, each waiting for all eight to
start, all run.
The pool of snapshot buffers (shadow.rs POOL, pooled and give_back) kept up
to 512 MiB, or its largest buffer when that is bigger (a snapshot is a
whole copy's size), and nothing ever trimmed it: after a burst of
submissions whose shaders write copies in the PC's memory, that memory
stayed committed for the rest of the run.

Each pooled buffer now carries when it was given back, and shadow::let_go_idle
(the sweep once a second before a submission) lets go of those no snapshot
took for crate::host::ram_idle_ms: five minutes with 12 GiB of the PC's
memory free and LEONIDA_KEEP_FREED on, 10 s otherwise, down to 2 s when
memory is short. A buffer in use is taken and given back at every
snapshot, so it starts its idle time again and stays. The count and byte
limits of give_back are as they were, and nothing the title sees changes.

Test: shadow::snapshot_pool_tests::buffers_the_pool_kept_for_the_idle_time_go.
On d44285197 it does not build (idle_snapshots is new); with
idle_snapshots as a stub that takes nothing out, as d44285197 behaves, it
fails with "0 of the eight idle buffers let go".
Every title pipeline created from a stream kept its own boxed copy of the
graphics state (about 540 bytes inline, plus its input elements and one
heap string per semantic name) for as long as the title holds the
pipeline, which is the whole session. The title creates some 84,000
pipelines from about 5,700 distinct states, and draws with only about
2,000 of them.

Pending now holds an Arc to one copy per state. The copy is found by a
hash of describe(), which Pending::new already computes for the key and
which holds every field of the state (it also names the host pipeline in
the library), so equal descriptions are equal states. The table holds the
states weakly, so a state is freed with the last pipeline that has it,
and it drops the dead entries each time it doubles. Compute pipelines
created from a stream, which all carry the default state, now share one.

Nothing the title sees changes: the states, keys and library names are
the same as before.
With LEONIDA_THIN=1 (scripts/play.ps1 sets it), allocate_upload writes
the Box<Upload> it made into the list's words, and translate takes it
back and keeps it for the list of ours. Words are handed over every
CHUNK words and at Close. A title list reset or released while it
records (no Close) cleared the words not handed over yet in
Front::leave, so their uploads were never dropped and their 64 KiB arena
blocks stayed taken for good.

Front::leave now walks those words and drops the uploads they name
before clearing them. Words already handed over are always translated,
also for a recording let go of (translate takes the upload back before
it skips anything), so Recording's drop needs nothing.

The new test puts an upload into a recording's words and resets the list
(and, in a second round, drops it) before any hand-over, then checks the
upload was given back; a test-only list in Upload's drop records which
uploads were.

Reset without Close and release of an open list are rare, so this is
small in practice (sweep R4-06).
process() allocated a zeroed Vec<f32> of MAX_FRAMES * channels, 46 KB
for stereo, for every PROCESS command, used it for one decode and freed
it again: about 50 times a second for every stream that plays, all of
it under the connection's lock.

The connection's State now holds that memory, made once in XApuConnect
for two channels; process() decodes into a slice of it. Only the frames
the packet decoded are read back, so what an earlier packet left in it
does not matter, and the lock that guards the decoders guards it too.

The new test counts, through a test-only global allocator, this
thread's allocations of a stereo packet's PCM size or more while ten
packets decode after a first one: ten before, none now. The allocator
is left out when the diagnostics or mimalloc features bring their own.

This is processor time more than memory: the heap gave the same block
back each time, so the footprint does not change (sweep R2-06).
exact() parks the buffers of the per-view copies it sweeps in EXACT_SPARE
for the next copy of the same width. The list was capped at 1,024 buffers
and nothing else: a spare left it only when a view of exactly its width
came again, so spares of widths that never came back stayed for the rest
of the run. Each is a committed buffer in the PC's memory, at least a
64 KiB block and up to 64 MiB (exact's largest view), so a full list was
at least 64 MiB and could be far more.

Now a buffer is parked only while the spares, counted in whole 64 KiB
blocks, stay within 64 MiB as well as 1,024 buffers (what comes after goes,
as before), and each spare carries when it was parked. shadow::let_go_idle
(the sweep once a second before a submission) retires the spares no copy
took for crate::host::ram_idle_ms (five minutes with 12 GiB of the PC's
memory free and LEONIDA_KEEP_FREED on, 10 s otherwise, down to 2 s when
memory is short), through host::retire_resource as idle windows go. The
same few widths the title's ring gives every frame are still reused, and
nothing the title sees changes.

Test: shadow::exact_spare_tests::spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle.
On d44285197 it does not build (park, idle_spares and Spare are new); with
d44285197's rule ported into them (count only, nothing ages out) it fails
with "1024 spares hold 160 MiB".
All idle workers waited on one shared condition variable, and each
queued task woke the one that had waited longest (std's Condvar on
Windows wakes waiters first in, first out). So a steady trickle of
tasks, such as the process queue's XAsync completions during play,
restarted every idle worker's linger before it ran out. A pool that
grew in a burst never shrank while tasks came more often than once
per linger divided by the number of workers.

Each idle worker now waits on a condition variable of its own, on a
stack, and a queued task goes to the worker that went idle last. Under
a trickle the same one or two workers run the tasks, and the others
wait out the linger untouched and leave. A worker woken for a task
counts as coming, like one being started, so the chain-start rule and
the number of workers a burst starts stay as they were.

The burst test no longer checks trimming. A new test grows a pool to
16 workers with callbacks that block until released, then queues one
short callback every 10 ms. The workers must drop to the one kept (or
two) while the trickle runs. Before this change 17 workers were still
there after 3 s and about 290 callbacks.
Pool::start counted the new worker as coming before it created the
thread, and std:🧵:spawn panics when the thread cannot be
created. On the chain path that panic ended the worker that called
start, lost the task it had just taken, and left the worker counted
as coming for good, so no task queued later would start another.

The thread is now created with std:🧵:Builder::spawn. On error
the counts are put back and a warning is logged. The worker that
called start keeps its task and runs it, and the tasks still waiting
go to the next worker that finishes a task, or to the worker the next
queued task tries to start.
The commit before this one freed a thread's read buffer after every read of
a texture larger than LEONIDA_TEXTURE_READ_KEEP_MB (16 unless set). The
22 MB 4096x4096 BC7 class it named as the reason, and a 2048x2048 RGBA8
texture with its levels, are above that limit, so each of their reads
allocated, faulted the pages in and freed them again, on the submitting
thread and the leonida-wide helpers while the world streams in. In a
standalone timing on a Ryzen 7 5800X, one read of 22.4 MB took 0.85-0.88 ms
in a reused buffer and 3.3-3.5 ms in a fresh one (with five threads at
once: 4.1 ms against 8.6-9.3 ms).

Reads larger than the kept bytes now take a buffer from a process-wide pool
(LARGE_READS) and give it back afterwards. A read takes the smallest buffer
there that is large enough, or else the largest, which it makes again
larger, so the pool never holds more buffers than reads ran at once. Large
reads that come one after another reuse touched memory as on d44285197
(0.82-0.84 ms in the same timing). The sweep (texture::let_go_idle) takes
out the buffers no read took for host::ram_idle_ms and hands them to
host::retire, so the reaper thread frees them, not the submitting thread.

A thread's own buffer serves reads up to the kept bytes, as in the commit
before. It is made exactly as large as asked (vec![0u8; size]), with no
doubling and no copy of the old contents.

The trade-off: a texture over 16 MiB no longer makes its room at every
read. After an idle stretch of ram_idle_ms (10 s, or 5 min with 12 GiB free
and LEONIDA_KEEP_FREED on) the first such read allocates again. At its
peak the pool holds one buffer per large read running at once, each up to
the largest texture read. That is what d44285197's per-thread buffers
held, but shared between the threads and given back when idle. Each
thread still keeps up to 16 MiB of its own for the run.

Tests: texture::read_buffer_tests::a_large_read_gives_its_room_back_when_it_is_over
now sizes its reads from read_kept() and checks the pool and its reuse.
On d44285197 it fails with "40 MiB kept after a read of 32 MiB" (with
read_kept and LARGE_READS stubbed in so that it builds).
texture::read_buffer_tests::the_pool_of_large_reads_reuses_its_buffers_and_lets_the_idle_ones_go
checks take_read and idle_reads.
let_go_idle_snapshots dropped every idle buffer of the pool at once, on
the submitting thread, inside shadow::let_go_idle. That sweep runs before
a submission while nothing is in flight, so the card waits for it. The
pool holds up to 512 MiB of touched memory, or its largest buffer when that
is bigger (174 MB for the big heap). Freeing 512 MiB of touched memory took
22-58 ms on a Ryzen 7 5800X, so the title could see a stall of that size in
the submit path after each idle stretch.

The idle buffers now go to crate::host::retire, after the pool's lock is
released. retire queues them past the bury lag, and the leonida-reaper
thread frees them, as it does for the idle windows the same sweep lets go.
The old comment pointed to give_back, but give_back frees only what goes
over its limits at that moment, not the whole pool.

The test is unchanged: shadow::snapshot_pool_tests::buffers_the_pool_kept_for_the_idle_time_go.
shadow::let_go_idle asked crate::host::ram_idle_ms once for the snapshot
pool and again for the windows. Each ask is a GlobalMemoryStatusEx call and
a look at the residency headroom. The idle time is now worked out once,
right after IDLE_FRAMES, and passed to let_go_idle_snapshots and to the
window filter. RS-EXACT-SPARE-CAP makes the same change and puts its own
call at the same place.
shadow::let_go_idle asked crate::host::ram_idle_ms once for the spare
buffers and again for the windows. Each ask is a GlobalMemoryStatusEx call
and a look at the residency headroom. The idle time is now worked out once,
right after IDLE_FRAMES, and passed to let_go_idle_spares and to the window
filter. RS-SNAPSHOT-POOL-TRIM makes the same change and puts its own call
at the same place.
When parking a buffer would take the spares of exact() over 1,024 buffers
or 64 MiB, park() refused the newcomer. Spares of widths that never come
back could then keep a width the title's ring repeats out of the list
until they aged out (up to host::ram_idle_ms, 5 min with 12 GiB free). Now
the spare parked longest ago goes to make room. The widths the ring
repeats are taken and parked again all the time, so the oldest spare is of
a width that did not come back.

park() now returns the buffers that go: the oldest spares it pushes out,
and a newcomer larger than the whole list may hold, which no view of
exact() is. exact() drops the copies it lets go before it takes the
EXACT_SPARE lock, and passes the returned buffers to host::retire_resource
after the lock is released. Before, a refused buffer of up to 64 MiB of
committed memory was released while the lock was held, and the eight
threads that translate lists queue on that lock. d44285197 did the same
when the count overflowed.

Test: shadow::exact_spare_tests::spares_of_widths_that_never_come_back_stay_under_64_mib_and_go_when_idle
now also checks that every buffer is either parked or returned, that the
last sweep's spares are all kept, and that a 640 KiB width parked into the
full list finds room. With d44285197's rule ported into park and
idle_spares it still fails with "1024 spares hold 160 MiB". With the rule
of the commit before this one (newcomers refused) it fails because none of
the last sweep's 30 spares is kept.
The comment said a new large read buffer comes zeroed without a second pass. alloc_zeroed only lets the allocator skip writing pages that come fresh from the system, and in a standalone timing on this PC vec![0u8; n] cost the same as reserve_exact plus resize. The comment now says only that.
# Conflicts:
#	d3d12/crates/leonida-gpu/src/shadow.rs
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-28 09:59:49 +00:00
@ -0,0 +120,4 @@
int main() {
vktest::Device vk;
if (!vk.create()) return 77;
Author
Owner

@⁠Copilot on GitHub · 2026-11-28 09:54 UTC · original

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** on GitHub · 2026-11-28 09:54 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480218) `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.
@ -525,0 +601,4 @@
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");
Author
Owner

@⁠Copilot on GitHub · 2026-11-28 09:54 UTC · original

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** on GitHub · 2026-11-28 09:54 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480227) 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.
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-11-28 09:54 UTC · original · reviewed

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

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-11-28 09:54 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6097138101) · **reviewed** <!-- 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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569) · 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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569) · 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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569) · 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>
@ -0,0 +49,4 @@
vktest::Device gpu;
auto status = gpu.initialize();
if (status == vktest::DeviceStatus::unavailable) return 77;
CHECK(status == vktest::DeviceStatus::ready);
Author
Owner

@⁠Copilot on GitHub · 2026-11-28 09:54 UTC · original

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.

**@⁠Copilot** on GitHub · 2026-11-28 09:54 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4726480242) `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.
# Conflicts:
#	runtime/shims/d3d12_xs_device.cpp
#	runtime/test/xs_proxy_mock_test.cpp
Author
Owner

@⁠lixonik on GitHub · 2026-11-28 10:16 UTC · original · reviewed

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** on GitHub · 2026-11-28 10:16 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6097209190) · **reviewed** 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).
set_vertex_buffers marked the list's DrawViews block stale for any call that wrote a slot, and
OMSetRenderTargets for every call, without comparing with what was bound. A title that binds the same
vertex buffer before each draw therefore made one make_shared<DrawViews> per draw, about 728 bytes each
(8 render targets and 32 vertex buffer views plus the control block), kept by the recorded draws until
the list's Reset.

set_vertex_buffers now marks the block stale only for a slot whose view changes, and OMSetRenderTargets
only when the target count or one of the copied target views differs. TargetView and VertexBufferView
get a defaulted operator== for the comparison. What each draw records is unchanged: the block always
holds the targets and buffers bound at the draw.

d3d12_draw_test --draw-views-sharing (ctest d3d12_draw_views_sharing) records 1000 draws with the same
IASetVertexBuffers before each and counts the distinct blocks: 1000 before, 1 now. It also checks that a
changed slot, an unbound slot, another render target and a rewritten RTV descriptor behind the same handle
each start a new block that holds the new views.
GeometryViews::resolve looked only for its exact key (source, bytes), so a
range inside a live view got a view of its own: (A, 128 KiB), (A, 64 KiB)
and (A + 4 KiB, 64 KiB) were three views and 256 KiB of copies of 132 KiB
of the title's bytes, each charged to LEONIDA_GEOMETRY_MB, each watched and
refreshed on its own. docs/d3d12_vulkan.md measured 4.4-6 GB of VRAM in
geometry copies in a world run.

The live views that no other live view holds now form an index by source
(outer_). As none of them holds another, their ends rise with their
sources, so one lookup finds the view a range is inside. A range inside a
filled live view is answered with that view's address plus its offset:
the view's tiles already watch it and its refresh copies it. A view that
is not filled (made over pages that were not all readable) is not used,
and the exact-key path is unchanged.

Such a range is that view's bytes, so it leaves with it. retire_range
retires it with the view, tells on_retire its own source, size and
address (the device drops its aliases, heap slots and stream-pool extent
by that address) and removes it from the lock-free answers; the live
views the retired one held take its place in the index. The next request
for the range makes a view of its own. Nothing is retired for disuse.

A release can now retire a range the title still uses: one inside the
released view that the release did not touch. A command list recorded
before the retirement may name it and be executed after, so such a view's
memory also waits until no list older than the retirement is left
(src/command_list_epochs.h), as a retired title window's does. A view with
no such range is freed as before.

The geometry buffers line counts the ranges answered from inside a view,
and LEONIDA_GEOMETRY_CONTAINED=0 gives every range a copy of its own, as
before.

Tests: geometry_views case 17. Largest first, the two inner ranges are
one view of 128 KiB (3 views and 256 KiB before); smallest first,
(B, 64 KiB), (B, 128 KiB) and (B + 4 KiB, 64 KiB) are two views; a write
inside an inner range reaches it through the view; retiring the outer
view by its tail retires the ranges inside it, each told with its own
address, and one asked for again gets a view of its own; once the larger
view of B goes, the smaller one answers what is inside it; while a list
stamped before the retirement lives, only the view retired with nothing
inside it is freed, and the other at the next replay's ticket once the
list is gone. On d44285197 11 of the 92 checks fail; with the change all
pass, and with LEONIDA_GEOMETRY_CONTAINED=0 the same 11 fail.
refresh() skipped every per-tile copy of a view over a tile that cannot be
guarded yet (a file read into it in flight), but update() had already
taken the versions of the view's other written tiles. Those writes never
reached the view: once the read ended only the retry tile was copied. With
whole-view fills this caught up after the pin; with per-tile copies it did
not, and containment widened it to every range inside such a view. A
pinned view is now only kept from being filled whole. The retry tile is
never among the written ones, so a filled view still takes its other
written tiles at once and the retry tile once it can be guarded.

retire_range took the command-list epoch for a view with an untouched
range inside it while that range was still answered: from the lock-free
answers until later in the same critical section, and from the alias
table, heap slots and stream-pool span until on_retire had run after the
lock. A list reset in that window carried a newer stamp, could still take
the range's address, and did not hold the view. Such a view is now
pending until on_retire has run, and only then takes its epoch.

The copy of an acceleration structure's whole range (copy_title_range)
is never answered from inside a larger view: a release elsewhere in that
view would retire the structure with it, and its next copy would be made
from the title's pages. resolve() takes contain = false for it.

Also: a range answered from inside a view twice by racing threads is
counted once, the geometry buffers line counts the retired views waiting
for older command lists, and docs/d3d12_vulkan.md says that such a view
is not refreshed while it waits, unlike a retired title window.

Tests: geometry_views case 17 gains a stamp made inside on_retire, which
must hold the view, and a range asked for with contain = false inside a
live view, which gets a view of its own that outlives it. Case 18: a view
over two tiles and a range inside its first tile; the title writes both
tiles while a file read into the second is in flight, and the write to the
first must reach both at the next refresh. Built with the one
contain = false argument removed (neither has the parameter), 16 of 98
checks fail on d44285197, both checks of case 18 among them, and 5 fail
on the previous commit. With this change all pass, and with
LEONIDA_GEOMETRY_CONTAINED=0 the 14 containment checks of case 17 fail.
# Conflicts:
#	runtime/CMakeLists.txt
Author
Owner

@⁠lixonik on GitHub · 2026-11-28 10:30 UTC · original · approved these changes

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

**@⁠lixonik** on GitHub · 2026-11-28 10:30 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6097249062) · **approved these changes** 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).
Author
Owner

@⁠GrahamboJangles on GitHub · 2026-11-28 11:17 UTC · original · reviewed

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.

**@⁠GrahamboJangles** on GitHub · 2026-11-28 11:17 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6097434581) · **reviewed** 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.
Author
Owner

@⁠zmasi on GitHub · 2026-11-28 12:02 UTC · original

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.

**@⁠zmasi** on GitHub · 2026-11-28 12:02 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7238951156) `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.
Once the device is lost, completed_retire_ticket() answers 0 and acquire()
returns before its drain, so nothing drained the context's deferred deletion
queue again until the context went away. Every image, buffer, device memory,
view and image-memory range the title released after the loss stayed
allocated, and the queue's ring kept doubling.

defer_destroy now destroys the object at once when the device is lost, and
the first such call also destroys everything queued before the loss. A lost
device runs nothing more, and vkDestroy* and vkFreeMemory are valid on it.
Bindless slots still wait in the queue: their release takes the device's
descriptor lock, which release() holds when it defers one, and the set gives
out no more slots than it has, so those entries stay bounded.

vk_deferred_destroy_lost_test defers 500 buffers, marks the context lost and
defers 500 more: all 1000 are destroyed while the context lives, none twice at
teardown, and the two bindless slots are released once, at teardown. Before
this change it stopped with none of the 1000 destroyed.
Every compressed request allocated zero-filled buffers and freed them at
the end: the source read from the file, the zlib output that BCPack then
unpacks (intermediate_size), and the destination's bytes when its
physical pages are not one allocation's in order. Blocks of 1 MiB and
more come from the host's virtual memory, fresh and zero-filled each
time, so streaming paid an allocation, page faults and a free per
request.

Each worker now keeps these buffers in its own frame (Scratch) and
passes them to execute(). A buffer grows only when a request needs more
than it holds. The source is read over what an earlier request left
(read_into writes all of it or fails), the zlib output is used only as
far as inflate wrote it, and the page buffer is zeroed as a new one was,
so the bytes written are the same as before. Between requests a worker
keeps at most 16 MiB, giving up its largest buffers first.

staging_bytes now counts every buffer a request holds: besides the
compressed source read from a file, the zlib output of a zlib+BCPack
request and the destination's bytes of a request to pages (the source's
for a raw copy). LEONIDA_DSTORAGE_STAGING_MB bounds all of them now.

compressed_requests_reuse_the_workers_buffers counts, under a test-only
counting allocator, the blocks of the three buffers' sizes over many
requests: one per request before (72 of each in 72 requests on 16
workers), at most one per worker now. Two smaller tests check the
staging accounting and the 16 MiB bound.
The shader table kept a private copy of every container the title
passes (container: bytes.to_vec()) for the whole process, also after
the shader was translated, when only small facts of it are still read.

What is still read is now kept apart: the program's name and whether
its immediate samplers are made linear go into the translation; what
pipeline creation asks (a structure builder program, the names make
leaves out) is answered once per shader, at the first creation or at
the latest before the container goes; the pipeline book uses the
stored BLAKE3. After a successful translation the container goes and
the memory line's container counters follow it.

A shader that stores keeps its container while LEONIDA_PICKED_WRITES
is on, until crate::picked has read its programs. Shaders not
translated (most of them: translation is lazy) and shaders that fail
to translate keep theirs as before.

The test translates 64 hand-built compute containers of 32 KB and
checks that they keep no container bytes afterwards (all 2,107,648 on
the parent), and that a pipeline created again from the first one
shares the translated shader and is left out by name as the first was.
Every 64 MiB arena of title memory by address (memory.rs) was held twice
in the PC's memory: the arena itself (committed, write-watched) and the
CPU side of its copy on the card, a shared buffer of the same size that
by_address made and that every refresh compared with the arena. memory.rs
already takes only the dwords title memory changed into the arena, so the
two held the same bytes. That is 64 MiB more commit per arena; reads alone
make a few arenas, the structure builder (LEONIDA_BVH_BUILDER=1) up to 48.

Now Memory::another() makes the copy with shadow::by_address_opened: the
arena is opened as a host heap (inplace::place_part, as the in-place
windows do) and is itself the CPU side, with Card::staging a buffer placed
over it. Such a copy is never refreshed or compared; bring() and take()
resend exactly the dword runs they change, so the card side keeps what the
builder made of the other dwords, as before. The whole arena goes up once
when it is made, as a new copy's first refresh sent it. If the host does
not open the memory, the copy is made as before.

The directory and the windows of title memory keep the old path. USED in
by_address is only ever added to; since copies by address are never let
go it is a live total apart from attempts over the limit, left as it is.

Tests: an_arena_is_in_the_pcs_memory_once (fails on main: the CPU side is
a buffer of its own, 192 MiB more commit per arena on an RX 7900 XT, whose
driver charges the card side too; 128 MiB with this change) and
an_arena_sends_up_only_the_dwords_the_title_changed (the card keeps its
own dword beside the one the title changed, with and without
LEONIDA_SEND_OWN).
DeviceState::release defers a bindless slot and then the image views paired
with it, and until the slot is released the set's pending writes and shadow
copy may still name those views. Before this the deferred queue drained in
order, so the slot's write was swapped for the fallback before the views went.
After a loss the previous commit destroyed the views at once (and drain_lost
destroyed those queued before the loss) while the slot stayed queued, so a
flush that still ran could hand a destroyed view to vkUpdateDescriptorSets.

Image views now stay queued after the loss like the slots, in their order,
and go at teardown after their slot. That stays bounded: no slot comes back
before its release, a slot has at most four views, and the context's view
cache grows only while batches replay.

The test now also defers a slot and its view before and after the loss and
expects no view destroyed before teardown, then each slot released before its
view. It counts only the buffers and views it made.
A queue holds tracker_mutex_ through its vkQueueSubmit, so it can find the
device lost while another queue's ExecuteCommandLists waits for that lock,
past its own checks of the loss (the first one and acquire()). Once lost,
defer_destroy destroys released objects at once and also what was queued
before the loss, so an image may be gone whose view the bindless set's
pending writes or shadow copy still name until its slot is released. The
waiting batch then flushed the set and handed that view to
vkUpdateDescriptorSets.

execute_now now checks the loss again right after it takes tracker_mutex_,
before the bindless prepare, and returns as its other checks do. The batch
would not have reached the queue anyway, since submit() refuses a lost
device, so nothing the title sees changes.

The test marks the device lost from an interposed vkBeginCommandBuffer, after
the batch's own checks, and expects the bindless prepare not to run.
Memory::take runs at a submission, under the memory lock. It had become
the scalar dword merge for every page, which builds the runs that
changed. Only one case uses those runs: a page that is not taken whole,
in an arena whose copy has the arena as its CPU side. Every whole take
(each placed page, each packed structure) and every arena on the old
path threw them away, at about 2.5 times the cost of the compare and
copy that was there before.

Now that case finds its runs with shadow's AVX2 word_runs_put, as a
refresh finds them. Every other case compares and copies as before.
The write watch is no longer told about writes to an opened arena,
since nothing asks it about one.

The arena test now also takes a page as land() does and checks that the
dword the title changed goes up beside the card's own dword.
The whole arena now goes up from Memory::another, once the copy has a
number. Before, by_address_with queued it, and a copy that number()
then refused left a dead entry in the queue of changed copies.

opened_side logs, once, why an arena was not opened, also when the host
placed it off a 64 KiB line. Before, that case fell back without a
word. It cannot happen for upload::reserve's memory.

The SAFETY comment in host/send.rs said that only the thread that asked
writes a CPU side. That is no longer true for an opened arena: a
recording thread may write it while a submission reads it to send. The
comment now says so, and why the card still gets the new bytes.

The arena test returns early on a host that cannot open memory as a
heap, as the inplace tests do, since the old path is the design there.
It also checks that the process memory counters were read.
RS-APU-SCRATCH (apu.rs) and RS-DSTORAGE-SCRATCH (dstorage.rs) each
installed a counting #[global_allocator] in their test module, and a
binary has one: with both merged, the leonida-hle tests no longer build
("cannot define multiple global allocators").

The allocator moves to src/test_alloc.rs and tells both counters of each
block; each module keeps only its counter (apu::tests::counting::note,
dstorage::tests::watched_blocks::note). Same features as before: not
with diagnostics or mimalloc, where leonida-gpu installs its own.

cargo test -p leonida-hle --lib: 189 passed, 2 ignored, including
packets_decode_without_memory_of_their_own,
compressed_requests_reuse_the_workers_buffers and
staging_counts_every_buffer_a_request_holds.
Author
Owner

@⁠lixonik on GitHub · 2026-11-28 13:42 UTC · original · approved these changes

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

**@⁠lixonik** on GitHub · 2026-11-28 13:42 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6098098882) · **approved these changes** 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).
Author
Owner

@⁠Tauwni on GitHub · 2026-11-28 14:24 UTC · original

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

**@⁠Tauwni** on GitHub · 2026-11-28 14:24 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7240641808) 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).
Author
Owner

@⁠lixonik on GitHub · 2026-11-28 14:36 UTC · original · approved these changes

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

**@⁠lixonik** on GitHub · 2026-11-28 14:36 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6098416927) · **approved these changes** 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).
With an offline seed, pipeline_cache.session.bin is the driver's whole union of the seed and the session, about
the seed's size again (1.88-1.89 GB beside a 1.88 GB seed on an RX 7900 XT). Every launch loaded the seed, then
created a second driver cache from the session file and merged it: two ~1.9 GB driver caches, private commit
8.1 -> 9.95 -> 8.3 GB in the first 20 s.

Whenever the session file is published while this device's shared cache came from the seed, a small
pipeline_cache.session.seed next to it (temp file + rename) records the seed's size and last-write time, taken
from the handle the seed was loaded through, and the session file's size. A session file published without a
seed of this device removes a stale record; a failed publish leaves both as they were.

At launch, when the record matches the pipeline_cache.bin there now, the session file still has the recorded
size and is at least the seed's size, and its header names this device, the shared cache is created from the
session file alone: the seed is not mapped and nothing is merged. g_offline_seed_bytes keeps the seed's size so
the save limit still counts what a session adds. Anything else, or a blob the driver declines, falls back to
the seed plus the merge as before. LEONIDA_SESSION_CACHE_DIRECT_SEED=0 turns the new path off;
LEONIDA_PIPELINE_CACHE_BYTES=0, no seed, build hosts, the heavy cache and the journal are unchanged.

The decision is pure in pipeline_cache_store.h (SeedStamp, SessionSeed, parse/format, session_holds_seed) with
unit tests. d3d12_session_cache_seed (d3d12_compile_teardown_test --seed) counts merges, cache creation blobs and
pipeline-creation-feedback cache hits through a hooked vkGetDeviceProcAddr over eight rounds; before this change
it fails at the relaunch round (1 merge, caches created from [seed, session]).
The driver's union of a cache it was given does not shrink. A session file written back smaller than the blob the
shared cache was created from (the seed, or a session file that holds it) lost entries on the way, for example a
damaged file the driver took only part of. Recording it would carry the loss to every later launch, because the
seed would not be loaded again. So the record is removed instead (may_record_session_seed, pipeline_cache_store.h,
with unit tests), and the next launch loads the seed and merges. DeviceState keeps the blob's size next to the seed
(CacheOrigin).

LEONIDA_DIRECT_SESSION_CACHE=0, which means no live cache created from a session file, now turns off the seeded
direct path too. The docs say so, name the files LEONIDA_PIPELINE_CACHE_BYTES=0 leaves alone (the seed still
loads), and say a session file falls back when its size differs from the record.

d3d12_session_cache_seed now gives the seed a real pipeline. A first round with no seed builds program 0, and its
session file becomes pipeline_cache.bin. Program 1 is the same SPIR-V with a 32-wide workgroup, so it is a pipeline
of its own. The relaunch must hit both, so a session file loaded alone that lacked the seed's pipeline fails it.
The LEONIDA_PIPELINE_CACHE_BYTES=0 round runs with a matching record and checks that the session file and the
record keep their bytes and times. A driver that reports no cache hit for the seed's pipeline gets size checks
instead of hit checks. With only d3d12_vulkan_device.cpp at 9c49bd533 the test still fails at the relaunch round
(1 merge, caches created from [3652, 7252]).
Under Wine the process's private commit does not move after it commits
and touches 64 MiB (reported in #2569: Wine 11.0 on macOS, 41555 -> 41555
MiB), while the region walk sees them. The private working set check
next to it was already Windows-only; this one is now too.
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-28 18:06 UTC · original

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** on GitHub · 2026-11-28 18:06 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7243530192) 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).
@ -0,0 +120,4 @@
int main() {
vktest::Device vk;
if (!vk.create()) return 77;
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-28 18:06 UTC · original

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** on GitHub · 2026-11-28 18:06 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728232952) `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.
@ -0,0 +49,4 @@
vktest::Device gpu;
auto status = gpu.initialize();
if (status == vktest::DeviceStatus::unavailable) return 77;
CHECK(status == vktest::DeviceStatus::ready);
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-28 18:06 UTC · original

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** on GitHub · 2026-11-28 18:06 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728233080) 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.
@ -525,0 +601,4 @@
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");
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-28 18:06 UTC · original

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.

**@⁠adrianmjim** on GitHub · 2026-11-28 18:06 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728233176) 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.
# Conflicts:
#	runtime/test/pso_stream_test.cpp
create_graphics and create_compute made a VkPipelineLayout for every PSO, and
~PipelineState destroyed it. A session makes ~50k PSOs from a handful of layout
shapes, and the driver copies the bindless set layout into each layout: ~2.3 KB
each on an RX 7900 XT, ~117 MB for 54k.

DeviceState::pipeline_layout now keeps one layout per distinct create info,
keyed by all of it (flags, set layout handles in order, every push-constant
range), made on first use under a mutex. A PSO keeps the handle in its layout
member as before and no longer destroys it; ~Device destroys them all once the
PSOs, the compiler, the pipeline workers and the GPU are done. The mem-probe
device line reports how many there are.

d3d12_shared_pipeline_layouts(_eager): 256 PSOs of four shapes made on four
threads give four layouts, none destroyed while the device lives, each
destroyed once at its teardown; a second device makes its own.
DeviceState::pipeline_layout made the layout and then inserted it. A failed insert
(out of memory for the map node) would have left a layout in no map, which
destroy_pipeline_layouts never frees. The entry now comes first and is erased
when the driver refuses the layout.

d3d12_shared_pipeline_layouts records and runs a dispatch with a shared layout
(set 0 bound where the device has it, constants pushed) and waits for it before
the PSO and the device are released, so validation sees a shared layout used by
a command buffer and destroyed at teardown.
Conflict in d3d12/crates/leonida-gpu/src/list.rs: main's 7efbbdd39
(LEONIDA_ALLOCATOR_TRIM=1, idle host lists older than the limit let go)
and RS-HOST-LIST-ALLOCATOR-PEAK (the idle pool as a Pool trimmed 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 the
oldest stale ones are taken out of the Pool (Pool::take_oldest, which
keeps its bytes and its count of untouched lists) and counted in
ALLOCATOR_TRIMS[2], as on main, when a list is given back.
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-11-28 19:23 UTC · original · reviewed

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.

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-11-28 19:23 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6099736896) · **reviewed** 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).
@ -239,0 +240,4 @@
// 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
Author
Owner

@⁠Copilot on GitHub · 2026-11-28 19:34 UTC · original

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** on GitHub · 2026-11-28 19:34 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512319) 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.
@ -1981,1 +2024,4 @@
DeferredDeletionQueue::destroy({0, raw_handle, kind}, device_, vk, nullptr, nullptr);
return;
}
std::lock_guard lock(submit_mutex_);
Author
Owner

@⁠Copilot on GitHub · 2026-11-28 19:34 UTC · original

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** on GitHub · 2026-11-28 19:34 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512338) 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.
@ -811,0 +859,4 @@
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()
Author
Owner

@⁠Copilot on GitHub · 2026-11-28 19:34 UTC · original

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** on GitHub · 2026-11-28 19:34 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512358) 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.
@ -76,0 +146,4 @@
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;
Author
Owner

@⁠Copilot on GitHub · 2026-11-28 19:34 UTC · original

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** on GitHub · 2026-11-28 19:34 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#discussion_r4728512378) 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.
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-11-28 19:34 UTC · original · reviewed

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

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-11-28 19:34 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6099772161) · **reviewed** <!-- 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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569) · 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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569) · 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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569) · 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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569) · 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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569) - <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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569) - <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://git.gtahub.st/github/ubiquitarianism--leonida/pulls/2569) </details> <sub>Review effort: Balanced</sub>
The shared all-zero BC image of each shape (zero_sampled_image) was kept for
the device's life on a write-back L0 heap, host memory on a discrete GPU, and
its bytes stayed counted against the 256 MiB cap. The device now counts the
placed textures showing each image (acquire_zero_image); when the last one is
destroyed, the image leaves the map and the cap, and the Resource's destructor
queues it for deletion after the submissions made so far, behind the views of
it that texture's forget_image queued. A texture that got memory of its own
keeps its count until it goes, since views of the shared image made before then
may stay in replaced_images. Shapes left without an image because they did not
fit get another try once room is freed.

d3d12_zero_image_release places twelve BC1 shapes (one twice), releases them,
and checks that no shared image or byte is left, that every one is destroyed
after two submissions, and that a shape placed again gets an image.
Every compressed, swizzled or page request allocated zero-filled buffers
and freed them at the end: the source read from its file, the zlib
output, the BCPack output and the unshuffled bytes, each a new vector.
Blocks of 1 MiB and more come from fresh virtual memory, so streaming
paid an allocation, a zero-fill, page faults and a free per stage.

Each queue's worker now keeps two buffers per request it runs (its own,
and its paired helper's) in its own frame, not in a thread_local, and
the stages take turns writing into one and reading the other. A buffer
grows only when a request needs more than it holds, and is replaced
rather than grown, since nothing in it needs copying. Between requests
a set keeps at most 16 MiB, the budget of a request that may run beside
another (can_prepare), dropping its larger buffer first.

The buffers no longer zero their new bytes: the read fills all of them
or fails, inflate appends only what it writes (zlib_inflate now takes
any vector of bytes), BCPack writes every byte of each block it returns
(BC6H and BC7 clear a block before setting its bits), the stripes of a
swizzle group cover all of it, and a failed request publishes nothing.

test_reused_buffers counts, under a test-only counting operator new,
the blocks of 128 KiB or more that 100 identical 512 KiB zlib plus
swizzle requests from a file allocate: three per request before (300),
six now (three for each of the worker's two sets). Every destination is
checked against the inflated stream unshuffled.
host-pipelines.bin was opened whatever translation its pipelines came from and saved back whole, so the entries of every earlier translator change stayed in the file and in what the host reads of it. The fingerprint leonida warm already keeps its list by (known::fingerprint: the translator, its settings, what it was told of the host, the driver) is now written beside it as host-pipelines.fingerprint; a start that finds none or another starts an empty library, and its first save writes over the old one. A save deletes the fingerprint before renaming a library of other shaders into place and writes it after, and drops a library an earlier save left waiting, so a save cut short never pairs a stale library with the current fingerprint.
A worker save and the shutdown save could interleave their fingerprint check, delete, rename and write, so one could delete the fingerprint the other had just written and then fail its rename: the next start found none and compiled everything again. They now take one lock. The start that cannot rename a waiting library into place says why it does not open the older file even under its own fingerprint (it may be of the shaders before), and the new comments are wrapped like the rest of the file.
Each queue has its own worker, and each worker kept two sets of buffers
(its own and its paired helper's), each trimmed to 16 MiB apart: a queue
whose requests pair could keep 32 MiB while idle, outside the 64 MiB
window docs/directstorage.md says bounds private staging. The worker now
trims both sets together after each request or pair, giving up the
largest buffers first until what it keeps holds at most 16 MiB, as the
Rust workers trim theirs. The doc now says what the workers keep, how
much per queue, and that it is outside the window.

test_kept_buffers_cap runs a zlib request inflating 20 MiB from 5.6 MiB
twice and counts the blocks of 2 MiB or more each allocates: the second
allocates both again (2, 2), so nothing over the cap was kept. A request
inflating 4 MiB after them allocates none, so the kept source buffer was
reused. On main the three allocate 2, 2 and 1. With trim doing nothing
the second allocates only 1, since the 20 MiB output buffer was kept;
dropping the smallest first drops everything and the third allocates 1.

test_reused_buffers now takes turns between two different streams of the
same size, so a stage that left bytes of a reused buffer unwritten would
publish the other stream's bytes, and checks each destination against
its own stream.
A placement held its claim on the shared zero image of its shape until it was
destroyed, even after it got memory of its own. By then publish_streamed_texture
has queued every view at the texture's address for deletion, the ones in
replaced_images included, and erased its pending keys, so nothing reaches the
image any more; yet it stayed in host memory and in the 256 MiB for as long as
any texture of that shape lived. publish_streamed_texture now gives the claim
back there. The bind runs inside command prepare with the context's resource
lock held, so the claim goes to a list the device drains before the next
submission, where the image is released through the deferred queue as before.

d3d12_zero_image_release also gives a placement memory of its own with a copy
and checks that its shape's image is gone while the texture lives, makes views
of placements and checks that no shared image is destroyed before its views,
and fills the cap with large shapes to check that the one that did not fit gets
an image once another is released.
test_kept_buffers_cap only sends requests over 16 MiB, which never pair,
so trimming each set apart gives it the same 2, 2, 0 blocks: it does not
test that a worker's own and helper sets share the cap.

test_kept_buffers_pair_cap submits a zlib request inflating 8 MiB from
2.2 MiB and one inflating 6 MiB from 1.7 MiB together. Each stages at
most 16 MiB, so they pair: their blocks of 2 MiB or more come from two
threads (the worker and the pool thread preparing the helper's). The two
sets then hold 17.9 MiB, each under 16 MiB, and the worker drops the
8 MiB buffer, so the first request alone afterwards allocates its source
and output again (2 blocks). With the per-set trim of 6c3a24ec5 restored
it allocates only its output (1) and the test fails.
Every save serialises into host-pipelines.tmp, yet only the serialisation (the library's own lock) and the rename with its fingerprint were locked. A worker save done serialising could rename that file into place while the shutdown save truncated and refilled it: a library still being written under a valid fingerprint, and the shutdown save, finding no file to rename, failed and wrote neither the slow nor the early list. Main shared the file the same way, with no lock on the rename at all; the fingerprint made it worse, as it now vouches for whatever was renamed. One lock now covers the whole save, from serialising to the early list, taken after the 20 s check so a worker that finds a save running returns instead of waiting; no caller of the save holds a lock and none taken inside it is held by anyone who saves. A file of its own for each save was not chosen: two saves could then rename in the other order, an older library over a newer one, and leave files to clean up. The save's file side takes the serialisation as a closure, so a test runs two overlapping saves against a temporary folder (it fails with only those two steps locked).
A placed texture gives its claim on its shape's shared zero image back during the prepare of a replay, whose
earlier commands may still sample the image and whose submission is recorded only later. Another queue's replay
can run before_execute meanwhile, drain the return and queue the image's deletion at the next ticket, which its
own submission takes: the image could be destroyed while the first submission is still pending.

Each return now records the last ExecuteCommandLists replay begun (GeometryViews::execute_epoch) and is drained
only once none of the replays in progress at that point is left (oldest_execute), as a retired geometry view
waits for kAfterExecutes. The deferred deletion is then ticketed after their submissions.

d3d12_zero_image_release starts a compute queue's replay from inside the copy's vkEndCommandBuffer, after the
copy gave the texture memory of its own, and checks the image is kept until the direct queue's next replay.
RT-ZERO-IMAGES-RETRY's comment said the shared images are never released;
since RT-ZERO-IMAGES-RELEASE they are, and release_zero_image drops the
empty entries of shapes that did not fit. Comment only.
Author
Owner

@⁠Maticcm on GitHub · 2026-11-28 21:17 UTC · original

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

**@⁠Maticcm** on GitHub · 2026-11-28 21:17 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7245906263) 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).
Author
Owner

@⁠lixonik on GitHub · 2026-11-28 21:17 UTC · original · reviewed

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.

**@⁠lixonik** on GitHub · 2026-11-28 21:17 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#pullrequestreview-6100124342) · **reviewed** 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.
Author
Owner

@⁠zmasi on GitHub · 2026-11-28 21:39 UTC · original

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.

**@⁠zmasi** on GitHub · 2026-11-28 21:39 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7246171846) ### 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.
pipeline.rs: the shader container freed after translation (RS-SHADER-CONTAINER-FREE)
meets main's masked pixel-shader twins. The title's pixel shaders keep their
container, since a masked twin is made from it once the pipeline exists; a twin
shares that copy and does not count it again in the memory lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: open_file (crates/leonida-hle/src/modules/dstorage.rs:157) pushed
(file object address, path) into the static WALLS_FILES on every DirectStorage file
open, with LEONIDA_WALLS_TRACE off too (its only reader, walls_request, returns at
once when the trace is off, :672-683), and no entry was ever removed: a String and
8 bytes per open for the whole run. With the trace on, the lookup by address
(find, first match) named a file object made where a released one had been by the
released one's path.

What changes: WALLS_FILES is gone. walls_file reads the path from the request's own
file object (File::name, stored at open, :153), as read_into and glyph_movie already
dereference request.source: the title keeps the file open until the request is done,
and the trace line is written before the request's status is. A null source names
"?". No switch: nothing outside the trace reads these names.

Test: dstorage::tests::the_walls_trace_names_the_file_a_request_reads opens a file,
releases it, opens files of a second name until one lands at the released address
(it did within the 256 tries on Windows 11) and asserts the trace name is the second path. On
the old lookup (extracted unchanged into walls_file) it fails:
  assertion `left == right` failed: a file object at a released one's address
  right: "...\second.bin"   (left was ...\first.bin)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: every landing of what shaders wrote (land.rs:744,
landing_cells) and every shadow copy-back (shadow.rs:3060, put_changed ->
landing_cells_whole) noted cells of 8 bytes into LANDED_CELLS
(watch.rs:2601), pieces of 65,536 PageCells of 136 bytes (8.5 MiB per
256 MiB of title addresses touched, aliases included) made on first note
and never freed. Their only reader is landed_lately_exact, which
host.rs:3758-3767 asks only with LEONIDA_LANDED_EXACT=1 (off by default)
or LEONIDA_AB naming it. So a default run committed the pieces for
nothing; landing_cells_whole also built a Vec of 72 B per page on every
copy-back, and the landing worked out each page's cells (new_cells: a
second compare of the card's bytes against the reference plus a read of
title memory) only to note them.

What changes: watch::landed_exact() is the reader's switch (moved from
host.rs, same meaning) and watch::landed_cells_kept() says whether it can
ever be on (the variable, or LEONIDA_AB naming it, so an AB on phase still
finds the spans before it). landing_cells and landing_cells_whole return
at once when the cells are not kept, and land.rs skips new_cells then.
Kept, landing_cells_whole works out each page's cells as it notes them
instead of collecting a Vec. LandedCells counts the pieces it makes.
Nothing else reads LANDED_CELLS (grep: only landed_lately_exact and the
tests). No switch: with the reader off nothing it answers changes;
LEONIDA_LANDED_EXACT=1 keeps and reads the cells as before.

Test: watch::cells_tests::cells_no_one_can_ask_for_are_not_kept lands a
1 GiB copy-back and pages in three more pieces with the reader off and
asserts no piece was made. With the gates removed it fails:
"pieces of cells made with nothing to read them, left: 7, right: 0".
a_copy_back_notes_every_cell_of_its_bytes_and_no_other checks the kept
path without the Vec (whole pieces, a stretch inside a page, one across a
page end). leonida-gpu lib: 550 passed, 46 ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with the relay, `submit` settled for room in the card
compare's results (`card_results_low`, host.rs:7191-7194) with
`settle(.., WHY_MOST)`, the reason also used when `late_most()` lists are
in the air (host.rs:6694-6696). The frame line's "lists in the air" and
`LATE_WAITED[WHY_MOST]` mixed the two, so a full drain of the card for the
results area could not be read off the frame line.

What changes: a reason of its own, `WHY_RESULTS` (place 18, after the
places of LATE_STATS that are not reasons). LATE_STATS grows to 19 places
and LATE_WAITED to WHY_RESULTS + 1 (`why.min(10)` becomes
`why.min(WHY_RESULTS)`). The frame lines print "room in the compare's
results" next to "lists in the air", the blame list names it, and the
relay wait's timeline name comes from a small `landing_wait(why)`. Only
counting and names change; no settle happens at another point.

Test: host::late_tests::results_waits_are_told_apart_from_lists_in_the_air
(every reason has its own place in both counters, none of them 11 to 17,
and the relay's waits have distinct names). It does not build on
perf/unified-memory (no WHY_RESULTS, no landing_wait). With the results
reason aliased to WHY_MOST, as the base counted it, it fails
("reason 9 has no place").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong (perf/unified-memory, LEONIDA_SEND_OWN on by default):
- host/send.rs:148 made every submission's send memory as
  size.max(8 MiB).next_power_of_two(): a send of 4 KiB held 8 MiB of the
  upload heap until its submission landed, one of 9 MiB held 16, so with
  the relay's submissions in the air the bytes held were up to 2-3 times
  those sent.
- host/send.rs:121-123,163-170: what came back was kept up to 768 MiB
  (256 MiB of CPU-visible VRAM with LEONIDA_SEND_BAR=1) for the rest of the
  run; nothing in the once-a-second sweep (host.rs:507-536) trimmed it.
  The smallest spare that fit served any request, so a burst's largest
  buffer, taken by every small submission after it, was never idle either.
- give_back sorted and dropped the largest buffers (ID3D12Resource
  release, up to hundreds of MiB) while holding the SPARE lock that the
  submitting thread takes in send::take.

What changes:
- The pool is a small generic Pool<M> (take / give / idle / bytes) so the
  policy is unit-tested without a device.
- With LEONIDA_SEND_TRIM (on by default; =0 restores the old sizing and no
  idle trim; LEONIDA_AB can name it): memory is made to within an eighth
  of the size asked for (made_size: least 1 MiB, then steps of 1/8 of the
  power of two below), and a spare serves only requests needing at least
  half of what it is (SLACK = 2).
- send::let_go_idle, called from host::sweep next to the other trims, lets
  go of spares no submission took for ram_idle_ms (vram_idle_ms with
  LEONIDA_SEND_BAR), and of all of them while host memory is pressured.
- Everything that leaves the pool (past kept(), or idle) is handed to
  host::retire_resource after the lock is released, as RS-EXACT-SPARE-CAP
  does for exact-view spares. This part is unconditional (a pure fix).
- The LEONIDA_SEND_OWN frame line now prints the MiB held by submissions
  not done with and the MiB kept spare, so the effect can be read in a run.

Tests (host::send::pool_tests, pure, no device):
- memory_made_for_sends_is_within_an_eighth_of_them
- a_bursts_memory_goes_once_idle
- small_sends_leave_a_bursts_large_spare_idle
- steady_sends_hold_less_and_still_find_spares: 30 submissions of 1-5 MiB
  a frame, each landing two frames later, 300 frames: 325 MiB peak held in
  the air against 720 before, 385 MiB held+kept against 720; 119 buffers
  made in all and 1 in the last 150 frames.
With the old policy expressed through the same functions (old made_size,
unbounded spare size, no idle trim) all four fail: "8388608 bytes made for
4096: an eighth over or more", "a 256 MiB spare served a send of 3 MB",
"0 of the burst's two left let go", "720 MiB held in the air, 720 before".

Not measured in a run: how often memory is made again with the trim on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: resource::let_go_idle, with a limit of bytes (the card
over its line, or LEONIDA_TEXTURE_BUDGET_MB), built by_age from every
texture of TEXTURES with Hosted::used != 0 and sorted it
(resource.rs:2276-2293 on perf/unified-memory). The let-go closure
(2313-2345) took the host copy but left `used` at the copy's last use,
and want_level (1464) did the same for a copy it replaced. So every
texture whose copy had ever been let go stayed in by_age at each look
under pressure, to be found with nothing to take under its lock, and
the commit floor's walk of all took each one's lock too. A play has
tens of thousands of placed textures (18,639 placed host copies after
nine minutes of run 24); with LEONIDA_COMMIT_FLOOR the look measured
2.2 -> 11.6 ms (d3d12/docs/findings.md). How much of that these
textures were is not measured.

What changes: Hosted::used is 0 while there is no host copy. The
closure becomes let_go_copy, which stores 0 under `made`'s lock with
the copy it takes; want_level does the same. The by_age walk becomes
idle_by_age. No reader treats 0 differently from "nothing to take":
hosted() stamps it again when it makes the copy, let_go_copy returns
at once on 0, targets_census reads it only for textures with a copy.
A pure fix (nothing that had a copy is looked at differently), so no
switch.

Test: resource::tests::a_copy_let_go_leaves_the_look_by_age (local
GPU): four placed textures with host copies are in idle_by_age; after
let_go_copy none is (red without the store in let_go_copy: left 4,
right 0); made again from level 2, one is back; replaced by want_level
from level 0, out again (red without the store in want_level: left 1).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: where lists are not cut at their waits (LEONIDA_CUT_WAITS=0, or
waits held list by list, queue.rs:111-114), wait_for files each wait in the static
VALUE_WAITS by list address (crates/leonida-gpu/src/list.rs:2672-2675). Entries
leave on Reset (:778-781) or when the list is submitted (unmet_waits /
waits_by_list), but list_release (:757-759) freed the List without touching the
table, and List had no Drop. A list recorded with a wait and released without a
submission or reset left its entry for good, and a list later allocated at the same
address took that wait with its first submission: a wait for a value nothing
writes held that queue.

What changes: Drop for List removes the waits filed under its address, before the
list's memory is free (so a list made there afterwards keeps its own). One lock per
list freed, and the retain only when the table holds anything. No switch: entries of
a freed list were never meant to be read.

Test: list::tests::a_released_lists_waits_go_with_it files a never-met wait for a
list as wait_for does uncut, releases the list, makes lists until one lands at the
released address (it did) and asserts (entries left for the released address,
unmet waits a list there submits) == (0, 0). On perf/unified-memory:
  assertion `left == right` failed: (waits left of the released list, unmet waits a list at its address submits)
    left: (1, 1)
   right: (0, 0)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: every HostHeap::new pushed a Weak of its placed spans into the
static PLACED_SPANS (crates/leonida-gpu/src/descriptor/host.rs:2079-2085, table at
:360) and (start, bytes, step, sampler) into GPU_RANGES (:2023-2028, table at :1807).
Neither table was ever pruned: Drop for Heap (descriptor.rs:827-840) cleans only
SHADER_HEAPS, and HostHeap had no Drop. Each descriptor heap the title released left
a dead Weak that next_start and first_viewed walk on every call, and a range that
near_heaps (device-removed reports) still listed, at a GPU address a newer heap may
have taken.

What changes: GPU_RANGES entries carry the heap's lease_id (its own number, never
given twice; now taken just before the push instead of in the struct literal), and a
new Drop for HostHeap removes its range by that id and, for a view heap, its Weak
from PLACED_SPANS by pointer. Both tables now hold the heaps standing. No switch:
nothing reads an entry of a heap that is gone except to skip it or misreport it.

Test: descriptor::host::tests::a_heap_that_goes_leaves_the_tables_of_every_heap
(host GPU; returns without one) makes a view and a sampler HostHeap, checks (ranges,
spans) == (2, 1) while they stand, drops them and asserts (0, 0). With the id in the
tuple but without the Drop (perf/unified-memory behaviour):
  assertion `left == right` failed: (heaps' ranges, view heap's spans) left once they went
    left: (2, 1)
   right: (0, 0)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: the shared buffers (PC memory, write-back, committed) that
pieces of copies in the card's memory are fetched to were made anew only
when a fetch did not fit, to that fetch rounded up to 16 MiB, and never
made smaller: CardWork::fetched in Host::card_back (host.rs:6504-6507) and
RelayFetch::buffer in the relay's landing (host.rs:6158-6161). One large
fetch (first compare of a new copy, an uncompared range fetched whole, the
torn::Check pieces fetched whole) left a buffer of its size committed for
the rest of the run, one per site.

What changes:
- New host/fetched.rs with a pure policy, fetch_size(current, total,
  sizes, shrink): grow at once as before; with shrink, once the last 128
  fetches (SEEN) all needed at most a quarter (OVER) of the buffer, make
  one of twice the largest of them (ROOM), in whole 16 MiB, at least 16 MiB.
  One large fetch in the window keeps the buffer for 128 more fetches, so
  sizes that come and go do not reallocate each time.
- fetched::fit applies it at both sites; a buffer made smaller goes
  through retire_resource (the fetch into it was waited for), and the old
  one stays if the smaller cannot be made. Growth is unchanged.
- Switch: LEONIDA_FETCH_SHRINK (on by default; =0: grow only, as before;
  LEONIDA_AB can name it), since a shrink makes a committed resource on the
  landing thread.

Tests (host::fetched::tests, pure):
- a_large_fetch_leaves_no_large_buffer_behind: 512 MiB then 200 x 1 MiB
  ends at <= 32 MiB (16 MiB, two buffers made).
- a_large_fetch_now_and_then_keeps_the_buffer: a 100 MiB fetch every 50
  makes one buffer only; after they stop it comes down to 16 MiB.
- growing_fetches_always_fit (every fetch fits the buffer it gets).
With grow-only (the old rule) the first fails "512 MiB kept after 200
fetches of 1 MiB" and the second "left: (117440512, 1) right: (16777216, 2)".

Not covered: a buffer is only resized when a fetch happens; with no
fetches at all (nothing on card copies) it stays as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: a view without a resource object that its record cannot
name whole became a table entry that nothing ever released
(descriptor.rs Views::entry, ~1176-1198 on perf/unified-memory; forget at
~1486-1510 frees only by resource). With LEONIDA_VIEW_INLINE on (the
default) that is a view of placed memory once the 4,194,304 shapes are
full (Views::shape, ~1143-1154) or at an address past 1 TiB, and a
constant buffer view its record cannot hold; with LEONIDA_VIEW_INLINE=0,
every one of the two. A title that streams then adds one entry per view
it writes. The 33.27 million views (11,985 MB, none free, at 79 minutes)
measured at main 33db04a70 were this path: that commit predates
normal_placed (a7bb8cba), so stack padding made nearly every placed view
a shape of its own until the shapes were full. normal_placed keeps the
shapes few now (29,404-47,445 in the runs quoted at 5702e05d), but the
fallback past the shapes was still unbounded.

What changes: such entries are marked ADDRESSED and counted. Every
lookup of an entry (view_at: a host slot made from it, a draw reading
it; entry_of: the title writing the same view again) sets a SEEN bit,
an atomic beside the entry, so readers sharing the lock can set it.
When a new addressed entry would make more than
LEONIDA_VIEW_ADDRESSED_MOST (1,048,576 if not given, about the title
heap's slot count: some 350 MB of table and index), a clock hand lets go
of the first addressed entry not seen since it last passed: out of the
index, generation one on, onto the free list, exactly as forget lets go
of a released resource's entries. A record naming it is stale from then
on (view_at gives None, never another view; the host makes the slot
null), and the view written again gets a new entry and record. Views of
resources, samplers and shapes are never let go. Lookups stay what they
were (record decode O(1), index BTreeMap); letting go is amortised O(1)
(at most two rounds of the table, the first clearing SEEN bits). The
policy moved into Views::name/Views::view_at with a Limits value, so a
test can run it on a table of its own. The memory line ("memory, more")
says how many were let go.

Switch: LEONIDA_VIEW_ADDRESSED_MOST=0 keeps them for the run, as before.

Test: descriptor::tests::entries_carrying_an_address_stay_bounded_when_a_title_streams_past_the_shapes
(a table with room for 16 shapes and 256 such entries; 8,000 placed
buffer views of 8 kinds with stack padding at 32 reused addresses give 8
shapes and no entry, which refutes padding as a growth left on this
branch; then 100,000 views of ever new widths, 64 slots shown and looked
up every frame). With the letting go disabled (base behaviour) it fails:
"99994 entries for 100,000 views written, 99992 carrying an address";
with it, at most 258 entries, every shown slot keeps its view, the
first entry's record is stale (None) and the view written again is
named again. descriptor::tests::entries_carrying_an_address_are_kept_without_a_most
checks the switch's old behaviour. leonida-gpu lib: 550 passed, 46
ignored (548 before + these two); the descriptor tests also pass with
--features diagnostics.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: Memory::another (crates/leonida-gpu/src/memory.rs:401-409) reserved
64 MiB with upload::reserve (MEM_RESERVE|MEM_COMMIT|MEM_WRITE_WATCH, upload.rs:60-87)
and returned false without freeing it when shadow::by_address_opened or
Memory::number refused the copy (no room on the card, no number left). map() calls
another() again for every page asked for once the free pages ran out, so a lasting
refusal grew the commit 64 MiB at a time. Memory::new (:232-239) had the same shape
for the 16 MiB directory (by_address or shared_buffer refusing), and ready() calls
it again at every draw that reads memory by address while it fails (MEMORY stays
None): with copies refused (LEONIDA_CARD_BUFFERS=0, or no card work) every such draw
kept another 16 MiB.

What changes: both failure paths give the memory back with the new
upload::release. An arena's copy refused after by_address_opened made it goes with
the heap opened on the arena, which the host lets go of a moment after its last
reference (VirtualFree fails with error 87 until then, inplace.rs:33-36 and its
test at :1506): release keeps such an address and tries again at its next call and
at every reserve (upload::release_late). On the 7900 XT, idle, all were given back
at once. No switch: the memory was unreachable once refused. Not done: remembering a
refusal so another() stops retrying (the map's proposal); that changes when arenas
are tried, so it is left for the item that owns the arena VA work.

Test: memory::tests::memory_whose_copy_is_refused_is_given_back (host GPU) refuses
copies on its thread through a test hook (memory::refused; the arena's copy is made
and then refused, so the opened heap path runs), fails Memory::new once and
Memory::another three times, and asserts every reserved address shows up in
upload::RELEASED within 5 s. With the hooks and without the release calls
(perf/unified-memory behaviour):
  assertion `left == right` failed: reservations given back of [100000000, 102000000, 106000000, 10a000000]
    left: 0
   right: 4

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: plans took the compare's result dwords from
`CardWork::taken` on (host.rs:5845, 5892 on perf/unified-memory), and
`card_done` put `taken` back to 0 only when `!relay() || work.out == 0`
(host.rs:5982-5987). With the relay a plan is out while flights keep
overlapping, so `taken` only grew; once half the 1 MiB area was taken
(131,072 pieces of 64 KiB, 8 GiB of declared ranges, `card_results_low`,
host.rs:5956-5962) every submission sent ahead first waited until nothing
was in the air, under the submission lock (host.rs:7190-7195; with the
relay `settle` is `relay_wait` until the line is empty). Ranges past the
end were fetched whole. In practice the sweep's forced settle every 1.5 s
(host.rs:7019-7031) was what brought `out` to 0. How often the drain hits
is a hypothesis from the code, not measured; the previous commit gives it
its own count ("room in the compare's results").

What changes: `ResultRing` (pure): a plan takes one run of dwords at the
head, never wrapped within it (so `differs[r.at + p]` of each range stays
in the run), going to dword 0 when the run behind the newest does not fit
and the oldest has passed it. A run is freed when its plan is given back
(`card_done`, after `card_back` / `relay_card_back` read it) and every
older run has been too, so a plan given back early frees nothing before
its elders. `ResultArea` holds either the ring or the old area
(`Whole`, the old taken/out logic unchanged). `card_before` collects its
ranges first (`card_declared`, `card_asked`, the same joining as before),
places them all in one run and compares what fits there, as before.
Under the relay a submission whose ranges do not fit waits
(`relay_wait(WHY_RESULTS)`) only until landings have given back enough
room (`RESULTS_ROOM`, set under CARD_WORK and read without it), or until
nothing is in the air if it asks for more than the ring holds. It no
longer drains whenever half the area is taken. The wait now happens after
`picked::declare`/`declared_writes`, still before `shadow.writing`. The
1.5 s settle stays; a note there says that with LEONIDA_COMPARE_RING=0
the results area still depends on it, and the ring does not.

Switch: LEONIDA_COMPARE_RING=0 restores the old area and its
half-full drain (read once).

Tests (host::result_ring_tests):
- the_ring_has_room_while_plans_overlap: 1 MiB of results, plans of
  40,000 pieces, 3 always in the air, 1,000 plans: the ring never needs a
  drain; the old area needs one at the fifth plan. Red: with
  `ResultArea::new` forced to the old area (the base policy) it fails
  `left: Some(4), right: None`.
- the_ring_wraps_between_runs_and_frees_in_order,
  the_ring_never_overlaps_runs_in_the_air: wrapping, freeing out of
  order, no run over another in the air or across the end (20,000 random
  plans).
- card_compare_flags_land_where_the_ring_places_them (device, the host
  D3D12 device; passed on the local RX 7900 XT): card_pass with the
  host's compare at the last dwords of the area and at a plan wrapped to
  dword 0 while the first is unread: each plan's flags are at its own
  dwords, and nothing outside the two runs is written.
None of these build on perf/unified-memory (no ResultRing/ResultArea).
leonida-gpu lib: 553 passed, 46 ignored (548 + 5 new).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with LEONIDA_INPLACE>=1, title memory is opened as a host
heap (OpenExistingHeapFromAddress1, inplace.rs place_part), and while such a
heap stands the host refuses VirtualFree and VirtualProtect on its pages with
error 87 (the probe measures it). The title's VirtualFree is the runtime's
(xmem.rs title_virtual_free), but watch.rs title_memory_freed (was
watch.rs:4243-4287) never called inplace::title_memory_freeing; only the
runtime's own remaps did (title_memory_changed, watch.rs:4321). So the
window stayed in the tables, the title's free failed, and both the title's
memory and our heap were kept for good. Even let go, the heap stands until
host::retire's bury lag has passed and every descriptor slot that shows the
placed buffer is written again, so a free right after still fails.

What changes:
- watch::title_memory_freed lets go of what is in place over the freed
  range first (the whole allocation for a release of size 0).
- inplace.rs keeps a reference of its own to every buffer place_part puts
  over title memory (HELD). When ours is the last (reap), nothing can reach
  the heap any more and it goes; tick reaps every 100 ms while there are
  holds or pending releases. This is the only way to know the heap is gone:
  descriptor slots keep the buffer until written again.
- inplace::title_memory_free_held (called by xmem's title_virtual_free when
  the host refuses with error 87 and a hold stands over the memory): a
  release is retried after a reap and, if still refused, kept (the
  allocation stays reserved, so nothing else comes to its addresses) and
  done from tick once no hold stands over it; the title is told it is done.
  A decommit decommits now what no heap stands over and zeroes the rest,
  which stays committed until the title releases the allocation (a later
  decommit could take pages the title committed again with the host's own
  VirtualAlloc, which is not the runtime's). place_for refuses memory kept
  for a pending release. Counts are on the "title memory in place" line.

Switch: LEONIDA_INPLACE_FREE=0 restores the old behaviour (nothing let go,
no holds, the free fails with 87). Default LEONIDA_INPLACE stays 0, so the
default path does not change. Documented in inplace.rs and
docs/README-fxceless.md.

Tests (software adapter, as the crate's other in-place tests):
- inplace::tests::warp_the_title_releases_memory_in_place_once_its_heap_is_gone:
  VirtualAlloc, place a window in place, a descriptor-slot clone of the
  buffer, free through the runtime's path; asserts the free succeeds, the
  window leaves the tables, the release waits while the retired window and
  the slot hold the heap, and the allocation is released and no hold is left
  once they are gone. Red with the fix's behaviour removed: "the title's
  VirtualFree succeeds" (and, with only the let-go removed, "the window is
  let go").
- inplace::tests::warp_a_decommit_under_a_heap_zeroes_what_it_cannot_take:
  red: "the title's decommit succeeds".
- inplace::tests::a_free_is_cut_into_what_heaps_stand_over_and_the_rest (pure).
- warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset reaps before
  it decommits (our reference now goes at the next reap).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: texture_at (resource.rs:3440-3505 on perf/unified-memory)
makes a Resource for every (address, description) the title ever views
through a placed descriptor and inserts it into PLACED_TEXTURES (3345,
"kept for the run") and, through hand_out_resource, TEXTURES (1480).
Nothing removed either: the sweep let the host copies go but kept the
Resource, its two table entries and its stale pointer into title memory.
Streaming gives a texture's memory to others with other descriptions,
so dead entries pile up (18,639 placed host copies after nine minutes
of run 24; "a play has over 100,000" textures), and every look of the
sweep, the card accounting and the census walk them.

What changes: Hosted::named is stamped by texture_at, under the table's
lock, each time it hands a placed texture out (every view, draw and
texture pass asks there). let_go_idle, after the copy sweep and once the
TEXTURES lock is given back (texture_at takes PLACED_TEXTURES first),
looks at up to 4,096 placed textures from a cursor (evict_placed) and
takes out of the table each one that
- nothing named for 60 s and 600 frames,
- has no host copy (lists and slots hold the copy of what they name, and
  the sweep lets a copy go only when the texture alone holds it),
- has the table's reference only, was not written by the host, was not
  refused, and has no descriptor slot waiting for it (descriptor::waits).
A second and four frames later (evicted_due, as REPLACED) its reference
goes through host::retire; Drop for Resource then forgets it from
TEXTURES, staging, views, tickets and THROUGH, as for a texture the title
releases. A view asking for it again makes it again, with no host copy,
as on its first view. object::references reads an object's count. The
memory line counts the released ones and the most in the table.

Switch: LEONIDA_PLACED_EVICT=0 keeps every placed texture for the run,
as before (a texture remade after release loses its `remade` history,
which the sweep's order by reuse reads).

Test: resource::tests::placed_textures_nothing_names_are_released:
eight placed textures; none goes with the sweep's times; with times of
0, one with an extra reference and one with a host copy (local GPU)
stay, the others leave the table in two parts from the cursor, are
still alive until due, are released by evicted_due (gone from TEXTURES),
and texture_at at a released key makes a new usable one. Red with the
eviction kept from taking any (the old behaviour): left (0, Some(..)),
right (2, Some(..)), "placed textures nothing names stayed".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: create_srv and create_uav (descriptor.rs ~1751-1770 on
perf/unified-memory) keyed a view of a resource object by its whole
40-byte description, padding included: a shader resource view's word 3
(the union starts on 8 bytes) and the union's words past the member of
the view's dimension. The same view written again with other bytes
there was another table entry and another record (the host made the
slot again), freed only when the resource is released (forget,
~1486-1510): for a resource the title keeps (a target, a pool it streams
into) such entries add up for as long as it lives, and a null view's
(no resource) are never freed, nor bounded by the previous commit (they
carry no address). normal_placed (a7bb8cba) already leaves exactly these
words out of placed views, which use the same 40 bytes and whose padding
the title left as its stack held it (measured in the fork it is from: of
a million shapes, word 3 held 131,392 values). That resource views are
filled the same way is a hypothesis, not measured here.

What changes: normal_placed's view part is now normal_view, shared by
both; create_srv and create_uav zero those words before the view is
named. The host hands the words to the device as they are (host.rs
srv_desc, uav_desc), which reads none of them, so the views made are the
same; what changes is that equal views get equal records.

Switch: LEONIDA_VIEW_NORMAL=0 keeps the descriptions as the title gave
them, as before.

Test: descriptor::tests::resource_views_that_differ_in_padding_alone_are_one_entry
writes a 2D shader resource view and an unordered buffer view of one
kept resource and a null view 1,000 times each with stack-like padding,
then checks one record and three entries, the kept words, and that the
most detailed mip still tells two views apart. With the normalisation
disabled (base behaviour) it fails: "one record for the view, whatever
the padding: left 1000, right 1". leonida-gpu lib: 551 passed, 46
ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: unmap() and change() note every placeholder a view leaves
behind as that view's own (Physical::holes, xmem.rs unmap and change), and a
hole goes only when something is mapped at the same address. The title's
VirtualFree (title_virtual_free, xmem.rs:2338) told the GPU side and freed,
but never touched the holes, nor LOW_RESERVATIONS (pushed by
XMemVirtualAlloc, never removed). After the title released a reservation of
64 KiB pages, its holes stayed for good; when the host gave the same address
again (VirtualAlloc2 hands out the lowest free one), a stale one-page hole
made change() take a page of the new, larger placeholder for its own
(op.own), skip the serial split, and let the pool threads split the same
placeholder side by side, which can fail (XMemMapPhysicalPagesScatter then
returns 0). arrange() looked through stale 32-bit reservations and took the
first match.

What changes: before a release (MEM_RELEASE, not splitting or joining
placeholders) title_virtual_free reads the end of the host's allocation at
the address; once the host has released it, the holes in it and its
LOW_RESERVATIONS record go (reservation_gone). Pure fix, no switch.

Measured on the way (the test asserts it): each placeholder the runtime
split off is an allocation of its own on the host, so a release of the
reservation's base takes only the first piece; holes are removed exactly
where the host released.

Test: xmem::tests::a_released_reservation_leaves_no_holes_behind: reserve 4
64 KiB pages, map and unmap them one at a time, release; asserts holes are
left exactly where placeholders are left, none once all is released, and
that a released 32-bit reservation leaves LOW_RESERVATIONS. Red on
perf/unified-memory: "a hole is left exactly where a placeholder is left",
left [0, 1, 2, 3], right [1, 2, 3].

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every decision that leaves GPU_UPLOAD (ReBAR) and in-place memory off
rested on an NVIDIA card on PCIe 4.0 x8 or the software adapter
(host/send.rs on_card, docs/findings.md LEONIDA_WINDOWS_BAR_MB row,
inplace.rs module notes). Nothing measured an AMD card.

host::placement (an #[ignore] device test in the style of
indirect::bench) fills buffers of 1, 16 and 256 MiB in default-via-upload,
upload, GPU upload (when D3D12_OPTIONS16.GPUUploadHeapSupported), custom
L0 write-back and VirtualAlloc memory opened with
OpenExistingHeapFromAddress, with memcpy and with non-temporal stores;
times on a direct queue a CopyBufferRegion into a device-local buffer and
a compute shader reading every byte (twice, in a second submission; its
XOR is asserted equal to the CPU's); and times the CPU reading the mapping
back with plain and streaming loads. It prints the adapter, the driver
version DXGI gives and the D3D12Core.dll loaded with its SDK version.

docs/findings.md gets the table from this PC (Ryzen 7 5800X, RX 7900 XT
on PCIe 4.0 x16, driver 32.0.32029.2010, Windows' D3D12Core SDK 616): the
card reads the PC's memory at 23-28 GB/s whether write-back or
write-combined, the CPU reads write-combined memory at 0.13-0.19 GB/s,
and Resizable BAR is off in this PC's firmware (256 MiB window,
GPUUploadHeapSupported false), so SEND_BAR and WINDOWS_BAR_MB fall back to
nothing here. No behaviour changes.

Run: cargo test -p leonida-gpu --release --lib host::placement -- --ignored --nocapture

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: every title texture read through a table kept a
write-combined UPLOAD staging buffer as big as its host footprint for as
long as its staging state lived (texture.rs Staging, STAGING), and the
sweep lets that go only after ram_idle_ms, which is 300 s whenever 12 GiB
or more is free (host.rs:465-482). Nothing on the CPU reads the buffer
after the copy, and the next copy follows a detiling that writes it whole:
it was a third copy of every sampled texture's bytes beside title memory
and the card's (2,246 buffers, 2.1 GB at the end of run 24, texture.rs
let_go_idle; 5.2 GB of staging blocks in run crash-1, pool.rs:35). It was
kept because the buffer and the change tracking were one object, and a
fresh Staging re-detiles and re-uploads (draw.rs:4084-4092).

What changes: the buffer's memory is its own object (Staged: buffer, base,
pool piece, mapping; counted in STAGED). The Staging keeps footprints,
layout, Last (hash, asked, hot_until, partial), uploaded/dirty, holds and
the on-demand state, and holds the buffer in an Option. With
prelude_upload (the default), PreludeUpload::claim hands the buffer to the
list (PreludeUpload::held, until the list is reset after its last
submission ran) and the texture lets go of it. A detiling makes it again
(a cut from a pool block); an unchanged texture is neither detiled nor
copied again and needs none. A texture detiled twice within 3 s
(HOT_STAGING_MS, longer than a pool piece rests, 2.5 s) keeps its buffer,
so one that changes often does not cycle resting pieces; the once-a-second
sweep lets go of it after 3 s without a change (let_go_cold). A claim that
finds the texture marked to be copied with no buffer and nothing detiled
(an on-demand level that waited for room) forgets what was detiled and
copies at the next check instead of copying zeros; the on-demand retry
forgets at once when the buffer is gone. A detiling that cannot get a
buffer forgets too, so the next check tries again and the card keeps what
it has. The record-time path (LEONIDA_PRELUDE_UPLOAD=0) and the copy-queue
path (ahead.rs) hold the buffer they record from. The memory line counts
buffers let go and made again.

Switch: LEONIDA_STAGING_RELEASE=0 keeps each buffer with its staging state
as before (it can cost a pool cut at a changed texture's detiling).

Tests: texture::staging_release_tests::
a_copied_texture_keeps_its_change_tracking_but_not_its_staging_buffer
(device test on the local GPU, after prelude_upload_tests): on the base it
fails at "the staging buffer goes once its copy is recorded" (left 90640,
right 0, a 256x256 BC7 with nine levels); now the list holds the buffer
until it is dropped, an unchanged texture is not copied and the card keeps
its bytes, changes reach the card with and without a kept buffer, and a
dirty mark with no buffer re-detiles instead of uploading zeros.
only_a_texture_detiled_often_keeps_its_staging_buffer checks the window.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: upload_from calls staging() first (texture.rs, the
staging() call ahead of the movie_plane branch), which made a staging
buffer the size of the texture for every linear one-level R8 2D texture
too. Those take the movie_plane path (Staging::movie_plane): each list
copies from an upload chunk of its own, filled at its submission
(HostList::plane_upload, fill_plane). The staging buffer was never written
or read, and since that path never checks or claims it, nothing let it go
before the sweep dropped the whole staging state (up to 300 s,
host.rs ram_idle_ms).

What changes: staging() makes the staging state of such a texture without
a buffer. A detiling makes one if one is wanted after all (the copy queue's
first uploads, ahead.rs, which now takes the buffer through
bytes_to_fill). No switch: nothing reads that buffer.

Test: texture::staging_release_tests::a_video_plane_has_no_staging_buffer
(device test on the local GPU): a 64x64 linear R8 title texture sampled by
a list has its staging state and no staging buffer, and the plane still
reaches the card. With the change undone it fails at "and no staging
buffer" (left 16192, right 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: every list that samples a linear one-level R8 2D texture
(Staging::movie_plane, the shape is the whole rule) took an upload chunk
of its own (HostList::plane_upload), filled it with the whole plane at its
submission (Step::Plane, fill_plane) and recorded the copy into the host
texture at record time (record_upload in upload_from's movie_plane
branch), with no change check: two lists of a submission copied it twice,
and a plane that stands still (a paused or 30 fps video in a 60 fps
title, or any static texture of that shape) was memcpy'd and copied over
PCIe again at every list.

What changes: with prelude_upload, the plane goes through the list's
prelude like other title textures. At the list's submission its fill
reads and hashes the plane (fill_plane_if_new) and fills the list's chunk
only if the digest differs from the one the host copy was last given
(Staging::plane_on_card); PreludeUpload::claim (claim_plane) then hands
the prelude a copy from that chunk, or nothing, and a second list of the
submission finds the picture there. The check and the copy happen at the
list's own submission, so a list recorded before a change reads it (not
a frame late, the ring-of-three history in upload_from), and a picture the
card had before is copied again when it comes back. Upload now names its
source buffer and base, holding the staging buffer when that is the source.

Switch: LEONIDA_PLANE_SAME=0 restores a fill and a copy by every list,
recorded where the list was.

Test: texture::staging_release_tests::
a_video_plane_is_copied_when_it_changed_not_by_every_list (device test on
the local GPU, 64x64 linear R8 title texture): two lists in one
submission copy it once; an unchanged plane is not copied again and the
card keeps it; a list recorded before a change reads the change; a ring
picture coming back is copied; a change between two submissions is the
later one's. On the previous commit (with a test-only copy counter in the
old branch) it fails at "the first list of the submission copies it, the
second finds it there" (left 2, right 1).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: dstorage::tests::the_walls_trace_names_the_file_a_request_reads
released a file object and opened up to 256 more until one landed at the released
address. When none did it printed a line and returned, and then it passed on the old
lookup by address too, which names every file object at a fresh address right: the
case it is for was reached only when the host's heap happened to hand the address out
again.

What changes: the test opens two files and swaps the two objects' states in place, so
the object at the first one's address is the second file, as one opened where a
released one was would be, with both opened through open_file. No retry loop, no
fallback.

Test: on the old lookup (WALLS_FILES restored with its push in open_file) it fails
every run:
  assertion `left == right` failed: the second file at the first one's address
  left: "...\first.bin"  right: "...\second.bin"
With walls_file reading File::name it passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With the ring, card_results_short asked for every dword its ranges would
take, and when that was more than the ring holds (cap) the wait in submit
ran until the line was empty: a full drain, also of flights holding no ring
space, that bought nothing since card_before places (0, cap) and fetches
the rest whole either way. The only case where the ring waited and the base
(which drained only at half-full) did not.

ResultArea::short now asks for room only when the ring is short and the
whole ring could hold the plan; the line-empty condition of the wait is
left as a net. The area's size is the module constant CARD_RESULTS so the
submission knows the ring's cap.

Test: result_ring_tests::a_plan_longer_than_the_ring_does_not_wait. With
short's condition as before (want > room) it fails "more than the whole
ring: left Some(101), right None"; with the fix it passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
SWEPT_US began after idle_by_age, so the look by age that the commit
before shrinks was never in it, and it took in evict_placed, evicted_due
and their retire, which the release of placed textures added: neither
number was comparable with the 2.2 and 11.6 ms recorded in
d3d12/docs/findings.md. It now runs from taking the table of textures to
giving it back (look by age, walk, commit floor's walk), and the release
of placed textures is timed in PLACED_EVICT_US, on the placed-textures
memory line. The docs of SWEPT_US and idle_by_age say what the recorded
numbers measured; the doc of let_go_idle no longer says the title
resource always stays.

No test: timing only. leonida-gpu builds with and without diagnostics,
no warning in the lines touched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fetched::fetch_size made a buffer smaller once the last 128 fetches all
needed at most a quarter of it, counting fetches only. A large fetch that
came back every 128-odd fetches (a new copy's first compare, a range
fetched whole, torn::Check's whole pieces) made it smaller and larger
again every time: a committed CUSTOM write-back buffer of its size made
anew, made resident and waited for, on the landing thread or under the
submission lock in card_back, where 128 fetches can be well under a
second. Now Sizes also notes when the last fetch that needed more than a
quarter of the buffer was, and a smaller buffer waits until that is
ram_idle_ms (2 s to 5 min) ago as well. The frame line counts the
buffers made smaller and those made larger again (fetched::STATS).

Test: fetched::tests::a_large_fetch_every_second_keeps_the_buffer, a
100 MiB fetch every 200 fetches 5 ms apart. With the count alone it
fails (40 buffers made, 20 smaller, 19 larger again); with the time floor
one buffer is made, and once the large fetches stop it comes down
exactly the idle time after the last.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With the cells kept (LEONIDA_LANDED_EXACT=1, or LEONIDA_AB naming it),
note_cells asked `pages()` for the whole stretch again for every block
`elsewhere` shows at other addresses and filtered it to the block. Since
landing_cells_whole no longer builds a list, that re-ran cells_between
(up to 512 cells a page) for every page of the copy-back once per
aliased block, where the base only filtered a prebuilt Vec. `pages` now
takes the page range it is asked for: the copy-back works out only the
block's pages again, the shaders' list is filtered as before.

Test: watch::cells_tests::a_copy_back_notes_its_cells_at_the_other_view_
working_each_out_once_more maps a 4-block view twice, copies back 6
blocks over one of them and counts the pages whose cells were worked
out (a test-only thread-local counter), and checks the cells noted at
the other view. RED before the fix: 480 (96 + 4 x 96), expected 160
(96 + 64). GREEN after; also with LEONIDA_LANDED_EXACT=1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
In ring mode every flown submission ran card_declared and card_asked twice,
once in card_results_short to size its wait and again in card_before to
place it: each run clones every carded declared range vector, applies
picked::with, and clones and sorts the ranges per copy, on the submission
thread under the submission lock.

submit now gathers them once (card_ask, a CardAsk holding the declared and
looked ranges and the asked list) right after declared_writes; the wait
sizes itself from it and card_before takes it by value, consuming the asked
list into the plan's ranges. Nothing between the two reads changes what
they gather: card_span depends only on the copy's place, and whether a copy
has its hashes from before (card_make_before) is still asked at placement.
The !cards() early-out moves into card_ask; card_before's order of locks and
its None cases are unchanged.

No behaviour change, so no red test: the leonida-gpu lib suite passes as
before, the ring tests included.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When fetched::fit could not make the smaller buffer it kept the old one,
but the window still said smaller: every later fetch asked
shared_buffer again, logged another warning and called
allocation_error, on the landing thread (or under the submission lock in
card_back), while memory was already short. Now Sizes::not_made starts
the window over and notes the failure as a large fetch, so the next try
waits SEEN (128) fetches and ram_idle_ms.

Test: fetched::tests::a_smaller_buffer_not_made_is_not_tried_at_each_fetch,
one fetch of 512 MiB then 999 of 1 MiB with no smaller buffer ever made.
Without the back-off it tried 872 times; with it 7 (one every 128).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
hold() was called from place_part, which by_address_opened (opened_side)
also uses for the runtime's own arenas: memory the title never frees.
Each arena was held for good, so WAITING never dropped back to 0 and
tick() reaped every 100 ms (an AddRef/Release per arena, the HELD and
PENDING locks) even with LEONIDA_INPLACE off, and every arena buffer
carried one extra reference. The hold is now taken in place_for, the
title-memory path, after place_part succeeds; place_part says why.

Test: inplace::tests::warp_memory_placed_by_address_is_not_held (WARP).
With the hold put back into place_part it fails with "an arena's memory
is not held" (left 1, right 0); it passes with the fix. The device tests
that stand for place_for place through place_held (place_part + hold).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With LEONIDA_UPLOAD_AHEAD, a job whose staging buffer could not be had
recorded no copy, but finish() still set uploaded, cleared dirty, noted
what the host copy holds and set ahead to DONE: a placed host texture
that was never written was taken for filled, ahead::there() kept the
draws from uploading it, and a later upload skipped the first upload's
aliasing barrier. finish() now gets which jobs were recorded; one that
was not goes back to LISTED with its upload state untouched, so the next
list that samples it uploads it (the first upload if none ran). What
waits for it is still told.

The worker also took the buffer with bytes_to_fill() after all the
detilings: a list's submission that claimed the texture after listed()
gave up waiting could let go of the buffer in between, and the worker
then copied a new all-zero buffer over what the list brought. It now
takes the buffer right after each job's detiling, and a job with none
records nothing (a video's plane that found nothing to detile included).

Test: texture::ahead::tests::a_job_that_copied_nothing_leaves_the_texture_to_the_lists
(device, 128x128 BC7). The job's buffer is let go and none can be had
(test-only TEST_NO_STAGED, by resource); red before: "nothing was copied:
not filled ahead" (there() was true). Green after, and a list then
uploads level 0 as the memory holds it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
send::let_go_idle used an idle time of 0 while the PC's memory was
pressured, so each sweep let go of every spare, including buffers given
back milliseconds before: the pipeline's working set. The next some 30
submissions then made theirs anew (above pool::small::MOST a committed
resource each, 1.6 ms an upload buffer in docs/findings.md) while the
ones let go still waited bury_lag submissions in retire_resource's line,
so pressure raised what was held instead of lowering it, every second.
Now idle_for gives PRESSED_MS (250 ms) under pressure; the trim() and
let_go_idle docs say so.

Test: send::pool_tests::under_pressure_what_just_came_back_stays, spares
given back 1000, 100 and 16 ms before a pressured sweep. With 0 all
three went ([1, 2, 3]); with the floor only the one a second old ([1]).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The ring's integration in card_before (one run placed for the pieces of the
ranges that can be compared, each compared range at the next dword of
[start, start + room), what does not fit fetched whole, looks not compared
left out, the run taken and its ticket kept for card_done's give_back) ran
inline and no test exercised it: the device test called card_pass at
offsets a standalone ResultRing gave, so a placement past the run or a run
never taken or given back would pass every test.

That glue is now ResultArea::plan, generic over the range so card_before
moves its CardAsked entries straight into CardRanges. Driving card_before
and card_done themselves was not done: they go through the process-wide
CARD_WORK, QUEUE_ORDER and the shadow registry's dirty lists, which other
lib tests running in parallel share.

Test: result_ring_tests::a_plan_compares_in_its_run_and_gives_it_back: with
the ring partly taken a plan's compared ranges lie one behind the other in
its run, clear of the runs in the air (also after wrapping to dword 0), a
copy without hashes and ranges past the run are fetched whole, a look that
is not compared is left out, a plan comparing nothing takes no ticket, and
the tickets given back (out of order, then in) free the whole ring. With
plan taking nothing for its run it fails "left: 100, right: 40".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
evict_placed released a placed texture whose host copy the sweep had let
go, and texture_at made a new resource for its key with gone false and
remade 0: its first copy counted as a first make. The memory line's
"made again" count (KINDS[4], KINDS[5]), the one d3d12/docs/findings.md
judges the sweep and LEONIDA_COMMIT_FLOOR by, undercounted from then on,
favour_reused ranked the texture as never reused, and the card's
accounting put it with those never made. evict_placed now keeps, for a
released texture whose copy had gone, its remade count by a hash of its
key in GONE_PLACED (the newest 65,536, oldest forgotten), and texture_at
hands gone and remade to the texture it makes for that key.

Test: resource::tests::a_released_placed_texture_made_anew_keeps_its_copy_made_again
fails with the hand-over in texture_at disabled ("a placed texture made
anew forgot that its copy was let go") and passes with it;
gone_placed_keeps_the_newest covers the bound. leonida-gpu lib suite 552
passed, 46 ignored, twice with --test-threads=4; clippy: no warning in
the lines touched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The trim() and SLACK docs said a spare serves only what asks for more
than half of it, but most_served allowed a spare up to twice what
made_size gives, which rounds up and to at least 1 MiB: a 2 MiB spare
served a send of 4 KiB and a 2.25 MiB one a send of 1.01 MiB, more than
doubling the bytes held in flight. Now most_served is the larger of
made_size (so a spare as large as would be made, the 1 MiB least among
them, still serves) and one under SLACK times the send, so what a
submission holds is less than twice what it sends or what would be made
for it anyway; the docs of trim(), SLACK and most_served say that rule.

Test: send::pool_tests::a_spare_holds_less_than_twice_the_send. With the
old bound it fails ("a spare of 2097152 serves a send of 4096"); with
the new one it passes, and steady_sends_hold_less_and_still_find_spares
still passes (spares are still found after the first frames).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: upload::release called VirtualFree at once, and upload::reserve
first freed every address still waiting (release_late). Their callers hold locks
other threads wait for: Memory::new and Memory::another run under MEMORY (memory::ready,
the draw path), and Upload::new reserves under ARENAS. So a 64 MiB arena whose copy
was refused, and any arena left from before, was freed with draws on other threads
waiting.

What changes: release only notes the address. release_late frees what was noted,
and runs where no lock is held: memory::ready calls it after the MEMORY guard is
dropped (ready's body is now ready_held), so what a draw was refused goes back at
that draw and cannot pile up while the directory and arenas are retried draw after
draw; and host::sweep calls it at every submission, before the LEONIDA_SWEEP gate,
for memory a heap opened on it still held at the draw (error 87). reserve frees
nothing. An atomic flag lets release_late return without the lock when nothing
waits, as it is now called per draw.

Test: upload::tests::memory_given_up_is_given_back_after_its_users_lock reserves and
releases two blocks and asserts nothing was freed on this thread by release or
reserve (a thread-local count of release_late's frees), then that release_late frees
both. With release freeing at once it fails "left: 2 right: 0"; with only reserve
draining, "left: 1 right: 0". memory::tests::memory_whose_copy_is_refused_is_given_back
now calls release_late after the refusals, as ready does: 4 of 4 given back at the
first try on the 7900 XT.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PreludeUpload::held got an entry at every claim and was emptied only at
the list's reset. A list may be submitted more than once without a reset
(host.rs, the descriptor ring note), and each such submission of a
texture that changed less often than the hot window copied from a new
staging buffer: the list kept every one of them, more upload memory than
the base, which kept one buffer per texture. Each entry now carries the
number of the submission that copied it (crate::host::submissions), and
a claim first drops those whose submission has finished; what the
current submission copies (begun, not finished) stays, so a list run
twice within one submission still holds both.

Test: texture::staging_release_tests::a_list_submitted_again_holds_only_what_its_last_submission_copies
(device, 128x128 BC7, hot window 0). One list submitted four times with
a change before each; red before: "only the last submission's buffer is
held", left 4, right 1. Green after, and the last one goes with the
list's reset.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
title_memory_free_held took a free over only while a hold stood at that
moment, and its decommit branch ran reap() and then cut the range by the
holds left, so the pages of a hold the reap had just let go of went into
one VirtualFree(MEM_DECOMMIT) with the rest. The host does not always
let go of a heap's pages at once (GIVE_UP_MS says so), and one decommit
is all or nothing: refused with 87, its result was not looked at and the
title was told TRUE with every page still committed and holding its old
bytes. A release (or decommit) arriving after tick() had reaped the hold
but before the host let go found no hold, was not taken over, and the
title got 87 back: the leak the take-over was there to close.

A hold let go of now stays in HELD as such (buffer None, the time) for
GIVE_UP_MS and counts as in the way of the title's frees; release_pending
waits only for standing holds. The decommit cuts the free parts where
lately-let-go holds were and zeroes, region by region, what the host
still refuses (only committed, writable pages; others are left and said
once), as it does under standing holds.

Tests (WARP), keeping the heap alive with its buffer gone to stand for
the host not yet letting go:
inplace::tests::warp_a_decommit_the_host_still_refuses_once_the_hold_went_zeroes
fails with the old cut and the refusal ignored (pages
[COMMIT; 5] instead of [RESERVE, COMMIT, RESERVE, RESERVE, COMMIT]);
inplace::tests::warp_a_release_before_the_host_let_go_of_a_heap_is_taken_over
fails with only standing holds looked at ("the title's VirtualFree
succeeds"). Both pass with the fix. The tests count standing holds only,
as let-go ones stay noted over addresses a later test may get.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Staging::plane_on_card was set only by claim_plane. In a diagnostics
build crate:🆎:pick switches prelude_upload (and so plane_same) while
the title runs: a prelude copied picture Y (on_card = Y), a list with the
prelude off copied picture Z on its own, the ring came back to Y, and the
next prelude list found on_card == Y and copied nothing, leaving Z on the
card until the plane changed again. The record-time path's fill, which
runs at that list's submission ahead of its copy, now clears on_card, so
the next prelude list copies its picture. The field's doc says so.

Test: texture::staging_release_tests::a_plane_copied_by_its_list_is_not_taken_for_the_prelude_s
(device, 64x64 linear R8, plane_same switched by TEST_PLANE_SAME between
lists). Red before: "the first again, not the second left on the card".
Green after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: the bound on table entries that carry an address
(c6afc1f7, on by default past 1,048,576 of them) let go of any such entry
nothing had looked up for a clock round. A slot holding the record was no
reason to keep it: a view written into a CPU-only heap (which no mirror
reads) or a shader-visible slot no draw read for a round lost its entry,
and when the title later copied the record into the heap the shaders see,
the host found it stale and made the slot null for good. The hand also
walked every entry of the table, views of resources and samplers too,
under the lock every draw-recording thread shares, and a round in which
nothing could go was gone through again for every new view.

Now every view heap, CPU-only or shader-visible, is registered
(VIEW_HEAPS), and each round of the hand begins with a look through their
records (heap_records, through the kernel as sync_heaps reads them): every
entry a record names at its generation is seen, so it is not let go
whether or not anything looked it up. The hand walks only the entries that
carry an address (Views::addressed); one let go is given the new view in
its place. The look also counts the distinct entries the slots name, and
the table is asked to let go again only once it holds a quarter more than
that (Views::put_off), so a table the slots hold nearly whole grows instead
of going round for every view. A view let go and written again is named
again, as before. The docs of Views and inline() no longer say
LEONIDA_VIEW_INLINE=0 alone restores the old behaviour: that also needs
LEONIDA_VIEW_ADDRESSED_MOST=0.

Tests: entries_a_live_slot_names_are_never_let_go keeps eight views in
slots nothing looks up through a hundred rounds of the hand (6,400 views
streamed past a most of 64), then looks them up; and
entries_live_slots_need_past_the_most_are_kept has slots name 100 entries
past a most of 64. RED with the look through the slots disabled (the
old policy): "a slot's view, first looked up now: left None", and
"left: None, right: Some(Constant(..))". GREEN: all kept, at most 64 and
126 entries, one look through the slots a round.
view_heaps_are_looked_through_while_they_are_there checks a CPU-only
heap's record is found while the heap is there and not after it is
released.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The take-over of a refused free lived in xmem::title_virtual_free (the
GPU side told first, the host's call, GetLastError() == 87, return TRUE
or SetLastError(87)), and the device tests of inplace.rs reimplemented
it by hand in title_frees: had xmem drifted from the copy, no test
would have seen it. That glue is now leonida_gpu::title_memory_free(at,
len, kind, free), with the host's call (and what xmem notes around it,
reservation_gone) passed in as `free`; xmem calls it, and title_frees
calls it with a plain VirtualFree. title_memory_free_held is crate-only.
The last error is now set back to whatever the host left, not to 87
alone (the same value on the only path that reaches it).

Tests: the inplace device tests now go through title_memory_free
(inplace:: 14 passed); xmem::tests::a_free_the_host_refuses_comes_back_refused_with_its_error
drives title_virtual_free with a release the host refuses for its own
reason (a size given) and checks 0 and error 87 come back through the
take-over. No behaviour was wrong, so there is no red run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With the staging buffer let go after its copy, each change of a texture
that is not hot makes one again at its detiling, on the submission's
refresh workers. A piece the pool gave out again was zero-filled whole
by pool::staging and then detiled: the write-combined memory was written
twice. pool::staging now takes whether the caller needs zeros; the
detiling asks without (Staging::bytes_to_detile), as it writes every row
the copy reads, zeros for levels not the title's. A subresource that
cannot be detiled zeroes the buffer from there to its end when the
buffer was made unzeroed, so what reaches the card is what a zeroed
buffer gave before. The first upload's buffer, a copy of a buffer never
detiled (bytes_to_fill) and a buffer of its own (new memory, zeros)
are as before.

Test: texture::staging_release_tests::a_detiling_writes_all_the_copy_reads
(device, 256x256 BC7, nine levels): the staging buffer is filled with
0xa5 before the submission's detiling, and every row of every level the
host copy then holds matches the layout's detiling. This guards the
premise; it is a cost change, with nothing red before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
inplace::title_memory_section_gone removed the section's own view
(Views.whole) and never its record in Views.sections, which then stayed
until the handle's number was given out again: the census counted
sections long gone, and the map grew with every handle number not yet
reused. Both go now. beside() looks a section up only through a view the
title sees of it, and the runtime says the section is gone once no view
is left, so nothing needs the record after.

Test: inplace::tests::a_section_let_go_of_is_forgotten. With the removal
left out it fails with "the section's record went"; it passes with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since the staging buffer goes once its copy is recorded, the comments
that said otherwise were wrong: keep_freed and ram_idle_ms said staging
buffers stay five minutes with 12 GiB free, let_go_idle that the buffer
is kept so an unchanged texture is not uploaded again, unstage that it
lets go of the buffer, and LET_GO, its trail line and the memory line
called what the sweep counts staging buffers. What is kept that long is
the staging state (its change tracking), with its buffer only while the
texture changes often; the sweep counts states, and the bytes of the
buffers that went with them. Comments and log text only; no test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
After the runtime split a reservation of 64 KiB pages (change and unmap
map and unmap page by page, each leaving a placeholder of its own), each
piece is an allocation of its own on the host, and the title's
VirtualFree(base, 0, MEM_RELEASE) released the first piece only: the
rest stayed reserved for good, address space leaked per reservation
released (and the GPU side heard of the first piece only).

XMemVirtualAlloc now records every reservation the host makes as a
placeholder (PLACEHOLDERS, bytes by base), and title_virtual_free joins
the pieces of one (MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS over the
recorded bytes) before the title's release, when the host's allocation
at the base is shorter than the record. The host joins any adjacent
placeholders of one original reservation, so the record follows the
title's own splits and joins through the same call (placeholder_split,
placeholders_joined): a join never takes in a piece the title split off
and sees as a reservation of its own. A join the host refuses (a view
still mapped there) leaves the old behaviour, said once. The record
goes with the release (reservation_gone).

Tests: xmem::tests::a_released_reservation_leaves_no_holes_behind now
expects all four pages released and no hole left; without the join it
fails with "all of the reservation is released" (left [1, 2, 3]).
xmem::tests::a_release_joins_the_runtimes_pieces_and_not_the_titles:
without the join, "the title's first piece, all of it" ([true, false,
false, false]); with the title's split not followed, the join takes the
title's other piece too ([true; 4]); with its join not followed, a piece
stays ([true, true, false, false]). All pass with the fix. Both tests
reserve top-down: the other tests take the lowest free addresses, and
took the released pages back before they were looked at.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
a_released_reservation_leaves_no_holes_behind and
a_release_joins_the_runtimes_pieces_and_not_the_titles both reserve from
the top of the range so that the rest of the suite, which takes the
lowest free addresses, does not take their released pages back before
they are looked at. Run side by side in the full leonida-hle suite they
took each other's: one released its reservation and the other's next
top-down reservation landed on it (both failed, 1 run in 2). They now
hold one lock (top_down_turn) and MEM_TOP_DOWN is one constant of the
test module.

Test: cargo test -p leonida-hle --lib, 6 runs in a row, 222 passed each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	d3d12/crates/leonida-gpu/src/host.rs
# Conflicts:
#	d3d12/crates/leonida-gpu/src/host.rs
What was wrong: pages_per_section(None) (leonida-hle xmem.rs:716 before
this) returned usize::MAX, one section for each allocation (6.1 GiB for
the title's page pool), and the comment above section_pages (xmem.rs:663)
said the switch stays off "until a run says". That run is in
docs/findings.md:647 (RTX 4060 Ti, one run of 4 minutes walking and
turning each, from one save): one section 111.6 ms a frame on average,
title memory held for mapping changes 43.2 ms a frame, mapping thread
46.2; 16 MiB 94.4 / 8.9 / 20.7. Only scripts/play-nvidia.ps1 set
LEONIDA_SECTION_MB=16; play.ps1 (the AMD launcher), cargo run and other
front ends got the slow layout.

What changes: LEONIDA_SECTION_MB unset means 16 MiB (DEFAULT_SECTION_MB);
0 or a value that is not a number is one section an allocation, as
before. The exclusions stay (renderer port 1, Wine). The comment cites
the measurement. play-nvidia.ps1 keeps its explicit 16 (the same value;
its comment says it is the default now); play.ps1 needs nothing.
README-fxceless.md and findings.md say so.

Why this one is flipped and the other two named with it are not:
- LEONIDA_SECTION_MB: what it saves is the host's work per view of a
  section (the kernel's list of a section's views, walked under the
  section's lock, and the address-space lock the title's mapping calls
  wait on), nothing of the card's or its driver's. Not NVIDIA-specific in
  nature: on by default.
- LEONIDA_ALIAS_DIRECT (leonida-gpu texture.rs:351-365, findings.md:768,
  -2.6 ms +-0.9): the gain is the card's copy work (3.6 -> 1.9 ms of a
  timing run) as NVIDIA's driver does a texture-to-texture copy between
  R32_UINT and R9G9B9E5, and its check that the bits arrive unchanged was
  made on that card with the debug layer (42ff296c). Both are the
  driver's: left off by default; an A/B on the RX 7900 XT
  (LEONIDA_AB=<s>,LEONIDA_ALIAS_DIRECT) is what would decide it there.
- LEONIDA_BATCH_KEPT (leonida-gpu host.rs:10576, switch.rs:9-15): CPU
  side, so not NVIDIA-specific in nature, but there is no measurement of
  it in this runtime at all: 1c731ebd ported it from a fork that measured
  a profile share only, left it off for want of a frame-time A/B, has no
  test of the equivalence it claims, and no launcher has ever run it.
  Turning on an unexercised 228-line path for every run is not a default
  change a measurement backs: left off.

Switch: LEONIDA_SECTION_MB=0 restores one section an allocation.

Test: section_sizes_come_from_the_switch asserts pages_per_section(None)
== 256 (and still Some("0") == usize::MAX). Red on perf/unified-memory:
"assertion `left == right` failed, left: 18446744073709551615, right:
256". leonida-hle lib: 223 passed, 2 ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: XMemAllocatePhysicalPages numbered pages from a counter
that only grew (xmem.rs:639 next_page 0x10_0000, :794-795 next_page +=
n * FRAMES) and XMemFreePhysicalPages never gave a number back (:827).
The title keeps a number as 21 bits of number >> 4 (FRAMES, :813-816),
so after (2^25 - 2^20) / 16 pages, 124 GiB of allocations in a session,
the numbers passed 2^25 and the title rebuilt them as number - 2^25:
below 0x10_0000 no page at all (the next 4 GiB of allocations: their
mappings fail, "XMemMapPhysicalPages: unknown page"), above it the number
of a page of another allocation, mapped in place of the title's own
without a word.

What changes: Numbers hands numbers out from the counter while it lasts
below END_NUMBER (2^25) and then from those freed, lowest first; freed
numbers are a bitmap (at most 2^21 - 2^16 bits, 248 KiB, grown as the
counter goes). With more than 2^25's worth live, the allocation fails
(count 0, FALSE, a warning) instead of handing out a number the title
cannot keep. Numbers are taken before any section is made and given back
if a section cannot be. Nothing else of the runtime names a page by its
number once freed (views, aliases and the GPU side know a page by section
and index or by address), and in the first 124 GiB the counter alone
serves, as before, so no switch: the change is only past the point where
the old numbers were wrong.

Tests: page_numbers_stay_in_the_titles_21_bits (with the counter alone,
as before: "the title keeps 0x2000000 as 0x0") and
page_numbers_come_back_round_after_round (10,000 rounds in a space of 64
numbers; with the counter alone the numbers leave the space).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: XMemAllocDefault (leonida-hle xmem.rs:335-371 on
perf/unified-memory) served every block that is not 32-bit from the Rust
global allocator, with a header in `align` bytes of padding (layout, 270).
That memory is not write-watched, so GetWriteWatch fails on it
(leonida-gpu watch.rs kernel_written), guard() answers None because it is
no view, and every refresh of a host copy of it re-read and compared all of
it ("all of it where neither works", shadow.rs module doc). It sat above
2^40 (the test binary's heap gave 0x1a5fdc60000), and a block aligned to
64 KiB - the executable's constant XMemAlloc attribute 0xf0814000,
docs/xmem_exe_calls.md - cost 64 KiB more than it asked.

What changes: a block of 64 KiB or more, or aligned to 64 KiB or more
(watched_block), is a reservation of its own made as XMemVirtualAlloc makes
the title's (virtual_alloc, the old body with an alignment for requests
above the host's 64 KiB granularity): MEM_WRITE_WATCH, below 2^40, told to
the GPU side (title_memory_allocated), committed to its own 4 KiB pages.
WATCHED_BLOCKS (address -> size) is authoritative for the free:
XMemFreeDefault releases what is there through title_virtual_free, which
tells the GPU side as the 32-bit path already did, and title_virtual_free
drops an entry with its reservation. A refused reservation falls back to
the heap. XMemAllocDefault now says, at powers of two, how many blocks and
bytes went each way, since nothing measured how much of the title's memory
its hook passes on here.

Switch: LEONIDA_XMEM_DEFAULT_WATCHED=0 serves every block from the heap, as
before (README-fxceless.md, "Speed and memory").

Test: xmem::tests::large_default_blocks_are_write_watched_and_below_2_40
(GetWriteWatch sees exactly the one page written, address below 2^40,
64 KiB and 4 MiB alignment, a 128-byte block commits one 4 KiB page, frees
reach TOLD_FREED) and default_blocks_from_64_kib_are_reservations_of_their_own.
Red with the old path (LEONIDA_XMEM_DEFAULT_WATCHED=0): "the kernel keeps
no written pages of 0x1a5fdc60000".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: a host descriptor slot keeps the resource it views
(descriptor/host.rs HostHeap::kept) until the title writes the slot again.
A buffer placed over title memory (LEONIDA_INPLACE) is held by every slot
that shows it, and the title need never write those slots again once it
freed the memory: inplace.rs HELD noted it ("descriptor slots keep the
buffer until the title writes them again"), so the heap stood and the
title's release stayed pending for good (PENDING, inplace.rs
title_memory_free_held).

What changes: when the title frees or decommits memory a held buffer is
placed over (title_memory_free_held), the slots of every host view heap
that view one of those buffers let go of it (descriptor::let_go_of_buffers
-> HostHeap::let_go_of): a title slot becomes the null view of its record's
kind and unmade, to be made again from the record when a draw or the
buffer pass reads it (told it changed); a dynamic slot no list holds
becomes a null view under the lock slots are taken with; a dynamic slot a
list holds is left (the list keeps the buffer itself until reset). The old
buffer is retired as any slot's is. While a release waits on a standing
hold, reap asks the slots again once a second (slots_again). The say line
counts the slots let go.

Switch: LEONIDA_INPLACE_SLOTS=0 restores the old behaviour (slots keep the
buffer until rewritten). Documented in inplace.rs and README-fxceless.md.

Test: inplace::tests::slots_over_memory_the_title_released_let_go_of_its_buffer
(the host's device, a real title view heap): red with the let-go disabled,
"the title slot let go of the buffer" fails at the first assertion after
the free; green with the fix, and the release completes once the list
gives its slot back.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: Shadow::writing (shadow.rs:4066 on perf/unified-memory)
made a copy's snapshot with pooled(total), room for the whole copy, at the
first range shaders were declared to write, whatever its size. One 64 KiB
range of a 64 MiB copy took 64 MiB of commit (Vec::with_capacity commits
all of it), and from the pool a buffer some earlier snapshot had touched
whole, for as long as any range of the copy was pending. Windows of 4 MiB
and buffers card_for turned away paid this at every submission with
shader writes.

What changes: the snapshot is a Snapshot, stretches (first offset, end,
buffer from the pool) apart and in order that begin and end where 64 KiB
pieces of title memory do. A declared range where no stretch is gets one
for the pieces it is in, up to its neighbours. Stretches never move and go
back to the pool together in copy_back_done, so find_all and take_snapshots
still hold addresses in them without the lock. Every user indexes by the
copy's offset through the stretch that holds it: writing (direct copy,
SNAPS notes, kept pieces), find_all (a scan per stretch, results put back
per range), copy_back_with (differing per stretch, the old bytes of each
found piece), relay_merge and land_back (a piece is in one stretch),
merge_under_writes (the page's bytes; merge_page_under_writes now takes
the page's own pointer), placed_copy (only what a stretch holds: where
none is, nothing was declared and a later declaration takes the copy's
bytes anyway). find_pieces adds offsets with wrapping_add, since a
stretch's base less its first offset is only a number.

Not measured in the game: one pooled/give_back per stretch instead of one
per copy and submission, which costs more where a copy's declared ranges
are many and apart.

Switch: LEONIDA_SNAPSHOT_DECLARED=0 gives one stretch for the whole copy,
as before; kept snapshots (LEONIDA_KEEP_SNAPSHOTS=1) take the whole copy
either way. Listed in docs/README-fxceless.md.

Test: snapshot_tests::a_snapshot_holds_what_is_declared_not_the_whole_copy
declares four 64 KiB ranges of a 64 MiB copy, checks the snapshot holds
at most 2 pieces per range, then that find_all and copy_back_with still
put the card's writes in those ranges into title memory and nothing
outside them, and that copy_back_done gives the snapshot back. With
LEONIDA_SNAPSHOT_DECLARED=0 (the old buffer) it fails: "the snapshot holds
0x4000000 bytes of the copy". stretches_hold_the_pieces_of_what_is_declared
covers the stretch cuts, gaps, the copy's ends, at() and spans().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: create_heap (leonida-gpu resource.rs:1162-1189 on
perf/unified-memory) took a heap's memory from Memory::new, the Rust
global allocator's alloc_zeroed (1112-1131). That memory is not
write-watched, so watch::writes answers None for it and every refresh of a
host copy of a resource placed in it re-read and compared all of it; it
sits above 2^40 (0x1df484f0000 in the test); it is no whole VirtualAlloc
allocation, so LEONIDA_INPLACE cannot open it; and its free never told the
GPU side, so what was noted of it stood for the next memory there.

What changes: leonida-gpu gets use_heap_memory(alloc, free), beside
use_allocator; Memory records where it came from (Source: ours, the
title's allocator with its attributes, or the runtime's heap memory with
its free) and Memory::for_heap takes the runtime's memory for a heap when
it is named, falling back to ours if it gives none. leonida-hle's
create_device names xmem::heap_memory, a reservation of its own made as
XMemVirtualAlloc makes the title's (MEM_WRITE_WATCH, below 2^40, told to
the GPU side, zeroed, at the heap's alignment), and heap_memory_free, which
frees through title_virtual_free (the GPU side forgets first, and in-place
holds are honoured). On the console a heap is title memory, so this is also
what XMemGetWorkingSetStatistics should count.

Switch: LEONIDA_HEAP_WATCHED=0 takes heaps from our allocator, as before
(next to the code and in README-fxceless.md, "Speed and memory").

Tests: resource::tests::heaps_take_the_runtimes_write_watched_memory
(create_heap with a write-watched routine on the test's thread:
watch::writes is Some and names the one page written; the heap's release
gives the memory back) - red with the old path (LEONIDA_HEAP_WATCHED=0):
"nothing is known of what is written in the heap at 0x1df484f0000"; and
xmem::tests::heap_memory_is_a_write_watched_reservation_below_2_40
(GetWriteWatch works, below 2^40, 64 KiB and 4 MiB alignment, a whole
MEM_PRIVATE allocation, zeroed, its free reaches the GPU side).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: XMemAllocatePhysicalPages (leonida-hle xmem.rs:758 before
this) made every section of the title's page pool with SEC_RESERVE, up
front. Two costs: (1) OpenExistingHeapFromFileMapping refuses a reserved
section (leonida-gpu inplace.rs:22-27, the probe's verdict "the pool must
be made committed to be opened"; E_INVALIDARG on this RX 7900 XT too), so
no page-pool memory could be read by the card in place except through a
view opened by address, which locks its pages; (2) every page's first
mapping (Section::commit_shown, xmem.rs:467) and every new run of
Section::window (xmem.rs:437-455) and View::map asked the host for a
VirtualAlloc(MEM_COMMIT) on a view, a call that waits for the process's
address-space lock, the mapping bottleneck the LEONIDA_MAP_LEAN comment
and findings.md describe: up to one call a page, some 100,000 for the
6.1 GiB pool.

What changes: a section of at most 64 MiB (LAZY_SECTION_MOST; with the
default 16 MiB sections, all of the pool's) is no longer made with its
allocation. Section::handle makes it the first time one of its pages is
mapped (show), written (Section::window, View::map), with SEC_COMMIT,
under a per-section lock (one section and one charge, whichever thread
comes first), and tells the GPU side (title_memory_section, committed)
before any view of it is noted. A committed section asks for no commit
of its own anywhere; the committed bitmap still marks pages handed out,
for arrange()'s fresh pages. Commit is charged a section at a time, for
the sections the title touches, not 6.1 GiB up front (the reason for
SEC_RESERVE); where the host refuses that commit, the section is made
reserved and its pages committed one by one as before. Sections larger
than 64 MiB (LEONIDA_SECTION_MB=0, renderer port 1) and Wine are
unchanged. leonida-gpu gains title_memory_reads_in_place(at, len): opens
the section behind a run of title views with From::Section, places a
buffer at the run's offset, and compares what the card copies out of it
with what the CPU reads, for these tests and as the first piece of
reading the pool in place. inplace.rs comments that said the pool is
reserved are corrected.

Switch: LEONIDA_SECTION_COMMIT=0 restores every section made reserved
with its allocation and committed page by page (it changes commit charge
behaviour: up to one section's worth more than page by page for each
section touched). Documented at lazy_commit and in README-fxceless.md.

Tests (leonida-hle xmem.rs, synthetic sections, no game data):
- a_committed_section_is_made_at_its_first_page: 48 pages in sections of
  16; a page mapped, the same page at a second address, a page beside it
  and a write into a page mapped nowhere ask for no commit (thread-local
  COMMITS); only touched sections are made (SECTIONS_MADE); bytes land in
  the right pages. Red with the fix reverted (lazy_commit() false):
  "assertion `left == right` failed: a page mapped: no commit of its own,
  left: 1, right: 0".
- a_committed_section_is_charged_when_first_touched: the process's
  SharedCommitUsage (PROCESS_MEMORY_COUNTERS_EX2): allocating two 32 MiB
  sections charges nothing, the first page shown charges one section, a
  second page nothing more, the free and unmap give it back. Red reverted:
  "one section charged: MiB of shared commit since the start: allocated
  0, a page shown 0, another 0, freed 0".
- a_committed_section_opens_as_a_heap (device; on this PC's RX 7900 XT):
  the section behind two mapped pages opens and the card reads the bytes
  the CPU wrote through the title view, and new bytes after the pages are
  unmapped and mapped at another address (a range not page-aligned).
  Red reverted: "left: Err(\"El parámetro no es correcto. (0x80070057)\"),
  right: Ok(true)".
leonida-hle lib 226 passed / 2 ignored (one run of 18 failed in
xasync::pool_workers_left_idle_leave_under_a_trickle_of_callbacks, a
timing test of xasync's worker pool, unrelated); leonida-gpu lib 598
passed / 47 ignored. No clippy warnings in the changed lines.

Not measured: what the commit calls cost the mapping thread in the world
(the streaming log's MAPPING counters, Call::Commit, would show it), and
the commit charge over a session with the title.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: xmem exported only VirtualFree (xmem.rs module()), so the
title's VirtualProtect went to the host's own. While a heap opened in place
(LEONIDA_INPLACE) stands over the pages the host refuses it with error 87
(the probe, inplace.rs top notes), and nothing let go of what was in place
there: the shortcut at inplace.rs level() named it ("one over memory in
place still fails with error 87").

What changes: xmem exports VirtualProtect (title_virtual_protect), through
the new glue leonida_gpu::title_memory_protect, as title_virtual_free goes
through title_memory_free. The host is asked first; a call it refuses with
87 while a hold stands over the pages (or was let go of lately) lets go of
what is in place there (title_memory_freeing), of the descriptor slots that
view its buffers (slots_let_go) and of what nothing else holds (reap), then
the host is asked again. If the heap still stands (retired objects wait for
the submissions that may use them) the protection waits (PROTECTS) and is
made from tick once no hold stands over the pages, the title told it is done
with the pages' current protection as the old one. A protection of pages one
already waits over waits behind it (made in order); a free of the pages cuts
what waits there; place_for does not open memory whose protection waits.
Calls with a null old pointer or a protection the host could not make, and
all calls while nothing is held, are the host's unchanged. The say line
counts protections made later and given up on.

Switch: LEONIDA_INPLACE_PROTECT=0 restores the old behaviour (the host
alone; error 87 under a heap). Documented in inplace.rs and
README-fxceless.md.

Tests: inplace::tests::warp_the_title_protects_memory_in_place_once_its_heap_is_gone
(WARP, through the glue): red with the take-over disabled, "the title's
VirtualProtect succeeds" fails with left (false, 1); green with the fix,
and both protections are made in the order asked once the heap went.
xmem::tests::the_title_protects_through_the_gpu_side: red without the
export ("the title's VirtualProtect is the runtime's", left None); green
with it, protections and refusals as the host's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: a queue standing at a wait for a memory value that lies
under a flight's declared write (host.rs late_met, was host.rs:4777-4783)
called settle_now(WHY_VALUE), and under the relay Host::settle waits until
LINE is empty and nothing is being landed (was host.rs:7386). The wait is
asked on the thread that prepares every submission, under the submission
lock, and declared writes are conservative (the skinning passes declare the
title's whole 174 MB heap): a value under the first flights only waited for
every later flight too, which never touch it, and nothing was prepared
meanwhile (map: submit "Value waits and blocking fence waits drain
everything", critic #5).

What changes:
- late_met waits (settle_until, under the submission lock as before) until
  value_landed: nothing in the air or being landed may write the waited
  bytes, or the line is drained (the old condition, kept as a net).
- line_may_write is the predicate: flights in the line by what
  card_steps::writers lists of them (declared shader writes, copies done on
  the card, read-backs and texture read-backs, bottom-of-pipe writes), the
  fences signalled behind them at their value's address (fence::value_at),
  and flights being landed by `written` (made again only when their landing
  is done), `in_hand` and `landing`. A declared write to a copy in the
  card's memory counts a 64 KiB piece either side (landing_reach): the
  relay merges whole pieces (Shadow::card_merge_relay), so bytes beside the
  range that something else wrote on the card land with it; the flights
  being landed keep that in Line::in_hand_reach. Nothing is counted as
  unknown because nothing else of a flight reaches title memory; memory
  written in place by the card (LEONIDA_INPLACE, off) is not landed, and
  the settle did not wait for it either. A value not met yet is asked
  again at every landing (poke), as late_met_known's "not met" always was.
- The line's joining, taking and landing are Line methods (push_flight,
  take_landable, landed), used by send_late, execute_own, relay_worker and
  relay_land as before, so the tests drive the same state changes.

Switch: LEONIDA_EXACT_WAIT=0 waits for everything, as before; on by default
with the relay's second stage (relay_exact; LEONIDA_RELAY=1 keeps waiting
for everything). Documented at exact_wait and in docs/README-fxceless.md.

Test: exact_wait_tests::a_value_wait_ends_when_the_flights_that_may_write_
it_have_landed: two flights, the first declaring the value; once the first
has landed the wait is done with the second in the air, and it is not while
the first is being landed, nor while a flight declares it (wholly, in part,
or as part of a wide range), declares bytes of a copy in the card's memory
less than a piece away (in the air and being landed), or has a timestamp
written there, a read-back into it or a fence signalled at it. With
value_landed waiting for a drained line, as before, it fails "no flight in
the air may write it". fence.rs' test checks value_at against the fence's
GPU address.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: title_used was the process's PagefileUsage (leonida-hle
xmem.rs:2287 on perf/unified-memory): the runtime's memory, the host
copies of title memory and the driver's included. The code's own note
records 27 GB in run 60's gameplay against a limit of 13.5 GB
(xmem.rs:2295-2302): a title that budgets its streaming from these two
figures believes it is twice over its limit and may let go and stream
again what the console would keep (a hypothesis; findings.md measures 850
to 1,600 pages mapped a second with the camera idle, and says it is not
known whether the console streams that much at rest).

What changes: title_used is what the title was given, which is what the
console counts and what it has no runtime beside: the private memory
committed through xmem (TitleCommit, disjoint page ranges: virtual_alloc
adds what XMemVirtualAlloc, XMemAllocDefault's reservations and the
device's heaps commit; title_virtual_free takes away what a decommit or a
release takes, a size-0 decommit or release the whole allocation; a range
committed twice counts once), plus its live physical pages (64 KiB each
from allocation to free, mapped or not, as on the console), plus
XMemAllocDefault's heap blocks (HEAP_BLOCK_BYTES). Not counted, and said
in a shortcut: what the title takes from the host itself (image, stacks,
its own heap through kernel32, which no shim sees), so the figure is low by
that much where the process's commit was high by the whole runtime; the
error now leans the console's way (the title may keep more resident, and
host commit rise, as it would on the console). The log line gives both
figures. Also: title_virtual_free forgets a WATCHED_BLOCKS entry, and the
commit it frees, with their locks held over the host's free (or after the
GPU side took a held free over), so memory given again at the address in
between is not forgotten with it, and a refused release keeps its entry.

Switch: LEONIDA_WS_TITLE=0 reports the process's commit, as before
(next to the code and in README-fxceless.md, "Speed and memory").

Tests: xmem::tests::the_title_is_told_its_own_use_not_the_processes
(512 MB of the runtime's own leave title_used within 256 MB of where it
was) - red with the old figure (LEONIDA_WS_TITLE=0): "the title is told it
uses 513 MB more for 512 MB of the runtime's";
the_titles_commit_is_counted_until_it_is_freed (16 MiB counted to the
page, a decommit of 4 MiB + 5 bytes off a page boundary takes 4 MiB + 4 KiB,
commits over committed pages count once, release takes the rest, an
XMemAllocDefault block counted and uncounted); title_commit_counts_each_page_once.
transfers_shrink_the_title_budget no longer asks for a used figure above 0,
which a test run alone need not have.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: a release of the title's that a heap opened in place was in
the way of is kept reserved until the heap is gone (inplace.rs PENDING),
and only tick retries it, every REAP_MS. XMemVirtualAlloc at a fixed
address (xmem.rs, the VirtualAlloc2 call with base non-null) into those
addresses before that was refused with ERROR_INVALID_ADDRESS, where the
console's succeeds: the address the title freed is still taken.

What changes: XMemVirtualAlloc at a title-given address goes through the
new glue leonida_gpu::title_memory_reserve. When the host refuses a
reservation that touches a kept release, the descriptor slots that view a
buffer there let go of it (slots_let_go), reap lets go of what nothing else
holds and retries the releases; while no standing hold is in the way the
host gets up to RESERVE_WAIT_MS (50 ms) to let go of the heaps' pages; once
no release is kept there the reservation is made again. A release a heap
still stands over (submissions that may use it not yet run) stays, and the
reservation is refused with the host's error as before. Reservations at an
address of the runtime's choice are untouched. The say line counts the
reservations made so.

Switch: LEONIDA_INPLACE_RESERVE=0 restores the old behaviour. Documented in
inplace.rs and README-fxceless.md.

Test: inplace::tests::warp_a_reservation_over_a_release_kept_for_a_heap_does_the_release_first
(WARP, through the glue): red with the take-over disabled, "the title's
reservation is made" fails with left 0; green with the fix. The same test
checks that while a list still holds the heap the reservation is refused
with error 487 and the release stays kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: SetEventOnCompletion with a null event (fence.rs:106-116)
called host::settle_for_fence, which under the relay waits until LINE is
empty and nothing is being landed (host.rs Host::settle). The fence's
signal stands in the line behind the flights submitted before it and the
relay thread sets it when it has landed those, so the title's thread also
waited for every flight sent behind the signal, which it cannot expect to
have run (map: submit "Value waits and blocking fence waits drain
everything", critic #5).

What changes: fence.rs calls host::settle_for_fence_value(this, value),
which waits (settle_until, under the submission lock as before) until
fence_landed: the fence has reached the value, or the line is drained.
When the signal is not in the line (a queue holds it behind a wait, or it
never comes) that is the old full drain, so the caller's 250 ms wait for
the value still counts from there and a held queue still gets the landings
it may need. The relay sets the fence before the landing's end, which
notifies LINE_LANDED under the line's lock, so no wake-up is lost. With
LEONIDA_TELL_EARLY=1 the fence is set before its flights' writes are in
title memory: the full settle is kept there. The other callers of
settle_for_fence (descriptor slots, texture bakes) still settle everything.

Switch: LEONIDA_EXACT_WAIT=0 (the same as for value waits) settles
everything, as before; documented at exact_wait, settle_for_fence_value
and in docs/README-fxceless.md.

Test: exact_fence_tests::a_blocking_fence_wait_ends_when_its_signal_has_
landed: a real fence signalled behind the first of two flights; once the
first flight and the signal have landed and the fence is set, the wait is
done with the second in the air; a value the fence has not reached waits
until nothing is in the air or being landed. With fence_landed waiting for
a drained line, as before, it fails "reached with the second flight in the
air".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: Shadow::pending was a Vec of the declared ranges
(shadow.rs:343 on perf/unified-memory). Shadow::writing looked through all
of them to dedupe (pending.contains, 4028) and again to find the parts of a
new range no range held (4043, every range against every part);
copy_back_done looked each pending range up in the submission's list
(pending.retain(|r| !ranges.contains(r)), 4351). Both are quadratic in a
copy's ranges at every submission, and every refresh, update, nothing_new,
stale_under_writes, merge_under_writes and send_copied walked all ranges to
find the ones over its stretch.

What changes: Pending keeps the ranges as declared in a BTreeSet (each
once, as the Vec held them) and their union (apart, in order), joined on
insert and made again from the set when next asked after a removal.
contains/insert/remove are searches; overlaps and outside search the
union; over (the ranges as declared that overlap a stretch, for the merges
that ask the journal range by range) starts at the first union piece
ending after the stretch's start. writing takes its parts from outside(),
mapped into the copy with inside(); copy_back_done removes each done range;
update copies the gaps outside() gives; send_copied sends what outside()
leaves. Same answers as the walk except for empty ranges, which hold no
byte and now overlap nothing (the walk counted one strictly inside a
stretch); no switch, since nothing else a caller sees changes.

Test: pending_tests::pending_ranges_answer_as_a_walk_of_all_of_them checks
over/overlaps/outside/contains against a walk of all ranges over 3,000
random inserts and removals. pending_tests::a_copys_ranges_are_searched_not_walked
declares 4,000 ranges of a copy twice, asks writes_pending_in in and
beside each, and copies them back: 116,000 steps (bound 4*N*(log2 N+1) =
192,000). With contains and remove charged as the Vec's walk and retain
it fails: "24106000 steps for 4000 ranges (at most 192000)".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: every dirty byte of a copy in the card's memory was copied
twice on the CPU. Shadow::take/copy put title memory into Card::staging, then
send::take (host/send.rs, called from Host::card_before) copied staging into
the submission's own upload memory on the submitting thread (73-93 MB a frame,
3-7 ms at the 13-28 GB/s measured on this PC), and the card copied that into
VRAM. The placement table in docs/findings.md shows the RX 7900 XT copies out
of write-back staging as fast as out of the upload ring (24-28 GB/s), so the
second copy bought only what LEONIDA_SEND_OWN exists for: a submission's sends
are its bytes as prepared, whatever later preparations put into staging before
the card gets to it. For the title's own CPU writes that needs no help (the
title is told of a submission once the card ran it; the opened arenas already
send out of live memory on that ground); it does for what the runtime writes
into title memory at submission: Step::Copy (send_copied), copies at their
place (Placed::prepare, placed_copy) and CopyMemoryToMemoryX done on the CPU
(list.rs copy_memory's deferred step).

What changes: long runs (not the paired words) go up with a CopyBufferRegion
straight out of staging. A new pure policy, shadow/direct.rs, keeps per card
copy (Card::direct) the 64 KiB pieces the runtime wrote at submission in the
last 1024 sends (those still go through the submission's memory) and the runs
in the air by send number. send::number/signal give each card_before send a
number and signal a fence of ours behind its sync list. Before the runtime
writes a card copy's range at submission (send_copied, shadow::copying from
Step::Placed and copy_memory), the pieces are noted and a send in the air that
reads them is waited for (send::wait). Opened arenas are left as they were.
The frame line counts bytes sent straight and the waits with their ms.

Switch: LEONIDA_SEND_DIRECT (crate::toggled!, on with LEONIDA_SEND_OWN; =0
every run through the submission's memory, as before). README-fxceless.md
lists it.

Tests: shadow::direct::tests (split/notes/in-air policy; a simulation of 40
frames of 30 submissions with the card 3 behind: 29 waits in the first frame,
0 after, against 1170 after the first frame without the notes);
host::send::direct_tests on the local GPU (RX 7900 XT):
what_the_title_wrote_goes_up_straight_out_of_the_cpu_side writes title memory
before each of two sends and reads each card side back; red with nothing sent
straight (as on perf/unified-memory): "bytes copied into the submissions'
memory on the CPU, left: 409624, right: 0".
a_copy_of_ours_waits_for_a_send_in_the_air_that_reads_its_bytes holds the
queue on a fence of ours, then does a buffer copy of ours over a send in the
air; red without the wait: "the card side after send 0 is not the bytes it was
prepared with"; red without the notes: "the copy's pieces go through the
submission's memory, left: 0, right: 204812".
leonida-gpu lib: 603 passed, 47 ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: XMemFreePhysicalPages only dropped table entries
(xmem.rs:819-831 on perf/unified-memory). A section lives while any page
of it has a number or a view, and the host cannot decommit pages of a
section (VirtualFree(MEM_DECOMMIT) on a view of one fails with error 87,
measured here), so what the title freed of a section it still used part
of stayed committed and resident for as long as the rest, and every later
allocation made new sections (:747-781) committed anew as written. A title
that frees part of its pages and asks again grew the commit by what it
freed, each round. With the default single section for the title's 6.1
GiB, freeing part of it released nothing.

What changes: Spare keeps, by section, the pages freed from sections that
still have pages with numbers; XMemAllocatePhysicalPages takes them before
it makes sections, longest runs of consecutive pages first (few views, one
DirectStorage window), and only pages no view shows (Shown, read with
PHYSICAL held, so every unmapping of the page was told to the GPU side,
title_memory_unmapping, before it changes hands; the GPU side knows pages
by views and section handle, never by number, and title_memory_section /
title_memory_section_gone keep their order: the section is the same one,
and it still closes, commit and handle, once its last numbered page is
freed and its views are gone). Pages written before are zeroed when given
out again, as a new section's read. While they wait, written pages that no
view shows go back to the host with DiscardVirtualMemory (measured on a
256 MiB section: all its 65,536 resident 4 KiB pages left the working set,
70-74 ms, about 18 us a 64 KiB page, and zeroing them after cost 71-77 ms
against 10 ms resident; MEM_RESET cost 8 ms but left them resident). Pages
still shown keep their bytes until unmapped, as XMemFreePhysicalPages
promises. View::map now sets the section's commit bits as every other
commit does: a page written only through it (DirectStorage with no window)
was not known written, so it would have been given out again unzeroed, and
renderer port 1's arrange took it for fresh.

Switches: LEONIDA_PHYSICAL_REUSE=0 restores the old behaviour (no reuse,
no discard); LEONIDA_PHYSICAL_DISCARD=0 reuses but keeps waiting pages
resident. Reuse is off with LEONIDA_PORT_CONSTANTS=1 (arrange hands out
slices of a section that have no number) and discard under Wine (sparse
sections). Both are in docs/README-fxceless.md, with the page-number fix
of the commit before.

Test: freed_pages_are_given_out_again_until_their_section_goes (a title
keeping one page of four and asking for two again for 50 rounds: the same
section's freed pages each time, zeros, not resident while waiting, the
page still mapped kept until unmapped, three pages given as one run, the
section closed after the last free, and a page written only through
View::map zeroed). Red with reuse off: "freed pages no view shows are let
go" (left: 32, right: 0), then "round 0: the freed pages, not a new
section"; red without View::map's bits: "zeros".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: send_copied (shadow.rs:1256-1269 on perf/unified-memory),
called for every Step::Copy while submissions take their own send memory
(host.rs:9784, send::own on by default), went through carded_copies():
every copy in the card's memory upgraded from its Weak into a new Vec,
then filtered by whether it held the destination. With the small buffers
on the card too that is thousands of copies per buffer copy (3,540 in run
int-m-kb, the figure card_queue's doc records).

What changes: CARDED_SPANS, a Spans index of the same copies by the title
memory they hold, kept beside CARDED by note_carded and swept the same way
(dead entries dropped when they may be half). Spans keeps the spans in
order of start with, for each, the furthest end of it and those before it,
so the spans over a stretch are two binary searches and a look at those
between (spans may nest and overlap; an insert moves the ones after it,
inserts being one per copy made). send_copied asks carded_over(dst, end)
and upgrades only those. CARDED and card_dirty are as they were. (No
branch djrolfes/d3d12-elide-watched-index exists in origin to borrow from;
elide's demote_overlapping still walks CARDED, behind
LEONIDA_COPYBACK_ELIDE, off by default.)

Switch: LEONIDA_CARDED_INDEX=0 makes carded_over return every copy in the
card's memory, as before. Listed in docs/README-fxceless.md.

Test: spans_tests::a_cpu_copy_looks_at_the_card_copies_it_writes notes
512 card copies and one big one over 64 of them, then a send_copied into
one (busy whole, so nothing is copied or queued) must look at exactly 1
copy, and carded_over must find what a walk finds for a stretch in one
copy, in a gap inside the big one and over four copies. With
LEONIDA_CARDED_INDEX=0 it fails: "send_copied looked at 513 copies in the
card's memory". spans_tests::spans_that_overlap_a_stretch_are_found_by_search
checks Spans::over against a walk over 2,000 random nested spans with
removals, and that a stretch among 10,000 apart spans looks at at most 2.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: a_committed_section_is_charged_when_first_touched
(leonida-hle xmem.rs:3432-3465) read SharedCommitUsage, the whole
process's counter, with 8 MiB of slack, on the assumption that other
tests move it "by a few MiB at most". With 16 MiB sections the default,
the module's other tests make and drop sections of their own on other
threads (a_scatter_of_many_pages_is_what_one_after_the_other_is maps
12.5 MiB at once), and between two readings the counter moved by 15-50
MiB: `cargo test -p leonida-hle --lib modules::xmem` failed 6 runs of
10 on unified/page-pool-open, e.g. "nothing more for a second page of
it: MiB of shared commit since the start: allocated 0, a page shown 33,
another 48, freed 16". The whole lib suite happened to keep them apart.

What changes: the test re-runs itself in a child process of the test
binary (--exact, --test-threads=1, LEONIDA_TEST_COMMIT_CHILD set), the
pattern of host.rs's loader-lock test, and asserts the child passed,
with the child's output in the failure. Alone, the readings are exact:
0, 32, 32, 0 MiB. The comment says why. No behaviour of the runtime
changes; no switch.

Test: the same focused command passes 15 runs of 15. A child failure
reaches the parent (checked by inverting the last assertion: "the child
failed: ... given back: ... allocated 0, a page shown 32, another 32,
freed 0").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: lazy_commit (leonida-hle xmem.rs:883-891) was on unless
LEONIDA_SECTION_COMMIT=0, so every run charged a whole section of commit
(16 MiB with the default sections) for each section the title touched,
where page by page it charged 64 KiB for each page used. Nothing measured
that with the title: the commit's own message lists the commit charge
over a session and the commit calls saved as not measured. Runs here
have had 1.8-2.0 GB of commit left (findings.md, the
LEONIDA_SMALL_BUFFER_POOL row of the six-core switches) and
README-fxceless.md already warns about error 1455; the fallback to a
reserved section where the host refuses a section's commit protects only
the pool, so once its sections have taken commit early what fails at the
limit is everyone else's (the host device's resources and upload
buffers, the title's own MEM_COMMIT). The doc's "at most a section's
worth more" said nothing of that. What it buys today is not used: nothing
places title buffers in the openable sections yet. The same branch kept
LEONIDA_BATCH_KEPT off for want of a measurement; the same holds here.

What changes: off by default; LEONIDA_SECTION_COMMIT=1 makes sections of
up to 64 MiB committed at their first page as before. The value is read
through lazy_commit_asked (on for "1" only), the convention of the
crate's other opt-in switches (LEONIDA_DSTORAGE_HALF and the like). The
doc says what it costs, what the fallback does not protect, and what a
session must measure before it is turned on. README-fxceless.md lists it
as off by default with the same costs; inplace.rs's comments and the
probe's log line say the pool is reserved unless LEONIDA_SECTION_COMMIT=1
(the reviewer's nit about "as it is made today" falls under this: with
the switch off that wording is again what happens, now it names the
switch).

Switch: LEONIDA_SECTION_COMMIT=1 turns it on; unset or anything else is
the measured behaviour of perf/unified-memory.

Test: committed_sections_are_asked_for (pure): unset, "0" and "" are
off, "1" on. Red with the old reading (is_none_or(|v| v != "0")):
"unset: reserved sections, as measured". The tests of committed sections
set the switch for their thread and are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: section_pages (leonida-hle xmem.rs:806-810) warned
"LEONIDA_SECTION_MB is left out with LEONIDA_PORT_CONSTANTS=1" whenever
port 1 was on and sections were not off. With 16 MiB the default for an
unset LEONIDA_SECTION_MB, every run with LEONIDA_PORT_CONSTANTS=1 logged
it though nobody had set the variable.

What changes: the warning is given only when LEONIDA_SECTION_MB is set;
unset, port 1 keeps one section an allocation as quietly as before the
default changed. Log only; nothing else changes, no switch.

Test: none (a log line); leonida-hle's xmem tests pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: the value wait's predicate (host.rs landing_reach, was
host.rs:4917-4936; Line::in_hand_reach, was host.rs:4174-4177;
card_steps::Writer::lands_in, was host/card_steps.rs:208-218) widened every
declared write to a copy in the card's memory by a 64 KiB piece either side,
on the claim that the relay fetches and merges whole pieces, so bytes beside
the range written through undeclared views land with it. It does not:
relay_card_back and Shadow::land_card merge only Shadow::card_piece, which
card_piece_of (shadow.rs:1348-1351) cuts to the declared span; with
LEONIDA_FETCH_CHECK the whole piece is fetched but the merge still takes the
cut range; card_asked joins only overlapping or touching declared ranges;
ranges picked as written are in Flight::back (picked::with, as the card's
own plan has them) and ranges only looked at are never landed
(CardRange::picked). So nothing outside a flight's declared ranges reaches
title memory, and the widening only made a value wait in a carded copy wait
for later flights whose writes lie up to 64 KiB away, under a doc that stated
a false invariant.

What changes: landing_reach and Line::in_hand_reach are gone (flights being
landed are still counted by `written` until their landing is done);
Writer::lands_in is the declared range itself. exact_wait's doc says why
that is enough, from the code above.

Switch: unchanged, LEONIDA_EXACT_WAIT=0 waits for everything as before.

Test: exact_wait_tests::a_value_wait_ends_when_the_flights_that_may_write_
it_have_landed: a later flight that declares other bytes of a carded copy in
the value's piece is no longer waited for, in the air or being landed, while
a value half under or under its range still is. With the widening restored
it fails at "beside what a copy in the card's memory declares, in its piece".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: XMemFreePhysicalPages read SHOWN, to leave out of the
discard the freed pages a view still shows, without PHYSICAL
(xmem.rs:1185-1190 before this). Every mapping call that changes a view
takes it out of SHOWN and notes again what stays of it only after its
system calls, under PHYSICAL (unmap :2610 -> map/note_view :2630-2634;
change :2236 -> :2266). A free read in between: a page freed while still
mapped inside a view the title was mapping over part of (8 threads map in
parallel) looked unshown, went through DiscardVirtualMemory, and the
title's view read zeros, against "pages still mapped stay readable through
their views until unmapped". Spare::take already read SHOWN with PHYSICAL.

What changes: the free takes PHYSICAL around its SHOWN filter (PHYSICAL
before SHOWN, the order the rest of the file keeps). Past it the pages
cannot be shown again (no number, not in Spare yet), so the discard
itself still runs without locks.

No switch: it only waits for a mapping call already running; the
discard behind LEONIDA_PHYSICAL_DISCARD is unchanged.

Test: a_free_keeps_a_page_a_mapping_call_puts_back (the half-changed
SHOWN held by hand with PHYSICAL, the free on another thread). Red
without the lock: "the page still mapped keeps its bytes" (left: 0,
right: 205).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
the_titles_commit_is_counted_until_it_is_freed (xmem.rs, tests) failed
about one run in four of the xmem tests: after its release it asserted
that TITLE_COMMIT counts nothing in the freed range, but tests run in
parallel and another one may be given that address at once. Worse,
virtual_alloc_meets_console_constraints freed its committed 4 MiB with a
host VirtualFree, which leaves the commit counted, so a range it took
and freed in that window stayed counted after the memory was gone (the
4,194,304 bytes of the failures).

That test now frees as the title does (title_virtual_free), and the
post-free checks go through counted_after_free, which reads 0 when memory
stands in the range again (asked again for up to 100 ms, since that
memory may be freed between the count and the look). 15 runs in a row of
the xmem tests pass; on the previous tip 2 of 8 failed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
title_virtual_free (xmem.rs, the hook for every kernel32 VirtualFree the
title makes) took the TITLE_COMMIT lock, and for a release of a 64 KiB
aligned base the WATCHED_BLOCKS lock, and held them over the host's
VirtualFree, so that memory given again at the address meanwhile would be
noted after the removal. Title frees on different threads then ran one at
a time, and every XMemVirtualAlloc commit, watched XMemAllocDefault block
and XMemGetWorkingSetStatistics waited behind a decommit in progress
(milliseconds on large ranges), with LEONIDA_WS_TITLE=0 too.

The address cannot be given again before the host's free succeeds, so
both entries now come out before the free, with what was removed kept
(TitleCommit::remove returns the ranges it took), the free runs with no
lock held, and the entries go back only if the host refused and the GPU
side did not take the free over. No switch: the bookkeeping ends the same.

Test: title_free_holds_no_lock_over_the_host_free (a probe at the host's
free tries both locks from the freeing thread; a refused release leaves
block and commit counted, a free forgets them). With the old body:
"a table's lock held over the host's free", left Some(false), right
Some(true). title_commit_counts_each_page_once checks what remove takes
and that adding it back restores the count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Snapshot::hold (crates/leonida-gpu/src/shadow.rs, was ~2374) returned on
`whole` as soon as the snapshot had any stretch. Shadow::writing reads
snapshot_declared() on every call, and in a diagnostics build with
LEONIDA_AB naming LEONIDA_SNAPSHOT_DECLARED it changes at a present, while
with the relay a busy copy's snapshot outlives one: a snapshot with
stretches of pieces from an "on" phase got nothing for a part declared in
an "off" phase, so Snapshot::spans gave nothing for it, find_all did not
scan it and copy_back_with did not compare it, and what the shaders wrote
there never reached title memory.

`whole` now makes the one stretch for all of the copy only when the
snapshot has none; otherwise hold fills the gaps piece by piece, as with
the switch on (a stretch for all of the copy already holds every part, so
nothing is made). No new switch: LEONIDA_SNAPSHOT_DECLARED=0 still gives
one stretch for the whole copy to a snapshot made while it is off.

Test: snapshot_tests::a_flip_of_the_switch_leaves_no_declared_part_unheld
drives hold with false then true (and true then false) on one Snapshot
and checks spans covers every declared part. Without the fix: "a part
declared after the flip is held", left: 0, right: 64.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: nothing tested Numbers where the calls use it. Deleting
XMemFreePhysicalPages' table.numbers.give (xmem.rs:1172 before this)
left the whole leonida-hle suite green (226 passed): the two number tests
drive the Numbers struct alone, and XMemAllocatePhysicalPages called
take(n, END_NUMBER) with no way to make the space small enough to go
round it in a test. Neither the refusal with every number live (count 0,
FALSE) nor the numbers given back when a section cannot be made were run.

What changes: Numbers::take takes a range; the calls pass number_range(),
FIRST_NUMBER..END_NUMBER, which a test's thread narrows (TEST_NUMBERS) to
numbers it took from the counter and gave back first, which no other
thread takes (they draw from the counter, far below 2^25). For the
title's range, which holds every freed number, take is as before (spare
counts them all); a narrower one counts and gives only its own bits.
TEST_NO_SECTION makes a test thread's sections fail as
CreateFileMappingW does on a busy host. Both are cfg(test). No switch:
nothing changes for the title.

Test: page_numbers_come_back_through_the_calls (400 rounds of 1-3 pages
allocated and freed through the calls in a space of 8 numbers: all in
the space, each with its page, none live twice, given whenever it fits;
with all 8 live the next is count 0 and FALSE and a freed one is the one
given; a refused section gives its numbers back; a narrower range leaves
out numbers freed outside it). Red without the free's give: "round 3: 2
refused with 0 of 8 live"; red without the give on the failed section:
"the numbers came back".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
spans_tests::a_cpu_copy_looks_at_the_card_copies_it_writes
(crates/leonida-gpu/src/shadow.rs, was ~978) noted 513 copies from
Shadow::unbacked in CARDED and CARDED_SPANS. unbacked leaks a clone, so
their weak entries never died and were never swept: they stayed for the
rest of the test process with `data` in a buffer the test freed and a
buffer that is no interface (8), where any later walk of carded_copies()
(crate::host::upcheck::look calls GetGPUVirtualAddress on it) would meet
them, and they kept the sweep from ever shrinking either map.

A #[cfg(test)] unnote_carded removes given copies from both maps; the
test holds its copies in a guard that calls it on drop (also when an
assertion fails), before the copies' memory goes. Tests only: no switch.

Test: the same test now checks, after its copies are let go, that none of
them is in carded_copies() or CARDED_SPANS. Without the cleanup: "the
test's copies stay noted in the card's memory", left: (513, 513),
right: (0, 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
XMemAllocDefault's watched blocks (xmem.rs, XMemAllocDefault) and the
device's heaps (heap_memory) go through virtual_alloc, which logged them
in note_protection under the same key (protection 0x4, kind
MEM_RESERVE|MEM_COMMIT, flags 3) as the title's own XMemVirtualAlloc
calls, so "title memory asked for as protection ..." no longer told what
the title asked for. And a watched block refused at the commit limit went
to commit_refused, which writes a crash report to crashes.log, although
the caller then falls back to a heap and the allocation may succeed.

virtual_alloc now takes `ours`: XMemVirtualAlloc passes false, the two
runtime callers true. Ours are left out of note_protection (their own
counts are logged by note_default_block and leonida-gpu), and a refusal
of one is a warning. No switch: logging only.

Test: only_the_titles_own_reservations_are_noted_as_asked_for (a
thread-local count of note_protection calls: a watched block and a heap
add none, the title's XMemVirtualAlloc one). With the runtime's noted
again: "a reservation of the runtime's noted as the title's", left 2,
right 0. The commit-limit path is not reached in tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: the host refuses a VirtualProtect of any 4 KiB page under
a heap opened in place, and a heap stands over whole 64 KiB pages, but
title_memory_protect_held (inplace.rs) let go of what was in place over
the protected bytes alone (title_memory_freeing(from, to - from)). A window
whose bytes lay beside them in the same 64 KiB page stayed in the tables,
its heap stood, and the protection waited as long as the window lived, the
title told it was done. slots_let_go meanwhile matched holds by their 64
KiB pages: it nulled the descriptor slots of that window, still in the
tables, at the protect and again from slots_again once a second; draws then
made them again from the same buffer (null reads in between, a full slot
scan on the submitting thread each second). A decommit of a page beside a
window did the same to the window's slots. place_for checked waiting
protections over the bytes asked for, while place_part opens their 64 KiB
pages, so a heap could be opened over a page whose protection waited.

What changes:
- let_go_under: a protection (and one that waits behind an older one, which
  let go of nothing before) lets go of what is in place over the whole
  pages of every standing hold over the protected pages.
- stale_buffers: slots let go only of buffers the tables no longer show
  (shadow::in_place_shown); slots_again scans once for all of them, and
  only while such a buffer exists.
- kept_from: place_for asks of the 64 KiB pages a heap would be opened on
  (waiting protections and kept releases).
- Docs of the slot scan's cost say where it runs.

Switch: as before, LEONIDA_INPLACE_PROTECT=0 / LEONIDA_INPLACE_SLOTS=0;
LEONIDA_INPLACE stays off by default.

Tests: warp_a_protection_beside_a_window_in_the_same_page_lets_the_window_go
(red without let_go_under: "the window under the same heap is let go";
red with place_for asking of the bytes alone: "nothing is opened again over
the page whose protection waits"), and
slots_keep_a_window_still_shown_through_a_decommit_beside_it (red without
the tables check: "and so the slot keeps its buffer").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Memory::new (leonida-gpu resource.rs) said of every large allocation it
gave the title "(a heap or a descriptor heap)". With LEONIDA_HEAP_WATCHED
on by default, CreateHeap heaps come from xmem's write-watched
reservations (Memory::for_heap), so the line now covers descriptor heaps,
and heaps only with LEONIDA_HEAP_WATCHED=0 or when xmem refused one. The
comment and the message say so. Log text only: no switch, no test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: host/send.rs what_the_title_wrote_goes_up_straight_out_of_the_cpu_side
wrote title memory for the second send while the first, sent straight out
of Card::staging, could still be on the queue: refresh_for_test (Shadow::copy)
rewrote the CPU side under it, which LEONIDA_SEND_DIRECT allows for the
title's own writes (the title writes after it was told the card ran the
submission). It passed only because the card was quicker than the debug
fill. Both device tests read process-wide counters (STATS[0],
DIRECT_STATS) that any other test's submission with a card copy moves, and
Rig::send panicked (.expect) when another test's card_before had taken the
copy's changes (card_dirty takes every copy's); in the gate test that panic
fell between queue.Wait(&gate, 1) and the opener thread, so the process's
queue waited for good.

What changes: the first test holds the card 200 ms behind (as the second
does) and waits for the first send (Rig::settle, the title's fence) before
the title writes again. shadow::direct::Direct counts the bytes it gave out
straight / through the submission's memory and the waits, per copy
(Shadow::direct_for_test); the tests assert those. Rig::send takes the case
where another submission took the changes: it waits for the copy's counts to
move and for the card's work, which that submission holds until its send is
on the queue. Gate holds the queue and signals its fence on drop.

Switch: none (tests).

Test: red with the first test's old body under the 200 ms gate: "the card
side after send 0 is not what the title wrote for it" (send.rs:1028); green
with the wait.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with reuse on (the default) XMemAllocatePhysicalPages took
PHYSICAL before anything else (xmem.rs:1057-1058 before this) and looked
at Spare only by whether it had sections, which it has from the first
allocation on (Spare::made notes every section). So every allocation,
with no freed page to give, waited for the mapping calls, which hold
PHYSICAL 0.4 to 3 ms a page while the title streams; before reuse it
never did.

What changes: Spare::waiting counts the pages in all Kept::freed (kept by
wait, take and a section leaving in freed). The allocation looks at it
under PAGES' read lock and takes PHYSICAL only when pages wait; with
PHYSICAL it takes from Spare only if pages still wait. Pages freed after
the look stay for the next allocation; nothing is taken without PHYSICAL.
Not measured in a run (no game here): the gain is the waits of
allocations made while nothing waits.

Spare::take still walks every waiting page to sort the runs longest
first; bounding it would change which pages go out (fewer views, one
DirectStorage window) and was left for a measured run.

No switch: what is given out is the same as before, only the wait goes.

Test: freed_pages_are_given_out_again_until_their_section_goes checks
after each step that waiting matches the pages in Kept::freed. Red
without the count leaving with a closed section: "Spare::waiting"
(left: 3, right: 0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: README-fxceless.md:138 said freed pages wait and "until
then the host takes their memory back", and Spare's and discard()'s docs
(xmem.rs:920-923, :1067-1070) read the same. Only pages no view showed
at XMemFreePhysicalPages are discarded; unmapping does not discard, so a
page the title frees before it unmaps it stays resident until given out
again or its section closes.

What changes: the three say so. Discarding at the last unmapping of a
waiting page would cost DiscardVirtualMemory (about 18 us a 64 KiB page,
measured) inside the mapping calls, under PHYSICAL; left for a run that
shows such pages matter.

No code change, no switch, no test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: shadow.rs send_copied (:1264) and copying (:1290) ran the
in-flight guard (Shadow::card_copying) only while send::direct() was true at
that moment. With the diagnostics build's LEONIDA_AB naming the switch,
crate::toggled! reads ab::on(bit), which changes at the title's present
while sends that copy straight out of Card::staging are still on the queue
(with the relay, about two frames of them). A Step::Copy, placed copy or
CopyMemoryToMemoryX done on the CPU right after the switch went off wrote
the CPU side under such a send, and the card read the later bytes for the
earlier submission: the hazard LEONIDA_SEND_OWN exists for.

What changes: the guard runs once any send was numbered (send::numbered,
re-exported as host::send_numbered; a send gets a number only when it may
copy straight), not on the switch's present value. Off to on costs at most
a wait (a piece written while off is not noted), never a byte. With the
switch off from the start nothing is numbered and the guard is one atomic
load. The direct() doc says so.

Switch: LEONIDA_SEND_DIRECT as before; LEONIDA_AB may name it.

Test: host::send::direct_tests::a_copy_of_ours_waits_for_a_straight_send_once_the_switch_is_off
(on the local GPU, RX 7900 XT): a send straight out of the CPU side held on
the queue, the switch turned off (TEST_DIRECT), then send_copied over it;
red before: "the card side after send 0 is not the bytes it was prepared
with" (send.rs:1107); green with the fix. The send-in-the-air test shares
its body (over_a_send_in_the_air).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: shadow/direct.rs Direct::blocking (:113) scanned every
straight run of every send in the air for the copy. With the relay some two
frames (~60 sends) are in the air, so in_air() hardly ever short-circuits,
and Shadow::card_copying pays (sends in the air) x (runs per send) for each
of the ~13,000 copies a frame that touch a card copy, under the submission's
lock. Not measured; the cost grew with the queue's depth for nothing.

What changes: Direct keeps, next to `copied`, one number per 64 KiB piece:
the last send that copies some of it straight out of the CPU side, plus the
highest such number and the highest send the card was told past. blocking
is the max over the pieces of [from, to) above that, landed and in_air are
O(1), and split marks the pieces it already walks. The granularity is the
piece: a write of ours beside what a send in the air reads in the same piece
now waits too, once (the piece is then noted and goes through the
submission's memory), as a new place did before. The simulation's waits are
unchanged: 29 in 40 frames with the notes, none after the first.

Switch: LEONIDA_SEND_DIRECT as before.

Test: shadow::direct::tests updated to pieces
(the_latest_send_in_the_air_that_reads_bytes_is_waited_for adds 10,000
sends in the air with a write looking at its two pieces; an older `reached`
is not taken back); a_steady_frame_never_waits and the device tests in
host::send::direct_tests pass unchanged. No red: a cost, not a wrong result.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: the protect path (inplace.rs title_memory_protect_held, and
slots_again for waiting protections) called slots_let_go at once, which
(descriptor/host.rs HostHeap::let_go_of, title-slot branch) wrote a null
view into the shader-visible title slots over the buffer. For a free that
is right: the title gave the memory up and was done with it on the GPU.
A VirtualProtect leaves the memory valid, the title need not wait for the
GPU first, and the console's GPU keeps reading it. Submissions already
sent (more of them with LEONIDA_LATE_WAIT) that read such a slot by index
read a null descriptor, so zeros, for memory still valid; slots_again did
it again once a second while the protection waited.

What changes:
- HostHeap::let_go_of / descriptor::let_go_of_buffers take `now`. Without
  it a title slot is only made unmade (and marked changed for the buffer
  pass): it goes on showing the buffer, still the title's memory while the
  heap stands, and a draw or the pass makes it again from a copy before
  reading it. Slots already unmade are skipped.
- let_go_under retires a Ripe token (crate::host::retire); each waiting
  protection carries its flag. Once the submissions sent before the
  protection have run the token drops, and slots_again (at once, through
  RIPENED, else once a second) lets go of the slots with `now`. Frees and
  decommits still let go at once.
- Docs (and README-fxceless) say so; a slot a racing lookup made just
  before the window left the tables is noted as a shortcut.

Switch: LEONIDA_INPLACE_PROTECT=0 (the whole protect path) and
LEONIDA_INPLACE_SLOTS=0, as before; LEONIDA_INPLACE stays off by default.

Test: slots_over_memory_the_title_protects_show_it_until_the_submissions_before_have_run
(red with the slots let go at once: "the slot still shows the buffer while
the submissions sent before may run").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: host.rs late_line printed the LEONIDA_SEND_DIRECT line only
inside `if relay() { if send::own() {..} }` (:5529-5538), while
README-fxceless.md said the frame line counts the waits. With late
submission and no relay, or without late submission, waits for a straight
send in the air can still happen and were never reported (and the counters
grew unread).

What changes: the line comes first in late_line, before the late() check,
whenever send::direct() is on or there was something to count (the switch
turned off by LEONIDA_AB with sends still counted). The README bullet says
"with or without the relay".

Switch: none.

Test: none (a log line); the crate builds and its suites pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: title_memory_protect (inplace.rs) deferred every protection
the host refused under a heap and told the title it was done, also ones
that add execute access (PAGE_EXECUTE_READ, PAGE_EXECUTE). Pages under a
heap are read-write, so code the title wrote and made executable faulted
(DEP) when it jumped there while the protection waited: the bury lag, or
longer. Removing access late only gives up a fault the title expected;
adding execute late is a crash.

Measured on WARP (a probe test, not kept): under a heap opened in place
the host takes VirtualProtect to PAGE_EXECUTE_READWRITE and PAGE_READWRITE
and refuses with error 87 PAGE_EXECUTE_READ, PAGE_READONLY, PAGE_EXECUTE,
PAGE_NOACCESS and PAGE_READWRITE|PAGE_GUARD: it refuses only less access.

What changes: protect_later makes the execute part at once
(PAGE_EXECUTE_READWRITE, under PROTECTS' lock so that no waiting protection
is made in between) and lets the write the title gave up wait with the
rest; the exact protection is made once the heap is gone, in order. If the
host refuses even that, nothing waits and the title is refused with error
87, as before (adds_execute).

Switch: LEONIDA_INPLACE_PROTECT=0, as before; LEONIDA_INPLACE stays off.

Test: warp_execute_the_title_gives_memory_in_place_is_made_at_once (red
without the execute made at once: "executable at once, the write given up
later").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: inplace.rs say() had ten spaces inside the format literal
("let go of          a buffer"), so the "title memory in place" line came
out with that gap.

What changes: the literal is continued with a backslash before the newline,
as the neighbouring lines are. No switch: log text only, and no test (a
string literal; the line's arguments are unchanged).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	d3d12/crates/leonida-gpu/src/shadow.rs
# Conflicts:
#	d3d12/docs/README-fxceless.md
# Conflicts:
#	d3d12/crates/leonida-gpu/src/lib.rs
#	d3d12/docs/README-fxceless.md
Takes back 14c8e4d0 and 69b9f0ab (unified/small-leaks): Memory::another
leaking its 64 MiB reservation when the copy is refused is part of zmasi's
D3D12-RT-FG-ARENA-VA-STORM, claimed and done in #2570 with its own fix of
upload::reserve and the arenas, so this branch keeps out of memory.rs and
upload.rs there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Both branches reshape how XMemAllocatePhysicalPages makes sections of
physical pages; the conflicts in xmem.rs are resolved so both work
together:

- The allocation takes its page numbers and the freed pages waiting in
  Spare first (physical-reuse), then makes sections for the fresh pages
  only, each with page-pool-open's Section::new(here, lazy): the lazy
  SEC_COMMIT decision (lazy_commit, LAZY_SECTION_MOST, not under Wine) is
  taken per fresh section, and Wine's committed-whole sections stay in
  Section::new.
- The GPU side is told of a section once: Section::new for one made with
  its allocation, Section::handle for a lazy one when it is made (before
  any view of it). physical-reuse's census loop after the sections are
  made (title_memory_section(section.handle, ..)) is dropped: it would
  register sections twice, and a lazy one before it has a handle. Reused
  pages are of sections already told; nothing registers them again.
- The test hooks of both sides are kept, in one cfg(test) thread_local:
  TEST_SECTION_COMMIT, SECTIONS_MADE, COMMITS, TEST_REUSE (TEST_NUMBERS
  and TEST_NO_SECTION stay beside number_range). TEST_NO_SECTION moves
  from the allocation loop into host_section, the one place a host
  section is made, so it refuses a section made with its allocation as
  before (page_numbers_come_back_through_the_calls) and a lazy one at its
  first page; it no longer makes a section and closes it.
- README-fxceless.md: every bullet of both sides; HEAD's in-place bullet
  is the newer version of physical-reuse's.

Spare, each_written and discard need no change for lazy sections: the
committed bits are set only after Section::handle gave a handle (window,
commit_shown after show, View::map), so a freed page of a lazy section
never made has no bit and nothing is zeroed, discarded or made for it,
and a reused page of such a section makes it at its first touch.

leonida-hle lib: 233 passed, 2 ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
xmem.rs merged on its own: title-alloc-watch's changes (XMemAllocDefault's
watched blocks, the device's heaps as xmem reservations, TitleCommit and
XMemGetWorkingSetStatistics) touch no line of the physical-page code.
title_used counts page_table().pages, the pages with a number, so a page
waiting in Spare is not the title's and a reused one is counted once
again; nothing of it depends on how or when a section is made.

The only conflict, README-fxceless.md: every bullet of both sides; HEAD's
in-place bullet is the newer version of title-alloc-watch's.

leonida-hle lib: 241 passed, 2 ignored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts resolved keeping both sides: the submission's own memory stays
optional (all sends straight) alongside main's copies beside the take;
the library's in-play save limit returns Some(0); BCPack dump kept with the
paged destination; both test sets in list::thin; both findings sections.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was missing: neither branch merged here tests the two together.
page-pool-open's tests (a_committed_section_is_made_at_its_first_page,
a_committed_section_is_charged_when_first_touched) run with reuse off
(TEST_REUSE defaults false), and physical-reuse's
(freed_pages_are_given_out_again_until_their_section_goes,
a_free_keeps_a_page_a_mapping_call_puts_back) with LEONIDA_SECTION_COMMIT
off. What the merge relies on was unchecked: that a freed page of a lazy
section never made has nothing to zero or discard and stays unmade, that
a reused page of one makes the section at its first touch, that
DiscardVirtualMemory and the zeroing work through a committed section's
window, and that reused pages charge no new commit.

What changes: a_committed_sections_freed_pages_are_given_out_again_with_no_new_charge
(TEST_SECTION_COMMIT and TEST_REUSE on, sections of 32 MiB). Two lazy
sections allocated: none made. Half of the first written (made, one
section charged), the page after it mapped; the written half and three
pages of the untouched second section freed: the written ones leave the
working set, the second section is still not made. As many pages asked
for again: exactly those pages, longest run first, no section made, the
written ones zeros, the second section still not made; writing them all
again charges nothing. One byte written into a reused page of the second
section makes it (SECTIONS_MADE) and charges one section, the rest of the
page zeros. No page asks for a commit of its own (COMMITS) throughout.
Everything freed: both sections close and the commit returns. Like
a_committed_section_is_charged_when_first_touched, it measures
SharedCommitUsage in a child process of the test binary; the child
launch is now one helper, in_a_child, that both tests call (the existing
test's behaviour is unchanged).

Readings alone (MiB of shared commit since the start): allocated 0, half
written 32, freed 32, given out again and written 32, the second section
written 64, all freed 0. Red with reuse off (TEST_REUSE false): "the
written pages freed are let go" (left 4096, right 0); with that and the
other non-charge checks turned into prints, "nothing more for the pages
given out again: ... given out again and written 48" (a new 259-page
section charged when written).

Docs: lazy_commit's measured list and Spare's say how the two meet
(written bits are set only once the host's section exists, so a section
never made has nothing to zero or let go); title_used's says a page may be
committed with its whole section and that a page waiting in Spare is not
the title's; README-fxceless.md's reuse bullet says the same holds with
LEONIDA_SECTION_COMMIT=1. No runtime behaviour changes; no switch.

leonida-hle lib: 242 passed, 2 ignored (6 runs: one failure each in two
runs, xasync::pool_workers_left_idle_leave_under_a_trickle_of_callbacks
and dstorage::a_read_into_memory_guarded_for_a_moment_is_tried_again,
timing tests under load, not xmem); xmem module 6 of 6; leonida-gpu lib
619 passed, 47 ignored; clippy -p leonida-hle --lib (and --tests): no
warnings in the changed lines.

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

@⁠adrianmjim on GitHub · 2026-11-29 11:34 UTC · original · edited 2026-11-29 15:00 UTC

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.

**@⁠adrianmjim** on GitHub · 2026-11-29 11:34 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7255200827) · edited 2026-11-29 15:00 UTC ### 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://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570) and [#2570 (round 2)](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570); 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.
What was wrong: texture::forget (texture.rs, the HOST_WRITTEN_AT retain)
ran BTreeMap::retain over every texture the host ever copied into that is
still alive, under a global mutex, for every Resource the title released;
Drop for Resource (resource.rs) called it for buffers too, which are in
none of the maps it clears (STAGING, HOST_WRITTEN, HOST_WRITTEN_AT,
THROUGH hold textures only: host_written is reached through
host_resource/texture copies, which refuse buffers). HOST_WRITTEN_AT is
read by the "HERO LEAD" warning, which is on in every build, so it is not
gated; the played build is target\diag with the diagnostics feature
(d3d12/scripts/play.ps1 -Build diag), so a cfg gate would not have reached
what players run anyway.

What changes: HOST_WRITTEN_AT is a HostWrittenAt, the same BTreeMap by
address plus a resource -> address index. forget removes the resource's
own entry (only if it is still the one at that address, as the retain
did); an insert over an address another resource held drops that
resource's index entry, as the overwrite always made it unfindable.
placed_in_host_written's lookup is unchanged (holding). A buffer's
release skips texture::forget. Nothing reported changes.

Switch: none; no rendering or timing behaviour changes, the warning's
content is the same.

Tests: texture::host_written_at_tests (a thousand noted textures, a
thousand foreign releases and their own: at most 1,000 entries looked at;
the retain looked at about 1.5 million) and
resource::tests::only_a_texture_release_clears_the_texture_maps (a
buffer's release leaves the thread's forget count as it was).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with the present sent ahead (LEONIDA_LATE_WAIT=3, the
relay's default) something is always in the air, so Host::submit made one
submission every 1.5 s settle everything first, a full drain of the card
under the submission lock, just to run sweep() (host.rs, the `else if
late_free_present() && now_ms() > SWEPT + 1500` branch). The note left by
the compare results ring named what depended on it: the sweep,
upcheck::at_rest, and the whole-area results with LEONIDA_COMPARE_RING=0.

What changes: the decision is a pure function, sweep_now(behind,
free_present, since_ms, rest). Behind flights with the present sent ahead
the sweep now runs at once (it lets itself go once a second) and no
settle is made for it, unless sweep_wants_rest(): LEONIDA_SWEEP_NO_SETTLE=0,
upcheck (diagnostics, wants no shader writing) or the relay with
LEONIDA_COMPARE_RING=0 (ResultArea::Whole starts from dword 0 only when no
plan is out). Then it settles every 1.5 s as before. Without the present
sent ahead nothing changes (the present settles).

Why it is safe, read in the code: every let-go in the sweep guards by
references a flight's lists hold (shadow::let_go_idle and
resource::let_go_copy at strong count 1 and one COM reference,
texture::let_go_idle at strong count 1) and drops through retire(), which
waits for every submission begun and queued plus the bury lag; the spare
pools (scratch chunks, read-back buffers, sends, pool blocks) hold only
memory given back after its submission landed; inplace::reap already runs
from the title's frees with flights in the air; the sweep runs under the
submission lock, which the landing thread never takes. Default on.

Switch: LEONIDA_SWEEP_NO_SETTLE=0 restores the forced settle. Documented at
sweep_no_settle and in docs/README-fxceless.md.

Test: host::sweep_now_tests (red with the old policy, which settled
behind flights every 1.5 s whatever wanted rest).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: copystat::range (copystat.rs, RANGES), compared (COMPARED)
and whole (WHOLE) each put an entry into one HashMap behind one
process-wide Mutex. range is called for every host-copy refresh
(host.rs Host::update), which runs on the wide threads in parallel;
compared for every range compared after a submission (host.rs, the
landing loops); whole for every copy of unwatched memory (shadow.rs). The
module is built only with the diagnostics feature, but that is the build
the launcher plays and every measurement is of
(d3d12/scripts/play.ps1 -Build diag, the default), so the refreshes
serialised on that lock in what users run. The counters beside them
already use 32 per-thread sets to avoid exactly this.

What changes: the three maps are Banked: one Mutex<Option<HashMap>> part
per counter set (the same bank() the counters use, cache-line aligned).
A thread adds to its own set's part; the frame line takes every part and
sums entries of the same range, so what it reports (counts, bytes,
microseconds, the largest ranges) is unchanged. The parts are emptied by
the line, as the single map was (no thread_local with a destructor:
AGENTS.md runtime traps).

Switch: none; diagnostics bookkeeping only, nothing rendered or paced
reads it.

Test: copystat::banked_tests::parallel_refreshes_do_not_wait_and_all_count
(8 threads x 20,000 range calls on 16 shared ranges, started together:
no wait for a part's lock on any of them while their sets differ, and the
merged map has every call). Runs with --features diagnostics.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with LEONIDA_INPLACE on, `loose` (shadow.rs, the window
maker) opened a window in place ahead of a side in the card's memory
(LEONIDA_CARD_WINDOWS_MB) and card memory the CPU maps
(LEONIDA_WINDOWS_BAR_MB), pulling windows out of VRAM where those
budgets were set; and `lookup` (shadow.rs, `!big && place_for`) never
opened a big title buffer in place, so one the card's memory turned down
(no room, past LEONIDA_CARD_BUFFERS_MB, 1 GiB or more) was a full copy
in a shared buffer: write-back PC memory the card reads over the bus at
the same 23-28 GB/s as the title memory itself (findings.md, the RX
7900 XT placement table), plus a refresh of every written page.

What changes: the order is a policy of its own (`window_ways`,
`buffer_ways`). Windows try mapped card memory, then a card side, then
in place, then a copy; title buffers a card side, then in place (level
2), then a copy. `window_card_for` is split into `window_room_for` (the
card side) and `window_own_for` (LEONIDA_WINDOWS_OWN's second side), so
the old order runs the same steps.

Switch: LEONIDA_INPLACE_LAST (on; =0 the order before). It only acts
with LEONIDA_INPLACE on, whose default (0) is unchanged.

Test: shadow::in_place_tests: the policy (red on the old order); a
window of private memory in place at level 1 through `find` (the card
reads the title's bytes before and after a CPU write, `update` copies
0); a big title buffer the card turns down in place at level 2 (red on
the old policy: it was a copy). On the host's RX 7900 XT;
`inplace::TEST_LEVEL` and `TEST_CARD_FULL` set the level and a full card
for the test's thread only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was asked: whether hashing every new guarded texture at every check
for its first 64 frames (texture.rs refresh_timed, "A texture starts
hot", HOT_FRAMES) is still needed now that LEONIDA_VIEW_GUARD opens every
view of a page on a write through any of them (watch.rs header). The
hot start was added for writes through another view, which the guard
now sees.

Why it is not changed: it cannot be shown redundant. Writes the guard
does not see remain, named in the code: pages shown in more than
watch::MANY_VIEWS places are guarded per address; a finished plain read
(watch::title_memory_written without pages) opens no guard unless
LEONIDA_PAGE_WRITES has bit 4, off by default, so a block guarded again
while the read was in the air is found only by the hash; with
LEONIDA_PAGE_WRITES=0 or slots, DirectStorage page writes open none
(10,000 to 50,000 guarded blocks under them per run, watch.rs
page_writes). No count says how many changes in a texture's first 64
frames came those ways. The doc on hot_textures says this and names the
count to take first (the frame line's "changes the guard did not see",
copystat::C::TexHot, on a streaming run with the default switches).

Also: a "Speed and memory" bullet in docs/README-fxceless.md for the two
bookkeeping fixes before this commit and for this re-check.

Switch: none (documentation). Test: none (no behaviour changes).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: every path that puts memory the CPU fills in the card's own
memory (LEONIDA_SEND_BAR, LEONIDA_WINDOWS_BAR_MB; host/send.rs `memory`,
shadow.rs `window_mapped_for`) asks host.rs `mapped_card_memory`, which logged
only "card memory the CPU maps supported=false" at the first ask, if any, and
each path then fell back to the PC's memory silently. Whether the firmware's
resizable BAR was on had to be found by hand (findings.md, last section: a
256 MiB window and GPUUploadHeapSupported false on the RX 7900 XT). The
placement benchmark (host/placement.rs) put "not offered" in a table cell and
left the GPU upload rows unmarked among the others.

What changes: host/bar.rs says once, when the host device is made, Direct3D's
GPUUploadHeapSupported and the size of the card's largest memory window as
Windows gave it out (the PCI resources of the adapter's device, through
cfgmgr32: windows-sys gains Win32_Devices_DeviceAndDriverInstallation), and
whether that is the fixed window (BAR off: what to turn on in the firmware), a
resized one, or one Direct3D does not take. `mapped_card_memory` asks the same
query. The placement benchmark prints that line with the adapter and ends with
the GPU upload rows side by side with upload, custom L0 and device-local memory
at each size, or one line saying why there are none.

Switch: none (a log line and benchmark output; nothing behaves otherwise).

Tests: host::bar::tests::the_line_tells_the_bar_on_from_off (the fixed window
of the RX 7900 XT against a resized one and a refused one),
the_adapter_is_found_by_its_pci_ids, the_hosts_window_is_found (on this PC:
256 MiB, BAR off), host::placement::lines_tests::
the_gpu_upload_rows_are_said_side_by_side. Red with the line and the summary
stubbed to what was there before (3 fail), green with them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with the relay, a submission that reads title memory a
flight may write waited with relay_wait(WHY_READ, |line| blocked_by(
&line.written, runs, ..) && !copied_read(copies(line), runs)) (host.rs,
Host::submit), and one that refreshes memory flights write with
relay_wait(WHY_STALE, all stale ranges' writes_pending_in) (settle_stale).
relay_wait evaluates its predicate with LINE held, first and after every
landing: a walk of every step of the submission (taking each list's
deferred() lock) or of every stale range's copy, while the landing thread
(at a landing's start and end), the helper thread, the title's fence
signals (late_signal) and value checks (late_met) wait for LINE.

What changes: relay_wait_apart(why, take, done) copies what the look needs
(written and card_steps::copies, or nothing) out of the line under the
lock and runs the walk without it. The line counts its landings
(Line::landings, bumped by Line::landed); the wait is for a landing after
the one the copy was taken at, so a landing between the copy and the look
is not missed. Same predicate, same state, same counters and timeline
span; used for WHY_READ and WHY_STALE.

Switch: LEONIDA_LINE_APART=0 evaluates under the lock, as before.
Documented at line_apart / relay_wait_apart and in
docs/README-fxceless.md. Default on: the result is the same predicate on a
copy of the same state; the tests cover the one new hazard (a missed
landing).

Tests: host::line_apart_tests::the_look_after_each_landing_runs_without_
the_lines_lock (red with the look under the lock: both looks find LINE
held) and a_landing_between_the_copy_and_the_look_is_not_missed (red
without the landing count: the wait hangs for a landing that already
happened).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: Line::written (the title memory flights in the air may
write, in order and joined) was kept by sorting. Line::push_flight called
join_ranges(written + the flight's ranges), a sort of everything; and
Line::landed, at every landing, collected every range of every flight
still in the line and sorted them all again (host.rs, Line::landed). Both
run with LINE held, which the landing thread, the helper thread, the
title's fence signals and value checks also take.

What changes: each Flight carries its ranges joined (Flight::joined, made
by flight_writes before the line's lock is taken in send_late and
execute_own). The line keeps a Cover: pieces of title memory in order,
apart, each with how many flights in the line or being landed declare it.
A flight joining adds its joined ranges, take_landable moves the taken
flights' ranges aside and Line::landed takes them away, each in one linear
pass over the cover and the flight's ranges (Cover::change); written is
the cover's joined view (Cover::joined, one pass). The non-relay settle
clears both with written.

Switch: LEONIDA_LINE_COVER=0 sorts as before. Documented at line_cover and
in docs/README-fxceless.md.

Tests: host::line_cover_tests::written_is_every_range_in_the_air_joined_
whatever_joins_and_lands (200 random sequences of flights with empty,
equal, touching and overlapping ranges, landing one or several at a time:
written equals join_ranges over the flights in the air and being landed,
with the switch on or off); keeping_written_is_one_pass_over_what_is_in_
the_air (16 flights of 1,024 ranges join and land one by one: 388,396
steps against a budget of 4 per range in the air; red with
LEONIDA_LINE_COVER=0 at 3,055,321 steps, the sorts' comparisons).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: upload arenas (upload.rs `Upload::new`, registered with
`shadow::register` as title buffers) got a full copy like any title
buffer: from the card's least size on (4 MiB on 12-20 GiB budgets, which
an arena is) a card side plus a 4 MiB CPU side for bytes the structure
builder reads once; and the 16 MiB directory of memory by address
(memory.rs `Memory::new`, `shadow::by_address`) had a 16 MiB staging
buffer with the same bytes that every list's `bring_up` refreshed from
the write watch by compare, though its one writer (under the mutex)
knows each entry it writes.

What changes: arenas are registered as ours (`shadow::register_ours`,
`Entry::ours`) and `lookup` opens them in place first
(`inplace::place_ours`: `place_part`, counted with title buffers, not
held for the title's frees, which never come); in place is what a host
upload heap is. The directory is made with `by_address_opened`, resent
whole once, and every writer (`map`, `opens`, `hold`, `gone`) resends
the entries it wrote (`Memory::sent`).

Switch: LEONIDA_INPLACE_OURS (on), acting only with LEONIDA_INPLACE 1
or more (default 0, unchanged); =0 copies both as before.

Test: memory::tests::the_directory_is_its_copys_cpu_side_and_sends_the_entries_written
(the directory is its copy's CPU side, `update` copies 0, an entry held
after a first send reaches the card's side; red with `ours()` off, and
red with `hold`'s resend taken out), shadow::in_place_tests::an_upload_arena_is_read_in_place
(the arena is in place, nothing holds it, the card reads it before and
after a CPU write, `update` copies 0; red with `ours()` off). On the
host's RX 7900 XT.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: to merge the declared ranges of the flights it lands,
Host::relay_land walked the copies merged so far for every copy of every
flight (back.iter_mut().find(Arc::ptr_eq)), and the non-relay
Host::settle did the same plus, for each range of a copy seen before, a
walk of that copy's ranges so far (all.contains(range)): O(copies^2) and
O(ranges^2) on the threads that fences, value waits and reads of title
memory wait on.

What changes: declared_by_copy(declared, key, once) indexes copies by
address in a ByCopy table and, with once, ranges seen in an AddressHash
set: one look per copy declared and per range. Same copies in the same
order, same ranges in the same order; with once a range repeated within
the first list of a copy is now kept once too, which the settle's
copy-back takes the same way (hand_back sorts and joins the ranges, and
Shadow::copy_back_done removes each from `pending`, a second time a
no-op). No switch: what lands and when is unchanged, only the CPU work
of the merge.

Tests: host::declared_by_copy_tests::the_merge_by_table_is_the_merge_by_
walk (300 random sets against the old walk, kept in the test) and
merging_many_copies_and_ranges_is_one_look_each (4 flights x 2,000 copies
plus one copy of 4,000 ranges: at most one look per copy declared and
range; red with the walk, 8,004,000 looks).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: `inplace::place_for` turned down all view memory
(inplace.rs `kept_from`: `cover(..) != Cover::None`), so with
LEONIDA_INPLACE on every window and title buffer in the page pool stayed
a copy, though with LEONIDA_SECTION_COMMIT=1 the pool's small sections
are made committed and open as heaps (`From::Section`; measured on the
RX 7900 XT by leonida_hle's `a_committed_section_opens_as_a_heap`).

What changes: a window or title buffer that is one run of a section
(`Cover::Run`) goes to `in_section`: the section the runtime noted
committed is opened once per device (`section_heap`, forgotten at
`title_memory_section(_gone)`), a buffer placed at the run's 64 KiB page
(`place_in_section`), counted as in place (and within
LEONIDA_INPLACE_MB) but not held: a section's heap locks nothing, so the
title's frees, protections and unmappings are not refused. The title
mapping other pages there lets it go as before (`title_memory_freeing`
from `watch::title_memory_changed`); a placement made while that
happened is let go at once (the run is looked at again after it is
counted, under the caller's table lock). A refused section is not asked
again. The in-place line counts placements in sections.

Switch: LEONIDA_INPLACE_SECTIONS (on). It acts only with LEONIDA_INPLACE
1 (windows) or 2 (title buffers) and committed sections
(LEONIDA_SECTION_COMMIT=1, or Wine), all off by default; =0 copies as
before. Default on because both outer switches are opt-in and the
hazards (remap, unmapped view, closed handle, reserved section) are
tested.

Test: inplace::tests::warp_a_run_of_a_committed_section_opens_in_it
(WARP: the card reads and writes the title's bytes through the run's
offset, one heap for the section, the bytes outlive the view and the
handle, the heap is forgotten with the section; reserved, unknown and
past-the-end are turned down without asking the host) and
shadow::in_place_tests::a_title_buffer_in_a_committed_section_is_read_in_place
(host RX 7900 XT: a title buffer over a view at level 2 is in place,
`update` copies 0, the card reads it before and after a CPU write, and
it is let go when the title maps other pages there; red with
`sections()` off, where it was a copy).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With the relay, the compare after a submission's lists flags the 64 KiB
pieces of card copies that changed; the landing thread then fetched them
with a list of its own and a wait (host.rs relay_card_back,
WaitForSingleObject after ExecuteCommandLists of the relay's fetch). On
the drawing queue that fetch runs behind whatever was sent meanwhile:
48 ms of a 120 ms frame waiting for seven fetches of 94 MB (relay_copy's
notes).

New host/landsame.rs (LEONIDA_LAND_SAME=1, off by default): two passes
of ours follow the compare in the same list. One group numbers the
flagged pieces of the declared ranges in order (a prefix sum over the
compare's flags, no atomics in PC memory); a group per piece copies each
piece that got a slot, whole as the compare hashes it, into a landing
buffer of the plan's (shared memory, mapped write-back). When the
flight's fence is reached relay_card_back merges those pieces, plan by
plan, each as a fetch behind the plan's own send (card_merge_relay /
land_card with after = sent_as): no second submission, no extra wait.
Still fetched as before, merged after the captures: pieces past the
plan's slots, ranges not compared, pieces a torn check wants, and
pieces an earlier fetch may hold newer than the capture (Had::touches,
noted by the last send when the fetch was done). With captures the
notes of sends are let go only up to the landed flights' last send
(landsame::forgotten), since a later flight's capture is merged against
the sends after its own. Slots per plan follow the last 64 plans' counts;
landing buffers are pooled, at most LEONIDA_LAND_SAME_MB (256) alive,
kept ones dropped when PC memory is pressured; the frame line counts
what landed and what was still fetched.

Not with the relay off (card_back merges against the CPU side as the
one reference; a second older capture would take the title's bytes for
shader writes), and not straight into title memory opened in place (the
merge is by byte, leaves out unsent title bytes and notes every block
for the write watch); the module doc says why.

Switch: LEONIDA_LAND_SAME=1 (default off: covered by tests on the card,
but every flight's flagged pieces cross the bus where one fetch brought a
piece several flights flagged once; no game run yet).

Tests (host::landsame, on the host's card): the passes put each flagged
piece in its slot, skew not a multiple of 16, unlisted flags ignored,
slots running out; a shader's writes land with title CPU writes kept and
no fetch sent (one without the switch); pieces past the slots fetched;
two flights landed together merged in order; a capture older than an
earlier fetch is fetched again, not merged; landing buffers do not leak;
pure tests of the layout, slot sizing, scan reading and the notes kept.
Red: with captures ignored the no-fetch tests fail (1 fetch), merged in
reverse order the two-flight test fails, without Had::touches title
memory goes back to the second flight's dword.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: a title buffer below the card's lower limit
(shadow.rs `lookup`, `card_for`: 4 MiB on 12-20 GiB cards) had one copy, a
write-back buffer in the PC's memory (host.rs `shared_buffer`) that every
shader load read over the bus: 23-28 GB/s against 690-1,000 from the card's
own memory on the RX 7900 XT (findings.md, last section). Only windows had a
GPU_UPLOAD path (LEONIDA_WINDOWS_BAR_MB, `window_mapped_for`), with one side,
whose snapshot and compare would read the mapping on the CPU (write-combined:
0.13-0.19 GB/s) if a shader wrote one.

What changes, off by default: with LEONIDA_BAR_BUFFERS_MB=<MiB> and a card
that offers GPU upload heaps (a resizable BAR), such a copy has two sides as a
big one has: the CPU's side stays the write-back buffer (Card::staging), the
card side is a GPU_UPLOAD buffer (Card::bar), within the budget and while the
card's memory is under four fifths of its budget (`bar_wanted`, BAR_BYTES,
counted in the frame line's card bytes and released when the copy goes).
- No CPU read of the card side: every compare, snapshot, merge, upcheck and
  stale-page look reads Shadow::data, the CPU's side; shader writes are found
  by the card compare and fetched by a card copy (Host::card_back), as for any
  copy with two sides (the snapshot and CPU-compare paths skip carded copies).
- host/send.rs `take`: what the title's CPU wrote is written into the card
  side by the CPU at the next send, short runs and long, straight from the
  CPU's side (with LEONIDA_SEND_DIRECT; no card copy, no submission memory,
  nothing in the air), then a fence before the list goes to the queue.
- What we write at submission (send_copied, copying: title buffer copies done
  on the CPU) is noted for such copies whether or not a send was ever
  numbered (before, only once one was), and goes through the submission's
  memory and a card copy behind what is in the air; shadow/direct.rs
  `split_mapped` lets the CPU write a piece only once the card is past every
  card copy of ours into it (the sends that took it through the submission's
  memory, and two sends past a write at submission: a copy at its place runs
  in that submission's lists). Exact, unlike KEPT, which is a guess that
  costs a wait there and would cost a byte here.
- The frame line counts the bytes the CPU wrote into such sides.
What a submission in the air reads of such a copy: the title's later CPU
writes, as the single copy it replaces did. Off by default because nothing is
measured with the title and this PC's card has no resizable BAR.

Tests need no BAR: test builds take LEONIDA_D3D12_WARP=1 too (host.rs
`create`), and the software adapter offers GPU upload heaps here.
host::send::direct_tests::card_sides_the_cpu_writes_hold_each_submissions_bytes
runs `bar_run` in a process of its own on WARP (and on the host's card where
it offers them; says so where not): a first copy of ours before any numbered
send stays behind a send in the air; the title's writes are in the card side
while the card, held back, has run nothing, none through the submission's
memory; a copy of ours goes behind a submission in the air with no wait; a
256 KiB registered buffer gets a GPU_UPLOAD card side and a write-back CPU
side, counted and released; a shader write in a declared range is found on
the card and lands in title memory and the CPU's side. Plus
shadow::bar_tests::small_copies_go_to_mapped_card_memory_within_the_number and
shadow::direct::tests::a_card_side_the_cpu_writes_waits_for_every_copy_of_ours.
Red, each alone: the guard as before (send_copied notes only once numbered),
the CPU write left to the card, split_mapped ignoring the marks, the selection
refused: each fails; green with all.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: texture.rs (refresh_timed, the write-watched branch) read the
whole texture into the read buffer and detiled every level of every array
slice whenever the write watch reported any written page, and the prelude's
Upload::record copied every subresource to the card. The watch already says
which 64 KiB pages were written; a texture array, cube or atlas whose title
rewrote one slice or level paid for all of them (the module's own "shortcut:
a change detiles the whole texture, not the pages written").

What changes: part_span gives the tiled bytes each subresource's detiling
reads (the level's blocks, or its slice's mip-tail block), parts_touched maps
the pages written since the last asking (written_since) to the subresources
they hold, rounded outwards. Only those spans are read, only those parts are
detiled (Staging::detile_parts), and Staging::parts_dirty collects what was
detiled until a prelude takes it, so Upload::record copies only those
subresources. Whole, as before: the first detiling, after a forget, a
staging buffer made anew (asked for before the read: it holds what its pool
piece held), levels on demand, a bake's exact refresh, 3D and multisampled
layouts, the first copy into a host copy, a subresource that fails to
detile, and the hashed and guarded paths (no pages to go by). Textures that
change seldom let their staging buffer go after each copy and so are still
detiled whole; the gain is for those that change often.

Switch: LEONIDA_TEXTURE_PARTS=0 restores the whole-texture path. On by
default: the hazard is copying too little, and the pure test proves every
span holds all a detiling reads, the device test that every subresource on
the card matches the CPU's detile after partial updates.

Tests: parts_tests::a_part_s_span_holds_every_byte_its_detiling_reads
(linear, 256 B, 4 KiB and 64 KiB S/D modes, BC1/BC7/RGBA8/R8, tails, odd
sizes: bytes outside a span changed leave its detile the same),
the_pages_written_name_the_parts_they_hold (1024x1024 BC1 cube),
the_pages_written_since_an_asking_are_cut_to_the_texture, and on the host
a_write_detiles_and_copies_only_the_subresources_its_page_holds (a
write-watched 256x256 BC7 array of six slices: 10 of 54 subresources read,
detiled and copied for a 4 KiB write, all 54 matching the memory; red on
perf/unified-memory: 54/54 and the whole texture read).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: texture.rs (refresh_timed, the write-watched branch) copied
every watched byte it detiled into the thread's read buffer first (up to
LEONIDA_TEXTURE_READ_KEEP_MB=16 MiB kept per refreshing thread), and detiled
from there. The copy is not only for unmapped pages, as its comment says: the
title's own threads free, decommit and protect write-watched memory through
inplace::title_memory_free/title_memory_protect without the lock the runtime
takes for its mapping changes (watch::title_memory_reading covers views),
so a plain read in place could fault on the submitting thread where the
kernel's copy, or the copy that takes the fault, reads zeros
(title_memory_tests::an_uncommitted_tail_reads_as_zeros decommits a page
between two reads). The proposal's "same locking as the guarded path" is
therefore not enough on its own.

What changes: with the switch the branch takes the range lock
(title_memory_reading_range, or the non-waiting whole lock under
LEONIDA_TEXTURE_NO_WAIT), registers an InPlaceRead of the texture's range,
checks the pages it reads are committed, and detiles the slice in place (the
parts of the previous commit, or all). title_memory_going, called by
inplace.rs for the title's VirtualFree and VirtualProtect and for the frees
and protections it makes later for the title (release_pending,
protect_pending), waits until no in-place read overlaps its pages; a read
does not begin while an overlapping one is under way and reads through the
copy instead. One mutex, uncontended unless a read is under way. Tearing is
unchanged: the write watch is asked before the read, so a write during it is
the next refresh's, exactly as with a torn copy; no re-check is needed.

Switch: LEONIDA_TEXTURE_WATCHED_IN_PLACE=1 turns it on; off by default,
because a title thread's free or protection of memory being detiled now
waits for that detiling, and memory taken away by a route that bypasses
those two functions (none known) would fault instead of reading zeros;
neither is measured with the title.

Tests: parts_tests::a_free_waits_for_a_read_in_place_of_its_pages (an
overlapping free waits for the read, others do not, no read begins under an
overlapping free, len 0 covers the rest of the allocation) and on the host
a_watched_texture_is_detiled_where_it_lies (whole and partial detilings in
place, nothing copied into the read buffer, all 54 subresources matching the
memory; with a free under way, and with the switch off, through the copy;
red without the path: the whole texture copied, nothing in place).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: host/placement.rs `gpu_upload_lines` (from the commit that
added it) joined its long format strings with thirteen spaces in the middle
of the "No GPU upload (BAR) rows" line and of each size's line, where a
string continuation was meant; seen in a run of the benchmark on this PC.

What changes: the strings continue with `\` and the lines read with single
spaces.

Switch: none (benchmark output).

Test: host::placement::lines_tests::the_gpu_upload_rows_are_said_side_by_side
now asserts each line is one line with its words a space apart: red with the
strings as they were, green now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
line_cover() (host.rs, used by Line::push_flight, take_landable and
landed) went through crate::toggled!, which in diagnostics builds follows
a LEONIDA_AB bit that crate::ab turns on and off at presents, while
flights are always in the air with the present sent ahead. The Cover keeps
counts from a flight joining to its landing, so a flip between them left
counts added and never taken away (written kept ranges no landing cleared:
a read waited on LINE_LANDED for good under the submission lock) or took
away counts never added (another flight's range left written while in the
air: title memory read before its copy-back wrote it).

LEONIDA_LINE_COVER is now read once through a plain OnceLock (as
compare_ring is), and the line latches what it said at its first flight
(Line::by_cover), so take_landable and landed take counts away exactly as
push_flight added them. Naming it in LEONIDA_AB does nothing (doc and
README say: compare two runs). Switch unchanged: LEONIDA_LINE_COVER=0
keeps written by sorting again.

Test: line_cover_tests::written_holds_whatever_the_switch_says_between_
join_take_and_land flips what line_cover says (a test-only thread-local)
before each join, take and landing and checks written against the join of
every range in the air, and that nothing is left once all have landed.
Red with the old per-call read (round 0, step 13: written held three
ranges with nothing in the air), green now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Host::send_late and Host::execute_own (host.rs) made Flight::joined
(flight_writes: an allocation, a sort and a join) for every flight even
with LEONIDA_LINE_COVER=0, where nothing reads it and the old path sorts
again under LINE: that setting did more work than before the cover.

joined is now made only while line_cover() says on, empty otherwise;
Line::push_flight joins a flight's ranges itself if its line is kept by
the cover and the flight came without them (never with the read-once
switch). No new switch: LEONIDA_LINE_COVER=0 now does what it did before
the cover.

Test: line_cover_tests::a_flight_not_joined_before_the_lock_is_counted_
all_the_same (a flight with no joined ranges on a cover line is counted
and taken away at its landing).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Only sweep_now (host.rs) was tested: a broken sweep_wants_rest (which
keeps the settle for LEONIDA_SWEEP_NO_SETTLE=0, for upcheck and for the
relay with LEONIDA_COMPARE_RING=0) would still have passed.

sweep_wants_rest now reads its four switches and hands them to
wants_rest(no_settle, upcheck, relay, ring); Host::submit still passes
sweep_wants_rest() to sweep_now. No behaviour change, no switch.

Test: sweep_now_tests::the_settle_stays_only_for_what_wants_rest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
let_go_idle_snapshots (shadow.rs), let_go_idle_reads (texture.rs) and
shadow::let_go_idle still said the sweep runs with nothing in flight and
the card waits for it ("Nothing runs now"). With LEONIDA_SWEEP_NO_SETTLE
(on by default) it runs behind flights in the air. The code was safe; the
reasoning next to it now says why: the pools hold only buffers given
back, host copies go at a strong count of 1 and one COM reference, and
retire() keeps all of them past every submission running.

Comments only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: texback.rs land() mapped each read-back buffer, copied it
into a freshly allocated Vec (to_vec) and unmapped it on the landing
thread, so the buffer could go back to the list; the writer then tiled from
that Vec. One allocation and one pass over every read-back's bytes on top of
the card's copy, the tiling and the write into title memory (two to ten
350 KB water maps a frame).

What changes: when every submission of the list so far has landed
(Back::runs, counted in HostList::run_deferred before the list goes to the
card, against Back::landed, counted at each landing), the landing keeps the
buffer mapped (Texels::Mapped, holding a reference) and write() tiles from
it. A buffer a landing holds is not pooled at the list's reset (the pool
takes only buffers nothing else names, host::sole); the landing unmaps it
and gives it back through host::give_read_back when it goes. What the old
copy also guarded against is kept: a list submitted again has the card write
the buffer again, so with a submission not landed yet the texels are copied
out as before, and a landing whose list was submitted again while it was
tiled (Mapped::still, checked after the tiling and before the write) is not
written; that submission's own landing writes the newer texels. Counted in
the read-backs line (land::stat::TB_OVERTAKEN).

Switch: LEONIDA_TEXBACK_MAPPED=0 copies out at the landing, as before. On
by default: the two hazards (pool reuse while the writer reads, a
resubmission's card copy over the texels) are covered by the reference the
landing holds and by the run counts, each tested.

Tests: texback::tests::a_readback_is_tiled_from_its_mapped_buffer (on the
host: mapped landing writes the tiled texels with nothing taken out, a
landing overtaken by a resubmission is not written and the next one is, a
list with a submission not landed and the switch off copy out; red without
the path: the first landing is a copy) and
a_submission_counts_before_its_landing (host.execute counts the run and the
landing: 1/1, 2/2; red without the run_deferred hook: 0/1).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
COVER_NOW, LINE_STEPS and MERGE_STEPS (host.rs, all new on this branch)
had their doc comments outside thread_local!, which clippy reports as
unused doc comments; the flip test used `% 2 == 0` where clippy asks for
is_multiple_of. Docs moved inside the macro, the test takes the low bit.
No new clippy warnings in this branch's lines now. Tests only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: a window or title buffer placed in a committed section
(inplace.rs `in_section`) is not held (`hold`, HELD), since a section's
heap locks nothing. When the title maps other pages at its address,
`watch::title_memory_changed` -> `inplace::title_memory_freeing` ->
`shadow::in_place_let_go` (shadow.rs:6957) only took it out of the
tables: the descriptor slots that view it were never let go of
(`stale_buffers`, `slots_let_go` and `slots_again` look at HELD alone).
A title descriptor written once for page-pool memory went on reading the
section's old physical pages after the remap (and whatever the title
wrote into them once it mapped them elsewhere), where the copy it viewed
before had the new pages' bytes at the next refresh, and kept the
section's heap (and its commit) alive for as long.

What changes: `in_place_let_go` returns the buffers it took out;
`title_memory_freeing` keeps those HELD does not have (`unheld_gone`),
and the slots that view them let go of them before the next submission
(`slots_let_go_of_unheld`, from `inplace::tick`, with `now`): made again
from the record, from what the address shows then. Not at once: xmem
maps with its own lock held, and the slot scan takes every slot's lock,
which a thread making a slot holds while it may wait for the mapping to
end (`watch::title_memory_remapping`). Lists recorded across the remap
keep the shortcut documented at `unheld_gone`.

Switch: LEONIDA_INPLACE_SLOTS (on; =0 the slots keep the buffer until
the title writes them again, as before). Acts only with
LEONIDA_INPLACE, LEONIDA_SECTION_COMMIT=1 and LEONIDA_INPLACE_SECTIONS.

Test: shadow::in_place_tests::a_slot_over_a_title_buffer_in_a_section_lets_go_when_the_title_maps_other_pages_there
(host RX 7900 XT: a title slot views a title buffer placed in a section;
after the title maps other pages there and a submission starts, the slot
keeps it no more; red with `unheld_gone` not called).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: memory.rs `Memory::map` (:381, :389), `hold` (:451) and
`opens` (:529) wrote a page's offset in its copy as `at - span().0`, and
the copy's raw view (:1135) covered `[0, len)`, neither counting
`Shadow::offset`'s bias: for title memory in place the heap begins on the
64 KiB line before the title buffer (`inplace::Placed::bias`). A shader's
address A reached title memory at A - bias, and the structure builder's
stores through `opens`/`keep_stores` landed bias bytes early in the
title's own memory, which no copy shields when the buffer is in place.
Older than this branch (small title buffers at LEONIDA_INPLACE=2), now
reachable for the big title buffers the card turns down and for title
buffers in a section (bias: the run's offset modulo 64 KiB).

What changes: the entries take `Shadow::offset(address)`; the raw view
covers the buffer to the copy's end (`viewed`: `offset(start + len)`).
For every copy that is not in place the bias is 0 and nothing changes.

Switch: none. Copies are unchanged; for memory in place the old offsets
read and store the wrong title bytes, nothing worth restoring, and in
place itself is off by default (LEONIDA_INPLACE).

Test: memory::tests::a_title_buffer_in_place_off_a_64_kib_line_is_found_by_address
(host RX 7900 XT: a title buffer 0x100 bytes past a 64 KiB line, in place
at level 2, mapped by address: the entry is `offset`, the raw view
reaches the page's end, the card reads the title's dword where a shader
would and its store lands in the title's memory at that address, not
0x100 bytes before; red with the old entries (0xff00 for 0x10000) and
with the old view length).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: `Memory::sent` (memory.rs:297), new on this branch,
queued the directory bytes of pages `[first, end)` unbounded, and
`opens` (:532) names every page of a numbered title buffer's copy: one
that reaches past 2^37 (title memory goes up to 2^40, the directory
covers `[0, 2^37)`) queued offsets past its 16 MiB, which `host.rs`
records as a `CopyBufferRegion` on the directory unchecked, a copy out of
its buffer that can remove the device. (`map` stops before the last
entry; `hold` and `gone` write pages inside the directory.)

What changes: `sent` takes the range cut to the directory
(`entry_bytes`), nothing when none of it is in it.

Switch: none (only ever a send past the directory's end is left out).

Test: memory::tests::the_entries_sent_stay_in_the_directory (pure; red
without the cut).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: nothing failed, but coverage was missing (review of this
branch). The windows' new order (mapped card memory, then a card side,
then in place: shadow.rs `window_ways`) only differs with
LEONIDA_CARD_WINDOWS_MB or LEONIDA_WINDOWS_BAR_MB set, and only the pure
ordering test covered it; `in_section`'s second look at the run after it
counted the placement (inplace.rs, for a remap racing the placement) had
no test.

What changes: tests only, with two thread-local test hooks:
`shadow::TEST_WINDOW_CARD_MOST` (what LEONIDA_CARD_WINDOWS_MB would set,
read by `window_card_most`) and `inplace::TEST_REMAPPED_WHILE_PLACING`
(views forgotten between the placement and the second look); and
`shadow::window_gone` for a test to take its window out of the tables.

Switch: none (tests).

Test: shadow::in_place_tests::a_window_with_room_on_the_card_gets_its_side_there_not_in_place
(host RX 7900 XT: with room for windows on the card a window at level 1
gets its card side, not in place; red with `window_ways(false)`, the
order before) and
inplace::tests::a_placement_in_a_section_the_title_maps_other_pages_over_meanwhile_is_let_go
(the placement is refused, the counts go back and one is let go, the
buffer is a copy; red without the second look).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With LEONIDA_LAND_SAME=1 on the drawing queue (LEONIDA_RELAY_COPY off),
relay_card_back noted every fetch in RelayFetch::newer by QUEUE_ORDER read
after the fetch's wait (host.rs:7331 `newest`, f.newer.fetched at
:7396-7401), and a capture whose 64 KiB block such a fetch touched at or
past the plan's send was fetched again (Had::touches, host.rs:7165).
Flights sent during the wait, put on the queue after the fetch and so
newer than it, had their captures fetched again; that fetch noted the
flights sent during its own wait, and so on: with flights writing a block
every frame, every landing fetched it and waited, for good. Flights that
ran before the fetch, whose bytes it had merged, were fetched again too.

Now on the drawing queue a fetch is noted by `after`, the count of sends it
went to the queue under: a flight with a later send took the order's lock
after it, so its sends and its lists ran after the fetch, and its capture
is merged. The copy queue keeps the count after the wait (the fetch runs
beside later submissions there). And a captured piece that an earlier
fetch held whole, with the flight in the line when that fetch went to the
queue (RelayFetch::had, as Had::holds), is left out, neither merged nor
fetched: that fetch ran after the flight and merged its bytes or newer
ones. A send at or below `after` alone does not say that: a flight's sends
go to the queue under the lock, its lists after it is let go. The rule is
landsame::fate; the frame line counts the pieces left out.

Switch: under LEONIDA_LAND_SAME=1 (still off by default), not under
LEONIDA_LAND_SKIP, since the alternative here is the very fetch the switch
removes.

Tests: a_capture_is_merged_left_out_or_fetched_by_where_its_flight_ran
(pure); flights_sent_after_a_fetch_land_with_no_further_fetch (on the
card, with the relay's order: sends numbered, flights in the line by their
fence via landsame::TEST_AHEAD, a send taken while a fetch waits): two
fetches over five landings, title memory with every write. Red on the
branch before this: one fetch per landing, [(c1,1),(d1,2),(d1,3),(e1,4),
(e1,5)]; with only `after` (nothing left out) or only the pieces left out
it fails too. title_bytes_sent_after_a_flight_stay_over_its_capture (the
review's nit): plans with distinct sends, title bytes of a written piece
gone up with a later send, kept over both captures and still noted for
the second after the first landing let notes go; red with the merge at the
order's count instead of the plan's send, and with landsame::forgotten
not holding the notes back. a_capture_older_than_an_earlier_fetch_is_not_merged
now pins no flight in the line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: the selection of f22f5796c checked only the size.
shadow.rs `bar_for` (called from `lookup`, where a title buffer's copy is
made) gave the LEONIDA_BAR_BUFFERS_MB budget first come, first served, to
every new copy below the card's lower limit, and nothing moved a copy
later: one shaders write, or one read once at load, kept its GPU_UPLOAD
side until the buffer went (the doc said so as a shortcut). Set to measure,
the budget went to the first small buffers made at load, and the buffers
read in steady state got none of it.

What changes, with the switch on (off by default; nothing changes with it
off): a copy is made with one side, as without the switch. Shadow::refresh
counts the submissions it is read in (`Shadow::read_in`, once per
submission begun, read before written). The sweep (`let_go_idle`, once a
second before a submission) moves copies by `bar_move`: one read in
BAR_READS (16) submissions and never declared written goes there while
there is room (`bar_wanted`); one there that shaders were declared to
write goes back to one side, and its buffer is marked so that no later
copy of it goes there (`Entry::bar`). A copy that moves is taken out of the
table and retired; the next ask makes it again, its card side where it was
decided, and copies it whole from title memory. Only copies nothing but
the table holds move (`held_by_none`, the rule `let_go_idle` lets a
window go by: no list not yet reset, no submission comparing or fetching
it, no descriptor slot viewing its buffer), so no slot is left showing a
copy the pass that refreshes slots no longer finds. shortcut: a copy some
list or slot always holds never moves; the trail's sweep line counts the
moves. README-fxceless.md's bullet says so.

Tests: shadow::bar_tests::copies_move_there_when_read_often_and_back_when_written
(the rules), and host::send::direct_tests::card_sides_the_cpu_writes_hold_each_submissions_bytes
on WARP (`bar_a_small_buffer_gets_such_a_side`: a new small copy has one
side; read often but held it stays; let go it is made again with a
GPU_UPLOAD card side and counted; unwritten it stays there; written it
goes back, uncounted, and does not go there again). Red with `lookup`
giving `bar_for` at once as before (the device test fails: "a new small
copy has a card side") and with `bar_move` reduced to the room alone (the
rules test fails); green with both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PreludeUpload::claim (texture.rs, the parts taken at the end of claim) left
Staging::parts_dirty as Some(empty) after every copy, whatever
texture_parts() said, and handed that set to Upload::record when the next
claim came with nothing detiled in between. One path does exactly that:
the levels-on-demand retry in upload_from marks a kept staging buffer
dirty without forgetting it (no detile). on_demand.uploaded() then gave
the waiting level card memory and the prelude copied no subresource into
it: the blurred/black texture the retry was added for came back, with
LEONIDA_TEXTURE_PARTS=0 too (the empty set came from claim, not from the
parts computation).

claim now copies only part of the buffer when the switch is on and the
set a detiling named is not empty; otherwise all of it, as before the
parts commit.

Switch: LEONIDA_TEXTURE_PARTS (unchanged; =0 now really copies whole).
Test: parts_tests::a_buffer_marked_with_nothing_detiled_is_copied_whole
(a kept staging buffer marked with no write copies 54 of 54
subresources, after a whole and a partial copy and with the switch off;
copied 0 before).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with LEONIDA_UPCOPY_CHECK=1 and LEONIDA_BAR_BUFFERS_MB,
host/upcheck.rs `record` looked at every copy a submission sends up and
left it in COPY_DEST (upcheck.rs, the barrier after the looks). For a copy
whose card side lies in card memory the CPU maps, `send::take` has already
written the title's bytes into that side, before the look is recorded
(host.rs `card_before`: take, then upcheck::record, then Own::record), so
the look compared the new bytes with the old ones and could report stale
words that were not there. And when everything went straight, the copy
had no runs, no straight card copies and no pairs, so `Own::record`
(send.rs) pushed no transition out of COPY_DEST, and the hash pass that
follows bound the buffer as a root SRV while it was still in COPY_DEST.

What changes: `upcheck::record` drops the notes of such copies and does
not look at them. The at-rest look reads them on the card and is
unchanged. Switch: none new (a diagnostics switch combined with an opt-in
one; both off by default).

Test: host::send::direct_tests::card_sides_the_cpu_writes_hold_each_submissions_bytes
on WARP (`bar_a_copy_the_cpu_writes_is_not_looked_at`: a noted take of
such a copy gives no look). Red with the skip taken out ("a copy whose card
side the CPU wrote was looked at"), green with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Mapped::drop (texback.rs) handed crate::host::give_read_back a clone of
self.buffer while the field itself still stood (fields drop after drop()
returns): at least two references, so sole() (host.rs) always said no and
give_read_back never pooled anything. A list reset while the async writer
still held the landing (the title is told at the landing, before the
writer has written: the 100-400 ms waits the writer exists for) could not
pool the buffer either, so it was freed and the next read back made a new
READBACK committed resource.

The buffer is now held in a ManuallyDrop and moved out after the Unmap,
so the reference given back is the landing's own and the last one when
the list let go first.

Switch: none new; LEONIDA_READ_BACK_POOL=0 and LEONIDA_TEXBACK_MAPPED=0
still restore the old paths.
Test: texback::tests::a_buffer_read_in_place_goes_to_the_pool_after_its_landing
(list reset first, then the landing dropped: the buffer is in
SPARE_BACKS; it was not before), with host::read_back_kept for tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
title_memory_going (texture.rs), called from every title VirtualFree and
VirtualProtect and every deferred release/protect (inplace.rs, the four
title_memory_going hooks), took the global IN_PLACE mutex twice and pushed
to and removed from a Vec with LEONIDA_TEXTURE_WATCHED_IN_PLACE off, the
default, where no read in place ever begins: title threads that free or
protect at once were serialized for nothing, a timing change on the
default path without a switch.

With the switch off it now returns a Going that registered nothing and
whose drop takes no lock; on, as before.

Switch: LEONIDA_TEXTURE_WATCHED_IN_PLACE (unchanged; off is now the old
default path exactly). README-fxceless bullet says so.
Test: parts_tests::a_free_waits_for_a_read_in_place_of_its_pages now runs
its waiting part with the switch on (both threads) and checks that with it
off a free registers nothing and stops no read (it was registered before).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: host/bar.rs `said` read "resizable BAR on" whenever
GPUUploadHeapSupported was true. The software adapter (WARP) offers GPU
upload heaps on this Windows (build 26300) and has no card and no PCI
memory window, so every test or diagnostics run on WARP logged "resizable
BAR on ... the card's largest memory window not known" (the BAR device
test prints the line before "BAR RAN"): a ReBAR state the machine does not
have (the RX 7900 XT here has its fixed 256 MiB window). The placement
module doc said the GPU upload rows appear "only where the firmware has
resized the card's memory window", which WARP's rows contradict.

What changes: `said` takes whether the adapter is the software one and
then says there is no BAR to speak of, with Direct3D's answer and that
those heaps are the PC's memory there. `bar::line(device)` (with
`software` and `adapter`, one DXGI query shared with `window`) is what the
log, the placement benchmark and the BAR device test print. The
placement doc says the rows appear where Direct3D offers the heaps, on a
card with its window resized and on the software adapter.

Switch: none (a log line and benchmark text).

Test: host::bar::tests::the_software_adapter_is_not_said_to_have_a_bar.
Red with the software case taken out of `said`, green with it. On WARP
the line now reads "resizable BAR: none, the software adapter (WARP) ...
(GPUUploadHeapSupported true ...)".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: host/bar.rs `the_hosts_window_is_found` asserted that
`window` finds a PCI memory window for every adapter without the software
flag. A card a virtual machine shares out (GPU partitioning), or any
adapter whose VEN/DEV/SUBSYS/REV match no present PCI device with an
allocated configuration, is not a software adapter, and there `window`
rightly gives None (the line then says the window is not known): the
default suite failed on such a machine with the code behaving as meant.

What changes: `the_hosts_line_is_said` (default suite) asserts only that
the line is well formed for the host's device and says so when a hardware
adapter has no window found; the strict assertion stays in
`the_hosts_window_is_found`, now ignored, to run by name on a PC's own
card (it passes on the RX 7900 XT here: 256 MiB).

Switch: none (tests only).

Test: the change is to the tests; no machine without a found window was at
hand to show the old one failing (this PC has its card's PCI window), so
no red run: the case is the one `window` documents as None.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	d3d12/docs/README-fxceless.md
# Conflicts:
#	d3d12/docs/README-fxceless.md
shadow.rs: the card side in card memory the CPU maps (LEONIDA_BAR_BUFFERS_MB)
is tried in the card way of buffer_ways, before card_for; a host copy whose
shared buffer cannot be made gives back what bar_for counted (BAR_BYTES), not
CARD_BYTES. send.rs: an Own of only sends straight or written runs keeps main's
beside and moved fields.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	d3d12/docs/README-fxceless.md
unified/land-same-submission named its switch LEONIDA_LAND_SAME (and
LEONIDA_LAND_SAME_MB), the name land.rs already gives, on by default, to
leaving out a copy in title memory that holds the bytes already. Setting it
to 1 for the new landing was harmless there, but =0 to turn the landing off
would also have turned land.rs's check off. The new switch takes its own name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Takes back 35fe73e9 (unified/inplace-free): removing a closed section from
Views.sections in title_memory_section_gone is part of zmasi's claim
D3D12-GPU-INPLACE-VIEW-ALIAS-AND-SECTION-LIFETIME (#2570, branch
fix/d3d12-gpu-inplace-view-alias-bounds), which also evicts the section's
remaining views.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since 8dc2c8f4 a hold let go of stays in HELD (buffer None) for
GIVE_UP_MS, 30 s, and counts as in the way of the title's frees: the
host may still keep its heap's pages. Nothing took it out when the host
did free those pages, by a release done at once, one done later by
release_pending, or a decommit. It stayed over addresses the title (or
the next test) was given again at once, as VirtualAlloc hands out the
lowest free addresses. A decommit of that new memory beside a hold let go
of just then was cut by holds of both lives: held_parts joined the old
hold's pages with the new one's, the host refused that one decommit whole
for the new heap, and zero_committed kept both committed and zeroed where
only the new heap's page had to be.

That is the flake of
inplace::tests::warp_a_decommit_the_host_still_refuses_once_the_hold_went_zeroes
(about 1 run in 5 of the full suite with --test-threads=4, 1 in 15 here,
never alone): an
instrumented run that failed found three let-go holds over page 1 of its
allocation, 11 to 490 ms old, from earlier tests whose 4 x 64 KiB
allocations had had the same base (one of them released through the
runtime's own path), and pages 1..5 were [COMMIT, COMMIT, RESERVE,
RESERVE, COMMIT] instead of [RESERVE, COMMIT, RESERVE, RESERVE, COMMIT].
In the 14 runs that passed no let-go hold lay over its range.

holds_freed forgets the holds let go of over pages the host freed (and
cuts one that reaches past them to the rest): after title_memory_free's
free succeeds (the allocation or pages asked of the host before the
call, freed_pages, only while anything is noted), after
title_memory_free_held's release or a part of its decommit succeeds,
and after release_pending's release. freed_pages is title_memory_free_held's
old match, shared. Standing holds are never touched: the host refuses a
free under them.

The tests that hold title memory release it at the end through the
runtime's path (title_released, or title_frees and no release pending
where the host's release used to be asserted at once) instead of the
host's own VirtualFree, which left their let-go holds noted over
addresses the next test's allocation may get.

Test (WARP):
inplace::tests::warp_a_hold_let_go_of_is_forgotten_over_the_memory_the_host_freed
releases memory under a hold let go of once the host let go of the heap,
releases it at once, or decommits it at once, gives new memory there and
decommits pages 1..3 beside a new hold let go of: with holds_freed
returning at once each of the three ways fails with [COMMIT, COMMIT,
RESERVE] instead of [RESERVE, COMMIT, RESERVE]; it passes with the fix.
The full leonida-gpu suite (--test-threads=4) passed 15 of 15 runs, where
before the fix 1 of 15 failed.

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

@⁠adrianmjim on GitHub · 2026-11-29 12:48 UTC · original · edited 2026-11-29 15:00 UTC

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.

**@⁠adrianmjim** on GitHub · 2026-11-29 12:48 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7256073326) · edited 2026-11-29 15:00 UTC ### Third round in `d3d12/` (pushed at `19006b0e6`) Seven more branches, claimed in [#2570](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/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.
What was wrong: a release of the title's that a heap opened in place was
in the way of is kept reserved until the heap is gone (inplace.rs
PENDING). title_memory_reserve (inplace.rs:979, called by xmem.rs:183 for
every XMemVirtualAlloc at a title-given address) asked the host first and
did the release only if the host refused. A reservation was refused
(error 487, the addresses still reserved) and taken over; but a commit of
the released pages without a new reservation (MEM_COMMIT alone) was taken
by the host inside the reservation kept for the title, and the release
done later by tick took those pages away under a title told they were
committed. The console refuses a commit of free memory.

What changes: when the title's addresses touch a kept release, the release
is done first (slots let go, reap, up to RESERVE_WAIT_MS for the host);
while a heap still stands over it the call is refused with error 487
without asking the host; once it is done the host is asked. The new
leonida_gpu::title_memory_held_in_place (with HeldInPlace) opens title
memory in place on the host device and holds it as place_for does, for
the runtime's tests through the glue.

Switch: LEONIDA_INPLACE_RELEASE_FIRST=0 restores the old order (host
first). Documented in inplace.rs and README-fxceless.md.

Test: xmem::tests::a_commit_into_a_release_kept_for_a_heap_is_refused
(leonida-hle, through XMemVirtualAlloc and the title's VirtualFree, on
the host device; RX 7900 XT here): red with the switch off ("a commit of
released pages is refused" fails: the host took it), green with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: while a heap opened in place (LEONIDA_INPLACE) stands over
title memory, the title's VirtualProtect and its release are done later
(inplace.rs PROTECTS and PENDING) and the title is told they are done, but
XMemVirtualQuery (xmem.rs:287) passed on what the host had: the old
protection and a committed allocation the title had released, for as long
as the heap stood (about two frames).

What changes: XMemVirtualQuery of this process's memory goes through the
new leonida_gpu::title_memory_as_asked, which makes the host's answer what
the title asked for: a release kept for it is free memory (to the end of
the allocation and on over the free run after it, AllocationBase 0,
PAGE_NOACCESS, no graphics flag), the newest protection that waits over a
committed page is the page's, and a region ends where a waiting
protection begins or ends. A decommit kept committed and zeroed still
reads as committed: the title may commit it again with the host's own
VirtualAlloc, which the runtime does not see (noted as a shortcut).

Switch: LEONIDA_INPLACE_QUERY=0 restores the host's answer. Documented in
inplace.rs and README-fxceless.md.

Tests: inplace::tests::a_query_tells_what_the_title_asked_for (pure: the
release run, the newest waiting protection, region edges, memory not
committed); xmem::tests::a_query_tells_what_the_gpu_side_does_later
(leonida-hle, through the title's VirtualProtect, VirtualFree and
XMemVirtualQuery with a heap held in place on the host device, RX 7900 XT
here): red with the switch off ("the protection the title asked for",
left 4 right 2), green with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: card_asked (host.rs:7349) joins a copy's declared ranges
only where they overlap or touch, so views a few bytes apart in one 64 KiB
piece stay separate ranges. ResultArea::plan (host.rs:3275) gave each its
own dwords and Host::card_before (host.rs:8062, 8100) a pass of its own over
all its pieces: a piece holding n declared ranges was hashed n times in the
check list, and since passes over the same piece do not go on at the next
piece, joined_compares could not join them (a pass per range). With the
relay's mode 2 the passes also raced: the second hash of a piece compared
with the hash the first had just stored (flagged_pieces' union kept the
landed bytes right).

What changes: card_asked marks a range whose first piece is the last piece
of the declared range before it in the same copy (shares_piece);
ResultArea::plan places such a range on that piece's dword when the one
before is compared; unshared_compares starts its pass one piece later, so
it goes on where the first ends and joined_compares joins it. Each range
still reads the flag of each of its pieces and lands only its own bytes.
card_results_short asks for the same dwords. The frame line gives the
pieces the compare hashed and those left to the range before them; the
plan keeps the count (CardPlan::hashed).

Switch: LEONIDA_CARD_COMPARE_SHARE (on; =0 hashes each range's pieces, as
before). On by default: the tests below cover the shared dword in every
consumer path (relay fetch, landing in the submission, a submission waited
for); README-fxceless.md "Speed and memory".

Tests: compare_join_tests::shared_pieces_are_hashed_once_where_each_range_reads_them
(400 random sets of ranges of two copies, room for all and for half: each
piece of every compared range hashed exactly once, at a dword that range
reads for it) and landsame::card_tests::ranges_in_one_piece_hash_it_once_and_land_the_same
(on the host's card: six declared ranges over five pieces, 9 pieces hashed
before, 5 now, title memory identical with LEONIDA_LAND_IN_SUBMISSION 0/1
and waited for). Both fail with shares_piece answering false (as on
perf/unified-memory: "a piece hashed twice", 9 pieces hashed where 5).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: at submission the preparing thread walked every step of
every list once per question, each walk under the list's lock and most
with a table of copies made anew (perf/unified-memory, host.rs):
blocked_by (5215; from late_blocked 4982, and again after every landing
the relay waits through, 9325-9329, which with LEONIDA_LINE_APART off ran
under LINE and took every list's lock there), stale_under_flights (5322;
also per round of settle_stale, 9251), the write-watch asking's walk
(9415-9430, when a list has no kept fronts), declared_writes (7393),
Batch::copy_spans (13038, LEONIDA_BATCH_KEPT) and joinable (5404-5416).

What changes: HostList::close makes a summary of the steps in one walk
(host/summary.rs), kept in Deferred until the reset: the title memory read
or copied into by the steps ahead of the first Step::Run (joined), the
copies at their place there (place::Fact: addresses and whether the
source goes through upload memory), whether there is a Run or a Copy, per
copy the span of its refreshes, and the declared writes deduplicated. Only
facts fixed at recording are kept; what flights write, which copies
shaders write, asked_ahead and landed_lately are asked at submission as
before, of the summaries' ranges and copies. Nothing takes a summary out
(a list submitted twice has it both times); one whose list has more steps
than it counted, or a list without one (card_steps' own), has it made at
the first question. The relay's predicate takes the summaries once before
waiting. Steps are still walked with LEONIDA_FILL_TITLE (per-range rule),
when a copy at its place waits only for its readers (place::reader goes by
order), and for the frame line's counts once a submission is stopped.
Placed::waits/titles moved onto place::Fact unchanged.

Switch: LEONIDA_CLOSE_SUMMARY (on; =0 as before; =check computes both,
takes the steps' answer and counts differences on the frame line).
On by default: answers equal the steps' by construction and the tests
compare them; not measured with the game.

Tests (host::summary::tests): summaries_answer_what_the_steps_answer
compares every question with the step walk over 400 random submissions
of synthetic lists (Copy/Fill/Host/Plane/Placed/GpuWrite/Refresh/Run;
summaries at close, late, remade; lists named twice; 6 different
in-air states per submission);
a_submissions_questions_walk_no_steps_of_closed_lists counts steps
walked: 0 with summaries, 8,231 for the same questions by the steps
(red: with summary::all forced to None, the old paths);
a_list_given_steps_since_its_summary_has_it_made_again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with LEONIDA_SEND_OWN each submission's sends took a
buffer of its own from a pool of spares (host/send.rs:413 `memory`,
:444 `give_back`, :269 `SPARE`): a submission that found no spare to
its size made a committed upload buffer (CreateCommittedResource,
MakeResident, Map; 1.6 ms each in docs/findings.md's small-buffer row),
the sweep released the idle ones (:475), each held up to an eighth over
what it sent, and with N submissions in flight N buffers were alive.

What changes: host/sendring.rs is a ring of one or two persistently
mapped buffers. A submission carves its bytes at the head of the open
buffer (256-byte aligned, never wrapped within a carve); a carve is
free again once its submission has landed (Host::card_done) and every
carve before it in that buffer has too, so out-of-order landing never
frees bytes in flight. When a carve does not fit, a new buffer is made
for the bytes in flight (an eighth over them plus twice the largest
carve) and the old one is closed and goes with its last carve; the
sweep closes a buffer more than twice what the last idle time needed
and lets every buffer go after the idle time with no carve; a carve of
more than 64 MiB gets a buffer of its own. host/send.rs: Memory carries
its offset and ticket (copies and the scatter's root view at the
carve's offset); a carve dropped without card_done comes back through
host::retire, never while the card may read it and never held for good.
Paired words and straight sends (LEONIDA_SEND_DIRECT) are unchanged; the
frame line counts buffers made for sends and the ring's buffers.

Switch: LEONIDA_SEND_RING (on by default with LEONIDA_SEND_OWN; 0: the
spares as before; LEONIDA_AB can name it, a carve goes back to the ring
and a buffer to the spares). On because the bytes on the card are the
same and the reuse hazard is covered by tests.

Tests: host::sendring::tests (wrap-around, out-of-order landing over
20,000 carves, growth/shrink/outsize/idle), host::send::pool_tests::
steady_sends_from_the_ring_make_no_buffers_once_warm (spares 121 made,
ring 6 and none after warm-up; 352 MiB held once warm against 391), and
the device test host::send::direct_tests::
submissions_in_the_air_each_send_their_bytes_from_one_ring (six
submissions held in flight on the card each read their own bytes; with
the ring path reverted it fails: "round 0: 6 buffers for 6 sends in the
air"). leonida-gpu: 694 passed / 50 ignored, also with LEONIDA_SEND_RING=0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was missing: the hash/compare pass after every submission's lists
(host.rs CARD_COMPARE, card_pass, the check list of Host::card_before) runs
over every declared range of every copy in the card's memory, and its cost
on the card was never measured by the card (only a CPU-timed bench in
indirect.rs, card_compare_costs, of rounds of passes and waits).

What changes: host/comparecost.rs, an ignored benchmark: the runtime's own
compare (make_card_work's root signature and pipeline, passes planned as
card_before plans them via compare_join_tests::planned) over device-local
copies of 64 KiB to 256 MiB, between timestamps on a direct queue of its
own, cold after a 192 MiB cache sweep and again; and the copies declared as
views of 256 bytes every 16 KiB with LEONIDA_CARD_COMPARE_SHARE off and on.
LEONIDA_BENCH_CS=<file> times another form of the shader. findings.md gets
the tables from this RX 7900 XT: 600 GB/s cold at 256 MiB (1.7 us a
declared MiB), 5-10 us for a pass of a few pieces; shared pieces 0.57 ->
0.45 ms at 256 MiB; a 256-thread form of the shader saves 5 us on a
one-piece pass and nothing from 16 MiB on, so the hash (mirrored by
host::torn) stays.

Switch: none (a measurement). Test: the benchmark itself
(cargo test -p leonida-gpu --release --lib host::comparecost -- --ignored --nocapture).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with LEONIDA_INPLACE on, place_for (inplace.rs:1231,
called from shadow.rs lookup and loose with the tables' write lock held,
on a list thread) opened private title memory on the spot:
OpenExistingHeapFromAddress1 and the placement cost about 1 ms for a part
of 1 MiB and 2 to 6 ms for 16 MiB on the RX 7900 XT (36 ms for 256 MiB,
findings.md placement table) and lock every page, so the recording thread
and every thread waiting for the tables stood that long at each new
window or title buffer.

What changes: the ask goes to a thread of its own (the opener,
open_asked) and the caller makes a copy, as when memory cannot be opened.
What the opener opens is held at once (hold, READY) and goes in place at
the next ask of the same memory (ready_for), or replaces the copy made
meanwhile at a safe point (switch_ready from tick, before a submission;
shadow::in_place_switch): only a plain PC-memory copy (no card side, not
mapped, not ours) that shaders were never declared to write (nothing in
flight to copy back, nothing kept out of title memory by WC_NO_BACK or
copy-back elision), that nothing but the table holds (strong count 1
under the table's lock after its change count went up, as let_go_idle)
and that no descriptor slot views (one COM reference). Title writes are in
title memory either way. What neither takes within READY_MS (10 s) is let
go, its heap with it, so pages are not locked for nothing. Races with the
title: the opener checks, opens and holds under GATE, which the title's
frees and protections hold shared for their whole call, and
title_memory_freeing first drops what the opener opened or was asked for
over the memory (ready_gone), so a free or protection never meets a heap
the runtime does not know of and is made at once when nothing took it.
anything_placed counts what waits. Sections and the runtime's own arenas
are still opened at once (cheap). The say line counts opened, taken,
switched and given up.

Switch: LEONIDA_INPLACE_ASYNC=0 restores opening on the ask. On by
default under LEONIDA_INPLACE, which stays off: the hazards (free and
protection against an open in progress and against an open not yet
taken, a copy held by a list or viewed by a slot or written by shaders,
heaps left locked) each have a test. Documented in inplace.rs and
README-fxceless.md.

Tests (WARP unless said): inplace::tests::
warp_a_window_is_opened_in_the_background_and_switched_in_at_a_safe_point,
warp_a_copy_written_or_viewed_is_not_switched_and_what_was_opened_goes,
warp_the_title_protects_and_frees_memory_the_opener_opened_at_once,
a_free_waits_for_the_opener; shadow::in_place_tests::
a_window_opened_in_the_background_takes_the_place_of_its_copy (host
device, through shadow::find; RX 7900 XT here). Red with the ask opening
at once again (place_for ignoring asynchronous: "the ask does not open
the memory", "a copy at first"), without ready_gone ("made at once": left
4 right 2), without the written check ("nor once shaders were declared to
write it") and without the gate ("not while the opener opens"); green
with all.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: host.rs:14452, the "our passes" frame line's literal had lost
its line continuation after "compare passes over", so about 22 spaces of the
next source line's indentation were inside every logged line. host.rs:14601
called CARD_STATS[2] (added per declared range in relay_card_back,
host.rs:8518 and :8919) "pieces compared on the card", while the new
CARD_PASSES[3] (host.rs:8247) counts the pieces the compare hashed, a piece
two ranges share once: with LEONIDA_CARD_COMPARE_SHARE on the two lines gave
two different "compared" figures. findings.md said 1 GB of declared ranges
takes "about 2 to 2.6 ms"; at 1.7 to 2.6 us a MiB, 954 MiB is 1.6 to 2.5 ms.

What changes: the literal continues with a backslash; the card line now
says "piece reads by declared ranges" and how they differ from the pieces
hashed (CARD_STATS's doc says the same); findings.md says 1.6 to 2.5 ms.
Log text and docs only: no switch, no behaviour change, no test (the full
leonida-gpu suite passes, 691/51).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: every copy in the card's memory had a second buffer of
its size in the PC's memory (Card::staging, made at shadow.rs:7882 of
perf/unified-memory), and every refresh copied the pages the title wrote
from title memory into it on the CPU (Shadow::take/copy, shadow.rs:6413
and 6470) before the card copied them from there into its side (straight
with LEONIDA_SEND_DIRECT). For a buffer shaders never write that buffer
holds nothing title memory does not: the card reads opened title memory
as fast as upload memory (23-28 GB/s on the RX 7900 XT, findings.md).

What changes, with LEONIDA_CARD_FROM_TITLE=1 (off by default):
- lookup opens the title memory of a big buffer's card copy as a host
  heap (inplace::place_source: private memory committed whole, held as
  windows in place are, or one run of a committed section; from a 64 KiB
  line on) and the CPU side is a buffer placed over it. Shadow::data is an
  AtomicPtr and Card::staging a RwLock, each changed once.
- take/copy note the written pages for the card (write watch as before)
  and copy nothing; sends copy straight out of title memory.
- our writes at submission are ordered as with SEND_DIRECT: Step::Copy
  wrote title memory before send_copied waited for straight sends in the
  air (host.rs:11597); for such a copy title memory is the CPU side, so
  shadow::source_copying waits first. placed_copy leaves title memory be.
- the first declared write (Shadow::writing) or keep_stores gives the copy
  a side of its own (Shadow::unsource): filled from title memory under the
  page state's lock, sent up whole, the old buffer retired. The merge
  (shadow.rs:6889) needs what the card held before the shaders, which
  title memory is not.
- a title free/decommit/protect of that memory, or a remap of a section,
  queues the copy in in_place_let_go; before the next submission it gets
  a side of its own (shadow::sources_going), and the title's call is made
  once the heap goes (title_memory_free_held / title_memory_protect).
- the memory line counts such copies, the staging RAM not made, and those
  given a side of their own.

Not with LEONIDA_SEND_CHANGED=1 nor for card sides in BAR memory. Off by
default: not measured with the title (its big heap may be declared
written in its first frame, paying the opening and a full copy), and a
title free of such memory now waits for a submission.

Tests (host::send::direct_tests, on the host's card; each fails with its
part reverted, checked): title_memory_reaches_the_card_side_with_no_copy_on_the_cpu
(409,624 bytes taken on the CPU without it),
a_copy_of_ours_into_title_memory_that_is_a_cpu_side_waits_first,
a_free_of_title_memory_that_is_a_cpu_side_is_done_once_its_heap_went,
a_copy_declared_written_later_gets_a_cpu_side_of_its_own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: since the summaries made at close (997a8f3c5), the
write-watch asking's by_steps closure (host.rs:9562) is asked_spans, which
goes by the lists' summaries whenever LEONIDA_CLOSE_SUMMARY is on. So the
FrontsMode::Check arm (9582) compared the fronts kept at close with the
summaries, another cache made at close, while its warning says they
"differ from their steps": neither was checked against the steps in a
run with both switches at their defaults.

What changes: the Check arm asks asked_steps(runs, Shadow::asked_ahead),
the walk over the steps, as before the summaries. Off and On are as they
were (by the summaries when LEONIDA_CLOSE_SUMMARY is on).

Switch: none new; LEONIDA_LIST_FRONTS=check is a diagnostic.

Test: none of its own (a diagnostic's comparison target; the walk it now
takes is the one host::summary::tests compare the summaries with).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with LEONIDA_CLOSE_SUMMARY=check, stale_under_flights
(host.rs:5372-5377) and asked_spans (7506-7509) computed the summaries'
answer and the steps' one after the other, each asking writes_pending /
asked_ahead of every copy when it got there. The relay thread can land a
flight between the two, so a "differed" count on the frame line could
come of the timing alone, against the README's "must be 0". What flights
stop (blocked_by_in, 5248-5250) asks what landed lately of copies at their
place through placed_is_titles, but only with LEONIDA_PLACED_TITLE=1 (off
by default). And a_submissions_questions_walk_no_steps_of_closed_lists
(summary.rs:588) only skipped with the switch off: run with
LEONIDA_CLOSE_SUMMARY=check in the environment, where the questions walk
the steps on purpose, it failed with "the submission's questions walked
steps".

What changes: summary::once asks a predicate once per host copy and keeps
its answer; in check mode stale_under_flights and asked_spans hand the
same one to both computations. blocked_by_in, summary::CHECK and the
README say that with LEONIDA_PLACED_TITLE=1 what stops a submission can
differ by a landing's timing. The walk-count test runs only with the
switch on. The README's list of where the steps are still walked adds a
submission stopped by a read (late_blocked's count=true, for the frame
line's count and name of what stopped it, host.rs:5246) and says that
the random test has no texture steps.

Switch: none new; check mode is a diagnostic and On/Off are unchanged.

Tests: check_asks_each_copy_once_for_both_answers (red with `once`
replaced by the predicate itself: the second walk saw no copy, left 3
spans, right none). a_submissions_questions_walk_no_steps_of_closed_lists
with LEONIDA_CLOSE_SUMMARY=check: red before (panicked at its first
assert), skips now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: a carve of more than OUTSIZE (64 MiB) gets a buffer of
its own "so a burst does not size the ring", but Ring::add sent it
through Ring::carved (host/sendring.rs:156), which raised `largest` to
its size and `peak` to Ring::held, and held counted the outsize buffer's
bytes too. With a 100 MiB send in the air, the next 1 MiB carve that did
not fit the open buffer asked Ring::carve (:184) for made_for(105 MiB,
100 MiB): a 320 MiB upload buffer for a few MiB of ordinary sends. The
sweep's shrink (Ring::let_go :245) and Ring::window (:257) used the same
figures, so a burst's buffer stayed open while the send was out.

What changes: a Part records whether it is one of the ring's (`ring`,
false for an outsize carve's buffer); the bytes in the air that size
what is made (Ring::air), the peak and largest carve in Ring::carved and
Ring::window count only the ring's buffers. README-fxceless.md says so.

Switch: none new (LEONIDA_SEND_RING=0 still restores the spares).

Test: sendring::tests::a_carve_past_outsize_does_not_size_the_ring: with
a 100 MiB carve out, the buffer made when 1 MiB carves outgrow the least
buffer is at most made_for(5 MiB, 1 MiB) (320 MiB without the fix), and
the sweep closes a burst's buffer while the big carve is out (it stays
open without the fix).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: host/send.rs:636 `held` reported Ring::bytes - Ring::held
as the ring's free bytes, kept spare on the frame line (host.rs:6458);
that counted the unused space of closed buffers draining and of outsize
carves' buffers, which is never carved again, so after a growth step the
line overstated what is reusable. README-fxceless.md said "one or two"
buffers, but growth steps and outsize carves can leave more alive at
once. And send.rs's submissions_in_the_air_each_send_their_bytes_from_one_ring
asserted at most two buffers a round and that the second round reused a
first-round buffer, while RING is the process's and LEONIDA_SEND_RING is
on by default: another test thread's carves (--test-threads=4) could
make the ring grow between the rounds and fail it.

What changes: Ring::free gives the open buffer's bytes not held, and the
frame line reports those; Ring::bytes and Ring::held are test-only now.
README: usually one open buffer, closed ones go once their carves have
landed. The device test counts the buffers the ring added (Ring::made,
test-only): a round may use one buffer more for each added during it,
and the reuse is asserted only if none was added from the first round's
carves to the second's.

Switch: none (reporting and a test).

Test: a_carve_past_outsize_does_not_size_the_ring checks Ring::free is
the open buffer's whole size once everything has landed with the
outsize buffer gone; the device test passes alone and in the full suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: a protection of title memory a heap stood over lets go of
what is in place over the heap's whole 64 KiB pages (inplace.rs
let_go_under), and the next ask made a copy, since a heap opens only pages
all committed and read-write (private_whole) and those pages now had mixed
protections, or a protection waiting. Once the title gave read-write back,
nothing asked again: the copy stayed in the tables for as long as it was
used (let_go_idle takes only idle ones), so memory the title once
protected never had a heap again.

What changes: let_go_under notes the pages of the heaps it let go of
(AGAIN, at most 1024 ranges, forgotten when title_memory_freeing sees the
memory change). When a protection to PAGE_READWRITE is made, by the
title's call (title_memory_protect) or late (protect_pending, after its
lock), each noted range over those pages that is now all committed and
read-write with no protection waiting is forgotten, and the plain copies
the tables have there that could be in place (shadow::copies_over: no card
side, not mapped, not ours, never written by shaders, a window, or a title
buffer whose ways include in place) are asked of the opener. Each then
takes its copy's place at a safe point (switch_ready) as any background
opening does.

Switch: LEONIDA_INPLACE_AGAIN=0 restores the old (copies stay). Documented
in inplace.rs and README-fxceless.md.

Test: inplace::tests::warp_memory_protected_and_given_write_back_is_opened_in_place_again
(WARP; both paths: read-write given back after the read-only protection
was made, and both waiting behind the heap and made together): red with
the two again() calls removed ("the copy is asked to be opened in place
again"), green with them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: shadow::source_copying (shadow.rs:2144 of the
card-from-title commit), which Step::Copy calls before it writes title
memory (host.rs:11605), looked only at copies whose CPU side is title
memory now, and returned at once when no such copy was alive
(sourced_any). Shadow::unsource (a declared shader write, a kept store,
a free of the memory) swaps in a side of its own but leaves the straight
sends recorded out of title memory in the air. A Step::Copy into that
range right after found the copy not sourced, wrote title memory under
those sends, and send_copied waited for them only after the write: a
submission in the air read the bytes of a later one's buffer copy.

What changes: Card::unsourced is set by unsource before the swap, and
source_copying waits first for copies sourced now or once, gated on
whether such a copy was ever made (SOURCED[2]). For other copies nothing
changes. The Step::Copy arm's CPU steps are a function of their own,
host::title_copy, which the tests call, so they run the production
order (the earlier test called source_copying by hand and would pass
with the call at the Step::Copy site deleted).

Switch: LEONIDA_CARD_FROM_TITLE (off by default), as before.

Test (host::send::direct_tests, on the host's card):
a_copy_of_ours_into_title_memory_that_was_a_cpu_side_waits_first fails
with either half reverted (the filter or the early-out): send 0 read the
copy's bytes. a_copy_of_ours_into_title_memory_that_is_a_cpu_side_waits_first
now goes through title_copy and fails with source_copying taken out of it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: source_side (shadow.rs:1154-1176 of the card-from-title
commit) opened a big buffer's title memory as a heap with
LEONIDA_CARD_FROM_TITLE=1 whatever LEONIDA_INPLACE_FREE and
LEONIDA_INPLACE_PROTECT said. With either at 0 nothing lets go of that
heap: inplace::hold does nothing without frees() (inplace.rs:313-316),
watch::title_memory_freed lets go only with it (watch.rs:4437), and
title_memory_protect hands the call to the host alone without
protects(). The title's VirtualFree or VirtualProtect of the buffer's
memory, an ordinary copy's without the switch, then failed with error
87 for as long as the copy lived.

What changes: source_side asks shadow::source_wanted, which also needs
inplace::frees() and inplace::protects() (now pub(crate)); with either
off the copy gets a CPU side of its own, as without the switch. The
from_title doc and the README-fxceless "Speed and memory" bullet say so.

Switch: LEONIDA_CARD_FROM_TITLE (off by default), as before.

Test: shadow::source_tests::title_memory_is_a_cpu_side_only_where_its_frees_and_protections_are_taken_over
(pure) fails with the two new conditions taken out of source_wanted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: lookup (shadow.rs:8195-8200 of the card-from-title
commit) opens a big buffer's title memory as a heap
(OpenExistingHeapFromAddress1, which locks the pages: 70 ms for 256 MiB
never touched, inplace.rs's notes) while it holds the BUFFERS write
lock, so every recording thread's lookup and the let-go from xmem wait
for it; nothing said so.

What changes: a comment there and the README-fxceless bullet call it a
one-time hitch per buffer. Moving the opening out of the lock is not
done: in_place_let_go takes that lock before it looks for copies whose
CPU side is title memory in the carded index, and that order is what
makes a let-go after the opening find the copy; a let-go between an
opening outside the lock and the copy's note would miss it, keeping the
heap and leaving the title's free waiting on it.

Switch: LEONIDA_CARD_FROM_TITLE (off by default), as before. No
behaviour changes; no test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: with LEONIDA_INPLACE_ASYNC, what the opener opened took
the place of the copy made meanwhile only once nothing but the table held
that copy (shadow.rs in_place_switch, the Arc::strong_count == 1 check,
called from inplace.rs switch_ready_at at each sweep). A HostList keeps
every copy it refreshes (Deferred.copies, Step::Refresh) until its reset,
two submissions after it ran, and the sweep runs inside a submission whose
runs and flights hold what they read: memory read every frame was always
held when the sweep looked. Nothing asked again (the copy is the table's
entry), so the heap stood locked READY_MS beside a whole PC copy, was given
up (STATS[19]) and the memory stayed a copy for good; the same for what
LEONIDA_INPLACE_AGAIN asked to open again. The tests only switched copies
nobody held.

What changes: the copy is switched while lists still hold it. Each list
keeps its own Arc: one not yet sent brings the copy up to date from title
memory at its submission (Refresh steps), one in flight reads what was
copied then, and retire keeps it for the submissions running; lists
recorded after get the title memory in place. The other conditions stay
(not written by shaders, no card side, not mapped, not ours, no descriptor
slot: one COM reference) and three are added: no pending shader writes or
landing (follow from not written; asked all the same), and not numbered by
the directory of memory by address (memory.rs Memory::number, now noted on
the copy: it keeps its copies for good and shows shaders that one, so it
would stand beside the memory in place for as long). The copy switched
while held is noted, and so is what took its place: shaders declared to
write either while the lists still hold the copy (two views of the same
bytes: a list submitted after the writer could read the bytes from before
until the copy-back; such memory was never declared written before) are
counted on the say line and said once (inplace::written_across_switch).

Switch: LEONIDA_INPLACE_SWITCH_HELD=0 restores the old rule (only a copy
nothing but the table holds). On by default under LEONIDA_INPLACE, which
stays off: the use-after-free, lost-write, slot and long-lived-holder
hazards have tests; the two-views window is bounded by the lists' life,
limited to memory never written by shaders, and counted. Documented in
inplace.rs, shadow.rs and README-fxceless.md.

Tests: inplace::tests::warp_a_window_is_opened_in_the_background_and_switched_in_at_a_safe_point
(WARP; now a list holds the copy across the switch: in place, counted,
the list's copy alive and noted), inplace::tests::warp_a_copy_memory_by_address_numbered_is_not_switched
(WARP), shadow::in_place_tests::a_window_a_list_holds_takes_the_title_memory_in_place_and_the_list_keeps_its_copy
(host device, a real HostList refreshing the copy; the next find is in
place, the list's copy is brought up to date by its submission's update
and the card reads the title's bytes through both). Red with the held
rule off ("though the list holds the copy") and without the numbered
check ("not switched"); green with both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was wrong: inplace.rs GATE (taken alone by open_asked for a whole
opening, shared by title_memory_free and title_memory_protect) and the
README told of opening costs of 1 to 6 ms a part, but at level 2 the
opener opens a title buffer whole, up to LEONIDA_INPLACE_MB: 36 ms for
256 MiB on the RX 7900 XT, 70 on the software adapter (findings.md,
placement table); and std's RwLock queues new readers behind a waiting
writer, so frees and protections on every thread that come while the
opener waits for the lock wait behind that opening as well.

What changes: documentation only (GATE's doc and the README's in-place
bullet), the wait named as not measured in the game. Not bounded in code:
an opening is one heap and one buffer over the whole ask (place_part), so
the gate cannot be let go between parts without opening several heaps,
which changes what a title buffer in place is.

Switch: none (no behaviour changes). Test: none (documentation).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	d3d12/crates/leonida-gpu/src/host.rs
# Conflicts:
#	d3d12/crates/leonida-gpu/src/host/send.rs
#	d3d12/docs/README-fxceless.md
# Conflicts:
#	d3d12/crates/leonida-gpu/src/inplace.rs
A hold let go of (HELD, buffer None) stays noted for GIVE_UP_MS over the
pages its heap stood on, and is forgotten early only when the title's
free goes through the runtime (title_memory_free -> holds_freed). The
send tests' TitleMemory freed its allocation with the host's VirtualFree
directly, so a hold let go of over it outlived the memory, and the next
VirtualAlloc that got those addresses (another test's, on another
thread) found an old hold "in the way": its decommit was cut where the
old hold had been and the part the host still refused was kept committed
and zeroed instead of decommitted.

- host/send.rs: TitleMemory::drop releases through
  crate::inplace::title_memory_free, as xmem does for the title, so a
  hold let go of over it is forgotten with it.
- inplace.rs: warp_a_decommit_the_host_still_refuses_once_the_hold_went_zeroes
  forgets the holds let go of over the memory the host just gave it
  (holds_freed, the runtime's path for memory the host freed), since any
  such hold is another test's whose memory already went.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
TitleMemory::drop asked title_memory_free for the release on each of its
300 tries while the heap over the memory still stood. Each ask the host
refused (error 87) was taken over (title_memory_free_held) and pushed one
more entry for the same allocation into PENDING: 298 and 299 entries for
the two 4 MiB allocations of a run, measured. Once the heap went,
release_pending released the allocation for the first entry; the others
found nothing to release and stayed GIVE_UP_MS (30 s) over addresses the
host gives the next allocation, so that:

- released() and kept_from() took fresh memory there for a release kept
  for the title, and turned down opening it in place:
  shadow::in_place_tests::a_big_title_buffer_the_card_turns_down_is_read_in_place,
  a_window_kept_only_in_the_pcs_memory_is_read_in_place, and the opener
  tests ("the opener opens it": the ask was never made);
- release_pending retried each one, and VirtualFree(at, 0, MEM_RELEASE)
  released whatever allocation the host had given at that base since:
  a_big_title_buffer's own memory, then a texture::parts_tests
  allocation at the same base, and the test process died with an access
  violation (5 of 8 runs). Memory that a test keeps for good, freed so and
  handed to another test, also explains the resource tests that found
  another test's placed texture at their address.

The title asks once: TitleMemory::give_back releases through the runtime's
path and notes whether the title was told it was done; the drop asks again
only while the release was refused and not taken over, and otherwise waits
for the runtime to do it (reap). The test that frees the memory itself
goes through give_back too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A hold let go of stays noted in HELD for GIVE_UP_MS (30 s) over the pages
its heap stood on, and is forgotten early only when a free goes through
the runtime (title_memory_free -> holds_freed). Five tests of
LEONIDA_INPLACE_ASYNC's opener, new with batch 4, released their memory
with the host's own VirtualFree once their holds were let go, so those
holds outlived the memory:

  warp_a_window_is_opened_in_the_background_and_switched_in_at_a_safe_point
  warp_a_copy_written_or_viewed_is_not_switched_and_what_was_opened_goes
  warp_a_copy_memory_by_address_numbered_is_not_switched
  warp_the_title_protects_and_frees_memory_the_opener_opened_at_once
  warp_memory_protected_and_given_write_back_is_opened_in_place_again

With the send tests' TitleMemory (card-from-title) they were what
warp_a_decommit_the_host_still_refuses_once_the_hold_went_zeroes met
over its fresh allocation: its decommit was cut where the old hold had
been, the part joined with its own hold's page was refused whole and kept
committed and zeroed ([4096; 5] for [8192, 4096, 8192, 8192, 4096]), in
9 of 15 runs of the suite at the merge of batch 4, with no other failure.
Found by noting who made each hold and logging, at reap, every hold let go
of whose pages the host shows free.

host_releases(base) releases through title_memory_free and still answers
whether the host's own call did it, so "no heap is left over it" is
checked as before. With it and the TitleMemory fix, no hold let go of
over free memory was seen in 5 runs, and the decommit test passed in all
of them without the holds_freed it now starts with.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
inplace::title_memory_free_held took over every release the host refused
with error 87 and noted it in PENDING. A title that released the same
allocation again while the heap stood (or decommitted in it) was taken over
again and noted twice; once the first note's release was done, the note
left over made release_pending release whatever the host had given out at
that address meanwhile, under its new owner (found by the suite's own
tests, whose memory went that way: a texture test's reservation was
released three times and the process faulted).

Now title_memory_free refuses a free of memory in a release kept for a heap
as the host refuses one of free memory (FALSE, ERROR_INVALID_ADDRESS) and
does nothing, and a release is noted in PENDING once only.

Test: inplace::tests::warp_a_second_release_of_memory_kept_for_a_heap_is_refused
(the second release refused with 487, a decommit in it refused, one note,
released once the heap went). Without the change it fails on "the second is
refused".

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

@⁠adrianmjim on GitHub · 2026-11-29 14:32 UTC · original · edited 2026-11-29 15:00 UTC

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.

**@⁠adrianmjim** on GitHub · 2026-11-29 14:32 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7257387207) · edited 2026-11-29 15:00 UTC ### Fourth round in `d3d12/` (pushed at `7cc8e1879`) Claimed in [#2570](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/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.
github-bot force-pushed github-bot/gh-2569 from 34143ad380 to 7cc8e18797 2026-11-29 15:00:57 +00:00 Compare
Spare::take (crates/leonida-hle/src/modules/xmem.rs, the take of the
Spare struct) walked every page waiting in every section, asked SHOWN of
each, and sorted every run of them longest first, under the page table
lock and PHYSICAL, for each XMemAllocatePhysicalPages: with a streaming
title's fragments, thousands of pages to hand out one or four.

Now each Kept holds its freed pages as runs (first -> length, joined on
wait, split on take) and Spare keeps every run in one set ordered as the
old sort was (length descending, section, first page). take walks it from
the front, splits each run by the views that show its pages, keeps the
fewest first runs that hold n pages, and stops at the first run that can
no longer go before the last of them (shorter, or as long and after it).
The pages given, and their order, are those of the old walk, exactly: no
switch, since nothing but the time taken changes.

Tests: spare_take_looks_at_the_runs_it_gives (65 sections, 2,048 runs of
one and one of 16: 16 pages looked at for 4, then 1 per page; 2,064 each
before, red on perf/unified-memory) and spare_take_gives_what_every_run_
sorted_gave (2,000 pseudo-random rounds of frees, sections closing, shown
pages and put_backs against the old walk kept as a test reference).
What was wrong: xmem (leonida-hle modules/xmem.rs, module(), on
kernel32.dll, kernelbase.dll and api-ms-win-core-memory-*) exported
VirtualFree and VirtualProtect of the kernel's memory calls, so the
title's (and its mapped DLLs') VirtualAlloc, VirtualAllocEx and
VirtualProtectEx bound to the host's own (HleResolver, leonida-hle lib.rs, takes the host's
for any name the registry lacks). With LEONIDA_INPLACE, a commit at a
fixed address into an allocation the title had released, its release kept
for a heap opened in place (inplace.rs PENDING), was taken by the host
inside the reservation kept for the title, and the release done later took
those pages away under a title told they were committed: the hazard
3e063ce0 closed for XMemVirtualAlloc alone. A VirtualProtectEx of memory a
heap stands over failed with error 87, which VirtualProtect has been
spared since title_memory_protect.

What changes: three new exports. title_virtual_alloc forwards to the
host's VirtualAlloc through leonida_gpu::title_memory_reserve, as an
XMemVirtualAlloc at an address of the title's goes: a fixed-address
reservation or commit touching a kept release does the release first and
is refused with error 487 while the heap stands; a commit of pages a heap
stands over is the host's (committed, read-write); anything else is the
host's call unchanged, its last error kept. title_virtual_alloc_ex does
the same for this process (another's is the host's alone);
title_virtual_protect_ex goes through leonida_gpu::title_memory_protect
for this process, as title_virtual_protect. NtProtectVirtualMemory
(ntdll) is not shimmed: nothing in the repository says the title imports
it (docs/runtime_imports.md and docs/exe_fail_fast.md list no ntdll memory
call), and its NTSTATUS contract differs from the glue's.

Which of these the executable imports is not documented
(docs/runtime_imports.md measures 432 host imports without naming them;
it names kernel32!VirtualAlloc only as an assumption about windows); the
package's C++ runtime DLLs are mapped by the loader and bound through the
same table.

Switch: LEONIDA_INPLACE_TITLE_ALLOC=0 leaves the three out of the table,
bound to the host's own as before (read once, when the table is made).
On by default: without a heap in place (LEONIDA_INPLACE stays off) the
glue is one atomic load and the host's call, the last error the host's.
Documented in xmem.rs and README-fxceless.md.

Tests (leonida-hle): xmem::tests::
the_titles_own_virtual_alloc_and_protect_ex_are_the_runtimes (exports,
plain calls, refusals with the host's error) and
the_titles_own_virtual_alloc_and_protect_ex_meet_a_heap_in_place (host
device through title_memory_held_in_place; RX 7900 XT here: a commit
under the heap is the host's, VirtualProtectEx told done and queried as
asked, a commit of released pages refused with 487 by VirtualAlloc and
VirtualAllocEx before and after the heap goes, the addresses reserved
again). Red with the exports left out ("the title's VirtualAlloc is the
runtime's": None), with VirtualProtectEx the host's ("told done": left 0)
and with VirtualAlloc the host's ("a commit of released pages is
refused"); green with all.
What was wrong: View::Sampler (13 words) and View::ConsoleSampler (27
words) entries were never released (crates/leonida-gpu/src/descriptor.rs:
Views::entry pushed only View::addressed entries for Views::let_go_one,
and forget frees by resource; Views' doc said samplers are "as many as
there are sampler states"). Each distinct description is an entry, and a
sampler's words hold floats a title may change as it plays (mip bias that
follows a dynamic resolution, a least LOD that follows streaming): the
CPU test writing 20,000 samplers with a new value each, shown slots looked
up every frame and nothing else naming them, kept 20,008 sampler entries
(20,009 in all) on the old policy. Whether this title writes such samplers
is not measured. Sampler heaps were not in VIEW_HEAPS either, so the look
through the slots (Views::keep_live) could not have kept them.

What changes: Limits::samplers (LEONIDA_VIEW_SAMPLERS_BOUND, crate::toggled!,
on by default) makes samplers View::let_go_able: they join
Views::addressed and go round the same clock under the same most
(LEONIDA_VIEW_ADDRESSED_MOST, 1,048,576 of both kinds), counted in
put_off. Sampler heaps, CPU-only too, are registered in VIEW_HEAPS with
their 16-byte step, and heap_records reads each heap at its own step, so
a record in any view or sampler heap keeps its entry. Below the most
nothing changes but that registration. The remaining hazard, as for
views carrying an address: a sampler record kept outside every heap for
a whole round, unread, and copied back finds its sampler gone (the host's
point stand-in). On by default for that reason only past the most, where
the table grew without bound before. Documented at samplers_bound and in
README-fxceless.md "Speed and memory".

Tests: sampler_entries_stay_bounded_when_a_title_writes_new_ones (most
64: at most 64 sampler entries for 20,000 written; eight in heap slots
nothing looks up and the shown ones keep their samplers; a let-go
record is stale, written again is named again; a resource view stays;
with samplers off 20,000 entries as before) and
sampler_heaps_are_looked_through_while_they_are_there. RED with the
policy reverted (samplers not let-go-able, sampler heaps not registered):
"20008 sampler entries for 20000 written" and "a CPU-only sampler heap's
record". The tests written before pass samplers: false, as they assert.
What was wrong: LEONIDA_CARD_FROM_TITLE gave title memory as the CPU
side only to big title buffers made through lookup (shadow.rs
source_side, called from lookup alone). A window of title memory
outside buffers that got a side in the card's memory
(LEONIDA_CARD_WINDOWS_MB, window_room_for) still made a second buffer
of its size in the PC's memory (loose, shadow.rs:8898 of
perf/unified-memory) and every refresh copied the pages the title wrote
into it on the CPU before the card copied them up. Windows are two
thirds of the PC memory the card shares (run 104: 3,552 MB of 5,400).

What changes: loose asks source_side for a window whose card side is
in the card's memory, under the window table's lock (as lookup opens a
buffer's under its own: in_place_let_go takes LOOSE before it looks in
the carded index, and the window is noted there before the lock is
free). Everything that keeps a buffer's case right is per copy and
already finds windows: source_copying and copying over the carded
index (our writes at submission), Shadow::writing / keep_stores ->
unsource (declared shader writes, kept stores), in_place_let_go ->
sources_going (title free, decommit, protect, remapped sections),
Drop and the memory line (SOURCED). Not for memory by address
(by_address sets changes_only: it sends only the dwords that differ
from its CPU side, which title memory cannot be, as keep_stores says)
nor for LEONIDA_WINDOWS_OWN windows (two PC-memory sides on purpose).
Documented at from_title_windows, from_title, window_card_most, loose
and in README-fxceless.md "Speed and memory".

Switch: under LEONIDA_CARD_FROM_TITLE (off by default, as before);
LEONIDA_CARD_FROM_TITLE_WINDOWS=0 (crate::toggled!) keeps windows on a
side of their own with the parent switch on. Stays off by default: not
measured with the title; the opening is a hitch of a few ms for 4 MiB
under the window table's lock, once per window; and a window is a
second view over title buffers inside it, so a send of it still in the
air may read part of a later copy-back into title memory (both values
the memory held; the next refresh sends the pages whole).

Tests (host::send::direct_tests, on the host's card, through loose
itself via shadow::card_window_for_test): the five card-from-title
tests are bodies over Of::{Buffer, Window}, and each has a window
variant:
a_windows_title_memory_reaches_the_card_side_with_no_copy_on_the_cpu,
a_copy_of_ours_into_a_windows_title_memory_that_is_its_cpu_side_waits_first,
a_copy_of_ours_into_a_windows_title_memory_that_was_its_cpu_side_waits_first,
a_free_of_a_windows_title_memory_is_done_once_its_heap_went,
a_window_declared_written_later_gets_a_cpu_side_of_its_own; plus a
protection through title_memory_protect for both
(a_protection_of_title_memory_that_is_a_cpu_side_is_made_once_its_heap_went,
a_protection_of_a_windows_title_memory_is_made_once_its_heap_went).
All six window tests fail with the loose change reverted ("the CPU
side is a buffer of its own"); with it in, the ordering one fails with
source_copying taken out of title_copy, the free and protection ones
without the in_place_let_go note, the declared-write one without
unsource in writing (checked).
What was wrong: a decommit of the title's that a heap opened in place
(LEONIDA_INPLACE) is in the way of is kept committed and zeroed
(inplace.rs title_memory_free_held, zero_committed) and the title is told
it is done, but XMemVirtualQuery (xmem.rs:296, through
title_memory_as_asked) told those pages committed graphics memory until the
title released the allocation: a shortcut noted in ca0d38ec, since the
title could commit them again through the host's own VirtualAlloc, which
the runtime did not see, so no record of them could be kept true. The
title's VirtualAlloc is the runtime's since the commit before.

What changes: the decommits kept are noted (inplace.rs DECOMMITTED, joined
where they touch) and read as reserved memory, Protect 0, no graphics flag,
on over the host's reserved memory and other kept decommits after them in
the allocation; a committed region ends where one begins. The note goes
where the title gets memory there again (the new
leonida_gpu::title_memory_alloc, title_memory_reserve then the record cut
for a commit or reservation that succeeded, now called by
XMemVirtualAlloc at an address of the title's and by the title's own
VirtualAlloc and VirtualAllocEx), where the host frees the pages (a
decommit or release done by title_memory_free, title_memory_free_held or
release_pending), and over the allocation once the title releases it.
The pages still stay committed (and zeroed) on the host until the title
releases the allocation: decommitting them later could take pages the
title committed again in between, or by a call the runtime does not take.

Switch: LEONIDA_INPLACE_QUERY_DECOMMITS=0 restores reading them as
committed (LEONIDA_INPLACE_QUERY=0 turns all of it off, as before). On
by default under LEONIDA_INPLACE, which stays off. Documented in
inplace.rs, xmem.rs and README-fxceless.md.

Tests: inplace::tests::a_query_tells_a_decommit_kept_as_reserved (pure:
the run of reserved memory over kept decommits and the host's reserved
pages, the committed region cut before one, the host's answer with none
kept, a kept release first),
warp_a_decommit_kept_under_a_heap_reads_as_reserved_until_committed_again
(WARP, through title_memory_free and title_memory_alloc: reserved, then
committed and zeros once committed again, reserved once decommitted again,
nothing noted once released); xmem::tests::
a_query_tells_a_decommit_under_a_heap_as_reserved (leonida-hle, through
the title's VirtualFree, VirtualAlloc, XMemVirtualAlloc and
XMemVirtualQuery with a heap held in place on the host device; RX 7900 XT
here). Red with the switch off ("reserved, as the title asked": left
(MEM_COMMIT, PAGE_READWRITE, graphics)), with as_asked ignoring the notes
("committed, to the decommit": region 0x20000 not 0x10000), and with the
commit not cutting the note (title_memory_alloc without decommitted_gone,
or the title's VirtualAlloc through title_memory_reserve: "committed again
by VirtualAlloc" read MEM_RESERVE); green with all.
The physical-reuse bullet in d3d12/docs/README-fxceless.md:155 said an
allocation looks only at the waiting runs it gives. Spare::take
(xmem.rs:1413) stops early only once it has found what was asked
(found >= n at its break): when fewer pages free of views wait than
asked, it walks every run and checks every page, as before; and it
checks every page of a run that views split. The bullet and the
Spare::runs doc now say so. No code change, no switch, no test (only
the wording changes); leonida-hle 247 passed/2 ignored, leonida-gpu
720/51.
What was wrong: the decommits kept committed and zeroed for a heap
(inplace.rs DECOMMITTED) were noted without the allocation they are in and
joined where they only touched (decommitted_kept, inplace.rs:1116), and the
query walk (as_asked, inplace.rs:1250 and :1260) followed any record at the
end of a region, while the host's reserved memory after it was checked to be
of the same allocation. Host allocations are 64 KiB pages and often side by
side: with a decommit kept at the end of allocation A and one at the start of
B beside it, XMemVirtualQuery of A's last page said MEM_RESERVE over two
pages, AllocationBase A, a region running into B (and a reserved tail of A
went on over B's kept pages the same way). VirtualQuery never gives a region
over two allocations, and a caller stepping by BaseAddress + RegionSize
skipped the start of B.

What changes: each record carries the host's AllocationBase of its pages
(decommitted_kept asks the host per region, so a range over two allocations
is noted as two); records join only within one allocation (the new pure
decommit_noted); and as_asked follows only records of the queried
allocation, from the page asked and at each step.

Switch: none new; it is LEONIDA_INPLACE_QUERY_DECOMMITS's (=0 reads such
pages committed, as the host has them), under LEONIDA_INPLACE, which stays
off.

Tests: inplace::tests::a_query_of_a_decommit_kept_stays_in_its_allocation
(pure: records of A and B noted apart, A's kept page and A's reserved tail
stop at A's end, B's page is B's, joins within one allocation) and
a_decommit_kept_over_two_allocations_is_noted_by_each (host memory, two
allocations side by side, through decommitted_kept, title_memory_as_asked
and release through title_memory_free). Red with the joins across
allocations ("apart: two allocations": one record (0x10f000, 0x111000)) and,
with the noting fixed, with the walk not checking the allocation ("a
decommit kept: to A's end": region 0x2000 not 0x1000); green with both.
What was wrong: xmem::tests::the_titles_own_virtual_alloc_and_protect_ex_meet_a_heap_in_place
(xmem.rs, after drop(held)) asked a MEM_COMMIT of the released page again
and again until the host said the memory was free, then reserved it: once
the glue (title_memory_reserve) had done the release, another test could take
the addresses in between, and the next commit was made in its memory or the
final `again == base` failed. And nothing said what LEONIDA_TIMELINE shows
of the title's VirtualAlloc now that it is an xmem export, not a host
import wrapped by leonida_gpu::timeline::import (leonida-hle host.rs:93-96).

What changes: the test asks the commit once after the heap is gone (refused
either way), then takes the addresses back by polling a MEM_RESERVE |
MEM_COMMIT of the base through title_virtual_alloc, the release and the
reservation one call. The xmem doc of title_allocs and the README
"Speed and memory" bullet say that the host's call made inside the glue is
still on the timeline as VirtualAlloc (and VirtualFree, VirtualProtect): it
goes through the runtime's own import table, whose entries the timeline
points at the same wrappers (timeline/hooks.rs wrap_own, matched by name);
the glue's own waits around it are not, and VirtualAllocEx and
VirtualProtectEx were never wrapped.

Switch: none (a test and docs).

Tests: the changed test, green on the RX 7900 XT (not skipped). The race it
removes is a timing one between parallel tests, with no deterministic red.
The README bullet of LEONIDA_CARD_FROM_TITLE said the window is opened once
per window and that every hazard has a test. Windows are let go by the idle
sweep and made again at their next ask, each time opened under the window
table's lock; and no test covers a section's remap, for windows or buffers.
The bullet and the comment in shadow.rs loose() say so.
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-29 15:16 UTC · original

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.

**@⁠adrianmjim** on GitHub · 2026-11-29 15:16 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7257964946) ### Fifth round in `d3d12/` (pushed at `6737559d3`) Claimed in [#2570](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/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.
Author
Owner

@⁠fiestorra on GitHub · 2026-11-29 17:38 UTC · original

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.

**@⁠fiestorra** on GitHub · 2026-11-29 17:38 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7259855257) 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.
Five-minute runs of a fixed scene (save restored before each start) with each
switch the memory work left off: none is far from the runs without them
except LEONIDA_LAND_IN_SUBMISSION, 5 ms slower with LEONIDA_RELAY_COPY=1; in
place reaches almost none of the title's memory, whose windows lie over pages
of several sections; the frame is held by the submitting thread, most of
whose time is keeping title memory and its copies in step.
Conflicts resolved keeping both sides:

- leonida-gpu Cargo.toml: windows-sys takes both feature lists
  (Win32_Devices_DeviceAndDriverInstallation from here,
  Win32_Security_Cryptography and Win32_Security_WinTrust from main).
- descriptor.rs: main's per-thread view cache (LEONIDA_VIEW_CACHE) over
  the view table's clock. The generation mirror is stored in words_for,
  the one writer of the run's table, for the entry Views::entry makes,
  reuses or takes from let_go_one; not in Views::entry, so the tables the
  tests build alone leave the run's mirror be. view_at answers entries
  from the cache only for views the clock never lets go (not
  View::let_go_able): those are still read through Views::view_at under
  the lock, which marks them SEEN, so an entry read only through the
  cache is not let go as unread. Placed views keep main's per-thread
  shapes (a shape never goes).
- list.rs: a submitted list still holds no host list until its reset;
  main's lists closed ahead (LEONIDA_CLOSED_AHEAD) now serve that reset
  (fresh_closed in reset) instead of detach and detach_parts, which take
  none. That pool is a Pool trimmed by trim_idle as the idle one is, and
  its lists go through idle_trim before they are closed; the frame line
  (host.rs) says they are counted at the reset, against those closed by
  the resetting thread.
- texback.rs: Back and Landing carry both the submission counts of the
  read-back read in place and main's subresource bits; land keeps the
  landing() split; the tests pass track's copy flag and all subresources.
- texture.rs: placed_in_host_written returns early with LEONIDA_COPY_BACK
  and looks through HostWrittenAt::holding; main's WRITTEN_BY and
  host_write_listed sit before the FORGOTTEN test counter and the
  texture-only forget; PreludeUpload carries held, plane, resource and
  list in both its constructions; claim checks main's upload guard before
  it takes or makes the staging buffer.
- dstorage.rs (leonida-hle): main's timeline spans around the reading,
  inflating and BCPack stages of the scratch-buffer path.
- findings.md: main's bullets close the section before; the section on
  the memory switches follows.
- d3d12_vulkan_device.cpp, create_texture's deferred placed path: main's
  reuse of with_host (have_host_requirements, else measured into it) with
  this branch's counted claim, acquire_zero_image and zero_claim_, which
  retry_host and a texture given memory of its own give back. Not built
  here (no Vulkan headers): the identifiers it keeps were checked in the
  file and headers, and its brace, bracket and line counts are this
  branch's plus main's changes.

cargo check --workspace --all-targets and -p leonida-gpu --features
diagnostics --all-targets; cargo test -p leonida-gpu --lib twice (744
passed, 51 ignored) and -p leonida-hle --lib (256 passed).
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-29 20:39 UTC · original

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.

**@⁠adrianmjim** on GitHub · 2026-11-29 20:39 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7262257703) 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.
Author
Owner

@⁠MoonEyes on GitHub · 2026-11-29 21:54 UTC · original

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

**@⁠MoonEyes** on GitHub · 2026-11-29 21:54 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7263247046) 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).
What was wrong: the sweep (resource.rs let_go_idle, let_go_copy) let a
placed texture's host copy go only after the card's idle time, ten minutes
while the card has room, whether or not the title memory it was made from
was still mapped; evict_placed releases only placed textures with no host
copy (made.is_none()). In a world run on the RX 7900 XT the memory line
estimated 1,443 MB of host copies of placed textures whose first page was
not mapped any more, none shown by a descriptor slot.

What changes: watch.rs title_memory_unmapping and title_memory_freed tell
resource::title_memory_unmapped the range (noted only, under a lock of its
own, once a placed texture exists: the runtime calls with its locks held
and texture_at takes the watch's locks under PLACED_TEXTURES). At each
look the sweep (let_go_unmapped) marks the placed textures whose first page
lies in the ranges noted and, for up to 4096 of them from where the last
look stopped, with a reference taken under the table's lock, lets the host
copy go on let_go_copy's terms (now shared as let_go_made: only the
texture holds it, no list not yet reset, no descriptor slot, filled by the
title, never written by the host) plus no slot waiting for it, once out of
use for 2.5 s and 60 frames, and only while the first page is still not
mapped. The texture stays in its table; mapped again and viewed, it is
made again from title memory as any copy the sweep let go. The memory line
counts the copies let go this way. descriptor::host::compact is shared to
join the ranges noted beyond 4096.

Switch: LEONIDA_PLACED_UNMAPPED=0 keeps the copies to the card's idle time,
as before. On by default: only when a copy goes changes, on the sweep's
own terms.

Test: resource::tests::a_placed_texture_s_copy_goes_with_its_memory_and_is_made_again
(local GPU or WARP): five placed textures, four unmapped through
watch::title_memory_unmapping and decommitted; a copy used lately stays,
one a list holds and one a slot holds stay until let go, one over memory
mapped again before the look and one over memory nobody unmapped stay;
the unheld one goes and, mapped again with other bytes, is made again and
the card reads the new level 0. Fails with the let go stubbed out (the
copy stays). an_unmapped_placed_texture_s_step covers the step's order.
What was wrong: a flush of more than 256 refreshes looked at which of them
copy nothing (Shadow::nothing_new) on the threads beside the submitting one,
each look just before the refresh it may spare (host.rs:13691 and 13714,
Batch::refresh_spans; host.rs:13852 and 13888, Batch::flush_all), and the
copies a submission's shaders write were looked at on the threads however
few they were (host.rs:13765, Batch::refresh_ahead). A look takes the write
watch journal's lock and one of its parts' for a few reads: about 30 ns on
one thread, but 4,400 looks at copies nothing wrote took 0.36-0.48 ms spread
over the 8 threads against 0.14 ms one after the other, in pieces of 1 to
256 alike, and the threads were woken even when every refresh of the flush
turned out to copy nothing. In a 5-minute run of the title the submitting
thread spent 11.7 ms a frame in refreshes, 5,753 of 6,590 known to copy
nothing and 5,795 handed to the threads.

What changes: with LEONIDA_LOOK_FIRST (on; toggled! style, =0 restores the
old way) every flush looks first, on the submitting thread, one after the
other (host::sift), and hands only the refreshes that may copy to the
threads; none is woken when fewer than two are left. The looks are the
same predicate, and all of them still come before the first refresh, as
they always did for 256 or fewer (a refresh's asking may note writes in
another copy's range that came after the submission's asking: those are the
next submission's either way). The refreshes made are the same. Looks that
take longer than 1.5 ms (LOOK_BUDGET, a hypothesis: ten times the 4,400
looks above) leave the rest to the threads, looked at there as before.
Renderer port #6's planning no longer moves the looks while the switch is
on. Documented next to the code, at watch::port_guard_plan and in
README-fxceless.md.

Measured (refreshes_of_nothing_written, an ignored bench, release build, RX
7900 XT PC of 8 cores): 4,400 copies nothing wrote, in front of the steps
0.65 -> 0.24 ms median, in three flushes between them 0.47 -> 0.17 ms; the
174 MB heap under 40 declared ranges, 60 copies and the heap, and 200 copies
in one flush unchanged. Not measured in the title yet.

Tests: a_flush_that_copies_nothing_wakes_no_thread (300 copies of
write-watched and of view memory, nothing written: no thread woken, in
front or in a flush; a byte written is taken) fails on perf/unified-memory
and passes; writes_between_refreshes_are_taken_whoever_looks (560 copies,
both kinds of memory, writes between submissions, both paths, switch on and
off: every refreshed range holds title memory); sifting_keeps_what_may_copy_in_order
(the budget leaves the rest unlooked, in order). shadow::WIDE_IN_TEST counts
a thread's spreads of work, for tests.
What was wrong: watch.rs title_memory_freed, for a free with no length
(MEM_RELEASE of the whole allocation), asked where the allocation ends with
allocation_end(at, at) once for crate::inplace::title_memory_freeing, once
more for crate::resource::title_memory_unmapped since placed textures' notes
(on by default once a placed texture exists), a third time when a view was
known at the address, and again from the first noted block for the guards.
Each is a walk of the allocation's regions with VirtualQuery on the title's
thread inside its VirtualFree (one question about the title's 1.1 GB block
took 8.8 ms, texture.rs).

What changes: the end is asked at most once, when the first of those needs
it, and handed to the others; the guards' end is taken from it (the
allocation's end if the noted block lies before it, else the address, as
allocation_end answers) when it was asked, else asked from the noted block
as before. No switch: the same ends, asked fewer times.

Test: watch::tests::a_whole_release_walks_its_allocation_once (a whole
release through crate::inplace::title_memory_free with placed textures'
notes, a view and two noted blocks, one past the allocation: one walk, the
notes inside forgotten and the one past it kept). Fails with each asking
again (two walks).
What was wrong: the list of ours ahead of each frame's first submission
(queue.rs ahead_begin/ahead_of_frame, draw.rs record_passes_ahead) is begun
at the line's present, and the title, a frame ahead, has the next frame's
first submission in the line by then: the line's thread stood 13.3 ms a
frame waiting for a list that took 13.8 ms to record (run e_base1, the
title's world), 4.9 of them looking at slots in draw.rs heap_buffer_pass
(some 29,000 a pass: a sixteenth of 160,000 buffer slots, and those written
since the last pass, whose host descriptors are made there). The slots were
written during the frame, while the thread that records the list waited.

What changes, with LEONIDA_HEAP_PRELOOK=1 (every LEONIDA_HEAP_PRELOOK_MS,
3): that thread looks ahead every few milliseconds while it waits for the
present (draw.rs heap_look_ahead/look_ahead): the slots written since its
last look, but those a draw's table has (left to the pass), and once a pass
the coming pass's part of the others; it makes their host descriptors,
finds their copies and keeps the ranges as the pass keeps them, with the
record each slot held. The pass then skips the part looked at ahead and
looks only at the slots written since and at those whose look no longer
holds (kept_from_ahead: another record in the slot, by a call or as bytes;
its host slot not made from that record any more; a draw's table has it;
the view's resource released). The look at slots is one function for both
(look_at_slots). The frame line counts the looks and what the passes kept
and looked at again.

What it changes on screen: a written slot shows its buffer from the look
on, where it showed none until the pass; lists sent in between that read it
by index read the copy as its last refresh left it instead of zeros (the
title, having written the record, does not read the slot from lists in the
air). An unordered view found ahead is declared written from the look on.
Off by default: no game run has been made with it.

Tests: draw.rs look_ahead_tests. The pure one checks what keeps a look and
what does not. The device one writes 18 buffer views, passes once, writes 8
again (one taken by a draw's table), looks ahead, then writes slot 2 again
by a call, copies slot 9's record into slot 3 as bytes, has a table take
slot 4 and writes slot 10: the pass looks at 5 slots, where with the look
disabled it looked at 10 (red: 10 != 5), and for every slot keeps the copy
and range a pass of its own finds, its host slot made from the record it
holds now.
What was wrong: resource.rs unmapped_step took a first page found mapped
for memory mapped again (Unmapped::Done) and let_go_unmapped dropped the
key at once. The notice comes before the memory goes:
watch::title_memory_unmapping runs before UnmapViewOfFile2, xmem tells all
of a change's unmappings before its calls, and watch::title_memory_freed
runs before a free that can fail and be done later
(inplace::title_memory_free_held). A look in that window gave the texture
up and nothing noted it again, so its copy waited for the card's idle time
as before the feature.

What changes: a first page found mapped is Unmapped::Mapped; the key stays
noted, with since when it has been found mapped at every look, and is given
up only once found mapped for UNMAPPED_MAPPED_MS (5 s); a look that finds it
unmapped, or a new unmapping over it, starts that time again. A free held
for a heap past 5 s (up to 30 s) still leaves its copies to the idle time,
as the docs now say. No new switch: LEONIDA_PLACED_UNMAPPED=0 still keeps
every copy to the idle time.

Test: resource::tests::a_placed_texture_noted_before_its_memory_goes_is_looked_at_again
(local GPU or WARP): two placed textures told unmapped while still mapped;
the look keeps both noted, the copy of the one whose memory then goes is let
go at the next look, the other is given up once found mapped for the time
given and keeps its copy. Fails with a mapped page taken as done (the
texture is not looked at again). The two tests that look with times of
their own now take a lock between them; the step's unit test and the first
test follow the new step.
What was wrong: watch::nothing_new (watch.rs:1420) judged a range by the
64 KiB pages it touches: once the title wrote any 4 KiB of the page a range
begins or ends in, after the copy last took the range, the refresh was not
known to copy nothing, although Shadow::copy_stale then takes only the
written 4 KiB the range holds a byte of (shadow::by_parts over
watch::parts_written): none when the write was beside the range, as in
memory where the views of many copies lie one after the other. Such a
refresh paid all of one that copies (the journal's notes of its range asked
again and collected, the copy's page notes held for writing, the runs
planned, the parts asked for) and went to the threads with those.

What changes: with LEONIDA_LOOK_PARTS (on; toggled! style, =0 restores the
page) a page written since its taking counts only if the parts written since
(Shard::parts_since, read under the part of the journal already held for
the look) meet the parts of it the range holds (watch::parts_in). These are
the parts the refresh itself trusts, so the answer is the refresh's: the
kernel's parts for write-watched memory and those of our own writes;
the guards name the whole block, so view memory is looked at as before.
Skipping such a refresh leaves the copy's note of the range taken whole at
an older asking, which only makes later looks see more parts written, never
fewer. Notes::all_newer gives its predicate the held part. Documented next
to the code and in README-fxceless.md.

Measured (refreshes_beside_writes, an ignored bench, release build, RX 7900
XT PC): 1,000 copies of 160 KiB one after the other, a byte written beside
each, 0.24 -> 0.10 ms a flush in front of the steps; 100 of them 0.029 ->
0.008 ms (no thread woken); 2,000 of them with the 1,000 written ones 0.49 ->
0.39 ms. How many of the title's refreshes are of that kind is not
measured.

Tests: writes_beside_a_range_on_its_end_pages (write-watched memory: a byte
beside the range in its first and last pages is known to copy nothing, fails
with the page as before and passes; one in a 4 KiB the range holds is taken,
3,000 and 3,596 bytes; view memory: a write beside is a write, as before;
the copy holds title memory after every refresh) and
the_parts_of_a_page_a_range_holds.
What was wrong: queue.rs ahead_begin caught a panic of
draw::heap_look_ahead and said the pass then looked for itself, but by the
time draw.rs look_ahead calls look_at_slots it has taken the written slots
out of the host heap's changed set (buffer_changes), forgotten the coming
part's ranges (forget_part) and set ahead.part_of to the coming pass. After
a panic there the pass skipped the part (part_of matched) and never saw the
written slots: no range, host descriptor or refresh for them until the slot
was written again or its part came round 16 passes later, though a slot the
title wrote must be mirrored before a submission that reads it. (Without the
look, a panic in the pass is fatal: ahead_of_frame calls host::fail.)

What changes: look_ahead catches a panic of its look and, before passing it
on, puts back into the changed set the slots that look took and those
earlier looks kept, and clears what looks found (ahead.part_of to 0), so the
pass looks at the written slots and at its part itself; the guard is let go
first, so the sweep's mutex is not poisoned. The comment in queue.rs says
so. Same switch (LEONIDA_HEAP_PRELOOK, off).

Test: draw.rs look_ahead_tests::a_look_ahead_that_panics_leaves_its_slots_to_the_pass
writes 18 buffer views, passes once, writes slots 2 to 4 again, has a look
panic (a test-only flag) and passes: every slot shows the copy and range a
pass of its own finds. Red without the restore: slot 1 of the pass's part
shows nothing.
What was wrong: draw.rs look_ahead kept in Ahead::slots only the slots that
showed a buffer at the look; one that showed nothing (a draw's table had it
at the look's frame, copied_tabled with COPIED_FRAMES 8; its memory had no
copy yet, buffer_copy None; its record not read) got no range and was not
remembered, and the pass, skipping the part looked at ahead, never looked at
it again. A pass of its own looks at it at the pass's frame and can find a
range to refresh there: until the slot was written again or its part came
round 16 passes later, it showed nothing. (The same boundary as a pass's own
look, moved a frame earlier; heap_prelook's doc said the pass kept what its
own look would find but for one case, which was not so.)

What changes: Ahead keeps those slots too (nothing), forgotten with the part
and when a later look sees them again, and the pass looks at them again with
those whose look no longer holds; the frame line counts them as looked at
again. The doc comment and the README bullet say so. Same switch
(LEONIDA_HEAP_PRELOOK, off).

Test: draw.rs look_ahead_tests::a_slot_that_showed_nothing_at_the_look_is_looked_at_by_the_pass
passes once over 18 buffer views, has a draw's table take slot 17 (of the
coming part), looks ahead (it shows nothing) and passes 9 frames later, when
no table holds it: the pass looks at that one slot and every slot shows what
a pass of its own finds. Red without it: the pass looked at 0 slots, not 1.
What was wrong: draw.rs heap_prelook and the README bullet for LEONIDA_HEAP_PRELOOK did not say that a look is made only by the leonida-ahead thread (queue.rs ahead_begin: passes_ahead() on, LEONIDA_PASSES_AHEAD not 2) and only with the slots spread over passes (draw.rs look_ahead returns 0 with LEONIDA_HEAP_SPREAD=0), nor that queue.rs ahead_line prints the frame line only with the passes ahead on: an A/B with the switch alone could change nothing and show no line.

What changes: one sentence in each says so. Documentation only; no switch, no test.
What was wrong: sift (crates/leonida-gpu/src/host.rs:12704-12722) asked
the clock only before the 64th, 128th, ... look, so LOOK_BUDGET never cut
short a flush of fewer than 64 refreshes, nor the first 63 looks of a
larger one, however many pages their ranges held. With the default setup
that changed nothing (flushes of 256 or fewer were looked at one by one
without a limit before LEONIDA_LOOK_FIRST too), but with
LEONIDA_PORT_GUARD=1 look_first overrides port_guard_plan, which existed
to take these looks off the submitting thread (one submission spent up to
6 ms in them), and a few dozen wide looks stayed there with no limit; the
docs of port_guard_plan and the README promised one.

What changes: a look counts as one plus one for each 64 KiB page of its
range, and the clock is asked once the count since it was last asked
reaches SIFT_EVERY (64): every 64 looks of ranges inside a page, as before
(one look later), and after each look of 4 MiB or more. The docs of
look_first, port_guard_plan and the README bullet say so.

Switch: none of its own; LEONIDA_LOOK_FIRST=0 still restores the old
placement. The benchmark refreshes_of_nothing_written (release, the RX
7900 XT PC) is unchanged: 4,400 copies in front 0.239 ms, in 3 flushes
0.167 ms, as before.

Test: sifting_asks_the_clock_after_a_wide_look (three looks of 64 pages
with no time: one looked at, the rest left in order; three of 128 bytes
all looked at) fails on the old rule (3 looked at, not 1);
sifting_keeps_what_may_copy_in_order follows the clock's new place.
What was wrong: the doc of look_parts (crates/leonida-gpu/src/watch.rs:
1448-1451) and the README bullet said the parts were honoured in
write-watched memory only and that view memory was looked at as before.
landed_beside (watch.rs:3080) notes 4 KiB parts for view-memory blocks as
well, and nothing_new honours them, so a refresh of view memory our own
landing wrote beside is also known to copy nothing. That is right (the
refresh, through parts_written and shadow::by_parts, takes the same parts
from the same journal); only the words were wrong.

What changes: the doc and the README bullet say that what the guards see
is noted as the whole block, so a title write in view memory still counts
for the whole page, while the parts our own landings note beside a range
there are honoured, as by the refresh.

Switch: none, words only. Test: none, no behaviour changes.
# Conflicts:
#	d3d12/crates/leonida-gpu/src/descriptor/host.rs
What was wrong: watch.rs ask_ahead (the run loop after "The runs asked about
together") joined every range closer than ahead_gap (8 MiB unless given)
into one kernel asking, across the ends of the title's reservations (which
lie side by side) and over view memory and memory that is not
write-watched. GetWriteWatch refused such a run, ask_run asked it again by
halves down to single ranges, and ask_rest asked each range left alone
again, refused again where it was a view's. In run e_base1 (ports 6 and 7
off): 259 askings a frame and 274 more refused.

What changes: the plan looks each allocation up once in the kernel's tree of
allocations (NtQueryVirtualMemory, MemoryRegionInformationEx, the question
placeholder() already asked; now region()). A run stops where its allocation
ends, and a range the kernel would refuse (not write-watched, or across two
allocations) is in no run and not asked by ask_rest: it is left to writes, as
a refused range was, which goes to the guards for view memory. A refusal that
still comes (memory freed meanwhile) is asked again by halves as before.
Whether the kernel's region type says "write-watched" (bit 10: 0x401 for a
write-watched private reservation, 0x1 without) is probed once on two
reservations of our own; where it does not, runs still end at allocations;
where the question is not answered at all, the plan is as before. Measured on
this PC (Windows 11): the lookup costs 0.4 us whatever the allocation's size,
where VirtualQuery walks page tables (16 ms for a committed, written GiB).

Switch: LEONIDA_ASK_BY_ALLOCATION=0 plans by distance alone, as before. On by
default: nothing the kernel answers for goes unasked, and what is no longer
asked was refused before.

Test: watch::tests::a_submission_asks_once_per_allocation_and_is_never_refused
(two write-watched reservations, plain memory and a view side by side, seven
ranges): 2 askings, none refused, against 11 askings with 8 refused when
planned as before (fails on perf/unified-memory: 8 refused); every page
written is found, through the journal or the guards, either way.
What was wrong: watch.rs ahead_gap said a call that resets written pages
costs 30-70 us whatever the range, the reason given for joining ranges up to
8 MiB apart. Measured on this PC (Windows 11, GetWriteWatch with reset, the
answer's room sized as kernel_written sizes it) the call costs what it walks:
0.5 us for 64 KiB, 8.3 for 8 MiB, 52 for 64 MiB, 860 for 1 GiB of committed
memory nothing wrote (0.4 us a MiB where nothing is committed), ~20 ns more
per 4 KiB page found written, 0.3-1 us for a refused call.

What changes: the comment only. The default stays 8 MiB: the frame measured
by turns kept 8 MiB against 256 KiB (findings.md, run d43), so the kernel's
time is not all the gap costs or saves in the game. A smaller default was
tried on this branch (1 MiB) and not kept for that reason; LEONIDA_ASK_GAP_KB
already sets it.

No switch, no test: nothing but the comment changes.
What was wrong: watch.rs writes asked the kernel about every range that had no
block read-only by our hand right then (a block the title had opened by
writing it, a hole), was refused for view memory and then went to the guards.
VIEWS, the blocks known for view memory, was set in guard and read by
known_views only with renderer port #6, which is off by default. Part of the
274 refused askings a frame of run e_base1 (75 view ranges a frame were
guarded block by block).

What changes: guard notes the blocks it found a view's in VIEWS with the
switch too, and writes for a caller that asks the guards goes to them at once
for such a range. A block wrongly known for a view (other memory there, with
nobody telling) is found no view by the guards, forgotten as one and asked of
the kernel, as with the port. title_memory_allocated now forgets VIEWS over
what it allocates, as title_memory_freed and title_memory_unmapping already
did. refused_as_view (ask_ahead, ask_rest, writes without the guards) still
needs the port: there a wrong bit would not be corrected.

Switch: LEONIDA_VIEWS_UNASKED=0 trusts VIEWS only with the port, as before. On
by default: the answer is the guards' with or without the refused asking.

Test: watch::tests::view_memory_known_as_such_is_not_asked_of_the_kernel (a
view guarded, written, looked at again: no kernel asking, against one refused
on perf/unified-memory; the write is found; write-watched memory wrongly
known for a view is still asked of the kernel; memory allocated anew is not
known for a view).
What was wrong: watch.rs protect_here (after the refused change of the whole
run) and unguard (after a refused run, "Not of one view, or not all there:
each for itself") changed the protection of a run that lies across several
views one block at a time. The title maps runs of its physical pages as one
view each (leonida-hle xmem map), so a run across two views of sixteen blocks
took the refused change and 32 more, each of which makes every core running
the title forget those pages (the frame line had 3.2-4.1 ms a frame of
"changing protections" for ~240 blocks made read-only, run e_base1).

What changes: after the refused change of a whole run, the run is done a view
at a time: where the view of its next block ends is one look in the kernel's
tree of allocations (region(), 0.4 us); a view's part that one change cannot
do (not all committed) is done a block at a time as before, and a view is
tried once. What it takes for granted is what one change for a whole run
already took for granted (unguard_runs, protect_here): that the first
block's protection speaks for the rest of its view.

Switch: LEONIDA_PROTECT_BY_VIEW=0 does such runs a block at a time, as before.
On by default: the same blocks end read-only or open as before, with the same
assumption the single-view runs already make.

Test: watch::tests::a_run_across_views_is_guarded_and_opened_a_view_at_a_time
(views of four, two and one blocks): 4 changes to guard the seven blocks and 4
to open them, against 8 and 8 on perf/unified-memory; every block ends
read-only, then open, as before, and the title's write through the second
view is found.
What was wrong: watch.rs writes (the viewed path, after the switch
LEONIDA_VIEWS_UNASKED made known_views true with the port off) counted every
look at view memory known as such in port6_count(P6_NOT_ASKED). port_guard_line
skips its line only when the port is off and every count is zero, so with the
defaults every frame printed "renderer port 6 (LEONIDA_PORT_GUARD=1) per
frame: ...", its shared-lock fields zeros that read as a measurement.

What changes: those askings left out are counted in ASKS (index 13, printed in
the frame line of asking about title memory beside the refused askings,
diagnostics builds), and in port 6's counts only with the port on.
refused_as_view already counted only with the port.

Switch: none; logging only (LEONIDA_VIEWS_UNASKED is unchanged).

Test: watch::tests::view_memory_known_as_such_is_not_asked_of_the_kernel now
also checks this thread's port-6 counts (PORT6_HERE, test builds) do not move
with the port off; on the commit before it counted 1 in P6_NOT_ASKED.
What was wrong: watch.rs Allocation::at (then :1386-1399) answered None for a
page with nothing there, a region the kernel did not answer for, and an
allocation that does not begin and end on a 64 KiB page (any reservation sized
in 4 KiB steps), and Allocations::of (:1417-1424) remembered only what was
found. Every range in such memory paid another NtQueryVirtualMemory, once in
runs_of for each run start and again in ask_rest_in for each range left
alone, in every submission; those allocations had no run ending at them
either, and nothing counted how often the plan could not apply.

What changes: an allocation off the pages is known as the pages it lies in,
with whether the kernel answers for them not said (watched None: its ranges
are asked about as before, the page reaching past its end is refused as
before), so runs end where it does and a range across its end is left to the
refresh, as for the others. A page found with nothing there is remembered in
the plan. The frame line of asking about title memory (diagnostics builds)
counts the allocations looked up and those it cannot tell the kernel answers
for (ASKS 14 and 15), so a run shows whether LEONIDA_ASK_BY_ALLOCATION applies
to the title's allocations. Nothing more is left out of an asking than before:
a range the plan does not take is asked about by its own refresh.

Switch: LEONIDA_ASK_BY_ALLOCATION (=0: by distance alone, as before), as for
the plan it belongs to.

Test: watch::tests::an_allocation_off_the_pages_is_looked_up_once_per_plan
(a write-watched reservation of 271 pages and 4 KiB, three ranges farther
apart than the gap: 1 look at it per submission and none refused, against 6
on the commit before; the writes are found; a run ends in the page it ends
in; a free page is looked up once).
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-29 22:09 UTC · original

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.

**@⁠adrianmjim** on GitHub · 2026-11-29 22:09 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7263446466) ### Sixth round in `d3d12/` (pushed at `8f5f02d80`), with current `main` merged Claimed in [#2570](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/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.
host.rs was 813,049 bytes; the repository policy (xtask/src/policy.rs,
`repository_passes_policy`) caps every file at 655,360. It is now 584,189.

This is a move with no code change. Every inline test module but
refresh_tests (moved on its own elsewhere) becomes `host/<name>.rs`,
its body dedented, so the tests keep their names. Five groups of
items move as they were, docs with them:

- host/present.rs: Presenter, Meter and Host::present / present_planes.
- host/compare.rs: the compare's ResultArea and ResultRing, CARD_COMPARE,
  card_pass and the joining of ComparePass.
- host/planes.rs: the plane pass and the twin copy.
- host/buffers.rs: the Host methods that make read-back, upload, shared,
  mapped card and UAV buffers, and the video-memory queries.
- host/lines.rs: the frame lines (late_line and the lines it logs).

What host.rs or a sibling still names is `pub(super)` and imported back
into host.rs; what the crate names is re-exported as before
(`crate::host::swap_format`, `CARD_COMPARE`, `METER_FPS_TENTHS`, ...).
docs/ultrawide.md points at present_planes' new file.
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-29 22:45 UTC · original

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.

**@⁠adrianmjim** on GitHub · 2026-11-29 22:45 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7263920495) `RS-HOST-RS-SPLIT` ([claim](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570)), 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.
What was wrong: State::early_textures (draw.rs:3853) took BAKE_UPLOAD
before anything else for every decoration bake draw, and under it
flush_for_bake (draw.rs:3687) waited up to 2 s for uploads on their way
(texture::ahead::drain) and settled everything in the air while the heap
needed it, before the pass and its synchronous execution
(draw.rs:3929). Every other list thread with a bake draw queued behind
the holder while it waited for the card, even when its own draw would
find no pass, no settle and no promotion to do once it got the lock.

What changes, with LEONIDA_BAKE_QUICK (on by default, read through
crate::toggled!; =0 keeps the old order):
- flush_for_bake is split: settle_for_bake does the drain, the settle
  loop and the flips, which need neither the bake list nor the lock; the
  rest (pending list flips and their promotion) stays. flush_for_bake
  runs both in the same order as before; the RESCUED counting moves to
  bake_rescued and counts what was done ahead of the lock once.
- A bake draw runs settle_for_bake before the lock, then bake_can_skip
  (not the frame's first bake, the pass exact, nothing on its way, no
  settle or own pending flip, and no pass due) decides whether the
  holder would find nothing to do; if so it remakes the views, flips the
  slots, waits for the pending gate and returns without the lock.
  Otherwise the whole old body runs under the lock.
- texture::ahead::in_flight reads IN_FLIGHT for that check, and the
  stores of BAKE_SERVED around a bake's pass are Release, so a pass under
  way on another thread (BAKE_SERVED 0) is seen and no draw goes on then.
- bake_gate holds that order (settle, look, lock) so it can be tested
  without a card. execute_sync_internal, LEONIDA_BAKE_AHEAD and the
  fallback without a host list are unchanged.

Tests (draw::bake_quick_tests): a table for bake_can_skip; with the lock
held on another thread for 400 ms, a draw with nothing to do goes on in
under 100 ms with the switch and waits for the lock without it; with
work left, the settle and the look run outside the lock and the flush
under it. With bake_gate taking the lock first and in-flight, settle and
pending flips left out of bake_can_skip, three of the four fail.
What was wrong: the global table of staging states (texture.rs:349,
STAGING) was held through all the work around an entry. staging()
(texture.rs:3636) took it at 3641 and kept it while a missing state was
made: texture_memory, texture_layout, GetDesc, a log line,
GetCopyableFootprints and new_staged (3758), which zeroes a pool piece
(megabytes written) or makes an upload buffer of its own
(CreateCommittedResource). let_go_idle (1157) kept it while
let_go_cold dropped staging buffers (let_go_staged, 2748) and
map.retain dropped staging states with their buffers; forget (1492)
and unstage (3267) dropped the removed state under it too. Every
recording thread that samples a texture the title fills asks that
table, so while textures streamed in, draws and dispatches waited
behind that work for textures they already had a state for.

What changes: texture/table.rs holds the table's lock only for the
look-up, the insert and the removal. get_or_make makes a missing entry
with the lock let go and checks again on the way in: an entry another
thread put in meanwhile that fits wins and ours goes after the lock;
else ours goes in and what it replaced goes after the lock. forget and
unstage count what they take out in STAGING_GONE under the lock; an
entry made across such a take-out goes in only if the texture's host
copy is still the one with the serial it was made for (made_copy, asked
with the lock let go: the host side is locked before the table), else
none is returned. take_out drops the removed state after the lock;
sweep takes the buffers let_go_cold lets go of (let_go_staged now hands
the buffer back) and the states retain refuses (extract_if) and drops
both after the lock. Counters and the trail line are unchanged.

Switch: LEONIDA_STAGING_SHORT (crate::toggled!, on); =0 makes and lets
go of everything under the lock, and forget keeps it to its end, as
before.

Tests (texture::table::tests): an entry there is found while another
is made (fails with the old path: the ask waits behind the make, which
under_the_lock_the_ask_waits_behind_the_make records); two makes of
one key leave one entry, both callers get it and the other goes once;
an entry made across a take-out goes in only if still wanted; what is
taken out goes with the lock free (take_out and sweep). Each failed
with its fix reverted. The texture tests pass with the switch on and
off.
What was wrong: every indirect execution (about 13,000 a frame, on up to
eight recording threads) looked its host command signature up in
host_signature (draw.rs:7076): one static Mutex<Vec> (7077-7079), held
while the list was searched and while a signature was made, and a clone
of the one found (an AddRef on an object all threads share, and a Release
after the call). The threads queued on that lock: 0.1 to 4.8 ms of waiting
a frame in three scenes, once six of the eight standing still for 3 ms
together because the thread holding it had been taken off its core.
pack_signature (7116) kept its signatures the same way.

What changes: draw/sigtable.rs has SigTable, a slot for each kind of
argument (draw, indexed draw, dispatch, mesh dispatch) and stride of
dwords below 128 bytes, each a OnceLock filled once and lent as a
&'static for the process's life (as the list kept them before): finding
one is two indexes and a load, and filling one holds up only the threads
that want that one. host_signature returns a HostSig (lent, or a
reference of its own) that execute_indirect hands to ExecuteIndirect
without a clone. A kind or stride past the table goes to the list as
before (Listed, the old lookup as a type). pack_signature keys a SigMap
by root signature, parameter and word: looked through under a shared
lock, added to under the exclusive one, the signature made outside it.
A refused signature is kept as refused in the table and the map.

Switch: LEONIDA_SIG_TABLE (on; =0 is the list under one lock, as
before), read through crate::toggled!, so LEONIDA_AB turns it; in
docs/README-fxceless.md under 'Speed and memory'.

Tests (draw::sigtable, no GPU needed): eight threads asking 100,000
times each, all at once and with a slow make, make each signature once
and are lent the same one (red with a fill that checks and then sets);
a thread looking up a made signature does not wait while another is
being made, for the table and the map (red with one lock around the
lookup), while with the list it does; kinds and strides past the table
(stride 6, 128, 256; kind 7) are left to the caller. With a host GPU,
host_signature(draw, 16) is one object on eight threads through the
table and through the list.
What was wrong: every table read of a slot the queue of textures picked by
index holds took that queue's lock and waited for it
(descriptor/host.rs:3446, HostHeap::tabled_in), and so did every slot
record, because the queue's marks that would spare the lock were off by
default (descriptor/host.rs:1326, asked!("LEONIDA_QUEUE_MARKS")), as was
the write of a view past the lock of placed texture views
(descriptor/host.rs:1127, asked!("LEONIDA_SPANS_QUICK")). Both were
weighed only on the submitting thread, which did not wait for these locks;
in timelines of three scenes the recording threads waited 23 to 72 ms a
frame for the locks of the host heaps, 3.3 to 18.9 ms of it for this queue
in table reads, and in a run not one note was spared and not one of some
17,000 slot writes a frame went past the lock of placed views.

What changes:
- queue_marks() and spans_quick() read toggled!: on by default,
  LEONIDA_QUEUE_MARKS=0 and LEONIDA_SPANS_QUICK=0 restore the lock on
  every note and every write.
- A table read that finds the queue locked (try_lock) leaves its slot in
  the heap's TabledInbox and goes on (LEONIDA_TABLED_INBOX, on;
  =0 waits for the lock as before). Every taker of the queue's lock goes
  through HostHeap::queue, which takes the waiting slots out before
  anything else, so a write or make after such a read lands after its
  take-out, as if the read had waited for the lock. A reader of the marks
  asks the queue instead while slots wait, since a slot marked held may
  be on its way out. The inbox holds at most 65,536 slots; past that a
  read waits as before. The frame line counts the reads so left
  (diagnostics builds).
- The per-thread batches of QUEUE_SPARED and SPANS_QUICK count one by one
  in tests, which read the counts at once.

Tests (descriptor::host::tests):
- table_reads_leave_their_slot_to_the_queues_next_holder: with the lock
  held by another thread a table read returns at once and the next taker
  of the lock finds the slot out; the old way waits (fails, timing out,
  with the read taking the lock).
- slots_left_to_the_queue_leave_it_before_the_next_change: a write and a
  make after a waiting take-out queue the slot again (fail without the
  take-out first in queue(), or with marks that answer for a waiting slot).
- notes_that_change_nothing_leave_the_locks_alone_by_default: a table read
  of a slot not queued and a write past placed views are spared with the
  default switches (fails with either switch off by default).
What was wrong: with LEONIDA_BAKE_QUICK a decoration bake draw went on
without BAKE_UPLOAD when bake_can_skip found nothing to do
(draw.rs:3953-3975), but what the holder of the lock was doing there was
not all to be seen. flush_for_bake (draw.rs:3786) takes this heap's flips
pending in lists (descriptor/host.rs:3204) before the holder promotes
them, runs its uploads (execute_sync_internal, or a settle) and shows the
slots, so for that whole time needs_gpu_settle_for_bake no longer counted
them, and with no pass due BAKE_SERVED stayed at the last pass's mark; and
with no milliseconds left bake_can_skip looked at no mark at all, so a
pass begun earlier on another thread was passed too. Either way the draw
that went on could reach the card before those slots were shown and bake
their stand-ins, which the old order (lock first) never allowed; with
LEONIDA_BAKE_AHEAD it could also read the pending gate before the
holder's gate was made.

What changes: BAKE_BUSY counts the bake draws at work under the lock: a
BakeBusy raised as the locked part begins, before the flush takes the
flips, and dropped on every way out of it, after the slots are shown (or
the gate that shows them is made). bake_can_skip's last argument is now
that (busy, where a hard false stood for the flips pending in lists,
which needs_gpu_settle_for_bake already covers), and it blocks the skip
with or without milliseconds left. bake_may_pass reads the skip's inputs
in order, BAKE_BUSY last (the flips are taken under the lock that
needs_gpu_settle_for_bake reads them with, so a draw that finds them gone
finds BAKE_BUSY raised). The doc comment and the README line that said
the pass's mark covered a pass in progress now say BAKE_BUSY does. Same
switch, LEONIDA_BAKE_QUICK (=0: the lock first, as before; the count is
kept either way, so a turn of LEONIDA_AB sees a holder of the other).

Test (draw::bake_quick_tests::a_bake_does_not_pass_one_at_work_under_the_lock):
on a host heap with a flip pending in a list, a bake draw with no
milliseconds left does not pass; with a holder that has taken the flip
and not shown it, or whose pass is under way, it still does not; once
the holder is done it does. Without BAKE_BUSY in bake_may_pass it fails
at the holder that took the flip. The table for bake_can_skip has the
busy case with and without milliseconds left.
What was wrong: HostHeap::queued (descriptor/host.rs:3587) read the slot's
mark before asking whether slots wait in the TabledInbox. A take-out
(TabledInbox::take_out_of, descriptor/host.rs:1419) between the two reads
clears the mark and then says no slot waits, so the reader kept a mark
that says held with an inbox that says none waits, and answered held for
a slot that had just left the queue. A make that expects the slot held
then skipped the lock and left it out of the queue, which the old way,
taking the slot out under the lock, never did.

What changes: queued reads the inbox first and the mark second
(queued_around, which runs a hook between the two reads for tests). A
reader that finds no slot waiting by a take-out's Release store finds the
mark it cleared, or a later write's. docs/findings.md now says that
LEONIDA_QUEUE_MARKS and LEONIDA_SPANS_QUICK are on by default again and
why, as the code comments that point to it do.

Switch: none new; the window exists only with LEONIDA_TABLED_INBOX on
(=0 never leaves slots in the inbox).

Test: descriptor::host::tests::marks_read_across_a_take_out_never_say_held
takes the inbox out between the two reads; with the old order it answers
held and fails.
What was wrong: pack_signature (draw.rs:7164) keys its SigMap by the root
signature's address and relied on the root kept in the slot to stop that
address from being reused, but its make returned None on a refusal
(`Some((root.clone(), make_pack_signature(..)?))`), so the slot kept the
refusal (sigtable.rs:122, get_or_init) with no root. The root could then be
freed (with LEONIDA_ROOT_DEDUPE=0 a pipeline owns its root) and a new one
with another layout made at its address would inherit the refusal: its
packed dispatches dropped although the host would accept its signature.
The list before kept no refusal, so this came with the table.

What changes: SigMap::get_or_make_pinned keeps the owner in the slot with
what make answered, made or refused; pack_signature keeps
(root signature, Option<command signature>) through it. The list
(LEONIDA_SIG_TABLE=0) is as before; the switch's note in
docs/README-fxceless.md says the refusal keeps its root.

Switch: LEONIDA_SIG_TABLE, as before (=0 is the list under one lock).

Test: draw::sigtable a_refused_packed_signature_keeps_its_owner: a refused
key's owner stays alive after the caller lets it go, the refusal is asked
once, and a made key keeps its owner too (red with the owner kept only when
made).
What was wrong: with the staging table's lock let go during a make
(texture/table.rs get_or_make), forget() in the title texture's release
(resource.rs Resource::drop, texture.rs:1512) no longer waited for a
make of that texture's state. The release could end and free the
resource while new_staging still read it, and staging()'s `still`
(texture.rs:3662), asked when a take-out came during the make, then
called made_copy on the freed resource. Before the change the release
waited on the lock that the make held. Also, every test went through
the generic helpers only: nothing checked that staging() passes the
switch, or that `still` compares the host copy's serial.

What changes: the table's Gone (was a bare count) also lists the keys
being made with the lock let go. get_or_make notes its key under the
table's lock at the look and lets go of it when it returns, `still`
included. take_out with `release` (forget) waits after the lock until
no make of its key is under way. The texture's host copy is taken
before forget, so the make's `still` finds none and nothing is put in.
unstage does not wait: its callers hold the host side that `still`
locks. A release with the switch off first waits for a make begun with
it on (LEONIDA_AB); in steady state that wait finds nothing. Only a
release of the same texture waits, as before; recording threads never
do. The `still` comment now says what it covers. A test-only hook runs
at the start of staging()'s make.

Switch: LEONIDA_STAGING_SHORT (crate::toggled!, on); =0 makes and lets
go of everything under the lock, as before.

Tests: texture::table::tests::a_release_waits_for_the_make_of_its_key_only
checks that a release of a key being made returns only after the make
and puts nothing in, while another key's release and an unstage-like
take-out return at once. It fails with the wait removed.
texture::staging_table_tests::a_state_is_made_with_the_table_free_and_kept_only_for_its_copy
goes through staging() on the host. While one texture's state is made,
another thread finds another texture's. When the host copy is replaced
by one with more levels during the make, no state is put in and none
comes back. It fails with staging() passing `false` (the other look
waits) and with `still` always true. The texture tests pass with the
switch on and off.
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-30 10:47 UTC · original

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.

**@⁠adrianmjim** on GitHub · 2026-11-30 10:47 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7276088274) ### Seventh round in `d3d12/` (pushed at `8164b315d`) Claimed in [#2570](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/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.
What was wrong: stacks::frames_of (LEONIDA_PROFILE, LEONIDA_STACKS)
handed each frame of a suspended thread to RtlVirtualUnwind as it found
it. The system unwinder believes the unwind data and the registers: with
a frame register it sets rsp from that register and reads the saved
registers and the return address there, an epilogue that restores rsp
from the frame register is emulated the same way, and none of these
reads is checked against the stack. unwind_into only checked the
incoming rsp. A thread suspended where its registers do not match its
unwind data (a return address taken from a stale stack slot by the leaf
rule, code that keeps a counter in the frame register, an epilogue the
unwinder does not recognise and unwinds as a prologue) had the unwinder
read a small odd number as a stack address, and the access violation in
the sampling thread ended the process.

What changes: unwind_into takes an optional check, asked before each
RtlVirtualUnwind with the context, the image base and the function table
entry; false ends the walk with the frames found so far. frames_of passes
stacks::unwind_check::Check, which replays on a copy of the registers what
the unwinder will read for that frame. The entry, its unwind info and the
chained entries must be in committed readable memory (VirtualQuery, its
regions remembered for the walk), of version 1 or 2, with known codes and
a chain no deeper than 16. The code bytes at rip are read, when readable,
to tell an epilogue as the unwinder does (add rsp or lea rsp from the
frame register, pops, then ret or a jump; both ways when it is a jump).
The epilogue's pops and return, or the prologue codes reached at rip
through the chain (pushes, allocations, the frame register, the saved
integer and xmm slots, the machine frame) and the return address, must be
inside the thread's stack. The check allocates nothing and takes no lock.
The crash handler's own walk passes no check and is unchanged.

Tests: stacks::tests::walks_stop_where_a_wrong_function_table_would_fault
registers a hand-written function table with RtlAddFunctionTable for code
that puts 0x8001 in rbp, its frame register, and walks a thread waiting in
it 200 times through frames_of, in a child process per case: waiting in
the body, waiting in a callee that returns to `lea rsp, [rbp]; pop rbp;
ret`, unwind info on a page that cannot be read, and an unknown unwind
code. Each walk must end at the expected frames. With frames_of passing
no check, all four children die with 0xc0000005.
stacks::tests::the_check_keeps_every_frame_of_a_sound_stack walks this
thread's stack with and without the check and gets the same frames.
What was wrong: stacks::unwind_check::Check told an epilogue by its bytes
more widely than RtlVirtualUnwind does, and where it found one it checked
only the epilogue's reads. The unwinder then took the prologue path,
which reads at the frame register, and a walk the check had passed could
still fault the sampling thread.
- Version 2 unwind info: the unwinder finds epilogues from its own epilog
  codes. Where none covers rip it unwinds through the prologue even at a
  `ret` or `pop; ret`. The check returned at the byte epilogue.
- Prefixes: the check took any REX.W prefix (0x48-0x4f) before `add rsp`
  and `lea rsp`, and any REX prefix (0x40-0x4f) before a trailing `ff /4`
  jump. The unwinder takes exactly 0x48 for `add rsp`, 0x48/0x49 for
  `lea rsp` and 0x48-0x4f for the jump. So `add r12, 8; ret`,
  `lea r12, [rbp]` and `jmp r11` read as epilogues to the check only.
- `jmp rel8/rel32` after the pops: the unwinder reads the displacement to
  find the target, and the check did not check it was readable.

What changes: in version 2 a byte epilogue is checked both ways, like a
jump: the epilogue, the whole frame from rsp and the prologue path. The
prefixes match the unwinder's. The displacement of a trailing jmp must be
readable. frames_of takes the TEB stack bounds from a new stacks::stack_of,
which a test shares.

Tests: walks_stop_where_a_wrong_function_table_would_fault gains four
child cases, each a caller with 0x8001 in rbp whose callee returns for it
so the code after the call never runs: `pop rbp; ret` with version 2
unwind info, `add r12, 8; pop rbp; ret`, `jmp r11`, and a sound frame
whose `pop rbp; jmp rel32` ends the last readable page. Before this change
all four children died with 0xc0000005; they now end at the expected
frames. unwind_check::tests checks the prefixes of each epilogue form
(lea r12 among them, which the child cases cannot tell apart since the
epilogue path already reads rbp) and that a jump at the end of committed
memory is refused. the_check_keeps_every_frame_of_other_threads suspends
four threads (recursive Rust code that allocates and formats, sleep,
allocation and yield, file system calls) 250 times each and walks every
sample with and without the check under one suspension, as the profile
does: the frames must be the same. It passes in debug and release.
What was wrong: stacks::frames_of (LEONIDA_PROFILE, LEONIDA_STACKS) kept
a sampled thread's stack walk from faulting by replaying, before each
RtlVirtualUnwind, every read the unwinder would make (stacks::unwind_check).
The replay has to follow the unwinder's rules exactly to be safe, and a
review already found three places where it did not.

What changes: ntdll's RtlVirtualUnwind2 (exported from Windows 10 build
20348 and in Windows 11; windows-sys does not declare it) is
RtlVirtualUnwind with LowLimit/HighLimit pointers. As read from ntdll's
code: it checks every stack read against [low, high - 8] ([low, high - 16]
for a saved xmm register): the saved registers, rsp taken from the frame
register, an epilogue's pops, the return address; and returns
STATUS_BAD_STACK instead of reading. With a null MachineFrameUnwound it
tells epilogues at every frame as RtlVirtualUnwind does, and UnwindFlags
must be 0. stacks::Unwinder looks it up with GetProcAddress once, as the
stacks and profile threads start (never while a thread is suspended: the
lookup may take the loader lock), and frames_of passes it the thread's
TEB stack bounds; a failing status ends the walk with the frames so far.
Where ntdll has no such export, the walk keeps RtlVirtualUnwind after the
whole replay. unwind_into takes a step that unwinds the frame itself in
place of the check asked before; the crash handler's own walk passes none
and still calls RtlVirtualUnwind.

What RtlVirtualUnwind2 does not bound is still checked first
(unwind_check::Check::tables): the function table entry, the unwind info
and its chain (readable, known codes, no deeper than 16) and the code
bytes at rip it reads to tell an epilogue, a jump's displacement included.
Without that, through RtlVirtualUnwind2, the child case with unreadable
unwind info and the one whose jump displacement is on an unreadable page
die with 0xc0000005, and the one with an unknown unwind code gets a wrong
frame. Entries of loaded images keep those in readable image sections,
but a function table registered at run time (RtlAddFunctionTable, as the
tests do) puts them anywhere, and the check costs a few VirtualQuery calls
per walk and no replay of the stack.

Tests: walks_stop_where_a_wrong_function_table_would_fault runs each of
its eight child cases twice, with RtlVirtualUnwind2 and with the replay.
With the RtlVirtualUnwind2 path calling plain RtlVirtualUnwind instead,
the frame, epilogue, v2, add and jmp children die with 0xc0000005 (the
test fails at the first); the info, code and jump children still pass
through Check::tables. The tests comparing walks of this thread and of
four suspended threads (250 samples each) now walk each sample plainly,
with the replay and with RtlVirtualUnwind2 under one suspension, and the
frames must be the same. cargo test -p leonida-loader with and without
--features diagnostics, and the stacks tests in release.
What was wrong: at `pops; jmp rel8/rel32` the system unwinder works out
where the jump goes and, outside the function, looks up the function
table entry there and reads its unwind info and chain to tell whether the
jump leaves the function. unwind_check read only the displacement, so a
run-time function table whose target entry has its unwind info on an
unreadable page faulted the walk on both paths (RtlVirtualUnwind2 after
Check::tables, and the replay before RtlVirtualUnwind).
And each walk started with no readable region known: Check::tables asked
VirtualQuery about 16 times per walk (the .pdata, .xdata and code regions
of every module on the stack, again at a lower page of a region already
seen), about 28 us per walk against 1 us for the plain walk, all of it
with the sampled thread suspended.

What changes: Check::epilogue resolves a jump's target with
RtlLookupFunctionEntry (the walk already calls it at every frame) and
checks that entry, its unwind info and its chain as it does the frame's
own; the target is looked up wherever it is, since which bounds the
unwinder compares with is not checked here.
Readable regions of loaded images (MEM_IMAGE) are kept in
unwind_check::Images, owned by the Unwinder of the thread that walks, from
one walk to the next. The loader's notice (LdrRegisterDllNotification,
asked once before any thread is suspended) counts unloads, and a walk
that sees the count moved forgets them all; without the notice they last
one walk as before. Other regions (run-time tables) are still asked about
in every walk. A region found again at a lower page widens the one known
instead of taking another slot. Unwinder is no longer Copy: frames_of
takes it by reference.

Tests: walks_stop_where_a_wrong_function_table_would_fault has two more
child cases, tail and tail8, a sound frame at `pop rbp; jmp` (rel32 and
rel8) to another registered entry whose unwind info is on the unreadable
page; before the change the child dies with 0xc0000005 (replay first).
a_warm_walk_asks_the_system_nothing walks this thread twice with the same
Unwinder and the second walk must make no VirtualQuery call, with the
replay and with RtlVirtualUnwind2 (12 calls when the regions are forgotten
at every walk). the_loader_tells_of_an_unload_before_it_unmaps_the_image
loads and frees a system module and checks that its unload notice comes
while the image is still mapped and moves the count.
Measured in release with the four worker threads of
the_check_keeps_every_frame_of_other_threads, 3000 samples each, every
sample walked five ways in rotated order under one suspension (14.9
frames a walk): plain RtlVirtualUnwind 1.0 us, RtlVirtualUnwind2 with the
kept regions 2.3 us and the replay with them 2.5 us, both with 0 queries;
regions forgotten at every walk 28 us and 16.1 queries; the same frames
from all five in all 12000 samples. cargo test -p leonida-loader with and
without --features diagnostics, the stacks tests in release, cargo check
--workspace --all-targets.
smooth::hold (smooth.rs:82) slept the presenting thread to 0.9 of the
recent mean interval whatever stood behind the present. With submissions
sent by a thread of ours, the present is sent by that thread (present.rs:924,
from queue/behind.rs Job::Present), the one that prepares and sends every
submission: the hold stopped the next frame's submissions too, the card
idled while it slept and the title's thread waiting on one of our fences
waited that much longer. In two traces standing, the host's present, nearly
all of it the hold, took that thread 3.6 and 2.1 ms a frame (longest 11.5 ms)
with the next frame queued behind it.

hold takes whether work waits; present.rs passes queue::queued() > 1 (the
count includes the present itself, and is 0 without the thread). With work
waiting the present is sent at once; otherwise it is held as before, and
presented() still feeds the mean every present. Diagnostics builds count
held presents and those not held for the line with what they would have
slept, printed with the frame-rate line, for the A/B against the evenness
of presents (frame generation) the hold was measured for.

Switch: LEONIDA_SMOOTH_YIELD (on; =0 holds whether or not work waits, as
before; LEONIDA_AB may name it). Documented in smooth.rs and README-fxceless.

Test: smooth::tests::a_present_with_submissions_behind_it_is_not_held
(hold_for_line: no hold with work waiting and the switch on; 13 ms without
work waiting or with the switch off); fails with the line ignored.
The thread that lands flights and sets every title fence (leonida-relay)
was only kept on the fast cores (host.rs:4780, relay_worker), which asks
nothing of a processor with one kind of cores, and ran at normal among
some twenty busy title threads on twelve logical processors; no
SetThreadPriority was made for it, where the submitting thread
(queue/behind.rs:822) and the helpers of land, wide and the heap
records (cores.rs Priority) run above normal. The title's busiest thread
spins on such a fence's value (mwaitx, then Sleep, on the address the
fence's gpu_address gave it), so every moment from the card's end of a
flight to fence::set is the frame's. In two timelines in the world the
relay's landings had gaps of 3 to 5 ms with no wait and no wake in them,
and the tails of its gathers, fetches' sends and wakes came to 0.8 to
3.3 ms a frame; 894 of its 975 profile samples were waits, so the tails
were its turn to run, not its work.

cores::Priority now follows a switch it is given (Priority::following;
Priority::new keeps LEONIDA_HELPER_PRIORITY), and relay_worker starts
with relay_thread_setup(): the fast cores, and a Priority that follows
cores::relay_raised (LEONIDA_RELAY_PRIORITY, on unless 0, which leaves
the relay at normal as before; LEONIDA_AB can flip it, kept at the top
of each turn of the relay's loop). Above normal only: the pools of land
it hands pieces to run there too. Nothing the relay does, nor its order,
changes: every merge, read-back and write behind a flight still comes
before the fence is set.

Tests: cores::tests::a_priority_follows_its_switch (above normal while
on, normal while off, asked of the system only when the switch changes;
fails when keep() reads the helpers' switch) and
cores::tests::the_relay_runs_above_normal (fails with the relay's start
as before, at normal). Documented under 'Speed and memory' in
docs/README-fxceless.md.
A host list makes its prelude (an allocator and a closed list for the
texture moves, twin copies and uploads before it) the first time a
submission needs one: HostList::prelude in host.rs (get_or_init around
make_prelude, ~8614), called from Host::submit (host.rs:7359). Host lists
are made anew in steady play (idle ones go once a second), so the
submitting thread went on making preludes in the middle of submissions,
while the card stood idle for it: a 30 s sampling profile in play had
297 samples of it in CreateCommandAllocator (host.rs:5442), 3.8 % of the
thread, about 1.9 ms a frame.

host/preludes.rs keeps 16 made ahead by a thread `leonida-preludes`
(Ready<T>: a vector under a lock and a condvar; the thread makes outside
the lock and is woken when fewer than half are left or one was missed).
HostList::prelude takes one of them; with none ready it makes its own
where it is, as before. The prelude is still reset and recorded only at
a submission under its allocator's lock, and its age for
LEONIDA_ALLOCATOR_TRIM counts from the take. The memory line counts
preludes taken made ahead and made where they were taken.

Switch: LEONIDA_PRELUDE_POOL (on; =0 makes every prelude where it is
taken, as before), crate::toggled!, so LEONIDA_AB can name it.

Tests: host::preludes::tests (taken from the pool's thread, made here
only when none are ready, refilled after) and
texture::staging_release_tests::a_list_s_prelude_is_made_ahead_not_by_the_submitting_thread
(a plane's list submitted with the pool warm makes no prelude on the
submitting thread and still reads the plane its prelude uploaded; with
the old make in HostList::prelude it fails: [1, 1, 1] made there).
a_priority_follows_its_switch (cores.rs:252-254) set the thread above
normal by hand before turning the switch back on, so its last check would
pass were keep() to note the change without asking the system; only the
first apply, from none, was shown to raise a thread from normal.

The test now sets the thread back to normal by hand before the switch
turns on again, so that keep() must ask for above normal itself. No
change to keep() or to LEONIDA_RELAY_PRIORITY. Red with keep() skipping
SetThreadPriority on a change from off to on, green as it is.
hold's caller passed `queue::queued() > 1` (host/present.rs:928) with
nothing to say why more than one: the count includes the present being
sent, which its job takes off only after the host's present
(queue/behind.rs:721), so `> 0` would skip every hold with submissions sent
by our thread and still pass every test. The docs also said "the title's
next submissions behind it" where the count is of every queue's line (a
submission stopped at another queue's wait counts too), and did not say
that it is read once, when the hold begins: work that reaches the line
during a hold does not end it, so the hold left is the frame-rate line's
"held" figure next to "not held".

smooth::waiting(queued) is the predicate (more than one), and present.rs
passes it the count; smooth.rs, the call's comment and README-fxceless say
what is counted and when it is read. Behaviour is unchanged.

Switch: LEONIDA_SMOOTH_YIELD, as before.

Test: smooth::tests::the_present_being_sent_is_not_work_waiting_behind_it
(0 and 1 are not waiting, 2 is); fails with the predicate at `> 0`.
The memory line's "N preludes made for them" (LISTS[1], bumped in
Host::make_prelude, host.rs:5456) also counts the preludes the pool's
thread made ahead and no host list holds yet, up to READY (16), so next to
"(X taken made ahead, Y made where they were taken)" N was more than X + Y
with no leak behind it (copystat.rs:1083). The line now prints those spares
too ("Z made ahead and not taken yet", Ready::len, built in diagnostics),
and the LISTS doc says made counts them when made. Diagnostics only: no
code path changes, no switch.

texture.rs a_list_s_prelude_is_made_ahead_not_by_the_submitting_thread
returned without a word with no D3D12 device or LEONIDA_PRELUDE_POOL=0 and
showed as passed; it now prints a SKIP line saying which, as trainer.rs's
host test does.

Tests: cargo test -p leonida-gpu --lib, 788 passed / 53 ignored; with
LEONIDA_PRELUDE_POOL=0 the host test prints its SKIP line.
What was wrong: SweepRanges::spans (crates/leonida-gpu/src/draw.rs:1697 before
this change) made the spans of each stale part from its slots with a walk of
its own, self.ranges.part_ranges(p, 16): every sixteenth slot of the whole
slot vector, 24 bytes a slot and so a load 384 bytes apart, for each stale
part. With many parts stale the slots were walked that many times over at a
stride that stalls on each load once they are out of the caches. A sampling
profile of the title's world put 729 of the 2,717 samples of the thread that
records the list ahead of each frame, between the present and the first
submission, on the one load of that walk, while the submitting thread waited
for that list 5 to 7 ms a frame.

What changes: with two parts or more stale (ONE_WALK_FROM), their spans and
view counts are cleared and made again in one walk over the slots, front to
back, 4,096 slots at a time (ONE_WALK_BLOCK, 96 KiB of ranges); within a
block each stale part's slots are looked at while the block is in the core's
cache, so the slots' memory is read once and each part's table is still
filled in runs. One stale part (the pass's own, forgotten) keeps its own
walk. The spans are the same: each is a copy's lowest start and highest end,
whatever the order its ranges are joined in. The frame-rate lines
(diagnostics builds) now say, in the heap pass's line, how many parts a pass
made again and in how many walks over the slots.

Switch: LEONIDA_SPANS_ONE_WALK, on by default, read through crate::toggled!
(LEONIDA_SPANS_ONE_WALK=0: a walk for each stale part, as before; LEONIDA_AB
can name it in diagnostics builds). Documented at spans_one_walk and under
'Speed and memory' in docs/README-fxceless.md.

Tests (heap_range_tests):
- spans_made_in_one_walk_are_those_of_every_slot: 72,000 slots, a third of
  them showing ranges of 4,400 copies (a seeded LCG), with 1, 2, 8 and 16
  parts left stale by set(); spans, views and each part's views equal those
  joined from every slot that shows something, with the switch forced on and
  off (a test-only thread-local override). Green before and after.
- stale_parts_are_made_again_in_one_walk: a test-only count of walks over
  the slots; 16 stale parts take 1 walk with the switch on (16 with the
  one-walk branch disabled: red, "left: 16, right: 1"), 16 with it off, and
  1 stale part 1 walk either way.
- spans_kept_by_part_are_those_of_every_slot and
  every_slot_is_looked_at_again_in_a_round unchanged and green.

Bench (spans_of_a_pass, --release --ignored, Ryzen 7 5800X, the median of 60
with the ways taken in turn, spans() as a pass asks for it, joining the
parts included; cold = 96 MiB written over before each):
- 72,000 of 1,152,000 slots showing, 8 / 16 parts stale: 1.91 / 3.26 ms a
  walk for each part, 1.42 / 1.98 ms in one walk (cold); 0.73 / 1.78 and
  0.67 / 1.24 ms warm. With 2 and 4 stale: 0.83 / 1.17 ms against 0.72 /
  0.91 ms (cold).
- every one of 72,000 slots showing (each part's table holds every copy,
  and the tables are taken in turn block by block), 16 parts stale: 1.46 ms
  a walk for each part, 1.64 ms in one walk (warm; 1.55 / 1.94 cold). With 2
  and 4 parts the two are equal (0.36 / 0.45 ms warm).
- With slots mostly showing nothing at 72,000 slots the two are within the
  bench's noise (about 0.06 ms between two runs of the same way).
A plain walk slot by slot over all of them, without blocks, was slower than
the walks of each part with 2 to 8 parts stale (up to 4.45 against 1.39 ms,
1,152,000 slots, 4 parts) and in the dense case; it is not used.
What was wrong: the note at spans_one_walk (crates/leonida-gpu/src/draw.rs:1612
before this change), the commit before it and README-fxceless.md gave the
pass's own part as the one part left stale alone that keeps its walk. It is
seldom that part: heap_buffer_pass forgets its part (draw.rs:2662 and :2752),
which clears its stale bit, and the slots it sets again into the forgotten
part join its spans in place. A part stale alone is mostly one the title
wrote to. The code was right; the reason was not. Also, the one walk was
measured slower than the walks of each part only with every slot showing
something (1.64 against 1.46 ms warm, 72,000 slots, 16 parts stale), and
nothing in the frame lines said whether the title's heap is like that.

What changes: the note and the README bullet give the right reason. The heap
pass's line in the frame-rate lines (diagnostics builds) now also says how
many slots a pass has and how many of them show something (SPAN_WALKS[3] and
[4], counted in SweepRanges::spans on both its paths), so an in-game
LEONIDA_AB naming LEONIDA_SPANS_ONE_WALK shows whether the run is the sparse
case the one walk wins in or the dense one it loses in. The threshold
(ONE_WALK_FROM) is not made to depend on the slots showing: the profile's
samples sit on the load that finds a slot showing nothing, the sparse case,
and the dense loss is to be confirmed in the game first.

Switch: LEONIDA_SPANS_ONE_WALK, unchanged (on by default; =0 a walk for each
stale part).

Tests: no behaviour changes (a note, a README bullet and two diagnostics
counts). heap_range_tests 4 passed, 1 ignored, with and without diagnostics;
cargo test -p leonida-gpu --lib 788 passed, 53 ignored; cargo check
--features diagnostics --all-targets clean; no clippy warnings in the changed
lines.
# Conflicts:
#	d3d12/docs/README-fxceless.md
Measured in the title on an RX 7900 XT (one LEONIDA_AB run, 67 phases of
7 s in the world, LEONIDA_SPANS_ONE_WALK, LEONIDA_PRELUDE_POOL,
LEONIDA_SMOOTH_YIELD and LEONIDA_RELAY_PRIORITY crossed, least squares per
switch with a time trend):
- LEONIDA_RELAY_PRIORITY: median frame +1.6 % (s.e. 1.9 %), submitting
  thread's work +1.4 % (s.e. 1.2 %), card idle +6.4 % (s.e. 6.2 %).
- LEONIDA_SMOOTH_YIELD: median frame +0.6 % (s.e. 1.9 %), p90 +2.2 %
  (s.e. 3.6 %), submitting thread's work +0.8 % (s.e. 1.2 %).
Neither gained anything, so both now need =1 (crate::asked!); LEONIDA_AB
can still name them.
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-30 14:38 UTC · original

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.

**@⁠adrianmjim** on GitHub · 2026-11-30 14:38 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7281692526) New round in this PR: `RS-SAMPLER-UNWIND-FAULT` and `RS-SUBMIT-THREAD-COST` ([claim](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570), [status](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570)). **`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.
What was wrong: the card time of our own lists outside the title's host
lists was only estimated. The timing run's table of commands is fed only
by the notes inside the title's lists (host.rs:7584, runs[i].slowest), so
the list card_before sends ahead of a submission (copies or send::Own
scatters up, one barrier call, the rehash passes; executed at
host.rs:5831) and the compare behind its lists (host.rs:5920 on) were in
no table, and the timeline's card spans begin behind the first one, which
shows as idle between submissions. With the card the frame, the in-game
A/B could not attribute them.

What changes (diagnostics builds only; release builds record nothing):
- host/owntimes.rs: a plan that records either list takes a stamp set
  from CardWork (a 5-slot timestamp heap and a read back mapped once,
  zeroed when taken; made on demand, given back by card_done like the
  sync/check lists; if none can be made, no stamps, said once).
- card_before stamps the first list at its start, before the barrier call
  that precedes the hash passes, and after the last hash pass (resolving
  slots 0..2 before Close), and the compare after its leading null UAV
  barrier, so the drain of the title's lists is not counted, and after
  its passes and landsame::record (resolving slots 3..4 at offset 24).
- card_done, after the plan's submission ran, reads them (a pair counts
  only if both stamps are there and in order), adds microseconds of sends
  up, rehash and compare and the lists measured to OWN_TIMES, and in a
  timing run gives them to copystat::command_took as "ours sends",
  "ours rehash" and "ours compare".
- The card-passes frame line (host/present.rs) ends with "on the card per
  frame: sends up X ms in N lists, rehash Y ms, compare Z ms in M lists
  (LEONIDA_CARD_OWN_TIMES)" and prints when only these are nonzero.
The submission loop, HostList::prelude and open_batch are untouched; no
wait or ordering changes (a timestamp orders nothing).

Switch: LEONIDA_CARD_OWN_TIMES (crate::toggled!, on; =0 records no
queries), documented in owntimes.rs and README-fxceless.md.

Test: host::landsame::card_tests::our_lists_are_timed_on_the_card (on
the host's card or WARP, debug layer clean): the first plan of a copy
records one hash and one compare pass between its stamps, reads all
three parts, raises the lists measured and CARD_PASSES[0]/[2]; with the
switch off no stamp is recorded or read. Fails without the change
(recorded stamps None). owntimes::tests covers which pairs count.
Every submission with a compare of its host copies in the card's memory
sent that check list in an ExecuteCommandLists call of its own after the
lists, before the signal: host.rs:7494 (sent ahead) and host.rs:7557
(waited for), since d1fe0bd01. That call was for state, not order: a title
list can leave a host copy's card buffer promoted to COPY_DEST (a copy at
its place, place.rs place_copy), buffers decay only at the end of a call,
and the compare reads them as shader resources (D3D12 error 538). Each call
more costs the RX 7900 XT 18-26 us of card time over the boundary with
everything queued, some 18 times a frame, on the fence chain the title's
thread spins on while the card is the frame.

With LEONIDA_COMPARE_JOIN=1 (crate::asked!, off by default; LEONIDA_AB
turns it by phases) host/compare_ecl.rs sends the last slice of lists, a
closed list of ours holding place::wait_for_all (one global barrier,
SYNC_ALL to SYNC_ALL, ACCESS_COMMON: every earlier access, copies' writes
too, done and seen) and then the compare with the stamps behind it in one
call; the signal follows it as before. Joined only where compare_joins
says: the switch on, enhanced barriers on the card (place.rs's probe, now
place::enhanced_barriers), and no list of that call copied into a host
copy's card buffer: HostList::copied_into_copy, a flag in Deferred that
place_copy sets and the list's reset clears, keeps exactly d1fe0bd01's
case apart. card_steps::record does not set it: it moves every buffer it
copies into back to COMMON in its list. The timing run keeps its calls.
The barrier lists come from a ring that reuses only lists whose last
submission the host fence has passed. The frame line of submissions sent
ahead counts compares sent in their lists' call and apart (for a copy, no
enhanced barriers, the switch off). Documented in README-fxceless.md.

Tests (host/compare_ecl.rs, on the card and on WARP): the truth table of
compare_joins; a list declaring writes at pieces A and B and storing at B,
sent through Host::submit with the switch on and off, flags B alone both
ways and hashes the same two pieces, and with the switch on is sent joined
(with enhanced barriers); with a copy into A as well the compare stays
apart for the copy and flags A and B; place_copy marks its list until
reset. Red without the join (counted apart) and without the flag in
place_copy. The debug layer is not installed on this PC, so the state
question of d1fe0bd01 is still to be seen in the title with it and GBV.
What was wrong: host/landsame.rs:1685 (our_lists_are_timed_on_the_card)
asserted exactly one hash pass recorded in the plan's sync list. That list
hashes every copy shadow::card_dirty() returns, which is global, and the
send.rs card tests (under their own turn lock, in parallel) make copies with
a 'before' side dirty; a plan that takes one of those records a second hash
pass and the assert would fail with [2, 1].

What changes: the test asserts at least one hash pass and exactly one compare
pass (the compare is over this plan's declared ranges only). No switch: the
change is in the test. Test: landsame, send:: and compare_join tests green on
WARP with --features diagnostics; leonida-gpu lib 794/53 and 860/53 with
diagnostics on the card.
What was wrong: open_batch (crates/leonida-gpu/src/indirect.rs:868) took each
pass's table of jobs from the list's scratch memory (HostList::scratch ->
take_chunk, host.rs:2291), which is upload memory in the PC without a
resizable BAR. The pass (indirect/batch.rs SOURCE) reads the count and then,
once it is known, its jobs: two reads across the bus, one after the other,
before it does anything. The timing run of the world scene on the RX 7900 XT
put "clamp batch" at 4.3-5.1 ms of the card's time a frame in 653 passes; a
standalone test on that card measured 4.8-5.0 us a pass against 3.4-3.5 us
with the table in the card's memory, its copy counted (0.85-1.0 ms a frame),
and the card's time is the frame now.

What changes: each scratch buffer of the batches (host.rs BATCH_SCRATCH) gets
a table area beside it, made the first time a batch in it wants one
(host/batch_tables.rs): an upload buffer the CPU fills exactly as before and
a buffer in the card's memory the pass reads, a table each 4,352 bytes. It is
pooled and given back with its scratch buffer at the list's reset, as the
scratch buffer was. Which batches read the card's copy is decided when each is
opened and kept per batch, and at close (batches_common) the list notes the
copies its prelude is to make, one per buffer with such batches, and moves
those mirrors back to COMMON with the scratch buffers. The prelude
(HostList::prelude) moves each mirror COMMON -> COPY_DEST, copies its tables
from the upload buffer, and moves it on to NON_PIXEL_SHADER_RESOURCE, in the
same ExecuteCommandLists as the list and right before it. The pass, its wait
for every earlier shader write, its scratch transitions, the table format and
the shader are unchanged, so clamp coverage is as it was. open_batch now takes
the batch's place last, after what else may fail, so a place taken is always
a batch recorded. The frame line of batch scratch buffers is followed by one
giving the passes reading each way, the copies and their KB.

Switch: LEONIDA_BATCH_TABLE_CARD (crate::toggled!, on by default; =0 reads the
tables from upload memory as before; never where the list's scratch memory is
already in the card's memory, LEONIDA_SCRATCH_CARD with a resizable BAR;
LEONIDA_AB can flip it per phase). Documented in host/batch_tables.rs and
under 'Speed and memory' in docs/README-fxceless.md.

Tests (indirect.rs, on the card and on WARP):
batches_read_their_tables_from_the_cards_memory (12 batches, two table
areas, recorded twice; with the
prelude's copy left out by a test hook the executions do not run what they
asked for), a_list_run_twice_in_one_submission_reads_its_tables_twice,
a_table_area_taken_again_holds_the_new_lists_tables (12 batches, reset, then 3)
and batches_read_their_tables_from_upload_memory_or_either (the old path, and
the two mixed in one list). With the prelude's copy removed these four fail,
and on the RX 7900 XT host_list_batches and
a_record_written_behind_a_batchs_pass_is_clamped_behind_its_writer fail too
(they take the new path there by default); all pass with it.
host/compare_ecl.rs:381 and :401 checked the open question behind
LEONIDA_COMPARE_JOIN with assert_eq!(host.log_messages(), None). Without the
debug layer (no diagnostics build, LEONIDA_D3D12_DEBUG unset, or the SDK
layers not installed, as on the RX 7900 XT machine) Host::messages is None
and log_messages returns None whatever the queue did, so the assert passed
as if the joined call had been validated clean.

The tests now go through debug_layer_says_nothing: with an info queue it
asserts no error among its messages; without one it prints that the state
was not checked instead of passing for clean. The file's notes and the
switch's bullet in README-fxceless.md say the copy flag keeps apart only
COPY_DEST: a host copy a title list wrote as unordered access (a write
state, nearly every compared buffer) is read by the joined compare in the
same call, so the run with the debug layer must judge that too before the
switch can default on, and GPU-based validation here runs without state
tracking, so states are the CPU layer's word alone.

No behaviour changes; LEONIDA_COMPARE_JOIN stays off by default. Tests:
compare_ecl::tests on the card and on WARP, with and without diagnostics
and with LEONIDA_D3D12_DEBUG=1 (no SDK layers here: they say so).
What was wrong: a_table_area_taken_again_holds_the_new_lists_tables
(crates/leonida-gpu/src/indirect.rs:4108) never checked that the second
list took the first one's scratch buffer with its table area: the table of
spare buffers (host.rs SPARE_BATCHES) is the process's, shared with the
tests running beside it, and the hits would be the same with a table area
dropped when its buffer was given back or a buffer made anew at every take.
The four tests of the tables (indirect.rs:4034-4180) asserted
host.log_messages() == None after host.execute, but every submission ends
by logging and clearing the debug layer's messages (host.rs:7709), so an
error of the submission was never seen there, while the first test's doc
said it was. Intra-doc links named HostList::batch_place, which is a test's
function now (host.rs:1470, 2102; host/batch_tables.rs:97, 121).

What changes: in tests, a thread can have a table of spare batch buffers of
its own (host::own_spare_batches, used by give_batches and
take_batch_scratch through with_spare_batches), and
HostList::batch_buffers gives a list's scratch buffers with their table
areas; the test holds the first list's buffers and asserts the second list
took the one given back last with the same mirror and upload buffer.
Host::log_messages keeps, in tests, the first error it finds on the thread,
and Host::errors_seen gives it (or what the queue holds now); the four
tests assert on that, and the doc says it checks only where the debug layer
is installed. The links name HostList::batch_place_table, whose doc is the
place's now. No switch: tests and docs only; LEONIDA_BATCH_TABLE_CARD is
unchanged.

Test: with take_batch_scratch giving back a pooled buffer without its table
area, the reuse test fails ("with its table area": other mirror and upload
buffer); as it is, it passes. leonida-gpu lib 799 passed / 53 ignored,
with diagnostics 863 / 53. The errors_seen hook could not be shown red on
this machine: its debug layer is not installed.
# Conflicts:
#	d3d12/docs/README-fxceless.md
In a LEONIDA_AB run in the world on an RX 7900 XT, the stamps and their
read-backs cost +2.8 % on the frame median and +2.2 % on the submitting
thread (s.e. 1.9 % and 1.2 %), so they no longer shift other measurements
by default. The README gives what they measured there and what the batch
table and compare-join switches did in the same run.
The clamps of indirect arguments take 4.2-4.7 ms of the card a frame and our
lists over card copies about 1.9 ms, of some 35 ms; the rest is the title's
translated shaders. Batch tables in card memory take 0.5 ms off the clamps
and stay on; the compare in its lists' call stays off until the debug layer
has judged it; none of the three moves the frame beyond the noise.
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-30 16:37 UTC · original

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.

**@⁠adrianmjim** on GitHub · 2026-11-30 16:37 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7284960967) New round in this PR: `RS-CARD-OWN-WORK` ([claim](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570)). 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.
Author
Owner

@⁠KelboLive on GitHub · 2026-11-30 17:33 UTC · original

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

**@⁠KelboLive** on GitHub · 2026-11-30 17:33 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7286496809) 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).
What was wrong: the_pass_looks_only_at_slots_written_since_the_look_ahead
(crates/leonida-gpu/src/draw.rs) read the process's frame (frame.rs FRAME)
once and gave it to the look and the pass, but had a draw's table take
slots 7 and 4 with HostHeap::slot_tabled, which stamps the frame of that
moment. The tests beside it begin frames of the same process: the frame
waits' test (frame::tests::waits_end_on_ticks_and_count_frames, through
frame::wait) and five resource tests (frame::test_advance). A frame begun
between the test's read and the stamp left slot 7 no table's at the test's
frame (HostHeap::copied_tabled), so the look ahead looked at it too: 9
slots for 8. It failed once in three runs of the lib tests with
diagnostics, and never alone.

What changes: in tests, HostHeap::slot_tabled_in has a table take a slot
in a given frame; the test takes slots 7 and 4 in its own frame. Tests
only: the runtime is unchanged.

Test: with one frame begun right after the test reads its frame, it failed
every time (left 9, right 8); with the change it passes with 20 frames
begun there and 20 more before slot 4 is taken. The draw, drops, dxgi,
fence, fg and frame tests together, 8 threads, where the frame waits' test
is the only one that begins frames: 24 of 40 runs failed before, each with
the frame one further at the look than when the test read it; 0 of 40
after. The whole lib suite with diagnostics, 8 threads: the test failed in
1 of 12 runs before, 0 of 12 after (other tests failed there, as before).
leonida-gpu lib 803 passed / 53 ignored, with diagnostics 869 / 53, 4
threads, RX 7900 XT.
What was wrong: landsame::on() (host/landsame.rs:71-78) read the variable
once into a OnceLock, so LEONIDA_AB could not weigh it in the same scene as
everything else, and it was asked separately where a plan's capture passes
are chosen (host.rs:5984), where the notes of sends are let go at a landing
(host.rs:6313, landsame::forgotten(..., landsame::on())), where a fetch is
noted as maybe newer than later captures (host.rs:6485) and for the frame
line (host/present.rs:423). Made flippable as it was, a flip between a
plan's making and its landing would let go the notes of sends a capture
still in the air is merged against (its older bytes then go over title
bytes that went up after it), or leave a fetch unnoted that is newer than a
capture in the air (that capture then goes over the fetch's later shader
bytes).

What changes: the switch is read through crate::asked! (off by default, =1
on, LEONIDA_AB flips it per phase in diagnostics builds) once per plan, in
Host::card_before right after its send is numbered, and kept in the plan
(landsame::Capturing); the capture passes follow it. What a landing keeps
for later captures, the notes of sends and the fetches noted as maybe
newer, is kept while any plan alive was made to capture
(landsame::capturing, counted under the order of the queue before the
plan's send number can be seen by a fetch), not by the switch at the
landing. The frame line is taken every period and also counts the plans of
the relay landed that were made to capture and those made to fetch. The
README's bullet says so, with the first game run's numbers.

Switch: LEONIDA_LAND_IN_SUBMISSION=1 (off by default), flippable with
LEONIDA_AB.

Tests (on the host's card, host/landsame.rs card_tests):
flights_made_on_and_off_in_turn_land_every_byte (flights made on, off, on,
off; a title write after their sends; the second's fetch newer than the
third's capture) and a_flip_after_a_plan_is_made_changes_nothing_it_does.
Both fail with the global switch read at the landing again (the third
capture merged over the later fetch, the title's bytes lost) and pass with
the plan's own decision.
What was wrong: inplace.rs:35 said tile mappings into a heap opened on
memory the process has remove the device, measured only on the software
adapter, and nothing said whether the asks turned down as view memory
not one run of a committed section (inplace.rs place_for, kept_from; 1,838
in a title run with LEONIDA_INPLACE=1 LEONIDA_SECTION_COMMIT=1) could be
held by a reserved buffer whose tiles follow the title's scattered pages.

What changes: inplace/tiled.rs. With LEONIDA_INPLACE_PROBE=1, after the
in-place probe, a probe on a device of its own (ID3D12DeviceFactory, not
kept as the process's device, so a refusal removes only that one; not
run where the factory makes none): scattered tiles, two on one page, on a
heap of ours and on a committed section opened as a heap; the card's
reads of the CPU's writes, a shader's reads and unordered-access writes,
a remap, an unmap; UpdateTileMappings of 1, 64 and 1024 tiles (CPU time
and time to a fence) and the card's reads through tiles, a placed buffer
and an upload buffer; after a loss, one tile on heaps that differ in one
thing says which part is refused; a VERDICT line.
LEONIDA_INPLACE_PROBE_TILES=0 leaves it out. On the RX 7900 XT (tier 4)
and the software adapter: the mapping onto any opened heap removes the
device (DXGI_ERROR_INVALID_CALL), as onto a heap of ours made shared and
cross-adapter, while shared alone takes it: Direct3D takes no tiles in a
cross-adapter heap, which every opened heap is. Everything holds on a
heap of ours; 1/64/1024 tiles a range each cost 19/23/2,021 us of CPU and
0.2/1.1/20 ms to a fence; reads through tiles as fast as placed.

In diagnostics builds, with LEONIDA_INPLACE on, a line every ten seconds
beside the in-place line counts those asks by what tiles could make of
them (every page in a view of a committed section; a reserved section;
holes; views off the 64 KiB lines), their pages and sections, and the
title's mappings and unmappings over those still alive. Only counted, no
switch: a walk over the views of each such ask, a relaxed load per
mapping while none is alive, the list of copies every ten seconds.

Tests: card_tiles_over_a_committed_section (ignored, on the card),
warp_tiles_probe_on_a_device_of_its_own, and the census's classification
and counts on synthetic view layouts (red with the reserved-section check,
the overlap test or the cross-adapter reading taken out).
What was wrong: inplace/tiled.rs:62-65 ran the tiles probe with every
LEONIDA_INPLACE_PROBE=1 (LEONIDA_INPLACE_PROBE_TILES on unless 0), though
it removes devices on the title's adapter on purpose (four on the RX 7900
XT) and the only test that the title's device survives it was on the
software adapter: card_tiles_over_a_committed_section (tiled.rs:1281)
probed with no other device on the card. The census of tiles began with
since = 0 (tiled.rs:1107, Census::default), the process's start, so its
first line divided the mappings counted by the whole uptime (begun at 95 s,
a line at 100 s: rates 20 times too low). And no test covered the census's
hooks in inplace.rs (place_for's turn-down, title_memory_view, views_gone).

What changes: LEONIDA_INPLACE_PROBE_TILES=1 asks for the tiles probe (off by
default; documented in tiled.rs and under 'Speed and memory'). The card
test makes a device as the host makes the title's (D3D12CreateDevice),
probes beside it, and asserts that it reports no removal and that a copy
and a fence on it complete; on the RX 7900 XT it does after the probe's four
removals. The WARP test checks the copy too. Census::starting(now) begins
the census at its first ask.

Tests: card_tiles_over_a_committed_section (ignored; fails when the probe
runs on the title's device), the_tiles_probe_runs_only_when_asked_for,
the_first_lines_rates_are_over_the_census_own_time, and
scattered_pages_of_a_committed_section_turned_down_are_counted_as_tiles
(diagnostics: place_for over scattered single pages of a committed section
is counted as tiles could hold, a views_gone under it as unmapped and a
title_memory_view as mapped; fails with any of those hooks removed or the
flags swapped).
None of the in-place paths faulted and none moved the frame. Title GPU
memory is scattered 64 KiB pages of the page pool, which no placed buffer
can show and no tiled buffer may map on Windows. Landing in the
submission stays off after LEONIDA_AB weighed it. Private memory is flat;
card memory counts in it, so only removing duplicates saves commit. A
finer window grid saves 1.3 GB but stays off until overlapping windows
are safe for shader writes. The up-copy check shows shader writes through
undeclared views in about nine title buffers.
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-30 18:44 UTC · original

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.

**@⁠adrianmjim** on GitHub · 2026-11-30 18:44 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7288284592) New round in this PR: `RS-ZERO-COPY-IN-TITLE` ([claim](https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570)). 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.
# Conflicts:
#	d3d12/crates/leonida-gpu/src/draw.rs
#	d3d12/crates/leonida-gpu/src/host.rs
#	d3d12/crates/leonida-gpu/src/pipeline.rs
#	d3d12/crates/leonida-gpu/src/resource.rs
#	d3d12/crates/leonida-gpu/src/texture.rs
#	d3d12/crates/leonida-hle/src/modules/apu.rs
#	d3d12/crates/leonida-hle/src/modules/xmem.rs
#	d3d12/docs/findings.md
#	docs/d3d12_vulkan.md
#	runtime/CMakeLists.txt
#	runtime/README.md
#	runtime/shims/d3d12_com.cpp
#	runtime/shims/d3d12_com.h
#	runtime/shims/d3d12_geometry_views.h
#	runtime/shims/d3d12_vulkan_device.cpp
#	runtime/shims/xmem.cpp
#	runtime/src/command_list.h
#	runtime/src/console_heap_slot_records.h
#	runtime/src/pipeline_cache_store.h
#	runtime/src/title_texture_refresh.h
#	runtime/src/vulkan_backend.h
#	runtime/test/console_heap_slot_records_test.cpp
#	runtime/test/d3d12_existing_heap_test.cpp
#	runtime/test/geometry_views_test.cpp
#	runtime/test/pipeline_cache_store_test.cpp
The doc of evict_placed still said a texture's stamp is set under the
table's lock held there, so that no thread can find it between the look and
its leaving the table. Since the tables in front (placed_shards) that is
not true: texture_at stamps under the shared lock of the shard only.

The doc now says the stamp is set under the lock of the table or under the
shared lock of the table in front, and that a texture that would go is
first taken out of the table in front under its write lock and its stamp
looked at again, so no thread still holds it once it has left.

The recheck had no test: the one that releases a texture from the tables in
front calls evict_placed with no idle time, which every stamp passes, so
the recheck could be deleted with every test green. A test-only hook, run
on the calling thread between the removal from the table in front and the
second look, now stamps one of two idle textures there; the test asserts
that one stays (still in the table, the same resource handed out again) and
the other is released. With the recheck replaced by `goes = true` the test
fails.
The up-copy check (LEONIDA_UPCOPY_CHECK=1) says where a copy's card side
holds what its CPU side does not, at a send or at rest, but not what put
it there: in the world scene it names the same ranges at every check, and
the labels it gives ("no shader was declared to write the buffer",
"declared; ...") are the union of all declarations ever made for the copy,
not what the submission that wrote the bytes declared. The causes weighed
since (shader writes kept on the card and undone by sends, a title rewrite
a shader then changes in place, a copy at its place, a write nobody
declared, the CPU side moving under an unchanged card) cannot be told
apart from those lines.

With LEONIDA_UNDECLARED_TRACE=1 (diagnostics builds, read through
crate::asked!, with LEONIDA_UPCOPY_CHECK=1; off by default), a copy either
look of the check flags in two frames is watched (256 KiB from the piece
flagged, 16 copies at most). Every submission from then on gets a pass of
ours ahead of its lists (behind its sends, in a call of its own) and one
behind them (first in its compare's call), comparing the watched bytes on
the card with a snapshot the card keeps and taking it anew; so the
submission that changed them, and whether its lists or its sends did, is
known exactly, with the span and one word before and after. While lists
are recorded and something is watched, each keeps what it told of watched
copies: every Shadow::gpu_writes over them with its bind, the line that
called it and what became of it (declared, kept on the card by
LEONIDA_WC_NO_BACK, elided, less GPU read-only parts), and every bind of a
program that stores past what its bind declared, with the reason
crate::draw already gives for indirect batches. A change by the lists is
logged with those writers, views picked from the heap for the copy, CPU
copies, bottom-of-pipe writes and read-backs into the bytes, and whether
what changed lies in a declared write at all; a change by the sends says
whether it undoes words an earlier submission's lists changed; a copy
flagged again while its watched bytes never moved on the card is said
once. At most two passes over 4 MiB a submission, 24 lines a copy, then
sums. Builds without diagnostics are unchanged, and with it nothing is
recorded until a copy is watched.

The code is host/undeclared.rs, with one-line hooks in Host::submit, the
two looks of host/upcheck.rs, Shadow::gpu_writes and State::bind. Tests on
the card: a dispatch storing through a view its bind did not declare is
traced to its submission and bind (not to a declaration outside the
window; a declaration inside it is named by its line), and the next
submission's send undoing it is traced too; the look at rest and the look
at a send each have a copy watched after two frames; a declaration over
GPU read-only memory is noted with what became of it; off, nothing is
watched, noted or looked at. Each fails with the hook it covers taken
out; the call in State::bind (it needs a translated pipeline) and the
notes of declarations kept on the card or elided (switches read once a
process) have no test of their own. The README's diagnostics list has the
switch.
The trace LEONIDA_UNDECLARED_TRACE=1 gives (with LEONIDA_UPCOPY_CHECK=1,
diagnostics builds, off by default) could give a false verdict in the world
scene, which is where it is meant to separate the causes findings.md
weighs:

- the notes of binds whose programs store past their views shared one list
  of 1024 notes per list with the declarations into watched copies, one
  note per bind: thousands of binds a frame pushed the declaration that
  tells "kept on the card (LEONIDA_WC_NO_BACK)" out of the eight a line
  names, or out of the notes altogether, and the line then said "what
  changed lies in no write it declared", the very sign of a write nobody
  declared; the text was built for all 16 watches at every submission;
- "over words the lists of submission M changed" was a test of overlapping
  spans: a shader writing words all over the window made any send in it
  look like one undoing the shader;
- with the switch turned off and on (LEONIDA_AB), the first look compared
  with a snapshot from before the gap, and laid everything the lists did
  meanwhile on that one submission's sends;
- title copies done on the CPU, bottom-of-pipe writes and read-backs were
  said with changes by the lists, which none of them can make.

Now a list keeps the declarations into watched copies apart (1024, and how
many more were not kept, which the verdict then says) and counts the binds
that store past their views per program and reason. A line names the
declarations in the window first, then the programs with their counts,
deduplicated by a map, and what the lists told is gathered in one walk for
the copies with lines left only. Beside the snapshot the card keeps, per
watched word, the submission whose lists last changed it: the look behind
the lists sets it, the look ahead of them counts the changed words that
carry one and clears them, so a change by the sends says "N of the W words
were last changed by the lists of submission M" with one such word, or
"none of them". A submission that was not looked at (its number is not the
one after the last asked) has the snapshots taken anew. Title copies into
the bytes are said with the change ahead of the lists (they go up with the
submission's own sends), and the last submission whose lists wrote values
there at the bottom of the pipe or read texels back is named there too.
Step::Fill only reads title memory into the list's upload memory and is
not a candidate. The module doc and the README bullet say what does and
does not tell a title rewriting records in place from shader writes
undone by sends: refreshes and changes in turns come with both.

Tests on the card: more than 1024 binds of ten programs storing past their
views ahead of a declaration in the window, and the line names the
declaration first and says what changed lies in it; a send between two
stores of the lists is said over none of their words; a submission run
with the trace off lays its change on no other; title copies are told
with the sends, not the lists. The first two fail on the trace as it
was, the last two with the gap check or the copies' place reverted. The
test switch is now one for every thread (the tests that set it take the
card's turn), so that submissions of other tests are looked at as well.
LEONIDA_UNDECLARED_WATCH names title addresses whose copies are watched
from the first look at rest, flagged or not, so that a run with
LEONIDA_WC_NO_BACK=0 (where the check finds nothing there) still tells
what changes those bytes.

findings.md: the up-copy check's sends-over-card lines come from its look
at a send and are nonzero in the world; with the launcher's
LEONIDA_WC_NO_BACK=1 the sends reset two buffers that a compute pass keeps
from frame to frame, while the rings flagged next to them are the title's
own rewrites.
Author
Owner

@⁠adrianmjim on GitHub · 2026-11-30 21:30 UTC · original

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

**@⁠adrianmjim** on GitHub · 2026-11-30 21:30 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7292513666) ### 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".
github-bot closed this pull request 2026-12-01 11:43:31 +00:00
Author
Owner

@⁠enlight3d on GitHub · 2026-12-01 14:38 UTC · original

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

**@⁠enlight3d** on GitHub · 2026-12-01 14:38 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/2569#issuecomment-7314586823) @⁠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

This discussion has been locked. Commenting is limited to contributors.
No reviewers
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.

Dependencies

No dependencies set

Reference
github/ubiquitarianism--leonida!2569
No description provided.