Skip to content

[integration] PageMirror, GPU detile, async queue & RDNA2->SPIR-V performance stack (INTEGRATION-PERF-CPU-GPU-R6) - #2566

Open
aslan2142 wants to merge 197 commits into
ProjectLeonida:mainfrom
aslan2142:integration/perf-cpu-gpu-r6
Open

aslan2142 wants to merge 197 commits into
ProjectLeonida:mainfrom
aslan2142:integration/perf-cpu-gpu-r6

Conversation

@aslan2142

@aslan2142 aslan2142 commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

Claimed in the coordination issue as: INTEGRATION-PERF-CPU-GPU-R6

What and why

Integration PR (aslan2142:integration/perf-cpu-gpu-r6, merged cleanly with upstream main d48a957bb) combining the PageMirror / in-place console descriptor heap / GPU detile runtime stack with ten rounds of CPU submission, bindless GC, memory-tracking, async synchronization, and RDNA2 → SPIR-V translator performance & correctness work.

1. RDNA2 → SPIR-V Translator Correctness & GPU Codegen (tools/rdna2spirv.py, tools/shader_meta.py, tools/lane_masks.py, docs/design.md)

  • Absent-lane subgroup UB elimination: Guards wave-uniform v_readfirstlane_b32, v_readlane_b32, v_permlane16_b32/v_permlanex16_b32, DPP (fi:1 & out-of-row), ds_append/ds_consume/ds_permute/ds_lane_read, and non-fragment s_wqm against unlaunched/absent subgroup lanes; adds static SPIR-V invariant checker (tests/semantic/check_absent_lane_ub.py), partial-wave CPU regression suite (tests/semantic/test_absent_lane_ub.py), and live GPU test (tests/test_absent_lane_gpu.py).
  • FTZ32 & fmulz enablement: Checks exact HW_REG_MODE bit overlap with [4, 6) (FP_DENORM.fp32) in _disables_ftz32(), re-enabling FTZ32 and fmulz across the corpus while keeping explicit software denormal flushing (force=True) on v_exp_f32 (GLSL.std.450 Exp2).
  • Compact outlined sbuf_slow + NonWritable SMEM: Replaces expanded per-load slow paths with compact OpLoopMerge ... DontUnroll %sbuf_slow_{ro,rw}_xN helpers with overflow-safe 64-bit bounds, and adds CFG store-reachability (WAR-safe) + descriptor-provenance NonWritable SMEM tagging.
  • Image, sampler, coherent VMM & write-back metadata:
    • SPV_KHR_vulkan_memory_model (MakePointerVisible/MakePointerAvailable) for glc/dlc loads & stores + reads_glc_buffer metadata.
    • Compile-time literal S# sampler OpSpecConstant specialization (literal_samplers / literal_sampler_spec_base) bypassing FNV-1a bindless probes.
    • Float-only image_read_typed dead-branch elision (f32/f16 consumers + bilinear/linear-mip literal samplers) and table-driven buffer_store_format.
    • writes_buffer and buffer_write_slots metadata for gating passive write-back.
    • Wide s_buffer_load, SPV_KHR_integer_dot_product (v_dot4), heap T# bindless index word in dword 6, and pure scalar-spill VGPR parking.
  • All new translator rules are documented in the contract table of docs/design.md.

