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
pull from: github-bot/gh-2569
merge into: github:main
github:main
github:perf/darner-title-priority-ceiling
github:gh-readonly-queue/main/pr-3311-b5c45b663dbc5a9c3532bb3f307e5f81b32faefa
github:gh-readonly-queue/main/pr-3088-af22e7847ff5808f72d1a1881c24be2fafd20b54
github:gh-readonly-queue/main/pr-3123-7f3fa026a94c6646e89244f28e1ce22290361867
github:gh-readonly-queue/main/pr-3354-637baa0b77ba47222e7280b17c1a59c6a1781d57
github:gh-readonly-queue/main/pr-3365-d7a0e0196a43834813014b4bd3aa5502a8263b14
github:gh-readonly-queue/main/pr-3361-5dfe8bbd05ed12fb2f2e1718d9af77a7c5f46fd8
github:gh-readonly-queue/main/pr-3366-8da9148204e9d12c585efa9ac2b7cc1ab08c7682
github:fix/runtime-test-conservative-fixtures
github:ci/shard-semantic-linux
github:docs/fg-limit-fps-switch
github:fix/runtime-test-fixture-paths
github:fix/runtime-test-fixture-readers
github:fix/read-file-hard-link
github:fix/book-slot-heap-never-read
github:fix/depth-resolve-spv-path
github:fix/indirect-unused-batched
github:gh-pr/3358/base
github:fix/xmem-refusal-diagnostics
github:gh-pr/3357/base
github:ci/shorten-ci-time
github:fix/alias-later-queued-submissions
github:claude/gallant-sagan-aamatr
github:gh-pr/3342/base
github:gh-pr/3341/base
github:d3d12/agility-sdk-621
github:gh-pr/3293/base
github:gh-pr/3319/base
github:gh-pr/3318/base
github:gh-pr/3315/base
github:gh-pr/3313/base
github:gh-pr/3314/base
github:claude/fervent-curie-m19lnr
github:gh-pr/3216/base
github:gh-pr/3272/base
github:gh-pr/3276/base
github:gh-pr/3279/base
github:gh-pr/3257/base
github:gh-pr/3258/base
github:gh-pr/3271/base
github:codex/skip-no-hit-ray-passes
github:gh-pr/3230/base
github:gh-pr/3266/base
github:gh-pr/3247/base
github:gh-pr/3246/base
github:gh-pr/3244/base
github:claude/sharp-sagan-1jqnp3
github:t3/preserve-fsr-sdk-restart-path
github:t3/propagate-host-failure-hresult
github:t3/launcher-custom-parameters
github:t3/series-x-2160-startup
github:codex/d3d12-uncapped-simulation
github:ci/less-to-run
github:perf/native-compute-shader-forms
github:claude/blissful-franklin-ukp7ag
github:codex/full-precompile-default
github:gh-pr/3166/base
github:gh-pr/3148/base
github:gh-pr/3138/base
github:gh-pr/3106/base
github:gh-pr/3057/base
github:gh-pr/2756/base
github:gh-pr/2812/base
github:gh-pr/3032/base
github:gh-pr/2992/base
github:notes/card-time-and-plant-flicker
github:gh-pr/2986/base
github:gh-pr/3000/base
github:gh-pr/2966/base
github:gh-pr/2924/base
github:gh-pr/726/base
github:gh-pr/2761/base
github:gh-pr/2663/base
github:gh-pr/2861/base
github:gh-pr/2862/base
github:gh-pr/2820/base
github:gh-pr/2811/base
github:gh-pr/2803/base
github:rt-call-trace
github:gh-pr/2802/base
github:gh-pr/2766/base
github:perf/ahead-split
github:gh-pr/2589/base
github:gh-pr/2699/base
github:gh-pr/2696/base
github:docs/readme-runtime-proposal
github:gh-pr/1346/base
github:codex/coord-claim-check-20261124-7e48
No reviewers
Labels
Clear labels
accessibility
Barrier affecting people with disabilities
area: ci
.github/ workflows and settings
area: d3d12
The D3D12 runtime in d3d12/ (Rust: leonida.exe and its crates)
area: docs
Documentation
area: launcher
The launcher (launcher/)
area: runtime (legacy)
The earlier Vulkan runtime in runtime/
area: shader translator
The shader translator (leonida-shader, tools/rdna2spirv) and its tests
area: tools
tools/ and scripts/
area: viewer
The map viewer (viewer/)
bug
Something isn't working
dependencies
Pull requests that update a dependency file
documentation
Improvements or additions to documentation
duplicate
This issue or pull request already exists
enhancement
New feature or request
good first issue
Good for newcomers
help wanted
Extra attention is needed
invalid
This doesn't seem right
missing claim
Needs a claim in #14
needs in-game run
Changes the code a frame runs through: needs the 300 s in-game gate (docs/game_gate.md)
needs rebase
Conflicts with the base branch: rebase it on main
needs-triage
Needs maintainer evaluation before the next triage state
question
Further information is requested
ready-for-agent
Fully specified and ready for an AFK agent
submodules
Pull requests that update submodules code
wontfix
This will not be worked on
No labels
accessibility
area: ci
area: d3d12
area: docs
area: launcher
area: runtime (legacy)
area: shader translator
area: tools
area: viewer
bug
dependencies
documentation
duplicate
enhancement
good first issue
help wanted
invalid
missing claim
needs in-game run
needs rebase
needs-triage
question
ready-for-agent
submodules
wontfix
Milestone
Clear milestone
No items
No milestone
Assignees
Clear assignees
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
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2569"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@adrianmjim on GitHub · 2026-11-28 09:48 UTC · original
leaks/all→main· +45518 −7041 · 107 files · 384 commits · closed without mergingClaimed 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_cacheinruntime/shims/d3d12_vulkan_device.cppand the end ofruntime/test/pipeline_cache_store_test.cpp: whichever lands second passesstate->cache_originin the checkpoint and callsrecord_session_seedonly when the save succeeded; a bool does not convert toCacheOrigin, 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
mainand 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.RT-UPLOAD-ARENA-REWINDRT-PSO-BYTECODE-INTERNRT-SPARE-LIST-EPOCHSRT-SLOT-RECORDS-BUCKETSRT-REHYDRATE-SCRATCH-TICKETRT-FSSM-ARENA-SHARERT-TITLE-BUFFER-FALLBACKRT-SLOT70-DEVICE-CYCLERT-MEM-PROBE-WINDOWSRT-ZERO-IMAGES-RETRYRT-TITLE-TEXTURE-GONE-RANGESRT-SHADOW-GPU-RELEASED-RANGESRT-SLOT70-OWNED-RETIRERT-SLOT70-OWNED-RETIREis off by default (LEONIDA_TITLE_IMAGE_RETIRE=1turns it on): a second review found cases where retiring an image too early could show wrong pixels.LEONIDA_UPLOAD_REWIND=0turnsRT-UPLOAD-ARENA-REWINDoff. 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 inruntime/shims/d3d12_xs_device.cppthat only ever advanced; onlydestroy_upload_stategave 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=0keeps the one shared arena that only grows, as before;LEONIDA_UPLOAD_LOG=1names 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 (includingLEONIDA_PIPELINE_COMPILE=on-demand), so each slot 86 PSO kept a private copy of every container it was made from.copy_pointed_datanow 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_recordinginruntime/shims/d3d12_xs_device.cpp) kept their last recording's stamp until the proxy was released, holding back every window retired after it.restart_recordingnow drops each new spare's recording throughrt::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; withoutLEONIDA_VULKAN_DEVICEthe 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.hnever 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), andset()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 noLEONIDA_*=0switch: 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 withrt::d3d12::hold_until_reset; in the default synchronous submit mode (LEONIDA_SUBMIT_ASYNCunset) the list released it at itsResetwhile the build could still run, and~Resourcereturned its arena range at once. A list now records those objects (kept_) andExecuteCommandListspasses them toVulkanQueue::executeas akeepcallback, 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_computeandcreate_graphicsinruntime/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=0gives every PSO a copy of its own, as before, and a compute index entry without auses_code_basekey is still copied. Not in this pull request: 2,426 of the 2,689 compute shaders in the main index have nouses_code_basekey 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_addressstill returned an ordinary DEFAULT buffer that resolved nothing; it was kept intitle_buffers_until the device went and counted againstLEONIDA_TITLE_BUFFERS_MB, and each rebind made another until the cap was used up. Nowmake_title_buffergetsE_OUTOFMEMORYinstead (ordinary_fallbackisfalse), keeps a buffer only when the context knows a buffer at the view's address (1 byte withLEONIDA_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_texturemakes for slot-70 views held a device reference (attach_device) while the device's registry (state_.title_textures) andretired_title_textures_held the images, and~Devicereleased 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~Devicereleases the registry's images and the retired ones aftervkDeviceWaitIdle(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>/smapsfor its process-memory line, so on native Windows it only printedno /proc entry names gta6rtand could not say where 20+ GB of commit go. Whenproc_dir()finds no/procentry,sample()now prints avmmapline: private commit and working set fromGetProcessMemoryInfo, committed bytes by kind (title, pe-private, pe-image, pe-section, vk-mapped) from aVirtualQuerywalk, and the largest private allocations. It is a diagnostic only, with noLEONIDA_*=0switch: withLEONIDA_MEM_PROBEunset nothing runs, and under Wine with a/procentry 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 inzero_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 inzero_image_retryand 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_goneerased a destroyed slot-133 texture's registry entry but left its key intexture_rangesandmapped_title_textures, so the mapped list kept theTitleTexturealive and the next refresh pass'stitle_textures.at()threwstd::out_of_range, ending the process (0xC0000409).drain_titles_gonenow erases the range key with the registry entry and also erases a mapped entry that has no resource. The async pass's apply lambda usesfind()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=1andLEONIDA_CONSOLE_HEAP_GPUunset, 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. Inruntime/shims/d3d12_vulkan_device.cppthe pushes inbacking()andtitle_block_gonenow askheap_pass_enabled(), the alias table records removals only when the pass runs,arena_releaseno longer callsbacking(..., false)twice, and~Devicereleasesheap_gpubefore the VkDevice goes. WithLEONIDA_CONSOLE_HEAP_GPU=1nothing 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_texturewere 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_imagesnow retires an image superseded by a newer overlapping texture and not named since, or whose pages are gone, afterLEONIDA_TITLE_IMAGE_IDLE_MS(2000 ms by default), with up toLEONIDA_TITLE_IMAGE_CHECKS(128) candidates a pass. Retirement is off by default (LEONIDA_TITLE_IMAGE_RETIRE=1turns 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
mainand passes here, and it still exists on its own branch.RT-GEOMETRY-VIEWS-CONTAINRT-DRAW-VIEWS-UNCHANGEDRT-GEOMETRY-VIEWS-CONTAINonly acts withLEONIDA_GEOMETRY_MBset (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 withLEONIDA_GEOMETRY_MBset 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, andLEONIDA_GEOMETRY_CONTAINED=0restores 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 itsDrawViewsblock stale inset_vertex_buffersandOMSetRenderTargetswithout comparing with what is already bound, so a title that rebinds the same vertex buffer before each draw got onemake_shared<DrawViews>per draw (about 728 bytes), kept by the recorded draws until the list's Reset. Nowset_vertex_buffersmarks it stale only for a slot whose view changes, andOMSetRenderTargetsonly when the target count or a copied target view differs. What each draw records is unchanged.Tested at
9fc3ad427(all 26 fixes, withmain33db04a70merged):-j 3: 521 of 524 pass; the three that fail are the same as on plainmainhere (d3d12_texture_tiles,pipeline_cache_seed,d3d12_clear).d3d12_compile_poolfailed once in an earlier full run and about 1 time in 3 alone; this branch does not touch the compile pool or its test.LEONIDA_VK_VALIDATION=1:xs_proxy_mock,geometry_views,d3d12_geometry_views,d3d12_title_va,d3d12_title_va_shadow,d3d12_draw,d3d12_draw_views_sharingandd3d12_existing_heappass 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'searlier D3D12-HLE-XASYNC-CALLBACK-AND-CANCEL-LIFETIME covers it. As above, each fix is its own merge with its own test that
fails on
mainand passes here, and still exists on its own branch,adrianmjim/leonida:leaks/rs-<name>.RS-HOST-LIST-ALLOCATOR-PEAKRS-XTASKQUEUE-POOL-TRIMRS-TEXTURE-READ-TRIMRS-SNAPSHOT-POOL-TRIMRS-EXACT-SPARE-CAPRS-GRAPHICS-STATE-INTERNRS-EARLY-START-AGERS-XMEM-FREE-DEFAULTRS-THIN-UPLOAD-DROPRS-APU-SCRATCHRS-REPLACED-DRAINNone of them changes what the title sees.
RS-EARLY-START-AGEkeeps the last 2 runs (LEONIDA_EARLY_RUNS, 0 = every runas before) and
RS-TEXTURE-READ-TRIMkeeps 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.rsREAD,with_read) only grows, so the submitting thread and eachshadow::wide_eachhelper keep room for the largest texture they ever read for the whole run. A thread now keeps at mostLEONIDA_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 forhost::ram_idle_msto 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, sinceEARLY_MAXis 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 holdskey 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/allwith the eleven merged; one conflict inshadow.rs, where two fixes add their call to the samesweep, 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 plainmainon this machine (RX 7900 XT, AMD 32.0.32029.2010).maind44285197without the fix and failed there (the commit messages say how).9fc3ad427(see the section above).9fc3ad427: the same results (leonida-gpu --lib493 passed with the same 4 failures;leonida-hle186 passed). Plainmain33db04a70:leonida-gpu --lib479 passed with the same 4 failures,leonida-hle181 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
mainand passes here, and it still exists on its own branch,adrianmjim/leonida:leaks/<name>.None of them has a switch.
RS-ARENA-ONE-COPYRS-SHADER-CONTAINER-FREERS-DSTORAGE-SCRATCHRT-DEVICE-LOST-DRAIN27. RS-ARENA-ONE-COPY: leonida-gpu: an arena of memory by address is in the PC's memory once
memory.rsheld 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; withLEONIDA_BVH_BUILDER=1that is up to 48 arenas, about 3 GiB.Memory::another()now makes the copy withshadow::by_address_opened, which opens the arena as a host heap so the arena itself is the CPU side, andbring()/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.rskept every distinct shader container in the staticSHADERStable (container: bytes.to_vec()) for the whole process, although after translation only small derived facts are read from it. Those facts are now kept inTranslatedand a newFacts, and after a successful translationShader::translatedlets the container go, except for a shader that stores whileLEONIDA_PICKED_WRITESis on, untilcrate::pickedhas 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.rsallocated new zero-filled buffers (read_source, the zlib output,into_pages) for every compressed request and freed them at its end, andstaging_bytescounted only the compressed source, so the other buffers were outsideLEONIDA_DSTORAGE_STAGING_MB. Each worker now keeps aScratchit reuses, holding at most 16 MiB (SCRATCH_KEPT) between requests, andstaging_bytescounts 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 deviceVulkanContext::defer_destroynow 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, andcompleted_retire_ticket()deliberately still answers 0 after the loss, so the other ticket-gated frees still stop there.Tested at
eb145de6f(all 30 fixes, withmaind48a957bbmerged):leonida-hletests no longer built:RS-APU-SCRATCHandRS-DSTORAGE-SCRATCHeach installed a counting#[global_allocator]in their tests, and a binary has one. The merge fixeb145de6fmoves it toleonida-hle/src/test_alloc.rs, which tells both counters of each block. Test code only.mainwithout 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}andvk_deferred_destroy_lost(ctest). All pass here, andvk_deferred_destroy_lostalso passes underLEONIDA_VK_VALIDATION=1.cargo test --workspace --no-fail-fastind3d12/:leonida-gpu496 passed with the same 4 failures asmain,leonida-hle189 passed. The other failures are the three described under "Latestmainmerge" below, in code that is the same as onmain.-j 8: 3 of 526 fail, the same three as onmain(d3d12_texture_tiles,pipeline_cache_seed,d3d12_clear).python -I scripts/check_no_game_data.pypasses 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
mainandpasses here, and its own branch,
adrianmjim/leonida:leaks/session-cache-unchanged.RT-SESSION-CACHE-UNCHANGED31. RT-SESSION-CACHE-UNCHANGED: d3d12: a session file written beside the offline seed is loaded alone
With the offline seed loaded,
pipeline_cache.session.binis the driver's union of the seed and what sessions added (on theRX 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 +MoveFileExhelper) 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.binis only stat'ed and nothing is merged. Everything else takes today's path: no record, a changed seed, asession file of another size, a driver that declines the blob,
LEONIDA_SESSION_CACHE_DIRECT_SEED=0orLEONIDA_DIRECT_SESSION_CACHE=0. A write-back smaller than what the cache was created from drops the record, so the next launchmerges 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 inmain9c49bd533, 63 commits afterd48a957bb, with no conflict):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 inpipeline_cache_store(the record's format and every truncation, a changed seed or session file, the shrink rule). Withmain'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.pipeline_cache_store,heavy_pipeline_cache,d3d12_compute_journal,d3d12_pipeline_checkpoint,d3d12_compile_teardown*, plusmem_probe_vmmap) underLEONIDA_VK_VALIDATION=1: 8/8.-j 8: of 527, the same three as onmainfail (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_callbacksfailed once because an incremental link left an oldgta6rt.map; after a full relink it passes.cargo test --workspace --no-fail-fastind3d12/and the 555 standalonetests/test_*.py: the same results as ateb145de6f(this fix touches neither).python -I scripts/check_no_game_data.pypasses on every changed file.gta6rtfrom this fix's branch (a580819a5, onmain9c49bd533), 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, thenmerged 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.652f45345also answers a review: under Wine the process's commit charge does not count what it commits, somem_probe_vmmapchecks 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
mainand passes here, and itsown branch,
adrianmjim/leonida:leaks/shared-pipeline-layouts.RT-SHARED-PIPELINE-LAYOUTS32. 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_layoutkeeps one layoutper distinct create info: the key is the whole create info (flags, every set layout handle in order, every push range), and a
pNextchain is refused rather than shared. Layouts are made on first use under a mutex, with the map slot reserved first. PSOsno longer destroy them;
~Devicedoes, once, after the compiler cancel,vkDeviceWaitIdle, the drained deferred deletions andthe stopped pipeline workers, and before the bindless set layout and the
VkDevice. The mem probe's device line addsPSO pipeline layouts N.Tested at
20ca6dcf5(all 32 fixes,main8b318bd40merged; this fix's based57b78a9cis already in it):d3d12_shared_pipeline_layoutsand_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 hookedvkGetDeviceProcAddr. Withmain'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.pipeline_workers,d3d12_pipeline_workers*,d3d12_compute,d3d12_draw,d3d12_set0_compute,d3d12_mesh*,d3d12_compile_teardown*,vulkan_mesh_limits): 15/15. UnderLEONIDA_VK_VALIDATION=1, the new two,d3d12_pipeline_workers*andd3d12_compute: 8/8, noVUIDline.-j 8: of 529, the same three as onmainfail, andd3d12_mesh_heavy_cachefailed once: it andd3d12_meshrun the same program, which rewrites the same%TEMP%\leonida_mesh_test\index.json, and its log readscannot open ...\leonida_mesh_test\index.json(READ IN CODE:runtime/test/d3d12_mesh_test.cpp:128, unchanged here). It passes alone and withd3d12_meshbeside it, 13 of 13 runs.And one more in
d3d12/From a seventh pass, claimed in #2570 (#2570), with its own merge, its own test that fails on
mainand passes here, and itsown branch,
adrianmjim/leonida:leaks/rs-host-list-scratch-trim.RS-HOST-LIST-SCRATCH-TRIM33. 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 indirectarguments, doubling it.
list::recyclereset a host list and put it in the idle pool with that buffer still attached, and the poolhands its lists to any title list, so one large
ExecuteIndirectkept its buffer in the card's memory for the rest of the run, inevery idle list that had served one (up to 512).
recyclenow callsHostList::idle_trimright after the reset: a scratch largerthan 1 MiB (
IDLE_INDIRECT_MOST) is taken out and handed toretire_resource, which drops it once the submissions still runninghave 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
Pooldescribed under the latestmainmerge.Tested at
ca5aed779(all 33 fixes,main8b318bd40; this fix's base is the samemain):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. Onmainit fails (the large buffer was let go: left 2097152, right 65536); here it passes, withlist::tests10/10.cargo test --workspace --no-fail-fastind3d12/:leonida-gpu524 passed andleonida-hle214 passed; the failures are the same 4 inleonida-gpu, 2 inleonida-shaderand 1 inxtaskas onmain.runtime/is unchanged by this fix.python -I scripts/check_no_game_data.pypasses on both changed files. Not run in the game (the Rust runtime is notgta6rt).Three more
From the same seventh pass, claimed in #2570 (#2570): one in
d3d12/, two inruntime/. Each has its own merge, its owntest that fails on
mainand passes here, and its own branch on the fork (leaks/rs-pipeline-library-fingerprint,leaks/zero-images-release,leaks/dstorage-cpp-scratch).RS-PIPELINE-LIBRARY-FINGERPRINTRT-ZERO-IMAGES-RELEASERT-DSTORAGE-CPP-SCRATCH34. 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.rsopenedhost-pipelines.binwhatever 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 fingerprintleonida warmalready uses (known::fingerprint()) is now written beside it ashost-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. OneSAVINGmutex now covers a whole save: overlapping saves sharedhost-pipelines.tmponmaintoo, 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 itsResourceis 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 commentRT-ZERO-IMAGES-RETRYleft inzero_sampled_imageis corrected in962bc1601).36. RT-DSTORAGE-CPP-SCRATCH: dstorage: queue workers reuse their staging buffers
Each compressed, swizzled or physical-page DirectStorage request in
runtime/shims/dstorage.cppallocated a new zero-filled buffer at every stage and freed it at the end, the C++ side ofRS-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 budgetcan_preparealready 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,main8b318bd40; the three branches' base is the samemain):mainand 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), ctestd3d12_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, indstorage,test_reused_buffers(100 requests of two streams, outputs compared byte for byte: 300 blocks of 128 KiB or more onmain, 6 here),test_kept_buffers_capandtest_kept_buffers_pair_cap.dstorage,d3d12_zero_image_retryandd3d12_zero_image_release: 3/3; the two zero-image tests underLEONIDA_VK_VALIDATION=1: 2/2, noVUIDline.-j 8: 3 of 530 fail, the same three as onmain.cargo test --workspace --no-fail-fast:leonida-gpu528 passed (pipeline::library15/15) andleonida-hle214, with the same failures as onmain.python -I scripts/check_no_game_data.pypasses 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
gta6rtwas running on the same GPU.Latest
mainmerge:leaks/allat5fe777296, all 31 fixes then in this branch withmain8b318bd40merged in (154 commits since7daa4a4a5). One conflict, ind3d12/crates/leonida-gpu/src/list.rs:main's7efbbdd39(LEONIDA_ALLOCATOR_TRIM=1, off by default: idle host lists older than the limit are let go) andRS-HOST-LIST-ALLOCATOR-PEAK(the idle pool as aPool, its untouched lists halved once a second) both changed the idle host-list pool. ThePoolstays; an idle list keeps when it was put by, and withLEONIDA_ALLOCATOR_TRIMits stale oldest are taken out of thePool(newPool::take_oldest, with a unit test) and counted inALLOCATOR_TRIMS[2]as onmain, under the same condition. MEASURED on the same machine:gta6rtand every test target, after a full relink.-j 8: 3 of 527 fail, the same three as onmain.pso_stream,xs_proxy_mock*,pipeline_cache_store,d3d12_session_cache_seedandmem_probe_vmmapunderLEONIDA_VK_VALIDATION=1: 14/14.cargo test --workspace --no-fail-fastind3d12/:leonida-gpu523 passed (withlist::tests9/9) andleonida-hle214 passed; the failures are the same 4 inleonida-gpu, 2 inleonida-shaderand 1 inxtaskdescribed further down, all onmaintoo.tests/test_*.py, the same 10 fail as at the merges before (listed below);tests/,tools/andscripts/are as onmain.Earlier
mainmerges, each MEASURED the same way with no failure that is not also onmain:d51ad23b7(main7daa4a4a5; one conflict inruntime/test/pso_stream_test.cpp, where #2476'stest_later_subobject_versionsandRT-PSO-BYTECODE-INTERN's three tests are all kept) andabdb93f0e(maind48a957bb, no conflict). The failures onmainthat show in every run:leonida-shaderemit::valu_tests::{typed_d16_table_uav_roundtrip_uint_sint_and_float, rdna_forms_give_what_the_spelled_out_ones_give}andxtaskpolicy::tests::repository_passes_policy(lower.rsover the size limit), both in code these fixes do not touch, and 10 standalone Python tests (tests/,tools/andscripts/are as onmain):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/allat098342d02: the 13 fixes, withmain33db04a70merged in. One conflict came from #958, which maderelease_child_referencethe 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'skind, so every path that drops an allocator's last reference frees it. The mock inxs_proxy_mock_test.cppkeeps the fields from both sides.RT-UPLOAD-ARENA-REWINDxs_proxy_mock(check_upload_rewind), newxs_proxy_mock_upload_rewind_offRT-PSO-BYTECODE-INTERNpso_streamRT-SPARE-LIST-EPOCHSxbox_list_cut_spares,command_listRT-SLOT-RECORDS-BUCKETSconsole_heap_slot_recordsRT-REHYDRATE-SCRATCH-TICKETxbox_bvh_builder,xbox_bvh_builder_checkRT-FSSM-ARENA-SHAREd3d12_code_base_share,d3d12_code_base_per_psoRT-TITLE-BUFFER-FALLBACKd3d12_title_buffer_fallbackRT-SLOT70-DEVICE-CYCLEd3d12_existing_heapunderLEONIDA_VK_VALIDATION=1RT-MEM-PROBE-WINDOWSmem_probe_vmmapRT-ZERO-IMAGES-RETRYd3d12_zero_image_retryRT-TITLE-TEXTURE-GONE-RANGESd3d12_existing_heap(check_mapped_plane_gone_in_registry)RT-SHADOW-GPU-RELEASED-RANGESd3d12_shadow_gpu_releases,d3d12_console_heap_gpu_releasesRT-SLOT70-OWNED-RETIREd3d12_title_image_retire,d3d12_title_image_idle,xmemmaind44285197without that fix, and failed there (the commit messages say how). Betweend44285197and33db04a70,mainchanged these files for the stub pipelines (bbc750655,78159b886), which do not touch the paths these fixes change, and for #958, merged as described above.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.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_proxyandxs_proxy_mockpassed 9/9. There were no validation errors and noVUID-vkDestroyDevice-device-05137. Onmain,d3d12_existing_heapleaves 93 objects atvkDestroyDevice.-j 4, run twice (before and after merging33db04a70): 519/523 both times. Three tests failed both times, and they also fail on plainmainon 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.dxgi_waitable_latencyin the first run andrun_tiny_game_abort_exit_codesin the second. Each passes when run alone (the second 3/3), so they are timing-sensitive under-j.gta6rtand every test target build and link.python -I scripts/check_no_game_data.pypasses on every changed file, andpython -m compileall -q make_game.py tools testsis clean. Of the 534 standalonetests/test_*.py, 7 fail, the same 7 with the same output as onmain33db04a70(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_varsfails only onLEONIDA_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:
maind48a957bbalone, and this branch at32d2020f7(all 30 fixes; itsruntime/is the same as ateb145de6f, which only adds the test-onlyleonida-hlemerge fix). Same build type, the same first-run-UI input, each started from the same copy of the pipeline caches,LEONIDA_TITLE_WATCHDOG=0with 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.main, 9,218 with the fixes, none failed).mainand 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.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;vkDestroyPipelinegives 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.d3d12/and do not run ingta6rt.AllocateUploadMemory(list slot 148) was never called in either session (the runtime logs every list slot's first call), soRT-UPLOAD-ARENA-REWINDwas not exercised, and an idle character does not churn PSOs or retire title windows.maind44285197against 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 currentmainmerged): 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. Branchesadrianmjim/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(withxmem-combined).leonida-gpu630 passed / 48 ignored,leonida-hle243 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-gpu690 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-gpu718 passed / 51 ignored.Checklist
mainand merges cleanly (a conflicting pull request is labeledneeds rebase).runtime/and sixteen ind3d12/, and twenty-five more ind3d12/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.)docs/design.md, with how it was confirmed. (n/a: no translator change)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.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.@ -0,0 +120,4 @@int main() {vktest::Device vk;if (!vk.create()) return 77;@Copilot on GitHub · 2026-11-28 09:54 UTC · original
vktest::Deviceleaves 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");@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
ExecuteCommandListsreturns:execute_syncdrains completed pins before returning, so resetting/releasing the lists can leave both sentinels at one reference and make the scratch range reusable. Keep completion deterministically blocked until after these checks, then allow completion and verify release. Avoid an unresolved D3D12 queue wait that sends the batch through the pre-existing CPU-held-batch path instead of exercising the new synchronous pinning.@copilot-pull-request-reviewer[bot] on GitHub · 2026-11-28 09:54 UTC · original · reviewed
🟡 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.
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:
Review effort: Balanced
@ -0,0 +49,4 @@vktest::Device gpu;auto status = gpu.initialize();if (status == vktest::DeviceStatus::unavailable) return 77;CHECK(status == vktest::DeviceStatus::ready);@Copilot on GitHub · 2026-11-28 09:54 UTC · original
vktest::Deviceleaves buffer device addresses disabled unless requested (vk_test_device.h:135,437–438), but line 60 advertises the feature as enabled to the runtime. This makes the test use device-address allocations and queries without enabling the required Vulkan feature, causing validation errors or driver-dependent behavior. Request the feature before initialization and skip this test if it is unavailable.@lixonik 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
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.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 cleanmain(33db04a70) with--test-threads=1: all 4 fail identically on cleanmain(pre-existing on this host), while all 14 newleonida-gputests introduced by this PR pass.Review notes
main(blocking merge): two content conflicts againstmain(33db04a70) inruntime/shims/d3d12_xs_device.cppandruntime/test/xs_proxy_mock_test.cppdue to recentmaincommits10eb17825,038980a38, and53ed711b8.vktest::Deviceunconditionally setsenable12.bufferDeviceAddress = VK_TRUEatruntime/test/vk_test_device.h:459, and bothd3d12_title_buffer_fallback_testandxbox_list_cut_spares_testrun with 0 validation errors underVK_LAYER_KHRONOS_validationon RTX 5070.untime/test/xbox_bvh_builder_test.cpp:603-604): the assertions
reset_sentinel.refs.load() > 1/release_sentinel.refs.load() > 1passed here, though as noted in the inline review, if the GPU completes the BLAS build beforeexecute_syncdrains 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_validation1.4.363).AI-assisted (Antigravity, Gemini).
@lixonik on GitHub · 2026-11-28 10:30 UTC · original · approved these changes
Re-verified after the
mainmerge in098342d02(Windows 11, MSVC 19.44, Ninja Release,LEONIDA_VK_VALIDATION=1).Verification at
098342d02runtime/shims/d3d12_xs_device.cpp,runtime/test/pso_stream_test.cpp, andruntime/test/xs_proxy_mock_test.cpp: cleanly preserves bothmain'srelease_child_reference/test_view_instancing_is_captured/ queue-fence ownership assertions and this PR'supload_allocator_gone/ bytecode-interning / mapped-upload additions.xs_proxy_mock_test,pso_stream_test,d3d12_existing_heap_test,xbox_list_cut_spares_test, andgta6rt.ctest(LEONIDA_VK_VALIDATION=1): 4/4 passed (0 validation errors), in addition to the full 13/13 C++ + Rustleonida-hle/leonida/newleonida-gpuverification atf4cc2b33f.GPUs tested: NVIDIA GeForce RTX 5070 12 GB (Windows 11, driver 610.88, Vulkan 1.4.341,
VK_LAYER_KHRONOS_validation1.4.363).AI-assisted (Antigravity, Gemini).
github-bot referenced this pull request2026-11-28 10:41:07 +00:00
github-bot referenced this pull request2026-11-28 10:49:13 +00:00
@GrahamboJangles on GitHub · 2026-11-28 11:17 UTC · original · reviewed
Reviewer pass over the sweep as a whole (nightly review; verified against current
mainb0c572464).Claims check out. All 24
RT-*/RS-*item IDs link to exactly oneclaiming: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 --searchper 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.cppwith #1521;runtime/CMakeLists.txt,runtime/README.md,runtime/test/d3d12_existing_heap_test.cppwith #2267;runtime/shims/d3d12_geometry_views.h+runtime/test/geometry_views_test.cppwith #2085. GitHub says mergeable butUNSTABLE— that matches: landing order against those three needs to be settled before merge.Tree checks (local merge against fresh main
b0c572464).git diffgives 51 files, +5543/−294 — same as GitHub's stats.git diff --check: no whitespace findings.scripts/check_no_game_data.pyover all 51 changed files: clean.mainalready fails four of them (test_docs_env_varsonLEONIDA_CLWB_PATCHatruntime/src/cpu_emulation.h:366;test_docs_cli_flagson 56 flags ind3d12/docs/*;test_docs_python_depsonport_ctl.pyvs AGENTS.md;test_docs_repo_pathson 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.5fa9c200fRT-UPLOAD-ARENA-REWIND: 25 chunks → 1 over 200 mock frames, plus a--upload-rewind-offctest for the switch;b179a98a0RS-HOST-LIST-ALLOCATOR-PEAK:a_submitted_list_keeps_no_host_list_until_its_resetassertsheld(&lists) == 0after 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 ond44285197).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:
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 theUNSTABLEstate.No approval given from this pass: the native tests are unrun, so this is verification-of-claims, not a substitute for a CI-green bundle.
@zmasi on GitHub · 2026-11-28 12:02 UTC · original
VERIFY-2569-D3D12— verified the Rustd3d12/crates (leonida-gpu,leonida-hle,leonida) and standaloneconsole_heap_slot_records_testat head9fc3ad427cmerged cleanly withmain030d2039eon Windows 11 Pro (build 26200), NVIDIA GeForce RTX 3090 (driver 610.88) + MSVC19.44, synthetic unit/GPU test inputs only.Red (
main030d2039e) -> Green (030d2039e+9fc3ad427c)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 (distinctGraphicsStatepointers allocated for identical stream states).leonida-gputargeted D3D12 + host suites:list::tests::-> 6 passed; 0 failedlist::thin::tests::-> 4 passed; 0 failedpipeline::tests::-> 3 passed; 0 failedpipeline::library::tests::-> 11 passed; 0 failedresource::tests::(--test-threads=1, includingLEONIDA_TEXTURE_SWEEP=0child-process D3D12 run inreplaced_copies_go_with_the_sweep_off) -> 18 passed; 0 failedshadow::snapshot_pool_tests::(1/1),shadow::exact_spare_tests::(1/1), andtexture::read_buffer_tests::(2/2) -> all passedcargo test --manifest-path d3d12/Cargo.toml -p leonida-hle --lib -- --test-threads=4-> 186 passed; 0 failed; 2 ignored (includingxasyncworker-linger/burst/rendezvous tests,xmem::tests::free_default_tells_the_gpu_side_of_32bit_memory, andapu::tests::packets_decode_without_memory_of_their_own).cargo check --manifest-path d3d12/Cargo.toml -p leonida --bin leonida-> clean.runtime/test/console_heap_slot_records_test.cpp(cl.exe /std:c++20 /W4 /permissive- /utf-8 /EHsc) -> 0 warnings, exit0(400differential rounds,console_heap_slot_records_test: ok).python -I tests/test_docs_links.py-> 17 OK.AI-assisted.
d48a957bbinto leaks/all abdb93f0e6RS-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.@lixonik on GitHub · 2026-11-28 13:42 UTC · original · approved these changes
Re-verified updated head
abdb93f0e(covering the two newly added leak fixesRT-GEOMETRY-VIEWS-CONTAINandRT-DRAW-VIEWS-UNCHANGED, plus the cleanmaind48a957bbmerge).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,kListsPendingdefers command-list epoch stamping untilon_retirecompletes, andcopy_title_rangeopts out withcontain = false.RT-DRAW-VIEWS-UNCHANGED(runtime/shims/d3d12_com.cpp,runtime/src/command_list.h):OMSetRenderTargetsandset_vertex_buffersmarkdraw_views_stale_only on actual bound view changes.Verification at
abdb93f0e(Windows 11, MSVC 19.44, Ninja Release,LEONIDA_VK_VALIDATION=1):geometry_views_testandd3d12_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_validation1.4.363).AI-assisted (Antigravity, Gemini).
github-bot referenced this pull request2026-11-28 14:12:50 +00:00
@Tauwni on GitHub · 2026-11-28 14:24 UTC · original
Under Wine the new
mem_probe_vmmapfails at the commit-charge check. Apple M3, macOS 26.5.1, Wine 11.0, Windows cross-build, headeb145de6fmerged ontomainec740bcc3; fails 3/3 runs (MEASURED, also 3/3 at the previous head87497c87a):The region walk sees the 64 MiB (
pe-private 3 -> 67), but the private commit Wine reports does not move after theVirtualAlloc+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.EXPECTreturns 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
xmemtests also fail under Wine here, but they fail the same way onmain, so not because of this pull request.Not checked by a second agent or human yet.
AI-assisted (Claude Code).
@lixonik on GitHub · 2026-11-28 14:36 UTC · original · approved these changes
Re-verified updated head
eb145de6fcovering the newly added fixes (RT-DEVICE-LOST-DRAIN,RS-ARENA-ONE-COPY,RS-SHADER-CONTAINER-FREE,RS-DSTORAGE-SCRATCH, and the sharedleonida-hletest allocator).Code audit (
abdb93f0e..eb145de6f):RT-DEVICE-LOST-DRAIN(runtime/src/vulkan_backend.h):kept_after_losspreservesbindless_slotandimage_viewordering until teardown,drain_lostcompacts kept items in-place safely in the ring buffer and destroys the rest outsidemutex_,defer_destroydrains pre-loss items once vialost_queue_drained_.exchange(true, acq_rel), andexecute_nowre-checksis_device_lost()after takingtracker_mutex_beforebindless_prepare_.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):vk_deferred_destroy_lost_test;ctest -R '^vk_deferred_destroy_lost$': 1/1 passed (0.23 s, 0 validation errors).d3d12/):cargo test -p leonida-hle --lib -- --test-threads=1: 189 passed, 0 failed, 2 ignored (includingpackets_decode_without_memory_of_their_own,compressed_requests_reuse_the_workers_buffers, andstaging_counts_every_buffer_a_request_holds).cargo test -p leonida-gpu --lib memory:: -- --test-threads=1: 4 passed, 0 failed (includingan_arena_is_in_the_pcs_memory_onceandan_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_gopassed; the sole failure is the untouchedpipeline::host::tests::depth_bounds_pipeline_loads_and_filters_draws(root_signaturereturningE_INVALIDARGon this host's inboxd3d12.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_validation1.4.363).AI-assisted (Antigravity, Gemini).
@adrianmjim on GitHub · 2026-11-28 18:06 UTC · original
Thanks. Taken as you suggest: in
652f45345the commit charge check (private_commitgrows 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;@adrianmjim on GitHub · 2026-11-28 18:06 UTC · original
vktest::Devicecreates the device withbufferDeviceAddresson whatever was requested:vk_test_device.h:459setsenable12.bufferDeviceAddress = VK_TRUEafter the request-gated line 438, and lines 378-379 refuse (the test then skips) a device without the feature.request_buffer_device_addressonly decides whether the helper's ownbuffer()/device_address()use device addresses (lines 842, 863). Soinfo.buffer_device_address = truematches the device the test made; that has been so sinceec64fd309. The test also passes underLEONIDA_VK_VALIDATION=1with 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);@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 enablesbufferDeviceAddress(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");@adrianmjim on GitHub · 2026-11-28 18:06 UTC · original
Agreed, for the synchronous path (the default).
execute_syncqueues the keep under the ticket it just submitted (vulkan_backend.h:2836) and then callsdrain_pinsin 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 beforeExecuteCommandListsreturns, 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
Waitmakes the batch held, which exercises the pins instead of the keep under test), so it will come as a separate change.github-bot referenced this pull request2026-11-28 18:10:07 +00:00
github-bot referenced this pull request2026-11-28 19:22:16 +00:00
github-bot referenced this pull request2026-11-28 19:22:16 +00:00
@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.
@ -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@Copilot on GitHub · 2026-11-28 19:34 UTC · original
The opened CPU side now aliases the arena that
Memory::bring/takemodify under theMEMORYmutex, but theseread_unalignedreads and thecopy_allcopies 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_);@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.@ -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()@Copilot on GitHub · 2026-11-28 19:34 UTC · original
When the early list already has
EARLY_MAXkeys 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;@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-pull-request-reviewer[bot] on GitHub · 2026-11-28 19:34 UTC · original · reviewed
🟡 Changes recommended
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
github-bot referenced this pull request2026-11-28 20:10:11 +00:00
github-bot referenced this pull request2026-11-28 20:38:45 +00:00
@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 ancestor8b318bd4037e37a29bebda7417da0062d869f365. RTX 3080 desktop, 10 GiB, NVIDIA 630.20, Windows 11 build 26340, MSVC 19.50.35717 RelWithDebInfo and Vulkan SDK 1.4.363.1.dstoragepassed on both revisions. The head includes and executed the new paired-worker scratch-cap check.d3d12_zero_image_releasepassed on the head on RTX 3080 with Khronos validation enabled, including the overlapping replay test.mem_probe_vmmappassed on native Windows. Its live measurement showed private commit rise from 1 to 65 MiB with the 64 MiB allocation.Overall 3/3 on the head and 1/1 on the ancestor, no CTest skips. Focused C++ synthetic checks only. AI-assisted (Codex).
@lixonik on GitHub · 2026-11-28 21:17 UTC · original · reviewed
Focused follow-up on RS-PIPELINE-LIBRARY-FINGERPRINT at
962bc1601merged locally withmainaa918e5d9. Windows 10 22H2, Rust/MSVC,diagprofile. The 15 library tests and one additional local file-lock fixture passed, including concurrent saves and fingerprint handling.The extra fixture held the old cache file open without delete sharing and saved a synthetic blob for the new fingerprint. The implementation wrote the replacement to the waiting file. A read while the old file was locked correctly returned an empty library; after releasing the handle the new file was promoted and its bytes were read under the new fingerprint. This check only covers the Rust pipeline library lane of the sweep.
AI-assisted.
@zmasi on GitHub · 2026-11-28 21:39 UTC · original
Native Windows 11 + NVIDIA GeForce RTX 3090 Verification (
d3d12/Rust Head962bc1601b)Verified the updated head
962bc1601b37be431f7417840dfa6adc85408224merged cleanly ontoorigin/main(aa918e5d9f9e2f03e078d8f08854324890b5e176,git merge-tree --write-treerc=0) on native Windows 11 (26200) + NVIDIA GeForce RTX 3090 (driver610.88), covering the 6 Rustd3d12/leak-remediation additions landed after9fc3ad427c(RS-HOST-LIST-SCRATCH-TRIM,RS-PIPELINE-LIBRARY-FINGERPRINT,RS-ARENA-ONE-COPY,RS-SHADER-CONTAINER-FREE,RS-DSTORAGE-SCRATCH, and sharedtest_alloccounting allocator) alongside all earlierd3d12/suites.1. Red -> Green Hardware Reproduction (
RS-ARENA-ONE-COPYon RTX 3090)origin/mainaa918e5d9f): ProbedMemory::another()across 3 consecutive 64 MiB arenas on RTX 3090 (ID3D12Device3::OpenExistingHeapFromAddresssupported): each 64 MiB arena added192 MiBof process commit (128 MiBbeside its64 MiBGPU side:64 MiBupload::reserve+ duplicate64 MiBUPLOADshared_buffer), failinggrew < card + ARENA + ARENA / 2.origin/main + 962bc1601b):memory::tests::an_arena_is_in_the_pcs_memory_oncepassed (4/4memory::testsgreen): each 64 MiB arena added128 MiBtotal commit (64 MiBGPU side +64 MiBCPU arena,64 MiBless commit per arena),card_data() == atfor all 3 arenas (by_address_openedviainplace::place_part), andan_arena_sends_up_only_the_dwords_the_title_changedconfirmed 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/4passed (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/10passed (an_idle_list_lets_go_of_a_large_indirect_scratchin 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/4passed (uploads_of_words_never_handed_over_are_given_back).pipeline::tests::*:4/4passed (translated_shaders_let_their_containers_go,pipelines_of_one_graphics_state_share_it).pipeline::library::tests::*:15/15passed (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/5passed.leonida-hle(defaultwithtest_alloc&--features diagnostics):modules::apu::tests::*:3/3passed (packets_decode_without_memory_of_their_ownunder sharedtest_alloc).modules::dstorage::tests::*:21/21passed in default (compressed_requests_reuse_the_workers_buffersunder sharedtest_alloc,a_worker_keeps_its_buffers_up_to_a_bound,staging_counts_every_buffer_a_request_holds) +20/20passed under--features diagnostics.modules::xasync::tests::*:15/15passed (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/22passed (free_default_tells_the_gpu_side_of_32bit_memory).leonida& Docs/Policy:cargo test --locked -p leonida:40/40passed (36unit +2agility+2census).tests/test_docs_*.py(56/56OK) andscripts/check_no_game_data.py(rc=0).AI-assisted.
github-bot referenced this pull request2026-11-29 11:11:48 +00:00
github-bot referenced this pull request2026-11-29 11:11:48 +00:00
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: 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: 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]>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]>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]>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: 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: 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: 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]>@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 apartTwenty-five more items in the Rust runtime, pushed to this pull request's branch (
leaks/all) at26e00403c, which also merges currentmain. 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 branchadrianmjim/leonida:unified/<name>, each fix with a test that fails without it.send-pool-trimRS-SEND-POOL-TRIM,RS-FETCH-SHRINKLEONIDA_SEND_TRIM=0); fetch buffers shrink after a window of small fetches (LEONIDA_FETCH_SHRINK=0)compare-ringRS-COMPARE-RINGLEONIDA_COMPARE_RING=0)landed-cells-gateRS-LANDED-CELLS-GATEsmall-leaksRS-WALLS-FILES-DROP,RS-VALUE-WAITS-RELEASE,RS-HEAP-SPANS-PRUNEPLACED_SPANSandGPU_RANGES(the branch's arena commits are taken back here: that part isD3D12-RT-FG-ARENA-VA-STORM)placed-texturesRS-PLACED-SWEEP-GONE-COPIES,RS-PLACED-EVICTtexture-staging-releaseRS-TEXTURE-STAGING-RELEASE,RS-MOVIE-PLANE-STAGINGLEONIDA_STAGING_RELEASE=0); video planes get no staging and are copied when changeddescriptor-viewsRS-VIEW-TABLE-BOUNDLEONIDA_VIEW_ADDRESSED_MOST=0); resource views kept without padding words (LEONIDA_VIEW_NORMAL=0)inplace-freeRS-INPLACE-FREE,RS-PLACEHOLDER-RELEASEVirtualFreeof memory in place succeeds once the heap is gone; a split placeholder reservation is released wholeplacement-benchRS-PLACEMENT-BENCH-AMDd3d12/docs/findings.mdcard-one-copyRS-SEND-DIRECTLEONIDA_SEND_DIRECT=0)inplace-blockersRS-INPLACE-PROTECTVirtualProtectof memory in place, slots over freed memory, fixed-address reservations over a pending release (LEONIDA_INPLACE_PROTECT,_SLOTS,_RESERVE);LEONIDA_INPLACEstays offpage-pool-openRS-SECTION-MB-DEFAULT,RS-SECTION-COMMITLEONIDA_SECTION_MB=0); committed sections at first touch, off by default (LEONIDA_SECTION_COMMIT=1)shadow-hot-pathsRS-SNAPSHOT-DECLARED,RS-CARDED-INDEXexact-waitsRS-EXACT-WAITLEONIDA_EXACT_WAIT=0)physical-reuseRS-PHYSICAL-REUSELEONIDA_PHYSICAL_REUSE=0,LEONIDA_PHYSICAL_DISCARD=0)title-alloc-watchRS-TITLE-ALLOC-WATCH,RS-WORKING-SET-STATSXMemAllocDefaultblocks andCreateHeapheaps are write-watched;XMemGetWorkingSetStatisticsreports the title's own usexmem-combinedphysical-reuseandtitle-alloc-watchmerged withpage-pool-open's sections, and a test of reuse with committed sectionsMeasured on the RX 7900 XT without the game (
host::placement, details infindings.md): the card reads the PC's memory at 23 to 28 GB/s from upload, custom L0 write-back and memory opened withOpenExistingHeapFromAddressalike, 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, soD3D12_HEAP_TYPE_GPU_UPLOADwas 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-targetsclean. 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 (xasyncpool workers, adstorage20 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.
github-bot referenced this pull request2026-11-29 12:26:09 +00:00
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: 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]>@adrianmjim on GitHub · 2026-11-29 12:48 UTC · original · edited 2026-11-29 15:00 UTC
Third round in
d3d12/(pushed at19006b0e6)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.land-same-submissionRS-LAND-IN-SUBMISSIONLEONIDA_LAND_IN_SUBMISSION=1, off by default)settle-and-lineRS-SWEEP-NO-SETTLE,RS-LINE-HOLDSLEONIDA_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-changedRS-TEXTURE-DETILE-CHANGEDLEONIDA_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-coverageRS-INPLACE-COVERAGELEONIDA_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-pathsRS-BAR-BUFFERSLEONIDA_BAR_BUFFERS_MB=N, off); the log says whether resizable BAR is on and its window sizehot-path-bookkeepingRS-HOT-PATH-BOOKKEEPINGHOST_WRITTEN_ATper release; diagnostics' copy maps lock per thread setinplace-flakeRS-INPLACE-FREE)Also:
d17b3e2b3(a closed section's record removed fromViews.sections) is taken back in favour of zmasi'sD3D12-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 usedLEONIDA_LAND_SAME, whichland.rsalready 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, andleonida-gpuwithdiagnostics, 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.github-bot referenced this pull request2026-11-29 13:03:52 +00:00
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: 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: 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: 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]>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]>@adrianmjim on GitHub · 2026-11-29 14:32 UTC · original · edited 2026-11-29 15:00 UTC
Fourth round in
d3d12/(pushed at7cc8e1879)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.card-from-titleRS-CARD-FROM-TITLELEONIDA_CARD_FROM_TITLE=1, off by default)inplace-async-openRS-INPLACE-ASYNCLEONIDA_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);XMemVirtualQueryreports what the title asked for (LEONIDA_INPLACE_QUERY); a reservation over a pending release does it first (LEONIDA_INPLACE_RELEASE_FIRST).LEONIDA_INPLACEstays offsend-ringRS-SEND-RINGLEONIDA_SEND_RING)compare-costRS-COMPARE-COSTfindings.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-closeRS-CLOSE-SUMMARYLEONIDA_CLOSE_SUMMARY=0: as before;=checkcompares both)suite-stabledouble-releaseRS-INPLACE-FREE)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-targetsandleonida-gpuwithdiagnosticsclean. Device tests on the RX 7900 XT (driver 32.0.32029.2010) and WARP, synthetic inputs only; nothing run with the game.github-bot referenced this pull request2026-11-29 14:38:33 +00:00
34143ad380to7cc8e18797What 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: 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.@adrianmjim on GitHub · 2026-11-29 15:16 UTC · original
Fifth round in
d3d12/(pushed at6737559d3)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.inplace-title-allocRS-INPLACE-TITLE-ALLOCVirtualAlloc,VirtualAllocExandVirtualProtectExgo through the runtime's glue, asVirtualFreeandVirtualProtectdid: 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).XMemVirtualQuerytells 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_INPLACEstays offcard-from-title-windowsRS-CARD-FROM-TITLE-WINDOWSLEONIDA_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-boundsRS-SPARE-TAKE-BOUND,RS-SAMPLER-ENTRIES-BOUNDLEONIDA_VIEW_SAMPLERS_BOUND=0: kept for the run)Still not shimmed, for whoever has the import list:
NtProtectVirtualMemory,NtAllocateVirtualMemory,VirtualAlloc2and kernel32VirtualQuery(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-targetsclean. Device tests on the RX 7900 XT (driver 32.0.32029.2010) and WARP, synthetic inputs only; nothing run with the game.@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/headreports 3 conflicted file(s):d3d12/crates/leonida-gpu/src/texback.rsd3d12/crates/leonida-gpu/src/texture.rsruntime/shims/d3d12_vulkan_device.cppThe last one is the file most pull requests trip over, so it may be worth rebasing after whatever else touches
d3d12_vulkan_device.cpplands.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.
github-bot referenced this pull request2026-11-29 20:08:47 +00:00
@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-treeagree with it. Currentmainis merged in now, conflicts resolved.@MoonEyes on GitHub · 2026-11-29 21:54 UTC · original
Tested
ca6f10dfbmerged (no commit) withmain060c47160: Windows 11, Rust toolchain fromd3d12/rust-toolchain.toml, CPU only, no game run.cargo test -p leonida -p leonida-gpu -p leonida-hle --locked:main809 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 onmainand the same 10 with the PR (all inleonida-luaandleonida-shader); this PR adds none.main, but merging it would force a rebase of #2566 (git merge-treeconflicts). Under the current merge freeze it should wait until #2566 lands, then be rebased.AI-assisted (Claude Code).
@adrianmjim on GitHub · 2026-11-29 22:09 UTC · original
Sixth round in
d3d12/(pushed at8f5f02d80), with currentmainmergedClaimed 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 branchadrianmjim/leonida:unified/<name>, each fix with a test that fails without it.placed-unmapped-releaseRS-PLACED-UNMAPPED-RELEASELEONIDA_PLACED_UNMAPPED=0: kept to the card's idle time)refresh-nothing-fastRS-REFRESH-NOTHING-FASTLEONIDA_LOOK_FIRST), and a range whose end pages were written only beside it is known to copy nothing (LEONIDA_LOOK_PARTS)heap-records-waitRS-HEAP-RECORDS-WAITLEONIDA_HEAP_PRELOOK, off)write-watch-askRS-WRITE-WATCH-ASKLEONIDA_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 goneIn 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_PARTSand 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-targetsandleonida-gpuwithdiagnosticsclean. The merge withmain(ca6f10dfb) also compilesruntime/shims/d3d12_vulkan_device.cpp,d3d12_com.cpp,dstorage.cpp,file_system.cpp,main.cppandpe_loader.cppwith MSVC 19.44 against the pinned Vulkan-Headers;ctestwas not run.github-bot referenced this pull request2026-11-29 22:14:07 +00:00
@adrianmjim on GitHub · 2026-11-29 22:45 UTC · original
RS-HOST-RS-SPLIT(claim), pushed at208eaf7ea: with this pull requestd3d12/crates/leonida-gpu/src/host.rshad grown to 813,049 bytes, past the 655,360-byte cap ofxtask/src/policy.rs. Its tests (24 modules,refresh_testsleft forD3D12-HOST-RS-SIZE) and five self-contained groups (the presenter, the plane pass, the buffer makers, the frame lines, the card compare) now live inhost/*.rs, moved as they are; host.rs is 584,189 bytes.repository_passes_policynow names onlyemit/lower.rs(D3D12-SHADER-LOWER-SIZE);leonida-gpu --lib762 passed / 53 ignored, the same test names as before.github-bot referenced this pull request2026-11-30 06:43:51 +00:00
github-bot referenced this pull request2026-11-30 07:47:05 +00:00
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).@adrianmjim on GitHub · 2026-11-30 10:47 UTC · original
Seventh round in
d3d12/(pushed at8164b315d)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 branchadrianmjim/leonida:unified/<name>, each fix with a test that fails without it, each behind a switch that is on by default (=0is the lock as before).staging-lock-shortLEONIDA_STAGING_SHORTbake-lock-quickLEONIDA_BAKE_QUICKtextures-queue-tabled-quickLEONIDA_QUEUE_MARKS,LEONIDA_SPANS_QUICK,LEONIDA_TABLED_INBOXindirect-sig-lockfreeLEONIDA_SIG_TABLEIn the running title (one
LEONIDA_ABrun, 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 ofd3d12/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-targetsandleonida-gpuwithdiagnosticsclean.repository_passes_policynames onlycrates/leonida-shader/src/emit/lower.rs, as before this round.github-bot referenced this pull request2026-11-30 10:53:00 +00:00
github-bot referenced this pull request2026-11-30 11:08:57 +00:00
github-bot referenced this pull request2026-11-30 13:52:34 +00:00
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.@adrianmjim on GitHub · 2026-11-30 14:38 UTC · original
New round in this PR:
RS-SAMPLER-UNWIND-FAULTandRS-SUBMIT-THREAD-COST(claim, status).RS-SAMPLER-UNWIND-FAULT:LEONIDA_PROFILEno longer takes the title down. On an RX 7900 XT it faulted about 20 s into sampling. The fault was an access violation insidentdllwhile walking a suspended thread's stack.rbpfor the next frame.stacks::Unwindernow usesRtlVirtualUnwind2with the thread's stack limits wherentdllhas it (build 20348 and later). Before each step it also checks the image's tables, and it stops instead of faulting.crash::unwind_intoare untouched.What that profile showed. The title's busiest thread is waiting, not working:
monitorx/mwaitxloop on a fence's GPU address, and 27 % inSleepinside that loop.Four cuts on that thread, each behind a switch, measured in one
LEONIDA_ABrun in the world:LEONIDA_PRELUDE_POOL: host list preludes made ahead on a thread of their own, not inCreateCommandAllocatorin the middle of submissionsLEONIDA_SPANS_ONE_WALK: stale parts of the heap pass's spans rebuilt in one blocked walk; 1 walk instead of 15 in the titleLEONIDA_SMOOTH_YIELD: a present not held for pacing while submissions wait behind itLEONIDA_RELAY_PRIORITY: the relay thread above normalWhat the run settles:
=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-gpu794 passed, 53 ignored;leonida-hle256 passed, 2 ignored;leonida-loader73 passed. The policy check names onlylower.rs, which was over the limit before.github-bot referenced this pull request2026-11-30 14:39:23 +00:00
github-bot referenced this pull request2026-11-30 14:44:54 +00:00
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.@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_TIMINGrun in the world (every command between two stamps, so slower than a normal frame) gave about 41 ms a frame:ExecuteIndirectOur 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):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_ABrun in the world: 68 phases of 7 s, the 8 combinations about eight times each, least squares per switch with a time trend.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 memoryLEONIDA_COMPARE_JOIN: the compare goes in the sameExecuteCommandListscall as the submission's last lists, behind one global barrier listLEONIDA_CARD_OWN_TIMES: the timestamps aboveWhat the run settles:
=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-gpu803 passed, 53 ignored (869 with diagnostics);leonida-hle256 passed, 2 ignored;leonida-loader73 passed. The policy check names onlylower.rs, which was over the limit before.github-bot referenced this pull request2026-11-30 16:39:10 +00:00
github-bot referenced this pull request2026-11-30 16:44:33 +00:00
@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).
@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.
LEONIDA_CARD_FROM_TITLE=1LEONIDA_INPLACE=1+ LEONIDA_SECTION_COMMIT=1LEONIDA_LAND_IN_SUBMISSION=1LEONIDA_TEXTURE_WATCHED_IN_PLACE=1No 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.
xmemmaps 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, behindLEONIDA_INPLACE_PROBE=1andLEONIDA_INPLACE_PROBE_TILES=1, on a device of its own):UpdateTileMappingsremoves the device withDXGI_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_ABcan flip it. One run of 67 phases gave: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.
pool.rslets 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.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.LEONIDA_UPCOPY_CHECK=1found 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_aheadread 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-gpu813 passed, 54 ignored (880 with diagnostics);leonida-hle256 passed, 2 ignored;leonida-loader73 passed. The policy check names onlylower.rs, which was over the limit before.github-bot referenced this pull request2026-11-30 18:47:41 +00:00
github-bot referenced this pull request2026-11-30 18:47:41 +00:00
github-bot referenced this pull request2026-11-30 20:27:34 +00:00
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.@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/allnow containsorigin/mainat8f41d7d01.runtime/.runtime/anddocs/d3d12_vulkan.mdare 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.draw.rsreadsAHEAD_RECORDINGthrough main'sRwLock;COPY_SCOPEDline goes throughhost/lines.rs;host/present.rs;apu.rsuses main'slookuptogether with our reborrow;findings.mdkeeps both sides' sections.Resource::evict_placed. WithLEONIDA_PLACED_SHARDSflipped while the title runs, a placed texture could be freed while still in its shard table.leonida-gpu846 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:
LEONIDA_WC_NO_BACKkeeps on the card, because those are never planned.What wrote them (
RS-UNDECLARED-SHADER-WRITES).LEONIDA_UNDECLARED_TRACE=1withLEONIDA_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.LEONIDA_WC_NO_BACK=1leaves on the card.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.Details are in
d3d12/docs/findings.md, section "Shader writes that a send undoes, in write-combined title memory".github-bot referenced this pull request2026-11-30 21:34:08 +00:00
github-bot referenced this pull request2026-11-30 21:34:08 +00:00
@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-COSTpart) are still a cost on cards held by the GPU:LEONIDA_OWN_STAMPS=1measures 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