Repository navigation
runtime, d3d12: memory leak fixes from one sweep (RT-LEAK-SWEEP) - #2569
adrianmjim wants to merge 82 commits into
Conversation
…a released device goes (RT-SLOT70-DEVICE-CYCLE) make_title_texture made its image with create_committed, which attaches the device; the registry (state_.title_textures) holds the image, and a retired image waits in retired_title_textures_ for a refresh pass 3 s later, which only runs before a submission. A device released while such an image existed was never destroyed and kept every Vulkan object it had: d3d12_existing_heap's device without host image copies left 93 at vkDestroyDevice (VUID-vkDestroyDevice-device-05137). The image now drops its device reference right after it is made, as the registry's reference keeps it alive, and ~Device releases the registry's and the retired images after the GPU is idle (release_title_images), before the deferred deletions are drained. d3d12_existing_heap checks that the last Release of each device returns 0 and fails on validation errors counted after vkDestroyDevice.
…SO-BYTECODE-INTERN) PsoStreamRecord::capture copied the bytecode of every stage into the record's own blobs, so each slot 86 PSO kept a private copy of every container it was made from, and a slot 55 PSO kept another one when keep_pso_stream captured its stream again. The title makes some 50 000 slot 86 calls in its first boot from about 26 500 shaders (docs/embedded_shaders.md), and the carved containers average 9.6 KB on this machine, so most of them were kept many times over: an estimated 0.65 to 1.0 GB of private bytes. Both compile modes copied: keep_pso_stream by default, prepare_console_stream with LEONIDA_PIPELINE_COMPILE=on-demand. copy_pointed_data now takes the bytecode from a process-wide table keyed by the size and the DXBC checksum (bytes 4..19, as key_shader uses; FNV-1a over the bytes for a container without one). A candidate is only taken when all of its bytes are equal, since hand-built containers can share a checksum. The record holds a shared reference in payloads_->shaders and its stream points at the shared bytes, which are never written. The table holds weak references, swept every 1024 new entries, so a container is freed with the last PSO that uses it; the copy is made outside the table's lock and looked up again before it is added. The stream bytes, the bytecode every consumer reads and the containers a caller passes in (shared_native_graphics) are unchanged. pso_stream_test: two streams with equal bytecode in different buffers, 10000 streams of one VS/PS pair, and records made and freed on 8 threads share one copy per container; bytecode with an equal checksum but other bytes, and checksum-less bytecode that differs in one byte, are not merged. On d442851 5 of its 41 checks fail and the 10000 records grow private bytes by 202.9 MiB; with this change all pass and they grow by 3.0 MiB.
…UPLOAD-ARENA-REWIND)
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.
…nsole heap pass (RT-SHADOW-GPU-RELEASED-RANGES) With LEONIDA_SHADOW_GPU=1 and LEONIDA_CONSOLE_HEAP_GPU unset, setup_console_heap_gpu makes heap_gpu for the shadows' page copies and turns the alias table's removal list on, but only the pass takes released_ranges and that list (console_heap_gpu_begin), and the pass runs only with LEONIDA_CONSOLE_HEAP_GPU=1. Every arena release (the per-submission geometry upload leases among them), title block destroyed, slot-133 import released and alias range removed added an entry nothing took, for as long as the process ran. The pushes in backing() and title_block_gone now ask heap_pass_enabled() (heap_gpu and LEONIDA_CONSOLE_HEAP_GPU=1), and the alias table records removals only when the pass runs. arena_release called backing() twice for a release since 9f98dcc. The second call erased nothing more: it only repeated the slot change, the generation bump and the released range. It is gone, so a release is one range for the pass and one slot change. A device that owns its VkDevice (create_vulkan_device_standalone) faulted when released with either variable set: the pass's pipeline and buffers went in ~DeviceState, after the VkDevice. ~Device now clears the context's prelude and releases them first. Test: d3d12_shadow_gpu_releases (new). LEONIDA_SHADOW_GPU=1 alone: 1,024 committed and 16 slot-133 buffers released over 16 submissions leave nothing waiting (2,064 released ranges and 16 removed alias ranges on d442851). With --console-heap-gpu, 64 releases are 64 ranges (128 before), all taken by the next submission. The accessors are console_heap_gpu_pending (d3d12_com.h) and TitleVaAliases::removals_pending.
…etired title window (RT-SPARE-LIST-EPOCHS) Since ProjectLeonida#2465 a retired title window is freed only once every command list whose recording began before the retirement is gone (src/ command_list_epochs.h). The list proxy's spare real lists never were: restart_recording moves the cut parts and the last real list into the spares closed and not reset, and cut_list reuses the newest spare first. After a recording cut twice or more, later recordings that cut at most once reset only the newest spare, so the others kept their last recording's stamp until the list proxy was released, and every title window retired after it kept its memory as long. The idle spares also kept their commands and the pipeline states, root signatures and BVH scratch those held. A spare is not executed again before a cut resets it: a submission names only the proxy's parts and current list, and the title's Reset ended the recording they made. restart_recording now drops a spare's recording through rt::d3d12::drop_recording: the layer list clears its commands, releases what it held and resets its state, as Reset does, and stays closed with no epoch stamp (CommandList::drop_recording, Stamp::drop). A copy a held batch made earlier keeps its own stamp. A retired window still without a ticket 30 s after its retirement is logged once, with what it waits for, and the title memory report at device release counts the retired windows not freed yet and how many command-list epochs ago the oldest live list began. Tests: xbox_list_cut_spares (new; a Vulkan device and the queue and list proxies, no game data) records a list with three cuts, advances the epoch as a retirement does, then records it eight times with at most one cut. On d442851 the oldest live recording stays at epoch 1 with the retirement at 2, and the root signature the first recording set keeps 3 references; with the change the oldest is 2 and the references 1. command_list checks CommandList::drop_recording and copies of a dropped list.
… refresh's indexes too (RT-TITLE-TEXTURE-GONE-RANGES) A slot-133 texture destroyed while its thread holds title_texture_mutex (a slot-70 view overwrote the descriptor that held its last reference, 5f549cf) only stops naming its resource, and drain_titles_gone erases the registry entry once the lock is free. With LEONIDA_TEXTURE_REFRESH_ASYNC=1 the entry is also in texture_ranges (index_texture) and, once mapped, in mapped_title_textures, and drain_titles_gone left both. The next refresh pass that saw a title write or a map change over the texture's memory looked the key up with title_textures.at(), and the std::out_of_range ended the process on the refresh worker. The mapped list also kept the TitleTexture alive. drain_titles_gone now erases the range key with the registry entry, as title_texture_gone does outside the registry, and the mapped entry when it has no resource (also when a texture made at the address since replaced the registry entry). The async pass looks a key up with find() and skips one without an entry. The other places an entry leaves the registry already erase its range key or replace it; a texture made for slot-70 views is never in the mapped list. Test: d3d12_mapped_plane_async (d3d12_existing_heap_test --mapped-plane-async) adds check_mapped_plane_gone_in_registry: a mapped slot-133 plane released under the registry's lock, then a write over its pages and a pass of the refresh worker. On d442851 the process ends with 0xC0000409 (std::out_of_range from the at() in refresh_title_textures, on the worker); now the registry is back to 0 entries, 0 range keys and 0 mapped textures. The accessors are title_texture_registry and release_in_title_registry (d3d12_com.h) and TitleTextureRangeIndex::size.
…s retired once no view names it (RT-SLOT70-OWNED-RETIRE) The images the layer makes for slot-70 texture views of the title's memory (owned TitleTextures) were retired only when their own address got another description or a slot-133 texture. A title that streams places its textures at ever new addresses of the same memory, so each address named kept its image (in VRAM, then in host-visible memory), its bindless index and its turn in every refresh pass for the device's life. place_title_view now records when a view last named an image, and the refresh pass (retire_idle_owned_images) also retires one once a texture made or registered after that view covers some of its bytes, or once none of its pages has been committed since a title_memory_map change over them, in both cases when no view has named it for LEONIDA_TITLE_IMAGE_IDLE_MS (2000 by default). An image over exactly the same bytes (the other view of a stream pool) is not covered, one never filled does not go with its pages, and two textures over the same bytes that views keep naming both stay. The image is released 3 s later, as before; a later view makes it again with the same T#, so the descriptors the title kept find it once it is filled. LEONIDA_TITLE_IMAGE_RETIRE=0 keeps the images as before. The title textures census line counts the retirements under a newer texture and with their pages gone. d3d12_title_image_retire (d3d12_existing_heap_test --title-image-retire, with LEONIDA_TITLE_IMAGE_IDLE_MS=0): 16 textures named 4 KiB apart in one committed MiB leave one image (64 KiB) and one bindless index, where they left 16 (1024 KiB) and 16; a texture named again after its image was retired reads its texels and its first T# finds it again; decommitted pages and a slot-133 texture over its bytes retire the last image. Tests read the registry through title_images and title_image (d3d12_com.h).
…-RECORDS-BUCKETS) The two indexes of src/console_heap_slot_records.h hold each V# half of a console resource heap under (span class, granule), one unordered_map per class. A half that moved or was cleared left a stale entry behind, and nothing erased a bucket: push() cleaned only a bucket that was pushed again until it held 32 keys, find() skipped stale entries, and only reset(), at heap creation, emptied the maps. The main resource heap lives as long as the session, and fix_vsharp records as waiting any non-image word with w[2] != 0, so data the title keeps in a slot made a new bucket whenever it changed. The bucket count was every (class, granule) the session had written, not the live slots: two halves moved 200,001 times held 600,003 buckets, 60.4 MiB of private bytes (measured with a scratch program), with nothing recorded. A bucket now counts the halves it holds. set() works out, per index, the bucket a half leaves and the one it enters, and the last half to leave a bucket erases it with its stale entries. The buckets held are at most twice the halves recorded. Lookups name the same slots: they skipped those entries already. The heap's slot-record log line gives the bucket count after the halves recorded. console_heap_slot_records_test: a new case moves two halves 200,001 times and expects at most 4 buckets while they live and none once both slots are cleared (on main: 600,003 both times). Every apply() of the model now also compares touched() with a walk of every recorded half, and the random case bounds the buckets by twice the halves recorded after each round; both checks hold on main too.
…by kind (RT-MEM-PROBE-WINDOWS) LEONIDA_MEM_PROBE's smaps line reads /proc/<pid>/smaps through Wine's Z: drive. Native Windows has no such entry, so there the line only said "no /proc entry names gta6rt", and the log had no breakdown of the process's own memory on the platform most testers run. Where no /proc entry is found, the probe now prints in its place [rt] mem-probe vmmap t=<s> (<ms>, <n> regions): private commit C MiB (peak P), working set W MiB (private V, peak Q); committed T MiB by kind: title A (n regions), pe-private B (n regions), pe-image C (n regions), pe-section D (n regions), vk-mapped E (n regions); reserved R MiB; largest private allocations MiB: 0x... N, ... The counters come from GetProcessMemoryInfo with the PROCESS_MEMORY_COUNTERS_EX2 size (the private working set, Windows 10 21H2 and later), falling back to the _EX size. The kinds come from a VirtualQuery walk over the user address space with the smaps line's title and vk_mapped ranges; the rest of a committed region is named by its type. A region is cut at the ranges' edges, so a reservation the title commits only part of counts in each kind it reaches. The walk's time is in the line: 131 203 regions take about 75 ms here. Diagnostic only: it runs on the probe's own thread, and with LEONIDA_MEM_PROBE unset nothing runs. Under Wine with a /proc entry the smaps line is printed as before. - src/mem_probe.h: VmTally (the classifier: regions and ranges in, committed bytes and region counts per kind out), process_counters, walk_address_space, vmmap_text and sample_vmmap; sample() prints the vmmap line when proc_dir() finds no /proc entry. - runtime/README.md: LEONIDA_MEM_PROBE's row names the vmmap line. Test: mem_probe_vmmap_test (CPU, Windows). Synthetic regions cut at unsorted, overlapping title ranges and a vk_mapped range give the expected bytes and region counts per kind; the line's text; a walk of the test process sees 64 MiB it commits as pe-private and in the commit charge, or as title memory inside a title range, and a 16 MiB section view as pe-section, or as vk-mapped inside a vk_mapped range; a 4 GiB reservation with 65 536 committed pages is walked and timed. It does not build on d442851, where the native sampler does not exist.
… has completed (RT-REHYDRATE-SCRATCH-TICKET) RehydrateRaytracingAccelerationStructureBatched2X makes its own scratch buffer when the title passes ScratchAccelerationStructureData = 0 (the retail title does) and hands it to the list with hold_until_reset. The list released it at its Reset or release, which D3D12 allows as soon as ExecuteCommandLists returns. In the default synchronous submit mode nothing else held it, and a default-heap buffer's arena range is free the moment the buffer is destroyed, so the next DEFAULT buffer of that size could get the range, and be zeroed by the CPU, while the build still ran. ExecuteCommandLists now also gives the queue the objects its lists hold through hold_until_reset (keep_lists), and a batch submitted at once keeps them until its submission has completed; drain_pins releases them as it releases the fences. Held batches and LEONIDA_SUBMIT_ASYNC already kept them, with the lists' pipeline states (pin_lists). A list without such objects costs one size check. The rehydrate is the only user of hold_until_reset. xbox_bvh_builder_test: a rehydrate without the title's scratch is executed, the list is Reset at once on another allocator (a second list is released), and a DEFAULT buffer of the scratch's size is made before any Signal. On d442851 it got the scratch's own VA and the sentinels the lists held were already released (3 of 33 checks failed); now its range is elsewhere, and the sentinels go once the submission has completed.
…(RT-FSSM-ARENA-SHARE) A compute or graphics PSO whose shader reads its code base (s_getpc_b64 and the constant tables in its own program) copies that program into the GPU address arena, which has a fixed size (256 MiB by default, at most 4095 MiB). Each PSO made its own copy, so N PSOs of one program held N copies of the same bytes until they were released. The device now keeps one copy per program, keyed by the SHA-256 the PSO found the program's translation by (fssm_sha256, or fspx_code_sha256 for a kind-6 program), which is the hash of the bytes copied. The first PSO makes the copy, the others take a reference, and the last one returns it to the arena when that PSO is deleted: the same point a PSO's own copy was returned, after any build of it a compile worker was running. Compute entries whose index has no uses_code_base key are still copied, as before. LEONIDA_SHARE_CODE_BASE=0 gives every PSO a copy of its own, as before (runtime/README.md). d3d12_code_base_share_test creates four compute PSOs of one program, others of programs with and without a code base or with no uses_code_base key, and two graphics PSOs whose pixel shader reads its code base. It checks the arena's shader bytes and each PSO's code base VA and bytes through two read-only test hooks (arena_shader_bytes, pipeline_code_base). Without the sharing it fails: four PSOs of a 4004-byte program held 16016 bytes. d3d12_code_base_per_pso runs it with LEONIDA_SHARE_CODE_BASE=0.
…t (RT-TITLE-BUFFER-FALLBACK) make_title_buffer makes a buffer over the title's pages the way slot 133 does: the pages imported, or a shadow copied from them. When both fail (no import, the arena full, no host-visible memory left), create_at_host_address still answers S_OK with an ordinary DEFAULT buffer that has neither the title's VA nor its bytes. make_title_buffer only checked FAILED(hr), so it kept that buffer until the device went and counted it against LEONIDA_TITLE_BUFFERS_MB. The view stayed uncovered, so the next IASetVertexBuffers or IASetIndexBuffer of the same view made another one (each with its own memory, zero fill and device reference), until the cap was used up; after that no new title view was resolved for the rest of the session, even once the memory was back. A buffer is now kept and counted only when the context knows a buffer at the view's address afterwards (knows_buffer_va over the backed prefix, as the check before it). Otherwise it is released, and its range is remembered for a second (refused_title_ranges_, by start, pruned of expired entries at 256), so the binds in between return without trying again. A range whose buffer could not be made at all is remembered the same way. d3d12_title_buffer_fallback_test fills a 16 MiB arena, refuses host-visible allocations behind the instance-proc pointer it hands the layer and runs with LEONIDA_SLOT133_IMPORT=0, then binds one 2 MiB title view 16 times as vertex and index views. Before: 16 buffers kept, 32 buffers of the view's size created. Now: none kept, 2 created (by the first bind), and after the retry delay one more try, still nothing kept.
…in (RT-ZERO-IMAGES-RETRY) A sampled BC texture placed on the title's memory waits for memory of its own, and its views name one shared, zeroed image of its exact shape (DeviceState::zero_sampled_image). When that image could not be made (create_texture failed, as it does under VRAM pressure, or the image lost its host-transfer usage after its memory was refused), the shape was stored as null in zero_images for the device's life: every later placement of it took memory of its own at once, for the rest of the session, even after the pressure had passed. Such a failure is now remembered in zero_image_retry with a time a second later: placements of the shape before then do not try again (each try makes an image and asks for its memory), and the first one after it does. A shape whose image would pass the 256 MiB the shared images may take still stays null: those images are never released, so it stays past the limit. d3d12_zero_image_retry_test refuses the next vkCreateImage of one BC1 shape behind the instance-proc pointer it hands the layer (the shared image, made before the placement's own), on a device without host image copies so that the shape takes a shared image at all. Before: after the delay a third placement still had memory of its own (one image of the shape made for it). Now it is shared (two made: the shared image and its own).
…it kept, and a failed call keeps nothing (RT-REHYDRATE-SCRATCH-TICKET) The queue lets go of what a submission kept in the first of its calls that finds the submission completed, after that call's own submission. With LEONIDA_SUBMIT_ASYNC that call runs on the worker, so the fence of its Signal can be reached before the release has run, and the test's last check read the sentinels too early: it failed in 2 of 20 runs with LEONIDA_SUBMIT_ASYNC=4. The test now signals and waits until both sentinels are released, up to eight more Signals. The worker runs the calls in order, so a release has finished by the time the next Signal's fence is reached. The sentinels are static, so a late release, or one at teardown after a failed step returned early, never touches a frame that has ended. execute_sync asks for the lists' kept objects only when the call succeeded. A failed call submitted nothing of the lists, and on a lost device the references would otherwise stay in pin_queue_ until the queue is destroyed. pin_lists and keep_lists take their references through one helper, reference_lists.
…ed views make one try a second in all (RT-TITLE-BUFFER-FALLBACK) The previous commit let go of the ordinary DEFAULT buffer that slot 133 answers with when a view's pages can be neither imported nor shadowed, but every retry still made one: vkCreateBuffer, a dedicated device-local allocation of up to 64 MiB (the arena being full is why the shadow failed), a zero fill, then a deferred free. That happened once a second for each refused range while the pressure lasted, under memory_mutex(), where the title's own allocations wait. create_at_host_address now takes ordinary_fallback (true by default, so slot 133 keeps its stand-in); make_title_buffer passes false and gets the shadow's HRESULT back instead. A buffer that does not cover the view is still let go. The retry was also per range: a title binding many views of one refused pool made one full try per distinct start per second. Now, after a refusal no range is tried for a second (title_buffer_retry_), and a range refused again waits twice as long as its last wait, up to 64 s, so one that keeps failing does not take every second's try from ranges that could get a buffer. Both checks come before the page walk, so a held-back bind makes no VirtualQuery call. d3d12_title_buffer_fallback_test now fills the arena with 64 KiB buffers, counts device-local allocations of a view's size while host-visible ones are refused, and binds a second view right after the first is refused and again later. With the previous commit: 2 device-local allocations (one per view) and the second view tried at once. Now: none, the second view held back for that second, and the first view, refused a second time, waits 2 s.
… a range, a few images a pass (RT-SLOT70-OWNED-RETIRE) title_memory_map::changed() with no range records [0, UINTPTR_MAX). On Windows, xmem records one for each run of pages it commits for a DirectStorage transfer, and one for every MEM_RELEASE. The refresh pass took such a change for a change over every owned image. It then walked the pages of each with VirtualQuery, under the registry lock, on the title's submitting thread, nearly every pass of a streaming load. A look costs about 0.5 us here, so 60,000 images would cost about 30 ms a pass. A change anywhere now marks no image: it says that something changed, not where. title_free_impl records a whole release over the range that allocation_extent finds before the free, so a released pool is still found. It falls back to a change anywhere when the walk stopped early. A pass visits at most LEONIDA_TITLE_IMAGE_CHECKS (128) of the images that may be retired, from where the last pass stopped. A candidate not reached keeps its mark. A slot-133 texture covers owned images only with the layout of the title's XG computer, or with the one its first slot-70 view gives it. The guess from its description (Layout 0) can be larger than what the title placed. The census line counts the images that a view named again after a newer texture covered them. The test hooks are now owned_title_images and owned_title_image, and the predicate is now owned_image_retirement_on. d3d12_title_image_retire adds four checks. A change anywhere with 13 images makes 0 looks (13 before). A change over 12 images makes 4 looks a pass with LEONIDA_TITLE_IMAGE_CHECKS=4 (12 in one pass before). A guessed slot-133 layout covers nothing until a view names the texture. An image never filled stays when its pages go. The new d3d12_title_image_idle (LEONIDA_TITLE_IMAGE_IDLE_MS=500) checks the idle time for both reasons, and that a view of an image whose pages went keeps it until a later change over them. xmem_test checks the range a whole release records. All of them fail on d442851.
…each failure, up to 64 s (RT-ZERO-IMAGES-RETRY) The previous commit tried such a shape again a second after each failure. A failure is not always transient: where the driver allows no memory type for host-transfer images (the NVIDIA Pascal case create_texture documents), the image loses host-transfer usage at every try, so each BC shape there would cost two vkCreateImage calls, a pool suballocation and bind, and a deferred free every second for the whole session, where before it cost one try per shape per session. zero_image_retry now keeps the last wait with the retry time. It is a second after the first failure and doubles at each failure after it, up to 64 s; a shape that gets its image is dropped from the map. A shape that fails for good costs about one try a minute. One that failed under pressure gets its image at the first placement after its current wait, so at most 64 s after the memory is back. d3d12_zero_image_retry_test now refuses the shape's image a second time at the first retry. 1.5 s after that, a placement still has memory of its own (refused twice, the shape waits 2 s); 1.5 s later one gets the shared image. With the previous commit the placement 1.5 s after the second refusal already took the shared image.
# Conflicts: # runtime/shims/d3d12_com.h # runtime/shims/d3d12_vulkan_device.cpp
…es it (RT-SLOT70-OWNED-RETIRE) LEONIDA_TITLE_IMAGE_RETIRE is off by default now; 1 turns it on. Retirement decides on a newer texture over an image's bytes or on its pages going, and on no slot-70 view naming it for a while. A title that samples such an image through a descriptor it wrote once (a heap it copies from, a table it keeps) with no later view of the address would sample the fallback once the image goes, and the census cannot see that. With the switch off nothing changes for the title; with it on, a streaming session can show whether the images stay at the textures still there. d3d12_title_image_retire and d3d12_title_image_idle run with the switch on. A negative LEONIDA_TITLE_IMAGE_IDLE_MS counts as 0.
# Conflicts: # runtime/shims/d3d12_vulkan_device.cpp
# Conflicts: # runtime/shims/d3d12_com.cpp
There was a problem hiding this comment.
🟡 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:
- Reclaims upload memory and stale bookkeeping, shares shader copies, and ties scratch lifetime to GPU completion.
- Improves allocation retries and texture cleanup, with additional slot-70 image retirement remaining opt-in.
- Adds synthetic regression tests and documents lifetime guarantees, diagnostics, and switches.
| File | Description |
|---|---|
| runtime/test/xs_proxy_mock_test.cpp | Tests allocator-owned upload reuse and cleanup. |
| runtime/test/xmem_test.cpp | Checks release notifications identify the freed range. |
| runtime/test/xbox_list_cut_spares_test.cpp | Tests idle spare lists release recordings and references. |
| runtime/test/xbox_bvh_builder_test.cpp | Checks scratch retention through GPU completion. |
| runtime/test/pso_stream_test.cpp | Tests bytecode sharing, collisions, and concurrent captures. |
| runtime/test/mem_probe_vmmap_test.cpp | Tests Windows memory classification and reporting. |
| runtime/test/d3d12_zero_image_retry_test.cpp | Tests shared-image retries and backoff. |
| runtime/test/d3d12_title_buffer_fallback_test.cpp | Tests failed title-buffer allocation and retry throttling. |
| runtime/test/d3d12_shadow_gpu_releases_test.cpp | Checks released-range cleanup in GPU copy modes. |
| runtime/test/d3d12_code_base_share_test.cpp | Tests shared shader arena copies and release. |
| runtime/test/console_heap_slot_records_test.cpp | Checks bucket counts follow live records. |
| runtime/test/command_list_test.cpp | Tests epoch cleanup when recordings are dropped. |
| runtime/src/vulkan_backend.h | Retains shim-owned objects until submissions complete. |
| runtime/src/title_va_alias.h | Exposes pending removal counts for tests. |
| runtime/src/title_texture_refresh.h | Exposes texture range-index size for tests. |
| runtime/src/title_texture_memory.h | Adds texture-page commitment checks. |
| runtime/src/mem_probe.h | Adds native Windows process-memory reporting. |
| runtime/src/console_heap_slot_records.h | Removes buckets when their last live record leaves. |
| runtime/src/command_list.h | Allows closed lists to drop their recordings. |
| runtime/src/command_list_epochs.h | Supports recordings without an active epoch stamp. |
| runtime/shims/xmem.cpp | Reports reservation ranges for whole-allocation releases. |
| runtime/shims/d3d12_xs_pso_stream.h | Documents shared shader-bytecode ownership. |
| runtime/shims/d3d12_xs_pso_stream.cpp | Interns identical shader bytecode across records. |
| runtime/shims/d3d12_xs_device.cpp | Rewinds allocator uploads and drops idle spare recordings. |
| runtime/shims/d3d12_com.h | Declares lifetime helpers and diagnostic test hooks. |
| runtime/shims/d3d12_com.cpp | Tracks shim-owned objects and releases dropped recordings. |
| runtime/README.md | Documents memory controls and diagnostics. |
| runtime/CMakeLists.txt | Registers new regression tests and variants. |
| docs/d3d12_xs_console_abi.md | Documents spare-list recording cleanup. |
| docs/d3d12_vulkan.md | Explains sharing, reclamation, and texture-retirement limits. |
| docs/d3d12_command_objects.md | Documents allocator-owned upload lifetimes. |
Review effort: Balanced
|
|
||
| int main() { | ||
| vktest::Device vk; | ||
| if (!vk.create()) return 77; |
| 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"); |
| auto status = gpu.initialize(); | ||
| if (status == vktest::DeviceStatus::unavailable) return 77; | ||
| CHECK(status == vktest::DeviceStatus::ready); |
# Conflicts: # runtime/shims/d3d12_xs_device.cpp # runtime/test/xs_proxy_mock_test.cpp
lixonik
left a comment
There was a problem hiding this comment.
Reviewed and verified at head f4cc2b33f (Windows 11, MSVC 19.44, Ninja Release, Rust 1.98.1, LEONIDA_VK_VALIDATION=1).
Verification
- C++ runtime (
untime/): built all 13 added/modified test targets plusgta6rt:ctest(LEONIDA_VK_VALIDATION=1): 13/13 passed (xs_proxy_mock,pso_stream,command_list,xmem,xbox_bvh_builder,d3d12_shadow_gpu_releases,d3d12_existing_heap,d3d12_zero_image_retry,d3d12_title_buffer_fallback,xbox_list_cut_spares,d3d12_code_base_share,mem_probe_vmmap,console_heap_slot_records), 0 Vulkan validation errors on NVIDIA GeForce RTX 5070.python -I scripts/check_no_game_data.py: clean.
- Rust (d3d12/):
cargo test -p leonida-hle -p leonida: 188/188 passed (0 failed, 2 ignored).cargo test -p leonida-gpu --lib: 493 passed, 4 failed (46 ignored). Re-tested the 4 failures (descriptor::host::tests::views_off_their_elements_get_a_copy_of_their_bytes,indirect::tests::batch_tables,indirect::tests::host_list_budget_starts_empty_at_each_submission,indirect::tests::warp_batch_charges_every_execution) on 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
- Needs rebase/merge with
main(blocking merge): two content conflicts againstmain(33db04a70) inruntime/shims/d3d12_xs_device.cppandruntime/test/xs_proxy_mock_test.cppdue to recentmaincommits10eb17825,038980a38, and53ed711b8. - Note on Copilot's BDA comments (false positive):
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. - Minor test robustness note (
untime/test/xbox_bvh_builder_test.cpp:603-604): the assertionsreset_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_validation 1.4.363).
AI-assisted (Antigravity, Gemini).
…nge holds its view until nothing answers it (RT-GEOMETRY-VIEWS-CONTAIN) refresh() skipped every per-tile copy of a view over a tile that cannot be guarded yet (a file read into it in flight), but update() had already taken the versions of the view's other written tiles. Those writes never reached the view: once the read ended only the retry tile was copied. With whole-view fills this caught up after the pin; with per-tile copies it did not, and containment widened it to every range inside such a view. A pinned view is now only kept from being filled whole. The retry tile is never among the written ones, so a filled view still takes its other written tiles at once and the retry tile once it can be guarded. retire_range took the command-list epoch for a view with an untouched range inside it while that range was still answered: from the lock-free answers until later in the same critical section, and from the alias table, heap slots and stream-pool span until on_retire had run after the lock. A list reset in that window carried a newer stamp, could still take the range's address, and did not hold the view. Such a view is now pending until on_retire has run, and only then takes its epoch. The copy of an acceleration structure's whole range (copy_title_range) is never answered from inside a larger view: a release elsewhere in that view would retire the structure with it, and its next copy would be made from the title's pages. resolve() takes contain = false for it. Also: a range answered from inside a view twice by racing threads is counted once, the geometry buffers line counts the retired views waiting for older command lists, and docs/d3d12_vulkan.md says that such a view is not refreshed while it waits, unlike a retired title window. Tests: geometry_views case 17 gains a stamp made inside on_retire, which must hold the view, and a range asked for with contain = false inside a live view, which gets a view of its own that outlives it. Case 18: a view over two tiles and a range inside its first tile; the title writes both tiles while a file read into the second is in flight, and the write to the first must reach both at the next refresh. Built with the one contain = false argument removed (neither has the parameter), 16 of 98 checks fail on d442851, both checks of case 18 among them, and 5 fail on the previous commit. With this change all pass, and with LEONIDA_GEOMETRY_CONTAINED=0 the 14 containment checks of case 17 fail.
# Conflicts: # runtime/CMakeLists.txt
lixonik
left a comment
There was a problem hiding this comment.
Re-verified after the main merge in 098342d02 (Windows 11, MSVC 19.44, Ninja Release, LEONIDA_VK_VALIDATION=1).
Verification at 098342d02
- Reviewed the merge resolution in
runtime/shims/d3d12_xs_device.cpp,runtime/test/pso_stream_test.cpp, 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. - Rebuilt
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_validation 1.4.363).
AI-assisted (Antigravity, Gemini).
GrahamboJangles
left a comment
There was a problem hiding this comment.
Reviewer pass over the sweep as a whole (nightly review; verified against current main b0c572464).
Claims check out. All 24 RT-*/RS-* item IDs link to exactly one claiming: line each in #1608 (by this branch's author), and the two geometry items (RT-GEOMETRY-VIEWS-CONTAIN, RT-DRAW-VIEWS-UNCHANGED) to #2570. No open PR duplicates any of the 26 IDs (gh pr list --search per ID).
Conflict notes check out. #1521, #2267 and #2085 are all still open, and the file overlaps are real: runtime/shims/d3d12_vulkan_device.cpp + runtime/test/d3d12_draw_test.cpp with #1521; runtime/CMakeLists.txt, runtime/README.md, runtime/test/d3d12_existing_heap_test.cpp with #2267; runtime/shims/d3d12_geometry_views.h + runtime/test/geometry_views_test.cpp with #2085. GitHub says mergeable but UNSTABLE — that matches: landing order against those three needs to be settled before merge.
Tree checks (local merge against fresh main b0c572464).
- Automatic merge is clean;
git 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.- Docs tests: current
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. - Sampled commit structure matches the PR body's promise: each fix is its own commit with its own test and quantified before/after (e.g.
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:
- AGENTS.md:133 requires the PR to say it was AI-assisted, what was tested, and on which GPU and driver — the body has no such statement for any of the 26 fixes.
- Given no CI signal on this PR and three open conflicting PRs, per-fix branches
adrianmjim/leonida:leaks/<name>are exactly the right fallback if the bundle has to be split; a line about intended landing order (vs #1521/#2267/#2085) would settle 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.
…RT-DEVICE-LOST-DRAIN) Once the device is lost, completed_retire_ticket() answers 0 and acquire() returns before its drain, so nothing drained the context's deferred deletion queue again until the context went away. Every image, buffer, device memory, view and image-memory range the title released after the loss stayed allocated, and the queue's ring kept doubling. defer_destroy now destroys the object at once when the device is lost, and the first such call also destroys everything queued before the loss. A lost device runs nothing more, and vkDestroy* and vkFreeMemory are valid on it. Bindless slots still wait in the queue: their release takes the device's descriptor lock, which release() holds when it defers one, and the set gives out no more slots than it has, so those entries stay bounded. vk_deferred_destroy_lost_test defers 500 buffers, marks the context lost and defers 500 more: all 1000 are destroyed while the context lives, none twice at teardown, and the two bindless slots are released once, at teardown. Before this change it stopped with none of the 1000 destroyed.
…TORAGE-SCRATCH) Every compressed request allocated zero-filled buffers and freed them at the end: the source read from the file, the zlib output that BCPack then unpacks (intermediate_size), and the destination's bytes when its physical pages are not one allocation's in order. Blocks of 1 MiB and more come from the host's virtual memory, fresh and zero-filled each time, so streaming paid an allocation, page faults and a free per request. Each worker now keeps these buffers in its own frame (Scratch) and passes them to execute(). A buffer grows only when a request needs more than it holds. The source is read over what an earlier request left (read_into writes all of it or fails), the zlib output is used only as far as inflate wrote it, and the page buffer is zeroed as a new one was, so the bytes written are the same as before. Between requests a worker keeps at most 16 MiB, giving up its largest buffers first. staging_bytes now counts every buffer a request holds: besides the compressed source read from a file, the zlib output of a zlib+BCPack request and the destination's bytes of a request to pages (the source's for a raw copy). LEONIDA_DSTORAGE_STAGING_MB bounds all of them now. compressed_requests_reuse_the_workers_buffers counts, under a test-only counting allocator, the blocks of the three buffers' sizes over many requests: one per request before (72 of each in 72 requests on 16 workers), at most one per worker now. Two smaller tests check the staging accounting and the 16 MiB bound.
|
Red (
|
…TAINER-FREE) The shader table kept a private copy of every container the title passes (container: bytes.to_vec()) for the whole process, also after the shader was translated, when only small facts of it are still read. What is still read is now kept apart: the program's name and whether its immediate samplers are made linear go into the translation; what pipeline creation asks (a structure builder program, the names make leaves out) is answered once per shader, at the first creation or at the latest before the container goes; the pipeline book uses the stored BLAKE3. After a successful translation the container goes and the memory line's container counters follow it. A shader that stores keeps its container while LEONIDA_PICKED_WRITES is on, until crate::picked has read its programs. Shaders not translated (most of them: translation is lazy) and shaders that fail to translate keep theirs as before. The test translates 64 hand-built compute containers of 32 KB and checks that they keep no container bytes afterwards (all 2,107,648 on the parent), and that a pipeline created again from the first one shares the translated shader and is left out by name as the first was.
… (RS-ARENA-ONE-COPY) Every 64 MiB arena of title memory by address (memory.rs) was held twice in the PC's memory: the arena itself (committed, write-watched) and the CPU side of its copy on the card, a shared buffer of the same size that by_address made and that every refresh compared with the arena. memory.rs already takes only the dwords title memory changed into the arena, so the two held the same bytes. That is 64 MiB more commit per arena; reads alone make a few arenas, the structure builder (LEONIDA_BVH_BUILDER=1) up to 48. Now Memory::another() makes the copy with shadow::by_address_opened: the arena is opened as a host heap (inplace::place_part, as the in-place windows do) and is itself the CPU side, with Card::staging a buffer placed over it. Such a copy is never refreshed or compared; bring() and take() resend exactly the dword runs they change, so the card side keeps what the builder made of the other dwords, as before. The whole arena goes up once when it is made, as a new copy's first refresh sent it. If the host does not open the memory, the copy is made as before. The directory and the windows of title memory keep the old path. USED in by_address is only ever added to; since copies by address are never let go it is a live total apart from attempts over the limit, left as it is. Tests: an_arena_is_in_the_pcs_memory_once (fails on main: the CPU side is a buffer of its own, 192 MiB more commit per arena on an RX 7900 XT, whose driver charges the card side too; 128 MiB with this change) and an_arena_sends_up_only_the_dwords_the_title_changed (the card keeps its own dword beside the one the title changed, with and without LEONIDA_SEND_OWN).
… (RT-DEVICE-LOST-DRAIN) DeviceState::release defers a bindless slot and then the image views paired with it, and until the slot is released the set's pending writes and shadow copy may still name those views. Before this the deferred queue drained in order, so the slot's write was swapped for the fallback before the views went. After a loss the previous commit destroyed the views at once (and drain_lost destroyed those queued before the loss) while the slot stayed queued, so a flush that still ran could hand a destroyed view to vkUpdateDescriptorSets. Image views now stay queued after the loss like the slots, in their order, and go at teardown after their slot. That stays bounded: no slot comes back before its release, a slot has at most four views, and the context's view cache grows only while batches replay. The test now also defers a slot and its view before and after the loss and expects no view destroyed before teardown, then each slot released before its view. It counts only the buffers and views it made.
… before the bindless flush (RT-DEVICE-LOST-DRAIN) A queue holds tracker_mutex_ through its vkQueueSubmit, so it can find the device lost while another queue's ExecuteCommandLists waits for that lock, past its own checks of the loss (the first one and acquire()). Once lost, defer_destroy destroys released objects at once and also what was queued before the loss, so an image may be gone whose view the bindless set's pending writes or shadow copy still name until its slot is released. The waiting batch then flushed the set and handed that view to vkUpdateDescriptorSets. execute_now now checks the loss again right after it takes tracker_mutex_, before the bindless prepare, and returns as its other checks do. The batch would not have reached the queue anyway, since submit() refuses a lost device, so nothing the title sees changes. The test marks the device lost from an interposed vkBeginCommandBuffer, after the batch's own checks, and expects the bindless prepare not to run.
… go up (RS-ARENA-ONE-COPY) Memory::take runs at a submission, under the memory lock. It had become the scalar dword merge for every page, which builds the runs that changed. Only one case uses those runs: a page that is not taken whole, in an arena whose copy has the arena as its CPU side. Every whole take (each placed page, each packed structure) and every arena on the old path threw them away, at about 2.5 times the cost of the compare and copy that was there before. Now that case finds its runs with shadow's AVX2 word_runs_put, as a refresh finds them. Every other case compares and copies as before. The write watch is no longer told about writes to an opened arena, since nothing asks it about one. The arena test now also takes a page as land() does and checks that the dword the title changed goes up beside the card's own dword.
… belong (RS-ARENA-ONE-COPY) The whole arena now goes up from Memory::another, once the copy has a number. Before, by_address_with queued it, and a copy that number() then refused left a dead entry in the queue of changed copies. opened_side logs, once, why an arena was not opened, also when the host placed it off a 64 KiB line. Before, that case fell back without a word. It cannot happen for upload::reserve's memory. The SAFETY comment in host/send.rs said that only the thread that asked writes a CPU side. That is no longer true for an opened arena: a recording thread may write it while a submission reads it to send. The comment now says so, and why the card still gets the new bytes. The arena test returns early on a host that cannot open memory as a heap, as the inplace tests do, since the old path is the design there. It also checks that the process memory counters were read.
RS-APU-SCRATCH (apu.rs) and RS-DSTORAGE-SCRATCH (dstorage.rs) each
installed a counting #[global_allocator] in their test module, and a
binary has one: with both merged, the leonida-hle tests no longer build
("cannot define multiple global allocators").
The allocator moves to src/test_alloc.rs and tells both counters of each
block; each module keeps only its counter (apu::tests::counting::note,
dstorage::tests::watched_blocks::note). Same features as before: not
with diagnostics or mimalloc, where leonida-gpu installs its own.
cargo test -p leonida-hle --lib: 189 passed, 2 ignored, including
packets_decode_without_memory_of_their_own,
compressed_requests_reuse_the_workers_buffers and
staging_counts_every_buffer_a_request_holds.
lixonik
left a comment
There was a problem hiding this comment.
Re-verified updated head abdb93f0e (covering the two newly added leak fixes RT-GEOMETRY-VIEWS-CONTAIN and RT-DRAW-VIEWS-UNCHANGED, plus the clean main d48a957bb merge).
Code audit (098342d02..abdb93f0e):
RT-GEOMETRY-VIEWS-CONTAIN(runtime/shims/d3d12_geometry_views.h,d3d12_vulkan_device.cpp):outer_index +contained_tracking cleanly serve inner ranges from ready outer views,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):
- Built
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_validation 1.4.363).
AI-assisted (Antigravity, Gemini).
|
Under Wine the new The region walk sees the 64 MiB ( The three Not checked by a second agent or human yet. AI-assisted (Claude Code). |
lixonik
left a comment
There was a problem hiding this comment.
Re-verified updated head eb145de6f covering the newly added fixes (RT-DEVICE-LOST-DRAIN, RS-ARENA-ONE-COPY, RS-SHADER-CONTAINER-FREE, RS-DSTORAGE-SCRATCH, and the shared leonida-hle test allocator).
Code audit (abdb93f0e..eb145de6f):
RT-DEVICE-LOST-DRAIN(runtime/src/vulkan_backend.h):kept_after_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_.- Rust additions (
leonida-hle/src/test_alloc.rs,dstorage.rs,apu.rs;leonida-gpu/src/memory.rs,shadow.rs,pipeline.rs,pipeline/host.rs): cleanly unify the test counting allocator, reuse per-worker DirectStorage scratch buffers within the 16 MiB bound, drop translated shader containers once metadata is captured, and avoid double-copying opened arenas.
Verification at eb145de6f (Windows 11, MSVC 19.44, Ninja Release, LEONIDA_VK_VALIDATION=1):
- C++: built
vk_deferred_destroy_lost_test;ctest -R '^vk_deferred_destroy_lost$': 1/1 passed (0.23 s, 0 validation errors). - Rust (
d3d12/):cargo test -p leonida-hle --lib -- --test-threads=1: 189 passed, 0 failed, 2 ignored (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_validation 1.4.363).
AI-assisted (Antigravity, Gemini).

Claimed in the coordination issue as: RT-UPLOAD-ARENA-REWIND, RT-PSO-BYTECODE-INTERN, RT-SPARE-LIST-EPOCHS, RT-SLOT-RECORDS-BUCKETS, RT-REHYDRATE-SCRATCH-TICKET, RT-FSSM-ARENA-SHARE, RT-TITLE-BUFFER-FALLBACK, RT-SLOT70-DEVICE-CYCLE, RT-MEM-PROBE-WINDOWS, RT-ZERO-IMAGES-RETRY, RT-TITLE-TEXTURE-GONE-RANGES, RT-SHADOW-GPU-RELEASED-RANGES, RT-SLOT70-OWNED-RETIRE (#1608 (comment)); 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 (comment)); RT-GEOMETRY-VIEWS-CONTAIN, RT-DRAW-VIEWS-UNCHANGED (#2570 (comment)); RS-ARENA-ONE-COPY, RS-SHADER-CONTAINER-FREE, RS-DSTORAGE-SCRATCH, RT-DEVICE-LOST-DRAIN (#2570 (comment))
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) and #2480 (runtime/src/command_list.h).What and why
Thirty fixes for memory that the two runtimes never give back, or keep longer than they need. Sixteen are in the C++ runtime (
runtime/: the D3D12 → Vulkan layer and the console D3D12 proxy), the thirteen below and three more further down. Fourteen 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 (comment)). 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 (comment)). 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 d442851'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 d442851'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 (comment)). 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.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/allatabdb93f0e, all 26 fixes withmaind48a957bbmerged in (330 commits since33db04a70, no conflict). MEASURED on the same machine:-j 8: 3 of 525 fail, the same three as below (d3d12_texture_tiles,pipeline_cache_seed,d3d12_clear). The presentation tests all pass this time.cargo test --workspace --no-fail-fastind3d12/:leonida-gpu493 passed, with the same 4 failures asmain(listed further up);leonida-hle186 passed. Three more fail in code these fixes leave byte for byte as onmaind48a957bb:leonida-shaderemit::valu_tests::{typed_d16_table_uav_roundtrip_uint_sint_and_float, rdna_forms_give_what_the_spelled_out_ones_give}(the crate has no path dependency onleonida-gpuorleonida-hle), andxtaskpolicy::tests::repository_passes_policy, becausemain'sleonida-shader/src/emit/lower.rsis 664,714 bytes, over the 655,360-byte limit.tests/test_*.py, 12 fail: the 7 below, plus 5 that also fail on plainmaind48a957bb(test_build_runtime_fallback,test_sampler_source_census,test_spirv_metal_set0_cli_errors,test_spirv_metal_set0_extra;test_make_game_pipelinesfailed here and timed out after 600 s onmain). None of the 26 fixes touchestests/,tools/orscripts/.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 d3d12_xs: retain queue and fence wrappers through forwarded calls #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 (test: texture tiles NOTE only for the measured CopyTiles offset rounding on AMD and Intel (D3D-TILES-AMD-BYTE-OFFSET) #964).pipeline_cache_seed: the checker's device differs from the runtime's (vk_pipeline_check: choose robustBufferAccess and VK_EXT_robustness2 as the runtime does (RT-PIPELINE-CHECK-ROBUSTNESS) #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). ASSUMED, not measured inside: most of it is the driver's memory for pipelines (thepe-privatekind of the vmmap line), so it is not from these fixes.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
AI-assisted: yes (Claude Code, Claude Opus 5.5)
Checklist
mainand merges cleanly (a conflicting pull request is labeledneeds rebase).runtime/and fourteen ind3d12/, 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)