2. Runtime PageMirror, Console Heaps in Place & GPU Detiling (runtime/src/title_mirror.h, title_mirror_hot_cold.h, shadow_keep.h, vulkan_title_detile.h, runtime/shims/d3d12_*, xmem.cpp)

  • PageMirror & in-place console descriptor heaps: Mirrors title memory pages into sparse device-local chunks (Chunk::pages[32768] direct table) with 256-byte piece-level CPU/GPU merge, hot/cold submission write tracking (kPromote = 6/8), 64 MiB copy-queue readback with sub-page 256 B copies, page_mirror_buffer resolve_cache, and hoisted FilterCacheScope + parallel Phase-A/disjoint-WC-flush console heap filtering (local_mirror chunk cache, AVX2 32-byte slots_equal_32, 8 KiB L1d seen_keys, per-batch T# dedup, lock-free in_place_work_pending fast-skip).
  • AVX2 / x86-64-v3 SIMD & 8-worker mirror pool: Enables /arch:AVX2 (x64 MSVC/clang-cl) and -march=x86-64-v3 (x86-64 GCC/Clang) for C/C++ targets; adds 4×256-bit AVX2 + 4×128-bit SSE2 shadow_keep::sum_of(), sum_of_batch_256(), and fused SEH-safe guarded::copy_and_sum_256(), plus an 8-worker TitleMirror::WorkerPool with 50 µs spin and WC streaming copies.
  • Low-syscall VM guard tracking & shared Cell::known_*: Unlocked parallel Phase-1 readback pre-hashing, shared Cell::known_* across CellGuard & TitleTextureCells (excluding PAGE_READONLY from VQ caches), TitleHeap::hooks.commit/decommit map-change scoping, batched copy_page_mappings(), safe per-tile bridged VirtualProtect rollback (preserving already-armed gap tiles), zero-syscall all_armed fast paths, and range-scoped reopen() / changes_since().
  • GPU detiling & batched texture refresh (title_texture_watch.h, title_texture_refresh.h, d3d12_title_image_upload.h):
    • GPU compute detiling directly from TitleMirror chunks + TitleMirror::range_sum() skip + 512-job / 128 MiB GPU-mirror upload batching (TitleImagePool 8 MiB/16 MiB cap, kMaxScratchSlots=64).
    • Deferred slot-70 uploads to GPU detile + publish_streamed_texture() fix, separated title_texel_writes, Stage-2 TextureVqCache + Stage-2b Cell::restore[] readability bypass, single-lock page_mirror_check_batch(), and TitleTextureWatch::examine_batch() + TitleTextureCells::arm_batch().
  • Bindless view sharing & two-phase dead-sweep GC (vulkan_bindless.h, d3d12_vulkan_device.cpp):
    • Refcounted ViewKey sharing, O(1) BindlessSet free-lists, single-lock bind_title_image(), ConsoleHeapSlotRecords kTexture/kSettled live tracking, and explicit evictable classification.
    • Two-phase GC (Phase 1 dead-key sweep with 0 texture notifications + 8,192-slot hysteresis, Phase 2 emergency live-LRU only on hard_full, multi-key sv.keys liveness, dim_2d mirror-slot room notifications) eliminating 65,536-slot saturation and GC thrash in long gameplay sessions.

3. Runtime Async Queue, Replay Cache, List-Value Sync & Single-Flight Coalescing (runtime/src/vulkan_backend.h, queue_holds.h, vulkan_replay.h, vulkan_presenter.h, runtime/shims/d3d12_com.cpp, d3d12_xs_list_values.h)

  • Dynamic rendering scope batching & ReplayStateCache: Batches compatible consecutive draws into single dynamic rendering scopes, elides redundant Vulkan pipeline/descriptor/push/viewport/scissor binds in emit_commands(), caches CommandList summaries, and fans out synchronous unbuilt PSOs concurrently via PipelineCompiler.
  • Zero-unmet list-value sync & GPU-to-GPU relays: Fixed Pump::choose_release() TOCTOU + quiet window (0 released unmet), dedicated QueueHolds barrier-drain thread, non-blocking release_ready(), SEH aligned volatile read_value(), 1000 ms slot-12 timeout, VulkanFence::signal_gpu_relay() (vis_seq=0) + retroactive QueueHolds::relay_wait() / VulkanQueue::apply_wait_relay() with WriteGroup::bare visibility safety, exact landed-value console_value_met() verification, wait_met re-check, relay_wait() gate preservation, and signal-only consumed_wait_vis transitivity.
  • Single-flight BeforeExecuteCoalescer + feed-only mirror drain: Reordered global refresh (wb -> mirror -> flush -> tex -> shadows -> 2nd flush) with decoupled lazy gpu_profile_.resolve() and 4-deep VulkanPresenter::frames_; coalesced submissions run a lock-free O(1) check / drain_page_mirror_feed_only() (0.11–0.29 ms when CopyPageMappingsBatchX remaps are queued) achieving 96–97% coalescing with 0 single-flight waits (opt-out LEONIDA_BEFORE_EXECUTE_COALESCE=0).

Measured Impact (RX 7900 XTX, RADV, Wine)

  • Stability: Continuous multi-minute cutscene + in-game runs (run107, post-merge run108: 370–400+ s) with 0 GPUVM faults, 0 VK_ERROR_DEVICE_LOST, 0 unmet list-value gates (across 28,372–42,047 held gates), and 0 bindless GC thrash (3 clean dead-sweeps of 8,192 dead keys each, 0 textures notified).
  • Opening cutscene FPS: Rose from ~0.6–0.8 fps baseline (3.6–5.9 fps at Round 6) to 7.4–13.9 fps (96–97% before-execute coalesced, 0 single-flight waits, own threads 50.8–88.3 ms/f, title threads 8.6–11.3 ms/f).
  • In-game gameplay FPS: Stable 6.0–7.4 fps (79–84 ms/f own threads, 7.0–15.1 ms/f title threads, Direct GPU now 66–75% utilized / 101–121 ms/f busy — shifting the bottleneck from CPU to GPU).

Tested

  • Shader translator & semantic suites (post-merge 232b4a1ee):
    • python3 -m compileall -q make_game.py tools tests: 0 errors.
    • python3 -m unittest tests/semantic/test_alu_exp_f32.py tests/semantic/test_ftz32_fmulz.py tests/semantic/test_buffer_format_d16_hi.py -v: 14/14 PASS.
    • All 17 merged-feature semantic suites (test_absent_lane_ub, test_ds_permute_eager, test_cvt_f16_denorm_mods, test_f16_denorm_preserve, test_buffer_format_d16_hi, test_gather4_c_lz, test_sample_g16, test_high_half_shared_readers, test_ftz32_fmulz, test_wave64_emulate_opt, test_wave64_halves, test_fma_denorm_product, test_alu_sat_pk_u8_i16, test_lds_bound_access, test_lds_write2_equal_offsets, test_active_runs, test_fp_edge_conformance): 278/278 PASS.
    • Full-corpus retranslation (32 shards): 29,267 / 29,267 shaders translated & spirv-val-valid; full-corpus check_absent_lane_ub.py sweep: 0 flagged / 0 UB sites.
  • Linux portable build & Vulkan tests (-march=x86-64-v3, MESA_VK_DEVICE_SELECT='1002:164e!'):
    • cmake --build runtime/build + ctest --test-dir runtime/build --output-on-failure -j8: 136/136 PASS (2 skipped: shader_library_corpus, vk_sync_validation).
    • LEONIDA_VK_VALIDATION=1 on list_value_progress, submit_frame, vk_title_mirror, vk_title_detile, vk_bindless_grow, vk_bindless_dimensions, title_mirror_hooks, r3b_runtime_hooks, replay_state_cache: 9/9 PASS, 0 validation errors.
  • Windows cross-build (clang-cl /arch:AVX2) & targeted Wine iGPU suite (r10-main-merge-igpu):
    • gta6rt.exe + gta6rt_tls_host.dll: clean build, 0 errors.
    • Targeted 41-test Wine iGPU suite (d3d12_existing_heap, d3d12_heap_in_place, d3d12_queue_wait, xbox_list_value_fallback, list_value_progress, submit_frame, console_heap_slot_records, title_mirror, shadow_keep, xmem, vk_bindless, vk_title_detile, d3d12_pipeline_checkpoint, xs_proxy_mock, acphal, d3d12_fence_timing): 40/41 PASS (xmem_write_watch passed on re-run; only upstream d3d12_fence_timing's EnumAdapterByLuid failed under headless Wine Xvfb without DRI3 — its GPU/CPU clock calibration checks passed).
  • Hygiene:
    • python3 -I scripts/check_no_game_data.py: PASS.

GPUs tested:

  • AMD Radeon RX 7900 XTX (RADV NAVI31), Mesa 26.3.1-arch1.3, Linux 7.3.6-zen1-1-zen (Wine)
  • AMD Ryzen 9 7950X3D iGPU (RADV RAPHAEL_MENDOCINO), Mesa 26.3.1-arch1.3, Linux 7.3.6-zen1-1-zen (native Linux + Wine)

AI-assisted: yes — Antigravity (Gemini 4 Neon & Claude Opus 5.5).

Checklist

  • Based on current main and merges cleanly (merged d48a957bb, reviewed by two independent reviewers).
  • One topic; follow-up work goes in a new pull request (integration PR of the PageMirror + CPU/GPU performance stack).
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed.

aslan2142 and others added 30 commits November 26, 2026 16:39
…cations need it (RT-MEMORY-BREAKDOWN-AND-SPARSE-ARENA)

The arena was one allocation of its whole size, made at start: with LEONIDA_ARENA_MB=4095 a world run used about
0.8 GB of it (peak end about 1 GB) and held 4 GiB of Resizable BAR memory. Where the device can, the arena is now a
sparse buffer: LEONIDA_ARENA_MB bounds the address range, and memory is bound as it is used.

- src/arena_backing.h (new): the backing units. A unit is one VkDeviceMemory, mapped once, bound over whole 2 MiB
  blocks. An allocation no larger than a block stays inside one block; a larger one takes whole blocks of its own
  (the free-block map's keep-out, footprint and alignment). A unit is bound before the first allocation in it is
  handed out, and when its last allocation is released it is pending with the release's retire ticket; it is unbound
  and freed only once completed_retire_ticket() has reached that ticket. An allocation in a pending block revives it.
- The CPU reaches the arena through one accessor, DeviceState::arena_host(offset, bytes): one table read, null with a
  rate-limited line for a range without memory. Callers that name an offset they do not hold (write_arena_value,
  read_arena, the fsdraw probe) use ArenaBacking::with_host under its shared lock; copy_destination and
  known_view_heap use offset_of. arena.mapped is gone, so every former `arena.mapped + offset` was converted.
- Binds go to a queue nothing else uses (pick_arena_bind_queue: RADV's sparse-only family, or a sparse family with
  a queue to spare) and are waited for there, so a bind never sits behind a submission that waits for a fence the
  CPU signals later. The device asks for that queue at creation.
- Unbinding is safe because: arena_release records submitted_retire_ticket() + 1 (as defer_destroy), so the
  submission being recorded is covered too; reclaim_arena() runs at the start of ExecuteCommandLists, reads
  completed_retire_ticket() before taking the arena lock, and unbinds only units whose ticket has completed; the
  table entries are cleared under the exclusive lock before the memory is freed. An unbound range reads as zero
  (residencyNonResidentStrict is required), never a fault.
- A D3D12 heap in the arena lends its unit's memory (at the heap's place in the unit) to reserved resources' tiles;
  Heap::offset() keeps the arena VA.
- Without sparse buffers, strict residency, a sparse address space as large as the arena, or a queue to spare
  (llvmpipe), one allocation backs the whole arena as before, through the same accessors. No new setting.
- The arena line at release gains `GPU address arena: bound N MiB now (peak P, U units of 2 MiB blocks, sparse)`;
  the mem-probe breakdown's arena `bound` is the bound bytes.

Tests: arena_backing_test (CPU, fake driver): placement never crosses a unit, binds shared per block, unbinding
waits for the ticket, revival, a random workload whose bound bytes equal the blocks live allocations touch, bind
failure, the one-allocation arena, the bind queue choice. arena_sparse_gpu_test (a real device, 77 without sparse
binding): a 256 MiB arena with 40 MiB allocated has 44 MiB bound; CPU writes are what the GPU reads; released blocks
stay bound while a submission that reads them is in flight and are unbound (reading zero) once it completes; a bind
made while the work queue is blocked completes. Both are new (fail to build on main).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…; a sparse arena only then (RT-MEMORY-MODEL)

RADV puts sparse buffers 64 TiB above ordinary ones, so with the sparse arena of the previous commit every geometry
copy and title-window block lay below heap_base and TitleBufferWindows::allocate refused it (it accepted only a
positive offset below 2^47). Shaders translated since 2026-11-24 sign-extend a V#'s 48-bit base and say so in their
index entry (vsharp_base_sign_extended), and RADV hands out every address from one 2^47 half of the 48-bit space, so
any block is within reach of heap_base as a signed offset.

- shader_library.h: VsharpBaseCensus counts the marker over every loaded module; signed only when all have it.
- The device reads V# bases signed when the census says so (or with LEONIDA_IMPORT_BELOW_ARENA=1, as before). The
  import refusal still follows that setting alone. One line logs the census.
- create_arena: the arena is sparse only with signed offsets; otherwise one allocation, and one line says why.
- TitleBufferWindows::shader_reachable replaces the positive-only check. The first failure of each Vulkan call while
  making a block, and the first block refused for its address, are logged.
- rebase_title_vsharp sign-extends a base it already rewrote below heap_base.
- device_arena_memory (for tests); cs_user_data.comp reads V# bases sign-extended, as translated shaders do.

Tests: d3d12_title_va_game_device and d3d12_geometry_views_game_device (d3d12_title_va_test --game-device: the
device the game makes, with the arena's bind queue); geometry_views_test (shader_reachable at the measured RADV
addresses and the range edges); shader_library_test (the census). Wine suite on the iGPU: 429 pass / 23 fail against
425 / 23 on main 8bc59a7, nothing pass to fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…on the CPU, and are never skipped (RT-TITLE-UPLOAD-GPU-ORDER)

A title texture upload waited on the CPU, with the submit lock held, for all work submitted on every queue, at
most 250 ms, and skipped the write when that work was not done. World frames take longer, so changed textures
(the planes of a video frame among them) arrived late or out of step, and the submitting thread stalled up to
250 ms per upload (the 200-277 ms maxima of the textures phase in world runs).

The staged transfer now waits for that work on the GPU: write_staged_title_image hands it every queue timeline
value submitted so far. Every such value is already submitted, and console waits whose signal is not submitted
live in QueueHolds, so the GPU wait cannot deadlock. The upload slots are reused once their transfer is done
(looked up, not waited for), and new ones are made while all are in flight. Every title fill goes through this
upload, so the host-copy path for title textures (write_host_texture, its bounded wait and
LEONIDA_ORDER_TEXTURE_UPLOADS) goes. As before, the transfer is submitted on the primary queue before the
submission whose before_execute runs the refresh, and the other queues wait for it on the GPU, so that
submission's draws sample the new texels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ere written, not at every texture's bytes (RT-TITLE-TEXTURE-WRITE-TRACKED)

Before every submission (at most every 16 ms, and not at all when a view held the registry), the refresh hashed
every mapped or stale texture and a round robin of the rest (sampled, a full hash every sixth pass), within
byte and time budgets that could split the planes of one video frame over passes.

Now each title texture filled from memory is watched through the geometry watch's cells: its 64 KiB tiles, at
its CPU view and every other address xmem maps them at, are armed read-only; a write faults once per tile, and
the fault, a mapping change or a kernel write's opening queues the tile (geometry_writes::WriteQueue, new). The
refresh, at every submission and with the registry waited for, takes that queue and reads only the textures over
the written tiles (TitleTextureWatch, src/title_texture_watch.h), arming them again before the read; a texture
nobody wrote costs nothing. A tile that cannot be armed (not committed, pinned, no fault handler) names its
textures at every pass: the one fallback. A fill whose full hash equals the last one uploads nothing. A slot-70
view no longer hashes its texture: it fills only one never filled or known changed.

Removed with the hash pass: LEONIDA_TITLE_TEXTURE_PERIOD_MS, _CHECK_KB, _FILL_MB, _FILL_MS,
LEONIDA_TEXTURE_HASH_BUDGET_US, LEONIDA_TEXTURE_SWEEP_BUDGET_US, LEONIDA_TITLE_EVERY_BUDGET_US,
LEONIDA_TITLE_VIEW_REFRESH_MS and the async mode LEONIDA_TEXTURE_REFRESH_ASYNC (its worker pass, first-use
fills, mapped list and range index). A line every 10 s counts passes, textures looked at, uploaded, unchanged,
written tiles and arms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nly at the slots it overlaps (RT-SLOT-RECORDS-EXACT-INDEX)

The records' two indexes kept each V# half in a bucket per power-of-two span class and 64 KiB-or-larger block,
and a change visited every entry of every bucket it reached, plus resolved halves for an addition that only
re-fixes waiting ones: 82,000-472,000 slots looked at per submission for 2-15 changes and 1,450-3,150 slots
fixed in the busiest world windows of one run, 4.4-13.4 ms a submission.

Now each index holds the halves by their exact range: halves naming the same range share a group with a resolved
and a waiting list, each half keeping its place in its list (a move or a removal is O(1), no stale entries, an
empty group goes). Groups are ordered by start per power-of-two class of their length; a query searches each
class in use once and walks the groups starting less than one class length before the change. A change looks at
exactly the halves whose range overlaps it (an addition: the waiting ones only); the groups compared besides are
those that start within one class length before it and end before it, one comparison each and no slot. 20 bytes
a half (was 24), plus a group per distinct range. Interface and device code unchanged.

Test: 300,000 slots of 16 bytes packed into 74 blocks of 64 KiB; a 40-byte release looks at the 3 it overlaps
(the bucketed index looked at the whole block and fails), by source it also finds a 1 MiB range starting two
blocks earlier, a moved slot leaves nothing behind, and an addition over all of them looks at the 1,000 waiting.
The 400 random rounds against a full re-resolution still pass (entries looked at 792,825 -> 133,506 for the same
81,005 slots fixed); copies that skip large ranges or the waiting lists on a removal fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tes, not host remaps (RT-MEMORY-MODEL)

The console queue's CopyPageMappingsBatchX goes through xmem's range callback in a retail run. It host-mapped every
destination page of a paired GPU-only range twice: the GPU-only page and its CPU twin. Each map is a VirtualQuery, a
placeholder split and a MapViewOfFile3/UnmapViewOfFile2, which are wineserver round trips under Wine. All of it ran on
the render thread under g_phys_mutex, which DirectStorage's page transfers take too. A local world run spent 3.9-6.0 s
mapping per 10-12 s.

Nothing on the host reads a GPU-only address of a paired range:
- the D3D12 layer, DirectStorage and the texture refresh read the CPU twin (title_gpu_views::to_cpu);
- the runtime reads a page by number through its section's scratch view (host_page);
- the title's CPU never touches the range (PAGE_NOACCESS on the console).

So such a page now gets its physical page in g_mapped and g_table_pages alone, with no host view, as the console edits
GPU page tables only. The twin is mapped as before, and so is a destination with no CPU pair: an independent-pages
range (LEONIDA_SLOT31_RUNS), whose pages are read where they are.
- A view the title mapped there itself is unmapped once when a copy lands on it.
- unmap_range_locked drops table pages in its range, so the title's own unmap or release clears them.
- A table page is not one of its physical page's host addresses (no note_mapping, no alias peer). It can be neither
  written nor guarded on the host, so a twin plus a GPU-only page is no longer "aliased" for the slot-133 shadows and
  the geometry watch.
- A table update raises title_memory_map::changed and geometry_writes::notify(replaced) for the GPU-only address, as
  a host remap did. A remap changes bytes, not what a V# resolves to, so the slot-record change list is not involved.
- The periodic slot-31 line gains "pages N by table, M by host remap" (slot31_mapping_counts).

Tests (Wine):
- xmem_test, test_copy_page_mappings_cpu_view: no host view on the GPU-only range; one host remap per page, not two;
  a copy from a GPU-only page finds what its table entry holds; a page the title mapped there is replaced by a table
  entry; the title's unmap clears the table.
- d3d12_xmem_placed, queue_remap_default_route: it read the GPU-only pages directly (the old behaviour). It now reads
  them through a slot-31 copy and checks that they have no host view.

Wine suite on the iGPU: 425 pass / 23 fail, the same as main e5a7c89, nothing changed. Linux ctest on llvmpipe:
115/115.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…guarded (4f364c8)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… when it appears; no T# retries

A title-written T# that found no texture went on a retry list that every submission tried again, round robin, for
500 us (LEONIDA_CONSOLE_RETRY_US). World runs had up to ~35,000 waiting, 200-550 retried per submission, and every
retry counted again as a T# "naming no texture" (1.56 million in 27 log windows of one run). A bound T# whose texture
went never came back unless the title rewrote its slot.

The per-slot records of RT-VSHARP-SLOT-RECORDS now hold T#s too (src/console_heap_slot_records.h): the exact base
address and bound / waiting / waiting for room, with an index by that address. Texture changes go on the same change
list: note_image_address, a GPU placement added and a streamed texture published (texture_added), forget_image and a
placement removed (texture_gone), freed bindless entries (texture_room), each also at the other view of pool memory.
The next submission fixes exactly the T#s naming the address. A V# refused a geometry copy for lack of room is fixed
again when geometry copies are freed (geometry_room, GeometryViews::free_generation), closing the gap A1 left.

"No texture at the T# address" is counted in "unbound T#s by reason" by what the address is: title memory, a texture
of ours that is gone, low 32 bits naming one of ours (same shape / other shape / gone), or none. The slot records
line gives T#s recorded, waiting, fixes left waiting and refills.

Removed: retry_console_slots. LEONIDA_CONSOLE_RETRY_US applies only to the opt-in GPU heap pass now; slots deferred
by LEONIDA_CONSOLE_FIX_US are fixed first at the next submission (fix_deferred_slots).

Tests: console_heap_slot_records_test (T# and room cases), new d3d12_tsharp_refill_test (the last of 60,001 waiting
T#s samples its texture at the first submission after it appears; its T# leaves the hash table when it goes),
d3d12_unbound_tsharp_rules_test (address classes). Linux ctest 115/115 (llvmpipe); Wine suite (clang-cl, iGPU RADV)
425 pass / 24 fail, against test/three-fixes 425/23: d3d12_tsharp_refill new and passing, xmem (known flake) the
only pass->fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ng else can make progress

A list value wait (wait32/wait64) that is not met at submission holds its queue until memory meets it. The fixed
200 ms timeout, LEONIDA_VALUE_WAIT_TIMEOUT_MS and the 4 ms demotions are removed (in Linux world runs 14-63 gates a
run timed out with the writer's value not there yet).

A held gate goes without its value only when nothing else can make progress (releaser idle, no title
ExecuteCommandLists in progress, nothing of the pump's running on the GPU; work the layer holds behind a wait is not
running, asked through the new rt::d3d12::fence_signal_submitted), and then only: in a cycle (at once), at a present
queued behind it (VIctory-Belobug-AMD's rule, queue/behind.rs step, queue.rs release_held), or when the title has made
no queue call for 2 s; every gate goes at device loss. src/list_value_progress.h (portable) replaces
list_value_wait_budget.h. Each release is logged with gate, queue, wait and reason; released waits met later are
counted. stop() drops gates it leaves shut so they no longer hold their queues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t probe their memory again (RT-TITLE-TEXTURE-WRITE-TRACKED)

A pending stream texture whose first bytes arrive through a noted write (the pending slot-70 views case of
d3d12_existing_heap) kept its cached unreadable answer and was never filled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…the GPU (8c579b7)

runtime/README.md: the sparse arena changed the LEONIDA_IMPORT_BELOW_ARENA row and the texture work removed the LEONIDA_ORDER_TEXTURE_UPLOADS row next to it; the arena's row is kept and the removed row stays removed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The T# records, the room lists and the texture and room changes of descriptor-refill now live in the exact-range
index of slot-records-index. src/console_heap_slot_records.h: a third index, by T# address (the exact range
[address, address + 1)), of the same groups with a settled and a waiting list; a texture gone visits exactly the
T#s recorded for its address, a texture added the waiting ones. The records waiting for room (V# halves refused a
geometry copy, T#s refused for a full bindless array) are kept in a list per kind with each record's place, so a
record leaves it in O(1) and room made visits only the records waiting for it. Interface as descriptor-refill
has it (states, set_texture, base, textures, textures_waiting); device code, README rows and both sides' docs kept.
32 bytes a half.

Tests: console_heap_slot_records_test, both sides' cases (60,010-slot release; 300,000 slots in 74 blocks, a
40-byte release looks at 3; 400 random rounds against a full re-resolution; a texture registered looks at the 10 of
60,015 waiting on its address; room changes touch only the records waiting for room); a copy that skips settled
lists on a removal fails. Linux ctest 115/115.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
runtime/README.md: the console-heap rows come from the refill branch, the shadow rows from ProjectLeonida#1867.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…nd a kernel write in progress is waited out, not read (RT-TITLE-TEXTURE-WRITE-TRACKED)

Run 57 showed 99.9 % of the arms refused, 60,637 tiles not armed and about 8,700 textures looked at per pass
(60-68 ms a pass). The refusals were this watch's own: a tile with any page not committed was refused, so
every streamed texture registered before its memory arrived was named and its arming retried at every pass,
and a texture never filled because its memory was not readable was named again at every pass too.

Now pages not committed are left as they are: xmem's commit or mapping bumps the tile's cell, and the mapping
change makes the textures over it probe their memory again. A texture whose memory is not readable is not
named again until then, except one the title mapped (its pages may be committed under the Map pointer). A tile
pinned for a kernel write is busy: the texture is not read (which uploaded half-written textures at every pass
until the write ended) and is read once the pin is gone. Only a tile whose guard cannot be set is read at every
pass. The log line counts busy looks and arms apart from refusals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…wait for the write (9aed60a)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…holds; a record is looked at once an index a submission

One world run with the merged index showed 60,000-135,000 records looked at per submission for 1,300-2,600 slots
fixed again and 130-210 changes. Two causes in ConsoleHeapSlotRecords::touched:

- An addition (an alias range, title memory, a backing) visited every waiting record whose range overlapped it.
  Waiting V#s with large spans (data words that read as V#s of up to 4 GiB into title memory) were visited by every
  addition anywhere inside their span, at nearly every submission, and fixed again to no effect. A V# resolves only
  through an alias range, backing, copy or title memory that holds its base (or a backing that holds its refused
  target), so an addition now visits the waiting records whose range starts inside it; the groups with waiting
  records are kept by start a second time for this, so only those are walked. TitleVaAliases tells title memory as
  the merged range it is now part of (a V# whose base lies in the older part may fit only now), and nothing for a
  commit inside a range it already has.
- A record named by several changes of one submission was looked at once per change. Each group's two lists now
  carry the touched() call that last visited them, so a record is looked at once an index a call at most.

Test: 5,000 waiting halves of 4 GiB; 200 additions inside their spans that hold no base look at none (the previous
index looked at all of them 200 times and fails), one that holds 10 bases looks at those 10; 200 removals over the
same 5,000 resolved halves look at each once. The 400 random rounds against a full re-resolution still pass (slots
fixed again there 81,005 -> 75,919, looked at 133,506 -> 97,952); a copy whose removals skip waiting records fails.
Linux ctest 115/115.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mission (67863b3)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… on several threads, and submits their uploads in order (RT-TITLE-TEXTURE-WRITE-TRACKED)

Run 58: with the watch in effect a pass still read, hashed and detiled every named texture on the title's
submitting thread, one after another: about 1,250 textures and 95 MiB a pass in the world load, 198 ms a pass,
up to 795 ms (read from write-combined title memory, a full hash, the detile into the upload slot).

The upload is split into three steps (TitleImageUpload::reserve, fill, commit). The pass reserves a slot for
each named texture on its own thread, a small pool of threads of ours (TitleReadPool, a quarter of the cores,
at most seven, plus the submitting thread) copies, hashes and detiles them in batches of 16 or 64 MiB, and the
submitting thread then records and submits the transfers one by one in key order, still before the submission
whose draws sample them. The reads of different textures are independent; only the submissions carry the
ordering, and they stay where they were.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…transfers committed in order (d170028)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…d to it; a rewritten V# whose range waits takes that answer

Two findings from one world run (every slot records line: 0 refills; fixing slots 18.2 ms a submission).

T#s: the title rebuilds T#s of the layer's textures from 32 bits. The run's unbound T#s name 0x7f0000021400 for the
layer's 0x100021400 and 0x2ef600 for 0x1002ef600 (bits 32-39 clear, 0x7f or 0 in bits 40-47): "its low 32 bits name
a texture of ours that is gone" (291-3,794 a window) and "no title memory and no texture of ours" (270-4,585, low bits
past the last address handed out: textures still to come). They were recorded under that address, while a texture's
arrival is announced at the layer's address, so no arrival ever reached them, and bind_title_image looked them up by
the exact address only. tsharp_texture_key maps such an address outside the title's memory to the layer's texture
address with the same low 32 bits (while fewer than 2^24 were handed out); the T# waits under it, and
bind_title_image takes the texture there when its shape fits (another shape stays unbound, as before).

V#s: about 2,100 rewritten V# halves a submission, 70% resolving to nothing at about 9 us each (the alias table,
the backings, the geometry copies and the title memory walked again, VirtualQuery included), 63% with words seen
before. A waiting record is fixed again by every change that could let it resolve, so while one waits its answer
stands: a rewritten half whose exact range another half of the heap waits for takes that answer
(ConsoleHeapSlotRecords::waiting_answer, one hash lookup; a half that asks for a geometry copy only from one that did,
and not after geometry room was freed since the refresh). To keep answers current, the submission's changes are
applied before the rewritten slots, and the changes noted during the pass (a window a fix made, a buffer another
thread released) are applied to the heap before an answer is taken (sync_slot_changes). The records keep a third
list per range for waiting halves that asked for a geometry copy. The slot records line counts the answered halves.

Tests: d3d12_tsharp_refill_test also writes the texture's T# in the title's two 32-bit forms before the texture exists
and expects both bound at the first submission after it appears, and gone with it. d3d12_unbound_tsharp_rules_test:
the 0x7f form with the texture's shape binds (it expected "no texture"). console_heap_slot_records_test: in the 400
random rounds half the writes take a waiting answer after applying the changes noted so far, and each answer must be
what resolving at that moment gives (a copy that skips applying them fails); the rounds still equal a full
re-resolution. Linux ctest 115/115.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…om it; textures are read at first use and by their written tiles (RT-TITLE-TEXTURE-WRITE-TRACKED)

Blocks of older frames in run 58: a texture without GPU-write flags placed over the memory of a GPU-written
one (a render target, depth or UAV texture) was filled from the title's pages there. Those pages never hold
what our GPU renders into the target's image, only what the CPU last put there, and every write mark over
them (a write-back of a GPU copy, a neighbour's write in the same tile) re-uploaded those old bytes. The
registry now keeps the CPU-view range of every GPU-written texture (DeviceState::gpu_owned), and a texture
over such a range is not watched or filled by the refresh (index_texture); one already watched stops when the
target is registered. Test: d3d12_existing_heap's "texture over a render target's memory" (fails without
this: the written 64 KiB piece shows in the texture).

Upload at first use: a title texture no descriptor names is not read, uploaded or watched. Its first
descriptor of any kind (a D3D12 view, a slot-70 view, a T# the title wrote into a console heap: all reach
Resource::note_shader_view) queues it, and the refresh before that submission reads it whole and uploads it.
A texture whose descriptors are all gone later stays on the write-driven path (nothing counts them down).

Reads by written tiles: each texture keeps a hash of its part in every 64 KiB tile (TilePieces). When some
of its tiles were written, those parts are hashed in place first; equal, and the texture is unchanged
without a whole read. The watch reports writes per 64 KiB tile (the geometry cells' fault reopens a whole
tile), so a neighbour in a written tile costs its share of that tile, not a read of all of it.

The 10 s line: textures written or new, read whole, found unchanged by their parts, uploaded, named for the
first time, not named by any descriptor (not read), ms a pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…#s in the title's 32-bit form wait under our address (d94b6c3)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…re's first descriptor, written parts hashed (f7c3df1)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…y resolve to the render target's image (RT-TITLE-TEXTURE-WRITE-TRACKED)

f7c3df1 stopped filling such a texture from the title's pages; its own image then held nothing the GPU
drew. A GPU-written texture placed at the address (render target, depth or UAV) now answers first, for
console T#s (bind_title_image) and slot-70 views (place_title_view), when the description fits: the T#'s
extent and samples, and mips and layers within the target's (TitleGpuPlacements::matches), in any format the
target's image takes a view in (its own, a castable one, or one its view list allows). Otherwise the other
texture answers as before, and the reason is counted (format; extent or samples; mips or layers) in a line
next to the refresh's.

Either order at one address: a render target placed over a texture placed first leaves that texture's
registry entry in place and drops its T# bindings, so they bind again, to the target. The ranges GPU-written
textures cover are kept by the resource (DeviceState::gpu_owned), so a texture placed later at the same
address does not take the target's range away; when the target goes, the texture at its address is filled
from memory again and its T#s find it. D3D12 views the title made of the plain resource itself still name
its own image.

Test: d3d12_existing_heap's "view over a render target" (both orders, and the target's release).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…(fix d3d12_existing_heap)

Two distinct deferred shared-BC slot-133 placements share a placeholder VkImage
until promoted; keying non-title-heap ViewKeys by image.address gives each
resource its own bindless slot while preserving full title-heap ViewKey dedup.

AI-assisted: Antigravity (Gemini 4 Neon).
@zmasi

zmasi commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

@aslan2142 — VERIFY-2566-VEGA20-RADV: not validation-clean on fixed-wave64 gfx906, RADV Mesa 26.0.8. Tested cd8b5632 plus 3ca0707dd (local tree bf6c9ea2). The only merge conflict was in runtime/CMakeLists.txt; I kept both new CTest registrations and main’s independent skip-code property.

Synthetic CTests Result
Native Linux 19/19 CPU passed. On GPU, 8/9 passed CTest, but only 7/9 were validation-clean. GPU detile matched 182/182 cases.
Wine/PE 52 passed, 2 write-watch capability skips. Of 32 non-skipped GPU runs, 31 were host-validation clean. Two additional existing-heap aliases were withheld after the teardown error below.

Actionable diagnostics (Khronos + sync validation active):

  • vk_title_mirror returns success despite VUID-VkShaderModuleCreateInfo-pCode-08737. CMake builds its shader for Vulkan 1.3 (SPIR-V 1.6); the test requests Vulkan 1.2. Recompiling only that fixture for 1.2 gave the same 64-page readback with zero diagnostics.
  • vk_device_markers fails with repeated SYNC-HAZARD-WRITE-AFTER-WRITE on its shared start/finish marker words (10 reports, the duplicate cap). The compute-marker loop is also present on main; I did not attribute its origin to this PR.
  • Wine d3d12_existing_heap passes its readback but reports VUID-vkDestroyDevice-device-05137: 4 buffers, 3 images and 3 command buffers still live at teardown. Baseline attribution unverified. Page-mirror, in-place heap and T# refill tests passed.

Translator: 407/407 methods passed across the 25 touched semantic files. The six ordinary translator test files gave 839 passed, 5 failed, 11 excluded from the reserved PC-tail lane. The five failures also fail on the unmerged PR and pass on main: one bpermute text-pattern assertion, two WQM instruction-shape checks, and both D16 gather type-name assertions. All five modules pass spirv-val; these failures are not evidence of incorrect pixels. Both absent-lane fragment readbacks passed on physical subgroup64; the wave32-only compute case skipped before dispatch. Four signed/unsigned dot and scalar-fallback graphics pipelines created successfully; the updated table-fetch and texture fixtures also passed.

Synthetic correctness results only, not a world-frame or performance claim.

AI-assisted.

@zmasi

zmasi commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

On pristine 33db04a70, vk_device_markers reproduced the same 10 write-after-write reports (the duplicate-report cap) on the same gfx906 / RADV Mesa 26.0.8 device with Khronos synchronization validation enabled. The started/finished marker words still read back 5/5 and 8/8, but CTest failed on validation, confirming that the hazard also exists on main without #2566.

AI-assisted.

…heap tracking, shared_zero_ dedup & two-phase dead-key sweep

- Track exact live console-heap textures via ConsoleHeapSlotRecords 0<->1 callback under pure leaf live_console_textures_mutex
- Classify non-UAV non-MS !known_heap placed-texture views as evictable when console_heap_count > 0; preserve evictable across PendingImage::keys & publish_streamed_texture()
- Propagate is_zero_view in bind_image_locked() and gate api_owner_address on is_zero_view && console_heap_count==0
- Two-phase GC (Phase 1 dead-key sweep emitting 0 texture_gone, Phase 2 emergency live-LRU only on hard_full) with evictable_views_in_dim O(1) exit, 8192-slot hysteresis, strict retire-ticket & wall-clock cooldown (always stamped on empty candidates)
- Emit SlotChange::texture_room in set_bindless_release() only on 0 -> >0 free-slot transitions

AI-assisted: Antigravity (Gemini 4 Neon).
…() scoping, 64-tile bridging, fused AVX2 copy_and_sum_256 & filter/collect cuts

- Move title_memory_map::changed() into TitleHeap::hooks.commit/decommit and !from_mirror_heap in free_title_block()
- Share Cell::known_* across CellGuard & TitleTextureCells (no PAGE_READONLY no-guard cache; MEM_RESERVE intra-pass in TitleTextureCells, cross-pass in CellGuard; seed on xmem::map_view)
- Persist TitleTextureCells VQ cache across outer batches; bridge across run_already_armed_ tiles with uniform restore[0..15] up to kMaxBridgeGap=64
- Persist 1024-entry local_mirror per ConsoleHeap*, flush Phase A/B disjointly, handle !base V#s in Phase A, skip redundant WC BAR writes for waiting T#s
- Fused SEH-safe AVX2/SSE2 guarded::copy_and_sum_256(), kMaxWorkers=8, single-reader title_write_watch::ask() fast path preserving mark() entries

AI-assisted: Antigravity (Gemini 4 Neon).
…U wait relay, coalescer reorder, readable fast path & decoupled GPU profile resolve

- Add VulkanFence::signal_gpu_relay() (vis_seq=0) strictly for GPU-landed list-value gates (!force && !lost && !action && !cpu_met)
- Retroactive GPU-to-GPU relay via QueueHolds::relay_wait() + VulkanQueue wait substitution (never GPU-signaling values->gate, reversing wait() before add_gate(), requiring after_gate==0 && different queue)
- Decouple gpu_profile_.resolve() onto lazy resolver thread off FenceWaitDispatcher & throttle take_open() device-loss checks
- Reorder BeforeExecuteCoalescer to wb -> mirror -> flush -> tex -> shadows -> 2nd flush -> conditional 2nd tex (killing in_feed CPU fallbacks)
- Hoist host_stop & add negative caching in TextureVqCache + Stage 2b all-16 Cell::restore[] readability bypass

AI-assisted: Antigravity (Gemini 4 Neon).
…values.h

AI-assisted: Antigravity (Gemini 4 Neon).
…-value check, wait_met re-check, relay_wait gate preservation & signal-only vis_seq transitivity

AI-assisted: Antigravity (Gemini 4 Neon).
…OU removal, bridged rollback gap preservation, RO VQ exclusion & bindless dim2D/multi-key fixes

AI-assisted: Antigravity (Gemini 4 Neon).
@ecox982745

ecox982745 commented Nov 28, 2026 •

Copy link
Copy Markdown

Resolved on the integration branch. The test change in this PR fixes both D16 gather assertions. On its parent 232b4a1eed, the fixed level-zero (lz) case passed and both explicit-LOD cases failed. On PR head a8b1abe4c2, all three passed. The separate test patch linked below is no longer needed for these failures.

I also regenerated the 12 synthetic fragment modules on a8b1abe4c2. All passed Vulkan 1.2 SPIR-V validation and were byte-identical to the modules from the earlier RTX 4090 run. The hardware results below are from that earlier run.

The two D16 gather failures in the Vega verification come from the test matching a SPIR-V type name. At cd8b5632b8, explicit-LOD gather still emits four float, four signed integer and four unsigned integer fetches. The unsigned vector is named %v4uint_sl; the assertion expects %v4uint_st.

One-file test fix · apply-ready patch. It resolves each fetch result through its four-component vector declaration before counting element types. The test still requires zero fetches for lz and exactly four of each type for l and l_o.

  • CPU: At the PR head, the parametrized test went from one pass and two failures to three passes. All three passed on main 4a54aedcb6 before and after the test edit. The related texture selection passed 95/95 on the PR. Including the separately reported WQM test adds one failure outside this patch.
  • GPU: Windows, RTX 4090, driver 616.64. I translated the same synthetic gathers on both revisions and ran them through the same PR-head vk_texture_test. I checked lz, explicit LOD 0, and explicit LOD 0 with a signed X offset of −1, with all four channel masks on UNORM, UINT and SINT textures. The fragment output exposed all four raw 16-bit tap values independently. All 36 main/PR pairs matched the expected texture values and tap order across 72 draws and 294,912 RGBA pixels. All 24 fragment modules passed spirv-val for Vulkan 1.2.
  • The first unscored run with hardware DenormFlushToZero 32 requested produced a validation diagnostic on this device. The scored comparison used the translator's --no-ftz32 setting on both sides and had zero Vulkan validation diagnostics. All inputs were synthetic.

AI-assisted with OpenAI Codex (GPT-6).

…y mirror drain on coalesced submissions

AI-assisted: Antigravity (Gemini 4 Neon).
Resolved conflicts in docs/design.md, runtime/CMakeLists.txt, and tests/semantic/spirv_wave_interp.py.
AI-assisted: Antigravity (Gemini 4 Neon).
…TZ32 and sync _vgpr_reads_of with buffer_load_format_d16_hi_x

Fixes the post-merge interaction between upstream's v_exp_f32 denormal flush
(eb39d27) and our FTZ32 fast path in Gen.flush_f32(), and keeps _vgpr_reads_of
aligned with read_before_write_vgprs (3ad34dd).

AI-assisted: Antigravity (Gemini 4 Neon).
@aslan2142

Copy link
Copy Markdown
Collaborator Author

Pushed Rounds 7–10c (232b4a1ee) and merged up-to-date main (d48a957bb, 508 commits) cleanly into integration/perf-cpu-gpu-r6.

Summary of Changes Since Round 6 (cd8b5632b → 232b4a1ee)

  • Round 7 — Rendering batching, parallel console heap filter & 64 MiB readback:
    • Dynamic rendering scope batching (replay ~2× faster), hoisted FilterCacheScope + parallel Phase-A filter, 64 MiB copy-queue readback, deferred slot-70 uploads to GPU detile + publish_streamed_texture() fix, per-fence vis_seq, unlocked QueueHolds::run_barriers(), 4-deep VulkanPresenter::frames_.
  • Round 8 — Zero unmet gates, 2-level mirror table & GPU texture batching:
    • Fixed Pump::choose_release() TOCTOU + present quiet window (0 released unmet), dedicated QueueHolds barrier-drain thread, batched copy_page_mappings(), SEH aligned volatile read_value(), 1000 ms slot-12 timeout (0 timeouts).
    • Chunk::pages[32768] direct table, sum_of_batch_256(), sub-page 256 B readback copies, page_mirror_buffer resolve_cache, OutScratchGuard, 512-job / 128 MiB GPU-mirror texture upload batching.
  • Round 9 — Low-syscall VM guards, WC streaming & bindless ViewKey sharing:
    • CellGuard zero-syscall all_armed, VQ cache, disarm_batch/set_hot_batch, range-scoped reopen(), WC streaming copy (kStripBytes=16 KiB), WorkerPool 50 µs spin.
    • Separated title_texel_writes, Stage-2 TextureVqCache, TitleImagePool 8 MiB/16 MiB cap, refcounted ViewKey sharing, O(1) BindlessSet free-lists, single-lock bind_title_image(), GeometryViews dedicated WriteQueue.
  • Round 10 / 10b / 10c — Two-phase bindless GC, GPU-to-GPU relays, fused AVX2 copy+sum & feed-only mirror drain:
    • Two-phase dead-sweep bindless GC (ConsoleHeapSlotRecords kTexture/kSettled live tracking, explicit evictable classification, Phase 1 dead-key sweep with 0 texture notifications + 8,192-slot hysteresis, dim_2d mirror-slot room notifications, multi-key sv.keys liveness) — eliminated 65,536-slot saturation and GC thrash.
    • Shared Cell::known_* cache across CellGuard & TitleTextureCells (with PAGE_READONLY excluded from VQ caches and safe per-tile bridged VirtualProtect rollback), TitleHeap::hooks.commit/decommit map-change scoping, fused SEH-safe AVX2/SSE2 guarded::copy_and_sum_256(), 8-worker pool, disjoint Phase A/B WC flushes & chunk-local local_mirror cache.
    • VulkanFence::signal_gpu_relay() (vis_seq=0) + retroactive QueueHolds::relay_wait() / VulkanQueue::apply_wait_relay() with WriteGroup::bare visibility safety, exact landed-value console_value_met() check, wait_met re-check, relay_wait() gate preservation, and signal-only consumed_wait_vis transitivity.
    • Lightweight drain_page_mirror_feed_only() on coalesced before-execute submissions (0.11–0.29 ms when CopyPageMappingsBatchX remaps are queued, 0 single-flight waits, 96–97% coalesced), plus decoupled lazy gpu_profile_.resolve(), reordered BeforeExecuteCoalescer, and Stage-2b Cell::restore[] readability bypass.
  • Upstream main (d48a957bb) merge & post-merge audit (66d4723f4, 232b4a1ee):
    • Resolved 3 conflicts (docs/design.md, runtime/CMakeLists.txt, tests/semantic/spirv_wave_interp.py) and audited with two independent reviewers.
    • Fixed a silent post-merge interaction in tools/rdna2spirv.py where upstream's v_exp_f32 denormal flush called Gen.flush_f32() under FTZ32 (added force=True for v_exp_f32) and synced _vgpr_reads_of with buffer_load_format_d16_hi_x.

Post-Merge Verification (232b4a1ee)

  • Live RX 7900 XTX (RADV NAVI31, Mesa 26.3.1-arch1.3, Wine) post-merge run (370+ s, visible + audio):
    • 0 GPUVM faults, 0 VK_ERROR_DEVICE_LOST, 0 unmet gates (28,372 gates held, 429 relayed, 0 failed), 3 clean bindless dead-sweeps (8,192 dead keys each, 0 textures notified).
    • Opening cutscene: 7.4–13.9 fps (up from 3.6–5.9 fps at Round 6), 96–97% before-execute coalesced, 0 single-flight waits.
    • In-game gameplay: stable 6.0–7.4 fps (79–84 ms/f own threads, 7.0–15.1 ms/f title threads, Direct GPU now 66–75% busy — bottleneck has shifted from CPU to GPU).
  • Automated suites:
    • Linux (-march=x86-64-v3, RDNA2 iGPU 1002:164e): 136/136 ctest PASS, 9/9 VVL PASS (0 VUIDs).
    • Python translator tests: compileall PASS, check_no_game_data.py PASS, 14/14 test_alu_exp_f32 + test_ftz32_fmulz + test_buffer_format_d16_hi PASS, 278/278 across all 17 merged-feature semantic suites PASS.
    • Windows (clang-cl /arch:AVX2): gta6rt.exe built cleanly; targeted Wine iGPU suite 40/41 PASS (xmem_write_watch passed on re-run; only upstream d3d12_fence_timing's EnumAdapterByLuid failed on headless Wine Xvfb lacking DRI3 — clock calibration checks passed).

AI-assisted: Antigravity (Gemini 4 Neon & Claude Opus 5.5).

@github-actions github-actions Bot added needs rebase Conflicts with the base branch: rebase it on main and removed needs rebase Conflicts with the base branch: rebase it on main labels Nov 28, 2026
- docs/design.md: escape bare pipes in wide scalar load table row
- runtime/README.md: document LEONIDA_BEFORE_EXECUTE_COALESCE and LEONIDA_CLWB_PATCH
- .github/workflows/runtime.yml: add descriptor_sources.py and heap_index_census.py path triggers
- tools/ptr_truncation_census.py: accept extra= kwarg in shader_meta.collect capture hook
- tools/shader_diff.py: disable FTZ32 during cpu_ref differential comparison (cpu_ref preserves denorms)
- tests/test_translate.py: update wave32 bpermute, ballot-based WQM, and deduplicated uvec4 OpImageFetch assertions
- runtime/test/replay_state_cache_test.cpp: add always-true gl_FragCoord.x >= 0.0 scalar select guard in build_fs_spirv to avoid Mesa llvmpipe linear-fastpath push-constant bug
- runtime/test/vk_gpu_profile_test.cpp: skip positive-duration checks on Apple Paravirtual GPUs returning constant zero-span timestamps while keeping all structural/query checks

AI-assisted: Antigravity (Gemini 4 Neon). Verified with full translator-tests pytest suite (2004 passed), PR-specific CI/check unit tests, and replay_state_cache_test + vk_gpu_profile_test on llvmpipe and Radeon iGPU (VVL=1).
@azsekazvamdimitar

Copy link
Copy Markdown
Contributor

Tested #2566 on NVIDIA (RTX 3090, Linux, GE-Proton11-14 and WineHQ 11.22, merged onto main 4938673): the runtime cannot create the GPU address arena there, so the title does not get past startup.

  • create_arena (runtime/shims/d3d12_vulkan_device.cpp, the sparse decision): with every loaded module sign-extending its V# base, the arena is made sparse. NVIDIA's driver offers no host-visible memory type for a sparse buffer (memoryTypeBits 0x2, device-local only), so the first unit's allocate(..., kArenaRequiredMemory, ...) fails: GPU address arena: no memory for its first 448 KiB -> the GPU address arena could not be created -> every pipeline refused (pipelines need the GPU address arena, ~70,000 refusals) -> the title crashes about 2 minutes in (two boots, cold and warm caches). There is no fallback to the one-allocation arena.
  • arena_sparse_gpu fails on the same card for the same reason (line 184: type != UINT32_MAX), natively, under WineHQ and under GE-Proton.
  • With a local fallback (create a probe buffer with the sparse flags; if memoryTypeBits has no type with kArenaRequiredMemory, log it and make the arena one allocation as before) the branch boots. Compared with main + the same caches on this card: world reached in about 5 min instead of about 12, a coherent picture where main showed untextured blocks, our submit path 4-25% of the wall time in the world instead of 100%+, no device loss or stalls in 3 boots. The frame rate in the world stays at 0.2-0.4 frames/s; the title then mostly waits on fences (99% of the fence-mirror waits end on the 10 ms timeout). The page mirror is off on this card either way (no aliased strict sparse buffers). Cold-cache boots still freeze on synchronous compiles.

AI-assisted (Claude). The fallback is about 25 lines; happy to push it as a suggestion if you want it in this PR.

@timbot103 timbot103 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independently verified 232b4a1ee (Rounds 7–10c) on native Windows 11 (MSVC 19.44 + Ninja, Python 3.14, AMD LLVM 23 llvm-mc) across two desktop Vulkan GPUs with zero game files:

  • NVIDIA GeForce RTX 5080 (driver 32.0.16.1664, wave32, shaderDenormFlushToZeroFloat32 == VK_FALSE)
  • AMD Radeon(TM) Graphics (gfx1036) (driver 32.0.21030.2001, wave32..64 default 64)

(Checked the diff 232b4a1ee..a8b1abe4c pushed while this run was finishing: d1f53516d/a8b1abe4c already fixed the 5 tests/test_translate.py assertions and resolved the tools/vk_subgroup_info.py merge conflict against main, so those are omitted below. All 6 native Windows / MSVC / NVIDIA / cross-GPU runtime issues below remain untouched in a8b1abe4c.)

What Passed Cleanly

  • Native Windows MSVC 19.44 + Ninja build: 1,119/1,119 targets compiled and linked with 0 errors.
  • Hygiene: scripts/check_no_game_data.py and python -m compileall -q make_game.py tools tests both pass.
  • Targeted #2566 semantic suites (18 files, including test_absent_lane_ub, test_ftz32_fmulz, test_alu_exp_f32, test_buffer_format_d16_hi, test_wave64_emulate_opt, test_wave64_halves): 285/285 PASS.
  • Full semantic suite (tests/semantic, 529 files, 6,563 tests): 528/529 files (6,561/6,563 tests) PASS; the sole failing file (test_valu_cvt_f16_int16_mods, 2 subtests in v_cvt_u16_f16/v_cvt_i16_f16) reproduces identically on clean merge-base d48a957bb (0 semantic regressions).
  • Live GPU absent-lane test (tests/test_absent_lane_gpu.py): 2/2 PASS on AMD Radeon gfx1036 with LEONIDA_VK_VALIDATION=1 (0 validation errors), and 2/2 PASS functionally on RTX 5080 with LEONIDA_VK_VALIDATION=0 (see validation blocker #3 and Windows .exe note below).
  • Key #2566 runtime & Vulkan CTests passing with LEONIDA_VK_VALIDATION=1 (0 validation errors) on both RTX 5080 and AMD Radeon gfx1036: vk_title_detile (187 cases + batched/3D/pool checks), vk_bindless_grow, vk_bindless_dimensions, vk_console_heap_gpu, d3d12_bindless_churn, d3d12_bindless_churn_validated, d3d12_tsharp_refill, d3d12_unbound_tsharp_rules, d3d12_queue_wait*, d3d12_xmem_placed, title_mirror_hooks, title_mirror_hot_cold, r3b_runtime_hooks, replay_state_cache, list_value_progress, d3d12_compute, d3d12_draw, d3d12_shadow_keep_refill.

Remaining Blockers Found on Native Windows / MSVC / NVIDIA (Still Present in a8b1abe4c)

  1. Native MSVC gta6rt.exe fails gta6rt_no_tls_callbacks (#35) — non-trivial thread_local destructors linked in:

    • check_pe_tls_callbacks.py rejects gta6rt.exe because MSVC emits __dyn_tls_init (MSVCRT:tlsdyn.obj) and __dyn_tls_dtor (MSVCRT:tlsdtor.obj) in the PE TLS directory (which causes the title's _register_thread_local_exe_atexit_callback to fast-fail with 0xC0000409).
    • Non-trivially destructible thread_local additions in #2566:
      • runtime/shims/d3d12_vulkan_device.cpp:4615 (static thread_local std::vector<...> stack)
      • runtime/shims/d3d12_vulkan_device.cpp:8286 (thread_local std::unique_ptr<FilterPageCache> tls_cache)
      • runtime/shims/d3d12_vulkan_device.cpp:8406 (thread_local std::unique_ptr<std::uint8_t[]> tls_buf)
      • runtime/shims/d3d12_vulkan_device.cpp:8893 (thread_local std::vector<PageWork> tls_page_work)
      • runtime/shims/d3d12_vulkan_device.cpp:8932 (thread_local std::vector<std::uint8_t> tls_batch_bufs)
      • runtime/shims/d3d12_vulkan_device.cpp:24469 (static thread_local std::vector<std::uint8_t> scratch)
  2. NVIDIA RTX 5080 sparse GPU address arena fails to initialize (confirming @azsekazvamdimitar's Linux RTX 3090 finding on native Windows):

    • On NVIDIA Vulkan, a VkBuffer created with VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT only exposes non-HOST_VISIBLE (DEVICE_LOCAL-only) memory types in vkGetBufferMemoryRequirements().memoryTypeBits.
    • In runtime/shims/d3d12_vulkan_device.cpp:22073-22101, sparse is enabled without verifying that requirements.memoryTypeBits includes a kArenaRequiredMemory (HOST_VISIBLE | HOST_COHERENT) type or falling back to the single-allocation non-sparse arena. arena.backing.acquire(0, head, true) fails (GPU address arena: no memory for its first 448 KiB -> the GPU address arena could not be created) and leaves arena.size == 0.
    • On RTX 5080 this cascades into failures/skips across arena_sparse_gpu (line 184: type != UINT32_MAX + leaks VkBuffer on early exit), vk_heap_alias (line 186: home_info.memoryTypeIndex != UINT32_MAX), vk_title_mirror (line 257), d3d12_page_mirror (Skipped), d3d12_heap_in_place (Skipped), d3d12_texture_tiles, d3d12_xdxr_rt, xbox_bvh_builder, d3d12_dxr_validation, d3d12_dxr_validation_khr, d3d12_placed_dimensions, d3d12_placed_heap_lifetime, d3d12_method_variants, d3d12_heap_properties, d3d12_title_va_game_device, d3d12_geometry_views_game_device, and d3d12_vulkan_device.
    • (Related note: arena_sparse_gpu_test.cpp:97, vk_heap_alias_test.cpp:100, and vk_title_mirror_test.cpp:114 pick physical device 0 directly and ignore LEONIDA_VK_DEVICE.)
  3. Default DenormFlushToZero 32 violates Vulkan validation on NVIDIA (shaderDenormFlushToZeroFloat32 == VK_FALSE):

    • Running tests/test_absent_lane_gpu.py on RTX 5080 with LEONIDA_VK_VALIDATION=1 emits 2 validation errors on FTZ32-enabled shaders:
      • VUID-VkShaderModuleCreateInfo-pCode-08740 (Capability DenormFlushToZero declared with no supported float width)
      • VUID-RuntimeSpirv-shaderDenormFlushToZeroFloat32-06300 (shaderDenormFlushToZeroFloat32 is VK_FALSE)
    • Either DenormFlushToZero 32 needs to be gated by a device probe (shaderDenormFlushToZeroFloat32) like the other translator fallbacks, or default off when the target GPU does not advertise it.
  4. Cross-GPU CTest regressions failing identically on both RTX 5080 and AMD Radeon gfx1036:

    • d3d12_com (#235): fails at d3d12_com_test.cpp:244 (rt::d3d12::last_execute_result(queue.p) == ReplayResult::list_open), which also causes run_tiny_frame (#452) and run_tiny_frame_queue_test_settings (#453) to fail --probe exited with code 1.
    • d3d12_present (#364): fails at d3d12_present_test.cpp:524 (driver::binary.size() == 2), out of sync with the 4-deep VulkanPresenter::frames_ change.
    • vk_presenter_sync (#229): hits VK_ERROR_DEVICE_LOST from vkWaitForFences (present readback) and fails at vk_presenter_sync_test.cpp:406 (presenter.presented() == shown + 3 && presenter.composed_presents() >= 1).
  5. NVIDIA RTX 5080 vk_gpu_profile (#211) unsigned 64-bit timestamp underflow:

    • Fails reproducibly at vk_gpu_profile_test.cpp:310 (e->ms > 0 && e->ms < 2000): vs spin_vertices reports 18446744073709.5469 ms (~2^64 wraparound in runtime/src/vulkan_gpu_profile.h:259: (ticks[k] - ticks[k - 1]) & r.mask_ when ticks[k] < ticks[k - 1]). Passes cleanly with 0 validation errors on AMD Radeon gfx1036. (Note: d1f53516d only added an Apple Paravirtual check in vk_gpu_profile_test.cpp, leaving vulkan_gpu_profile.h:259 unchanged.)
  6. Teardown leaks under LEONIDA_VK_VALIDATION=1 + minor Windows/Radeon notes:

    • d3d12_existing_heap, d3d12_existing_heap_no_write_watch, d3d12_existing_heap_write_watch, and xbox_list_value_fallback log VUID-vkDestroyDevice-device-05137 (VkDevice has 87 leaked objects that have not been destroyed) at teardown on both RTX 5080 and AMD Radeon gfx1036.
    • On AMD Radeon gfx1036 under LEONIDA_VK_VALIDATION=1, vk_device_markers (#207, vkCmdWriteBufferMarker2AMD) read back started=0 finished=0 (expected 5) with 0 validation errors (passed with LEONIDA_VK_VALIDATION=0), and submit_frame (#202) flaked once at submit_frame_test.cpp:95 (worker_ns[worker_texture_reads] > 0, passed on RTX 5080 and Radeon without validation).
    • tests/test_absent_lane_gpu.py:31-32 hardcodes runtime/build/vk_compute_test and runtime/build/vk_ps_sweep without .exe, so it skips automatically on Windows unless patched.
    • (On AMD Radeon gfx1036, d3d12_page_mirror and d3d12_heap_in_place skipped cleanly due to missing bufferDeviceAddressCaptureReplay on Windows AMDVLK.)

Full CTest totals on 232b4a1ee (507 tests, 2 not run / 15–17 skipped): RTX 5080 25 failed (17 cascading from #2 above + #1, #4, #5), AMD Radeon gfx1036 15 failed (incl. #1, #4, the 3 device-0-hardcoded sparse tests from #2, plus Windows AMDVLK driver/test items vk_null_descriptor, d3d12_texture_tiles, pipeline_cache_seed, d3d12_clear, d3d12_mesh*).

@Tauwni

Tauwni commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Another device class, in case it helps: Apple M3 under Wine on macOS (Wine 11.0 with its MoltenVK 1.4.1, macOS 26.5.1), Windows cross-build of the runtime tests, no game files. This head (a8b1abe4c) conflicts with today's main in runtime/README.md, so both sides are on main 7ce011205, the tree this branch merged cleanly onto.

Test main 7ce011205 + this PR
d3d12_existing_heap passes 3/3 fails 3/3
d3d12_title_va passes 3/3 fails 3/3
d3d12_title_va_shadow passes 3/3 fails 3/3

(MEASURED, 3 runs each side, same machine and build directory.)

  • d3d12_existing_heap: vulkan slot-133 written pages line 795: first_difference(got, want) == -1, twice per run. That is step 4 of the written-pages check, which this pull request does not change: 64 bytes written to the first watched page from another thread, then a GPU read. No other line N: failure is printed.
  • d3d12_title_va and _shadow: line 276: srv_other == 0, with read-write pages: GPU copy in the arena (shader VA an arena offset); V# read run, 64/64 words matched, 32/64 read the other buffer's (negative control). The test's module now has "vsharp_base_sign_extended": true, so this may be the V# sign extension reaching the neighbouring buffer on this device. That cause is ASSUMED, not traced: I have not checked whether the arena is sparse here.

The 41-test Wine suite in the description ran on RADV, where the arena can be sparse; NVIDIA's arena problem above is a different one. Happy to rerun anything on this Mac.

Not checked by a second agent or human yet.

AI-assisted (Claude Code).

@ecox982745

Copy link
Copy Markdown

The cross-thread written-pages mismatch reported on Mac/Wine did not reproduce on native Windows 11 build 26300 with an RTX 4090 and NVIDIA driver 616.64.

Revision Fresh processes Cross-thread updates matched Full-buffer GPU readbacks matched
Main 7ce011205869 3 12/12 48/48
PR head a8b1abe4c201 3 12/12 48/48

I built each revision with MSVC in Release and used a local test entry point to run just the four existing check_written_pages layouts. The comparison function and production code were unchanged. Each layout checks initial data, a partial rewrite, an unchanged submission, and finally a 64-byte write by a second thread followed by GPU readback. This includes both half-committed layouts and the fully committed write-combined layouts at offsets 0 and 64. Every byte matched, with Vulkan validation enabled and zero diagnostics.

This narrows the platform comparison for the written-pages case. The title-VA failures in the Mac report are separate. To distinguish the two failing Mac layouts, the final assertion can print its existing kind argument and the offset returned by first_difference(got, want).

Coordination claim. AI-assisted with OpenAI Codex (GPT-6).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs rebase Conflicts with the base branch: rebase it on main

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants