[Audit] Deep Code & Telemetry Findings #282

Open
opened 2026-12-01 11:52:12 +00:00 by Androtim · 67 comments
Androtim commented 2026-12-01 11:52:12 +00:00 (Migrated from github.com)
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-01T11:52:12Z.


Deep read-only static code and telemetry audit across victory-gpu, victory-hle, victory-formats, and victory-shader, cross-checked against plain --release 60s captures, --features diagnostics 90s captures, and current main (fd5a4206, post-#278/#279/#281).

All file:line citations are verified against main fd5a4206. Work already merged in #278/#279/#281 or covered by open PRs (#265, #266, #269, #270) is excluded. Every proposed fix is a default-on architectural replacement (no opt-in switch bloat).


Pass 1 — Command-List Translation & Draw Hot Path

1. [Tier-1] Global Lock Contention (RETIRED + HostHeap::next) & D3D12 Call Explosion in Dynamic Descriptor Tables

  • Where: crates/victory-gpu/src/descriptor/host.rs:4026-4052 (keep_inner) -> crates/victory-gpu/src/host.rs:784-794 (retire_resource); descriptor/host.rs:2512-2550 (HostHeap::dynamic), descriptor/host.rs:3858-3874 (HostHeap::release), crates/victory-gpu/src/draw.rs:599-620 (State::tables_done); descriptor/host.rs:3953, 4194-4245, 4291 (make_listed, constant_at, copy_to).
  • Proof & Telemetry:
    • Plain --release baseline (eb9dc68d): list::thin spends 428.9 ms/frame across 8 workers (88.5% saturated, 155 submitted lists still untranslated at submit time). Doubling workers to 16 regresses FPS 16.5 -> 15.0 and inflates total worker CPU time +57% (428.9 -> 675.4 ms/frame, 13.6 us/call), proving severe cross-thread lock contention.
    • Diagnostics 90s capture measures 17,512 dynamic tables/frame and 12.0 ms/frame just scanning inside HostHeap::next.
    • Every dynamic slot overwrite (~100k–140k/frame) whose prior COM resource differs locks the single global RETIRED mutex (bury_lag() is 16/64, never 0). Meanwhile HostHeap::next: Mutex<(u32, Vec<bool>)> is locked 35,024×/frame (17,512 allocs + 17,512 unbatched per-table releases via SHADER_HEAPS.read() + self.next.lock()), linearly scanning up to 262,144 bool bytes.
    • make_listed and copy_to emit CopyDescriptorsSimple(1, ...) one slot at a time plus per-slot host::settle(), and constant_at (descriptor/host.rs:4242) unconditionally creates a raw SRV twin (CreateShaderResourceView + CopyDescriptorsSimple(1)) for every CBV slot (4 D3D12 COM calls/CBV).
  • Estimated Impact: ~2–5 ms/frame wall + ~150–250 ms/frame worker CPU + ~3.2 ms/frame on relay thread (host.rs:7099).
  • Architectural Replacement:
    1. Buffer retired ID3D12Resources in a per-list/thread-local Vec and flush once per list close into RETIRED (~600× fewer global locks).
    2. Replace Vec<bool> in HostHeap::next with a Vec<u64> bitset (32 KiB, L1-resident) + per-list 256–512-slot bump slab + single batched release_batch() in tables_done() (one SHADER_HEAPS.read() + one lock per list).
    3. Batch CopyDescriptors per table (hoisting host::settle() once per table) and skip the CBV raw SRV twin unless the bound TableGroup reads that slot as raw bytes.

2. [Tier-1 Bug] VICTORY_FRESH_OPEN Fast Path Fails 100.0% of the Time (1-Line Ordering Bug)

  • Where: crates/victory-gpu/src/list.rs:848 (reset calls with_state(this, ...) -> list.rs:152-154 -> list.rs:240-244 host_list(this) -> crates/victory-gpu/src/host.rs:8958 title_call()), checked against crates/victory-gpu/src/host.rs:8850-8862 (still_left_open()).
  • Proof & Telemetry:
    • list.rs:848 calls with_state(this, ...), which invokes host_list(this) -> list.title_call() (incrementing title_calls by 1) before host.reset() checks still_left_open() (calls == self.title_calls() + 1). Because title_calls was already incremented, the predicate is mathematically always false.
    • Plain --release baseline confirms 233.6 left open, 0.0 resets found them so, 234.18 closed after all. Diagnostics attributes 23.7 ms/frame to lists reset.
  • Estimated Impact: ~3–8 ms/frame worker CPU (~234 redundant Close() + 234 allocator.Reset() + 234 list.Reset() per frame).
  • Architectural Replacement: Change crates/victory-gpu/src/list.rs:848 from with_state(this, ...) to with_state_on(host_list_held(this), this, ...) so still_left_open() observes the pre-reset call count.

3. Host Command-List Pool Thrash & 4.17 GiB Private-Bytes Churn Under RAM Pressure

  • Where: crates/victory-gpu/src/list.rs:312-347 (IDLE_MOST, pressure_idle_cap, trim_on_pressure), list.rs:411-450 (recycle), crates/victory-gpu/src/host.rs:802-808 (bury_lag), crates/victory-gpu/src/list/thin.rs:412, 428-436 (BACKS).
  • Proof & Telemetry:
    • Diagnostics logs 13 host lists made 6.0 ms/frame continuously (12,741 total created, 1,071 alive, private bytes grew 4,172 MB), while baseline release trips host memory pressure trims every 1s.
    • list/thin.rs BACKS retains hidden idle HostLists detached from IDLE, and allocator recycling is delayed by bury_lag (16/64) instead of actual GPU fence completion (FINISHED).
  • Estimated Impact: ~2–6 ms/frame CPU + multi-GiB commit churn.
  • Architectural Replacement: Attach HostList lazily inside back_list() rather than eagerly in detach_parts (eliminating ~150–300 hidden HostLists in BACKS), recycle command allocators immediately on GPU fence completion (FINISHED), and floor trim_on_pressure at 1.5× rolling per-frame list demand unless commit is critical.

4. Zero Redundant-Bind Deduplication for Root Constants, Static Heap SRVs, VBs, and IBs

  • Where: crates/victory-gpu/src/draw.rs:1911-1950 (IASetVertexBuffers/IASetIndexBuffer + shadow::find_any/refresh), draw.rs:2122-2286 (SetGraphicsRoot32BitConstants + static heap Set*RootShaderResourceView).
  • Proof & Telemetry: Every draw (~6.8k steady-state, 12.8k–28.7k peak) re-looks up VB/IB shadows and re-emits IASetVertexBuffers, root 32-bit constants, and invariant static heap SRVs (SLOT_STRIDES, SLOT_TABLE_STRIDES, SLOT_VIEW_ADDRESSES, SLOT_CODE_TABLE, SLOT_MEMORY) across stages — ~40k–70k redundant D3D12 COM calls/frame.
  • Estimated Impact: ~1–2 ms/frame wall / ~15–30 ms/frame worker CPU.
  • Architectural Replacement: Track per-list VB/IB dirty bits + cached emitted root-arg state per (compute, param), invalidated on root-signature change or replay().

Pass 1 Do-Not-Chase Kill List

  • VICTORY_INDIRECT_MERGE: Baseline logs 0 / 5,447 indirect executions eligible to merge.
  • VICTORY_WAIT_SHARE=1: Probed 14.3 fps vs 16.5 fps baseline (GPU 0.0 ms, CPU-bound).
  • Raising VICTORY_THIN_THREADS above 8 before fixing P1-1: 16 threads regressed 16.5 -> 15.0 fps (+57% worker lock contention).
  • Steady-state pipeline wait stalls: 0.2 ms/frame; >99% of "dropped without a host pipeline" are intentional RT/BVH skips.

Pass 2 — Submission, Copyback, Shadow & Watch Pipeline

1. [Tier-1] Global GUARDS Mutex Held Across Kernel VirtualProtect() + TLB Shootdowns (Why Closed PR #280 Wasn't Enough)

  • Where: crates/victory-gpu/src/watch.rs:2387, 2420, 2514-2562 (ask_guards -> protect/cover), watch.rs:2797, 2825 (writing/kernel_writing), watch.rs:3631 (VEH on_write).
  • Proof & Telemetry:
    • Diagnostics measures guards waited 62.80 ms/frame across 189 waits: watch.rs:2387 = 35.18 ms, watch.rs:2420 = 10.16 ms, watch.rs:2825 = 4.37 ms (with read-only 1614 + 2362 waiting 26.35 ms behind 2387). Plain --release logs land::guards = 6.60 ms/frame (spiking to 25.49 ms).
    • Closed PR #280 empirically proved that making only the read-side fast paths (publish() / guard() clean/held) lock-free only cut 35% of wait time and left wall-clock preparing (30.9 -> 31.35 ms) and copyback (12.5 -> 12.3 ms) flat because ~65% of the lock hold time is kernel VirtualProtect() + cross-core TLB shootdowns executed while holding the single global GUARDS mutex, serializing the submitting thread, all 4 copyback merge threads, and title VEH faults on unrelated memory ranges.
  • Estimated Impact: ~4–9 ms/frame wall across preparing (write watch 6.0 ms) and copyback (land::guards 6.6 ms).
  • Architectural Replacement: Shard GUARDS into a 64-way address-striped array ((block >> 6) & 63, locked in ascending stripe index order for multi-stripe ranges) so a VirtualProtect + TLB shootdown in one 4 MiB stripe never stalls unrelated stripes, combined with lock-free read fast paths once write-side serialization is eliminated.

2. [Tier-1] Serial Per-List HostList::prelude() Allocator/List Resets Hiding in lists' steps

  • Where: crates/victory-gpu/src/host.rs:8059 (for list in runs -> list.prelude(&uploads)), host.rs:9275-9410 (prelude()).
  • Proof & Telemetry:
    • Baseline submitting thread spends lists' steps = 16.7 ms (refreshes 8.6 + copies/fills 1.4 = 10.0 ms, leaving 6.7 ms/frame unaccounted). Even after #279 coalesced refreshes, 5.2 ms/frame remains in lists' steps "other".
    • Diagnostics shows 177 preludes alive/frame: prelude() pops a separate (ID3D12CommandAllocator, ID3D12GraphicsCommandList), heap-allocates 4 Vecs + 1 HashMap, and executes allocator.Reset() + list.Reset() + ResourceBarrier() + list.Close() serially on the submitting thread for every list.
  • Estimated Impact: ~4–6 ms/frame on the serial submitting thread.
  • Architectural Replacement: Use one shared per-submission prelude ID3D12CommandAllocator (~18 allocator.Reset()/frame instead of ~177), merge adjacent non-conflicting preludes into one prelude list, and reuse scratch buffers on Batch.

3. [Tier-1] Coarse Per-Shadow merging Write Lock & Unskipped 174 MiB Heap Refreshes

  • Where: crates/victory-gpu/src/shadow.rs:4794-4908 (merge_under_writes), shadow.rs:5065-5082 (nothing_new_with), shadow.rs:3784-3795 (stale_pages_in_atomic), shadow.rs:5225-5275 (copy_stale), shadow.rs:5965, 6007 (merging.read()).
  • Proof & Telemetry:
    • Diagnostics shows ONE 174 MiB buffer (0x1c110000+0xae00000) refreshed 9.8×/frame (1,778.91 MB/frame, 5.68 ms/frame alone) because nothing_new_with bails whenever any pending GPU write overlaps the 174 MiB heap (true almost continuously due to skinning dispatches), forcing stale_pages_in_atomic and copy_stale to scan all 2,784 blocks + binary search.
    • merge_under_writes holds self.merging.write() over the entire 174 MiB shadow while diffing ~109 pages, emitting 34,788 micro-runs (118,821 scatter words, under flights = 2.9 ms), and calling card_changed_runs 109× under the exclusive lock — blocking the 4 copyback threads 4.37 ms/frame on self.merging.read().
  • Estimated Impact: ~3–5 ms/frame preparing + ~2–4 ms/frame copyback.
  • Architectural Replacement: Stripe Shadow::merging into a 64-way RwLock array indexed by block & 63; flush card_changed_runs once after releasing the lock; maintain uncopied_pages: AtomicUsize so stale_pages_in_atomic/copy_stale run in O(|written|) instead of O(pages log |written|); coalesce adjacent micro-runs within a 64-byte gap.

4. Post-#279 card_steps::fill_to() O(L) Linear Scan & 7,225 Per-Fill Mutex Locks + Unbatched release_tables() in relay_land

  • Where: crates/victory-gpu/src/host/card_steps.rs:521-568 (does_of), card_steps.rs:618-624, 1242 (fill_to), card_steps.rs:1359-1370 (late::on() 3rd walk); crates/victory-gpu/src/host.rs:7099 (detached.release_tables()).
  • Proof & Telemetry: Even after #279 moved CopyBufferRegion into compute gather (card_steps dropped 9.3 -> 5.8 ms/frame), fill_to() still linearly scans runs and re-locks list.deferred() for every fill step, and late::on() locks and walks all lists a third time. Separately, host.rs:7099 runs outside land::stat::GATHER and accounts for the 3.19 ms/frame unaccounted gap on the relay thread (16.6 ms total vs 13.41 ms instrumented).
  • Estimated Impact: ~1.5–2.5 ms/frame in card_steps + ~3.2 ms/frame on relay thread (latter solved by P1-1's batched release).
  • Architectural Replacement: Capture (list_idx, FillTo) directly inside does_of() (single pass covering late::on() fills as well).

Pass 2 Do-Not-Chase Kill List

  • host::mapped() holding ASIDE across WaitForSingleObject: Already fixed on main (host.rs:456-467 drops ASIDE before aside_wait and coalesces waiters on ASIDE_CV).
  • Whole-texture kernel re-read fallback: Only 0.6/frame (10.5 ms total over 60s).
  • take_snapshots() / quiet.rs: 0.1 ms/frame and already skipping ~246 MB/frame.
  • VICTORY_SUBMIT_SPLIT offline: Regressed to 13.9 fps and +549 MB VRAM over-budget.

Pass 3 — VRAM, Textures, Aliases & Visual Correctness (Verified Post-#281)

1. [Tier-1 Correctness — #150 Root Cause] Dual Visual Bug Still Present on main (fd5a4206)

  • Where:
    • Bug A (BC7 confetti/specks): crates/victory-formats/src/bcpack.rs:519-524 (and reference test bcpack.rs:1942-1945).
    • Bug B (Decoration-bake colored noise blocks): crates/victory-gpu/src/list/thin.rs + crates/victory-gpu/src/draw.rs:340, 2762, 2884-2970, 3045-3114.
  • Proof & Telemetry:
    • Bug A: While rotation() (bcpack.rs:1290) is already guarded to BC7 modes 4/5, dictionary table loading at bcpack.rs:519-524 still skips a u16 (r.u16();) and reads only &mut ix.ix.as_flattened_mut()[..31]. The format takes that word as pixel 0's index across all 32 i16 slots (ix.ix.as_flattened_mut()), shifting every BC7 dictionary-coded block's pixel indices by 1 texel -> colored specks/confetti on textures.
    • Bug B: Under default-on VICTORY_THIN=1, decoration-bake draws have no cross-list ordering barrier. Any list recorded after a bake list can be picked up first by one of the 8 translation workers and claim due texture slots into its later-submitted command list; when the bake draw executes early_textures() + bring_bake_sources(), those slots are no longer due or still show a stand-in/stale bytes (baseline logs other_bytes=13, showed_another_view=3; longer sessions log other_bytes=489, showed_another_view=117), permanently baking colored noise blocks for the scene.
  • Estimated Impact: Fixes both primary visual artifact classes tracked in #150 (~0 ms steady-state cost; only ~2–6 bake draws/frame).
  • Architectural Replacement:
    1. Remove r.u16(); and populate all 32 slots (for v in ix.ix.as_flattened_mut()) in bcpack.rs:519-524 (and 1942-1945).
    2. In list/thin.rs, detect bake-pipeline binds via draw::bake_pipeline (default-on, no switch bloat), drain prior recordings, and translate bake draws inline in submission order until another pipeline is bound.

2. [Tier-1 VRAM — #149 Root Cause] Double Eviction Dead-End: slot_evict() Blocks 100% of Streamed Textures & evict_idle_host() Skips Pinned Unmapped Textures

  • Where: crates/victory-gpu/src/descriptor/host.rs:3477 (slots_showing_from_raws), descriptor/host.rs:3630-3634 (tabled_lately), descriptor/host.rs:1113-1125 (seen_since), crates/victory-gpu/src/descriptor.rs:1911-1968 (evictable_slots), crates/victory-gpu/src/resource.rs:2672-2679 (evict_idle_host), resource.rs:2880-2896, 2989 (VICTORY_SLOT_EVICT / slot_evict).
  • Proof & Telemetry:
    • descriptor/host.rs:3477 computes let ok = i < count && !sampler && tabled_lately(i);. Every bindless texture picked by index (>95% of streamed VRAM textures) has stamp == 0, so tabled_lately(i) is always false -> evictable_slots classifies 100% of them as blocked. Even tabled textures idle > 240 frames flip to tabled_lately == false (blocked), while newer ones hit seen_since == true (kept).
    • Sweep profiling confirms all=43109 raws=30393 evictable=0 kept=0 blocked=30393 (7.90 ms spent finding 0 evictable slots), matching #149's reclaim: 0 over 19 minutes.
    • Independently, evict_idle_host() (resource.rs:2679) requires references(&host.texture) == 1, which is always false while any HostHeap::kept[slot] holds a COM reference (pinning unmapped placed textures indefinitely). Even with #281's poolsmall cutting 60s VRAM 6,803 -> 6,030 MB, longer sessions still fill VRAM monotonically to permanent room=false with zero reclaim.
  • Estimated Impact: Unlocks 500–2,000+ MB dynamic VRAM reclamation on 8–12 GiB GPUs (resolving #149), with zero overhead on 16+ GiB GPUs below budget.
  • Architectural Replacement: Track bindless slot last-use frames independently of table-copy stamp (removing tabled_lately(i) from ok), run slot_evict automatically when DXGI used > 85% of budget (default-on reactive policy, no opt-in switch), and allow evict_idle_host on unmapped placed textures to reset their HostHeap::kept slot to null/neutral before releasing the resource.

3. Why levels_on_demand Regresses Both FPS (-1.5 fps / +10 ms) & VRAM (+213 MB) on Top of #281's poolsmall, Plus shadow Card Budget Crowding 8 GiB Cards

  • Where: crates/victory-gpu/src/tiles.rs:194-226 (parse_floor_for / floor), tiles.rs:534-557 (uploaded_on), tiles.rs:303 (host::resident); crates/victory-gpu/src/shadow.rs:205-219 (default_card_limits_mb).
  • Proof & Telemetry:
    • Paired 60s A/B proves poolsmall alone achieves 15.8 fps, VRAM 6,030 MB, room_false=0%, final_waiting=2,178, whereas adding levels_on_demand regresses to 14.3 fps, preparing +10 ms (heaps/sweep 7.1–9.3 ms), VRAM 6,243 MB (+213 MB worse), final_waiting=3,310 (+1,132 worse).
    • Cause: tiles.rs:194 lowers the tiled floor to 256 KiB on <= 9 GiB GPUs, pulling thousands of medium textures out of #281's 4 KiB-packed pool into 64 KiB-tile tiles::POOL — losing sub-64 KiB packing, duplicating 64 MiB heap slack across two separate pools, and running serial UpdateTileMappings + texture_views_remade() on the submitting thread (tiles.rs:534-557).
    • Meanwhile, shadow.rs:205-219 allows up to 1,474 MiB of card-resident shadow buffers on an 8 GiB card (1,356 MiB observed = ~20% of 6.7 GiB DXGI budget), crowding out textures before tiled mips are even needed.
  • Estimated Impact: ~200–600 MB VRAM headroom on 8 GiB cards + prevents +10 ms preparing regression.
  • Architectural Replacement: Raise tiles::floor() to >= 2 MiB (restricting tiled reserved resources to large 2K/4K mip-streamed textures while < 2 MiB stays in 4 KiB poolsmall), batch UpdateTileMappings per submission, and make shadow card-buffer limits dynamically reactive to DXGI texture headroom (demoting idle card shadows when texture pressure exceeds 80% of budget).

4. 21,648 Committed Buffers Driving 15,000 Synchronous MakeResident (3.91s) + 16,200 mapped() (1.28s) Stalls

  • Where: crates/victory-gpu/src/ahead.rs:219, 227; crates/victory-gpu/src/host.rs:13441-13442 (shared_buffer_with), host.rs:13531-13532 (mapped_card_buffer), host.rs:13607-13608 (uav_buffer_with).
  • Proof & Telemetry: Diagnostics logs 10,482 shared buffers (5,265 MB) + 11,166 card buffers (1,958 MB) allocated as individual committed D3D12 resources. Even WITH poolsmall active (only 33 texture pool blocks), mapped() STILL runs 16,200 times (1,277.6 ms) and resident() runs 15,000 times (3,911.7 ms, 28.06 ms/s) — 5.18s of per-buffer WDDM residency + aside copy-queue fence waits, plus ~20k kernel residency allocations inflating Dxgkrnl submission overhead.
  • Estimated Impact: >95% reduction in MakeResident/mapped() stalls (~4–5s/60s saved across threads + reduced WDDM ExecuteCommandLists overhead).
  • Architectural Replacement: Sub-allocate 64 KiB ahead buffers (and small <= 4 MiB shadow buffers) as placed resources inside 64 MiB ID3D12Heap blocks (mirroring pool.rs: 1 MakeResident + 1 mapped() per 1,024 buffers), or batch MakeResident(32, ...) + 1 mapped() fence per refill batch.

Pass 3 Do-Not-Chase Kill List

  • GPU compute detiling: Previously proven 7.6–8× slower than CPU detile (#235).
  • Enabling VICTORY_LEVELS_ON_DEMAND=1 at 256 KiB floor on top of #281's poolsmall: Empirically regresses both VRAM (+213 MB) and FPS (-1.5 fps).
  • VICTORY_RENDER_XOR & VICTORY_UNORDERED_NOW_KB: Already implemented on main (crates/victory-formats/src/texture.rs:576, crates/victory-gpu/src/resource.rs:1774, 4021).

Pass 4 — Concurrency, Deadlocks & HLE/Shader Structural Hazards

1. [Tier-1 Freeze/Deadlock Hazard — #148] Unprotected Critical GPU Pipeline Workers & Unbounded WaitForSingleObject(INFINITE) / LINE_LANDED.wait()

  • Where: crates/victory-gpu/src/host.rs:5125-5142 (wait_host_fence: WaitForSingleObject(event, INFINITE)), host.rs:5339-5399 (relay_worker: line.settling = true at L5372, relay_land at L5388 with NO catch_unwind or RAII guard, cleared only at L7253), host.rs:5260-5299 (relay_wait_most: unbounded LINE_LANDED.wait(line), escape hatch at L5282 requires !line.settling), host.rs:5149-5199 (late_helper: no catch_unwind), crates/victory-gpu/src/queue/behind.rs:275-312 (Line::serve: no catch_unwind while drain()/wait_presents() wait unbounded on self.moved), host.rs:604 (wait_asked: WaitForSingleObject(e, INFINITE) under global WAITING mutex).
  • Logical Proof: Unlike sender() (host.rs:4423), list/thin.rs:464, and descriptor.rs:344-377, none of the three primary GPU completion/submission workers catch panics or clean up state on unwind. If any panic occurs inside relay_land (e.g., texback::land, shadow::land_card, card_steps), line.settling stays true forever, relay_worker silently exits, every Late::Signal stops, and every caller of Host::settle / fence::block_until hangs permanently at LINE_LANDED.wait() (host.rs:5298). Likewise, if a cross-queue/Streamline FG2x stall holds a fence without triggering OS TDR, wait_host_fence (host.rs:5132) blocks silently forever with zero timeout or diagnostic output while xmem keeps ticking 0 noted — matching the exact #148 symptom profile.
  • Estimated Impact: Eliminates silent permanent mid-gameplay hangs (#148-class) and guarantees actionable DRED/queue-state diagnostics on any GPU fence stall.
  • Architectural Replacement: Wrap relay_worker, late_helper, and behind::Line::serve in catch_unwind -> host::fail(...) plus an RAII SettlingGuard clearing line.settling = false and notifying LINE_LANDED; replace INFINITE in wait_host_fence() (host.rs:5132) and wait_asked() (host.rs:604) with a 5s polling wait loop that checks GetDeviceRemovedReason() and logs stalled fence/queue/flight state.

2. [Tier-1 Hang Hazard] Uncapped Per-Frame 10-Second Re-Stall on screen Pipelines

  • Where: crates/victory-gpu/src/pipeline/make.rs:274 (screen_budget = 10_000 ms), make.rs:441 (if !screen && p.missed_wait.load(Ordering::Acquire)), make.rs:451 (SPENT resets every frame), make.rs:475 (if !screen && ... { p.missed_wait.store(true, ...); }).
  • Logical Proof: Non-screen pipelines set p.missed_wait = true after missing one 80 ms frame wait so subsequent frames stop blocking. screen pipelines explicitly bypass missed_wait (!screen) and reset SPENT on every new frame (L451). If any screen-classified graphics or compute pipeline takes >10s (or stalls in the driver compiler), every subsequent frame blocks another 10,000 ms indefinitely (0.1 FPS freeze -> trips the title's 30s hang watchdog).
  • Estimated Impact: Eliminates infinite 10s/frame stall loops and 30s watchdog kills on slow/hung driver PSO compiles (0 ms steady-state cost).
  • Architectural Replacement: Track cumulative lifetime waited time (waited_ms: AtomicU64) on Pending and cap total waiting across frames at 10,000 ms even for screen pipelines (while allowing background compilation to finish asynchronously).

3. Cross-Crate Lock-Ordering Hazard: texback::land Calls xmem::materialize_for (PHYSICAL + GUARDS) Under MAPPING.read() + TICKETS

  • Where: crates/victory-gpu/src/watch.rs:3168-3174 (invariant: "Not to be taken twice by one thread, nor held across anything that maps title memory"); crates/victory-gpu/src/texback.rs:241-291 (_mapping = title_memory_reading() -> _ticket_guard = TICKETS.lock() -> read_into at L254 and copy_mapped(..., title_dst=true) at L291); crates/victory-gpu/src/host.rs:11674 (watch::materialize -> crates/victory-hle/src/modules/xmem.rs:2977 physical() + MapViewOfFile3 + title_memory_made_real -> GUARDS).
  • Logical Proof: texback::land runs on relay_worker holding MAPPING.read() + TICKETS, yet calls copy_mapped(..., title_dst=true) which materializes soft views via xmem::materialize_for (taking PHYSICAL -> GUARDS and calling MapViewOfFile3 while MAPPING.read() is held). This creates a lock-order inversion (TICKETS -> PHYSICAL in texback::land vs PHYSICAL -> TICKETS in xmem::map_lazy/map_as/unmap -> title_memory_remapped -> texback::remapped) currently only masked because those xmem paths acquire MAPPING.write() before PHYSICAL. Any non-MAPPING PHYSICAL caller invalidating tickets or contention with a pending MAPPING.write() risks deadlocking relay_worker right inside texback::land.
  • Estimated Impact: Eliminates a latent relay_worker lock-order inversion directly at the #148 texback path and enforces MAPPING's documented invariant.
  • Architectural Replacement: Call crate::watch::materialize(at, len) before acquiring title_memory_reading() and TICKETS in texback::land (texback.rs:241), and copy ticket metadata out under TICKETS rather than holding TICKETS across read_into/copy_mapped.

4. Wave64-to-Wave32 Translation Failures (6 Dropped Compute Shaders, 2.89s Wasted Cold Compile) & LDS Spin-Barrier Overhead (Lower::meet)

  • Where: crates/victory-shader/src/emit/mod.rs:748-868 (digest allowlist for wide_on + 5–7 full lowering retries before "no wave32 lowering for this wave64 program"); crates/victory-shader/src/emit/lower.rs:1402, 4910-4955 (Lower::meet: MEETING_POLLS = 4096 LDS barrier(8) + load + waveReadLaneFirst spin loop).
  • Proof & Telemetry:
    • Plain --release logs 6 compute shaders failing identically with no wave32 lowering for this wave64 program is not supported: 6871d6e4b3ac9a10 (1,834 ms), 6b82bc7d22016cb5 (603 ms), 1f1fbd86759b3da2 (182 ms), eae3498e6553afa8 (137 ms), b8f3f7979d6bbc50 (105 ms), a1bf269d5b19f025 (29 ms) — 2.89s wasted cold translation and 5.4+ dropped compute dispatches/frame in diagnostics.
    • In Lower::meet (lower.rs:4910-4955), pairs mode emits a 4,096-iteration barrier(8) + LDS load + waveReadLaneFirst spin loop at every pair meeting even at uniform blocks where all threads in the group are guaranteed to reach the meeting (where a single hardware GroupMemoryBarrierWithGroupSync barrier(9) avoids spin-loop SM warp-slot starvation).
  • Estimated Impact: Eliminates ~2.9s cold compile waste, recovers up to 5.4 dropped compute dispatches/frame on wave32 (NVIDIA) GPUs, and cuts warp spin-wait overhead in wave64-emulated compute passes.
  • Architectural Replacement: Cache negative unsupported translation outcomes keyed by translator version; replace the digest allowlist at emit/mod.rs:748-752 with a structural convergence + LDS-fit predicate for auto-widening; emit hardware group_sync (barrier(9)) in Lower::meet whenever the IR block is threadgroup-uniform (all_lane_blocks outside divergent loops), reserving the LDS spin-poll strictly for divergent-wave pair meetings.

Pass 4 Do-Not-Chase Kill List

  • list/thin.rs:456-462 PARKED_N vs WORK.wait(ready): Rigorous trace shows the worker calling park() always stores PARKED_N before looping back to wait_timeout(1ms), preventing an all-worker missed wakeup.
  • xmem.rs MAPPING vs PHYSICAL in map_pages/alias_as/map_aliases/scatter: Consistently ordered MAPPING.write() -> PHYSICAL, covered by unit test xmem.rs:3772.
  • dstorage.rs:1034 staging cap: self.staged == 0 || ... prevents head-of-line deadlock on requests exceeding staging capacity.
  • Shader LOOP_LIMIT constant-trip loop caps: Already addressed by open PR #266.
  • Replaced BVH structures (memory.rs:756): Already handled via replaced() / remove_packed().
<!-- greyfinch-sync:Androtim/MiniVI:issue:6719664111 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-01T11:52:12Z. --- Deep read-only static code and telemetry audit across `victory-gpu`, `victory-hle`, `victory-formats`, and `victory-shader`, cross-checked against plain `--release` 60s captures, `--features diagnostics` 90s captures, and current `main` (`fd5a4206`, post-`#278`/`#279`/`#281`). All `file:line` citations are verified against `main` `fd5a4206`. Work already merged in `#278`/`#279`/`#281` or covered by open PRs (`#265`, `#266`, `#269`, `#270`) is excluded. Every proposed fix is a default-on architectural replacement (no opt-in switch bloat). --- ## Pass 1 — Command-List Translation & Draw Hot Path ### 1. [Tier-1] Global Lock Contention (`RETIRED` + `HostHeap::next`) & D3D12 Call Explosion in Dynamic Descriptor Tables - **Where:** `crates/victory-gpu/src/descriptor/host.rs:4026-4052` (`keep_inner`) -> `crates/victory-gpu/src/host.rs:784-794` (`retire_resource`); `descriptor/host.rs:2512-2550` (`HostHeap::dynamic`), `descriptor/host.rs:3858-3874` (`HostHeap::release`), `crates/victory-gpu/src/draw.rs:599-620` (`State::tables_done`); `descriptor/host.rs:3953, 4194-4245, 4291` (`make_listed`, `constant_at`, `copy_to`). - **Proof & Telemetry:** - Plain `--release` baseline (`eb9dc68d`): `list::thin` spends **`428.9 ms/frame`** across 8 workers (88.5% saturated, `155` submitted lists still untranslated at submit time). Doubling workers to 16 regresses FPS `16.5 -> 15.0` and inflates total worker CPU time **`+57%` (`428.9 -> 675.4 ms/frame`, `13.6 us/call`)**, proving severe cross-thread lock contention. - Diagnostics 90s capture measures **`17,512` dynamic tables/frame** and **`12.0 ms/frame`** just scanning inside `HostHeap::next`. - Every dynamic slot overwrite (~100k–140k/frame) whose prior COM resource differs locks the single global `RETIRED` mutex (`bury_lag()` is 16/64, never 0). Meanwhile `HostHeap::next: Mutex<(u32, Vec<bool>)>` is locked **`35,024×/frame`** (17,512 allocs + 17,512 unbatched per-table releases via `SHADER_HEAPS.read()` + `self.next.lock()`), linearly scanning up to 262,144 `bool` bytes. - `make_listed` and `copy_to` emit `CopyDescriptorsSimple(1, ...)` one slot at a time plus per-slot `host::settle()`, and `constant_at` (`descriptor/host.rs:4242`) unconditionally creates a raw SRV twin (`CreateShaderResourceView` + `CopyDescriptorsSimple(1)`) for every CBV slot (4 D3D12 COM calls/CBV). - **Estimated Impact:** **`~2–5 ms/frame` wall + `~150–250 ms/frame` worker CPU + `~3.2 ms/frame` on relay thread** (`host.rs:7099`). - **Architectural Replacement:** 1. Buffer retired `ID3D12Resource`s in a per-list/thread-local `Vec` and flush once per list close into `RETIRED` (~600× fewer global locks). 2. Replace `Vec<bool>` in `HostHeap::next` with a `Vec<u64>` bitset (32 KiB, L1-resident) + per-list 256–512-slot bump slab + single batched `release_batch()` in `tables_done()` (one `SHADER_HEAPS.read()` + one lock per list). 3. Batch `CopyDescriptors` per table (hoisting `host::settle()` once per table) and skip the CBV raw SRV twin unless the bound `TableGroup` reads that slot as raw bytes. ### 2. [Tier-1 Bug] `VICTORY_FRESH_OPEN` Fast Path Fails 100.0% of the Time (1-Line Ordering Bug) - **Where:** `crates/victory-gpu/src/list.rs:848` (`reset` calls `with_state(this, ...)` -> `list.rs:152-154` -> `list.rs:240-244` `host_list(this)` -> `crates/victory-gpu/src/host.rs:8958` `title_call()`), checked against `crates/victory-gpu/src/host.rs:8850-8862` (`still_left_open()`). - **Proof & Telemetry:** - `list.rs:848` calls `with_state(this, ...)`, which invokes `host_list(this)` -> `list.title_call()` (incrementing `title_calls` by 1) *before* `host.reset()` checks `still_left_open()` (`calls == self.title_calls() + 1`). Because `title_calls` was already incremented, the predicate is mathematically always `false`. - Plain `--release` baseline confirms **`233.6` left open, `0.0` resets found them so, `234.18` closed after all**. Diagnostics attributes **`23.7 ms/frame`** to `lists reset`. - **Estimated Impact:** **`~3–8 ms/frame` worker CPU** (~234 redundant `Close()` + 234 `allocator.Reset()` + 234 `list.Reset()` per frame). - **Architectural Replacement:** Change `crates/victory-gpu/src/list.rs:848` from `with_state(this, ...)` to `with_state_on(host_list_held(this), this, ...)` so `still_left_open()` observes the pre-reset call count. ### 3. Host Command-List Pool Thrash & 4.17 GiB Private-Bytes Churn Under RAM Pressure - **Where:** `crates/victory-gpu/src/list.rs:312-347` (`IDLE_MOST`, `pressure_idle_cap`, `trim_on_pressure`), `list.rs:411-450` (`recycle`), `crates/victory-gpu/src/host.rs:802-808` (`bury_lag`), `crates/victory-gpu/src/list/thin.rs:412, 428-436` (`BACKS`). - **Proof & Telemetry:** - Diagnostics logs **`13 host lists made 6.0 ms/frame`** continuously (`12,741` total created, `1,071` alive, **`private bytes grew 4,172 MB`**), while baseline release trips `host memory pressure` trims every 1s. - `list/thin.rs` `BACKS` retains hidden idle `HostList`s detached from `IDLE`, and allocator recycling is delayed by `bury_lag` (16/64) instead of actual GPU fence completion (`FINISHED`). - **Estimated Impact:** **`~2–6 ms/frame` CPU + multi-GiB commit churn**. - **Architectural Replacement:** Attach `HostList` lazily inside `back_list()` rather than eagerly in `detach_parts` (eliminating ~150–300 hidden `HostList`s in `BACKS`), recycle command allocators immediately on GPU fence completion (`FINISHED`), and floor `trim_on_pressure` at `1.5×` rolling per-frame list demand unless commit is critical. ### 4. Zero Redundant-Bind Deduplication for Root Constants, Static Heap SRVs, VBs, and IBs - **Where:** `crates/victory-gpu/src/draw.rs:1911-1950` (`IASetVertexBuffers`/`IASetIndexBuffer` + `shadow::find_any`/`refresh`), `draw.rs:2122-2286` (`SetGraphicsRoot32BitConstants` + static heap `Set*RootShaderResourceView`). - **Proof & Telemetry:** Every draw (~6.8k steady-state, 12.8k–28.7k peak) re-looks up VB/IB shadows and re-emits `IASetVertexBuffers`, root 32-bit constants, and invariant static heap SRVs (`SLOT_STRIDES`, `SLOT_TABLE_STRIDES`, `SLOT_VIEW_ADDRESSES`, `SLOT_CODE_TABLE`, `SLOT_MEMORY`) across stages — ~40k–70k redundant D3D12 COM calls/frame. - **Estimated Impact:** **`~1–2 ms/frame` wall / `~15–30 ms/frame` worker CPU**. - **Architectural Replacement:** Track per-list VB/IB dirty bits + cached emitted root-arg state per `(compute, param)`, invalidated on root-signature change or `replay()`. ### Pass 1 Do-Not-Chase Kill List - **`VICTORY_INDIRECT_MERGE`:** Baseline logs `0 / 5,447` indirect executions eligible to merge. - **`VICTORY_WAIT_SHARE=1`:** Probed `14.3 fps` vs `16.5 fps` baseline (`GPU 0.0 ms`, CPU-bound). - **Raising `VICTORY_THIN_THREADS` above 8 before fixing P1-1:** 16 threads regressed `16.5 -> 15.0 fps` (+57% worker lock contention). - **Steady-state pipeline wait stalls:** `0.2 ms/frame`; >99% of "dropped without a host pipeline" are intentional RT/BVH skips. --- ## Pass 2 — Submission, Copyback, Shadow & Watch Pipeline ### 1. [Tier-1] Global `GUARDS` Mutex Held Across Kernel `VirtualProtect()` + TLB Shootdowns (Why Closed PR `#280` Wasn't Enough) - **Where:** `crates/victory-gpu/src/watch.rs:2387, 2420, 2514-2562` (`ask_guards` -> `protect`/`cover`), `watch.rs:2797, 2825` (`writing`/`kernel_writing`), `watch.rs:3631` (VEH `on_write`). - **Proof & Telemetry:** - Diagnostics measures **`guards` waited `62.80 ms/frame`** across 189 waits: `watch.rs:2387` = **`35.18 ms`**, `watch.rs:2420` = **`10.16 ms`**, `watch.rs:2825` = **`4.37 ms`** (with read-only `1614` + `2362` waiting `26.35 ms` behind `2387`). Plain `--release` logs `land::guards = 6.60 ms/frame` (spiking to `25.49 ms`). - Closed PR `#280` empirically proved that making only the read-side fast paths (`publish()` / `guard()` clean/held) lock-free only cut 35% of wait time and left wall-clock `preparing` (`30.9 -> 31.35 ms`) and `copyback` (`12.5 -> 12.3 ms`) flat because **~65% of the lock hold time is kernel `VirtualProtect()` + cross-core TLB shootdowns executed while holding the single global `GUARDS` mutex**, serializing the submitting thread, all 4 copyback merge threads, and title VEH faults on unrelated memory ranges. - **Estimated Impact:** **`~4–9 ms/frame` wall** across `preparing` (`write watch 6.0 ms`) and `copyback` (`land::guards 6.6 ms`). - **Architectural Replacement:** Shard `GUARDS` into a **64-way address-striped array** (`(block >> 6) & 63`, locked in ascending stripe index order for multi-stripe ranges) so a `VirtualProtect` + TLB shootdown in one 4 MiB stripe never stalls unrelated stripes, combined with lock-free read fast paths once write-side serialization is eliminated. ### 2. [Tier-1] Serial Per-List `HostList::prelude()` Allocator/List Resets Hiding in `lists' steps` - **Where:** `crates/victory-gpu/src/host.rs:8059` (`for list in runs` -> `list.prelude(&uploads)`), `host.rs:9275-9410` (`prelude()`). - **Proof & Telemetry:** - Baseline submitting thread spends `lists' steps = 16.7 ms` (`refreshes 8.6 + copies/fills 1.4 = 10.0 ms`, leaving **`6.7 ms/frame` unaccounted**). Even after `#279` coalesced refreshes, **`5.2 ms/frame`** remains in `lists' steps` "other". - Diagnostics shows **`177` preludes alive/frame**: `prelude()` pops a separate `(ID3D12CommandAllocator, ID3D12GraphicsCommandList)`, heap-allocates 4 `Vec`s + 1 `HashMap`, and executes `allocator.Reset()` + `list.Reset()` + `ResourceBarrier()` + `list.Close()` serially on the submitting thread for every list. - **Estimated Impact:** **`~4–6 ms/frame` on the serial submitting thread**. - **Architectural Replacement:** Use one shared per-submission prelude `ID3D12CommandAllocator` (~18 `allocator.Reset()`/frame instead of ~177), merge adjacent non-conflicting preludes into one prelude list, and reuse scratch buffers on `Batch`. ### 3. [Tier-1] Coarse Per-Shadow `merging` Write Lock & Unskipped 174 MiB Heap Refreshes - **Where:** `crates/victory-gpu/src/shadow.rs:4794-4908` (`merge_under_writes`), `shadow.rs:5065-5082` (`nothing_new_with`), `shadow.rs:3784-3795` (`stale_pages_in_atomic`), `shadow.rs:5225-5275` (`copy_stale`), `shadow.rs:5965, 6007` (`merging.read()`). - **Proof & Telemetry:** - Diagnostics shows ONE 174 MiB buffer (`0x1c110000+0xae00000`) refreshed **`9.8×/frame` (`1,778.91 MB/frame`, `5.68 ms/frame` alone)** because `nothing_new_with` bails whenever *any* pending GPU write overlaps the 174 MiB heap (true almost continuously due to skinning dispatches), forcing `stale_pages_in_atomic` and `copy_stale` to scan all 2,784 blocks + binary search. - `merge_under_writes` holds `self.merging.write()` over the entire 174 MiB shadow while diffing ~109 pages, emitting **`34,788` micro-runs** (`118,821` scatter words, `under flights = 2.9 ms`), and calling `card_changed_runs` 109× under the exclusive lock — blocking the 4 copyback threads **`4.37 ms/frame`** on `self.merging.read()`. - **Estimated Impact:** **`~3–5 ms/frame` preparing + `~2–4 ms/frame` copyback**. - **Architectural Replacement:** Stripe `Shadow::merging` into a 64-way `RwLock` array indexed by `block & 63`; flush `card_changed_runs` once after releasing the lock; maintain `uncopied_pages: AtomicUsize` so `stale_pages_in_atomic`/`copy_stale` run in `O(|written|)` instead of `O(pages log |written|)`; coalesce adjacent micro-runs within a 64-byte gap. ### 4. Post-`#279` `card_steps::fill_to()` O(L) Linear Scan & 7,225 Per-Fill Mutex Locks + Unbatched `release_tables()` in `relay_land` - **Where:** `crates/victory-gpu/src/host/card_steps.rs:521-568` (`does_of`), `card_steps.rs:618-624, 1242` (`fill_to`), `card_steps.rs:1359-1370` (`late::on()` 3rd walk); `crates/victory-gpu/src/host.rs:7099` (`detached.release_tables()`). - **Proof & Telemetry:** Even after `#279` moved `CopyBufferRegion` into compute gather (`card_steps` dropped `9.3 -> 5.8 ms/frame`), `fill_to()` still linearly scans `runs` and re-locks `list.deferred()` for every fill step, and `late::on()` locks and walks all lists a third time. Separately, `host.rs:7099` runs outside `land::stat::GATHER` and accounts for the **`3.19 ms/frame`** unaccounted gap on the relay thread (`16.6 ms` total vs `13.41 ms` instrumented). - **Estimated Impact:** **`~1.5–2.5 ms/frame` in `card_steps` + `~3.2 ms/frame` on relay thread** (latter solved by P1-1's batched release). - **Architectural Replacement:** Capture `(list_idx, FillTo)` directly inside `does_of()` (single pass covering `late::on()` fills as well). ### Pass 2 Do-Not-Chase Kill List - **`host::mapped()` holding `ASIDE` across `WaitForSingleObject`:** Already fixed on `main` (`host.rs:456-467` drops `ASIDE` before `aside_wait` and coalesces waiters on `ASIDE_CV`). - **Whole-texture kernel re-read fallback:** Only `0.6/frame` (`10.5 ms` total over 60s). - **`take_snapshots()` / `quiet.rs`:** `0.1 ms/frame` and already skipping `~246 MB/frame`. - **`VICTORY_SUBMIT_SPLIT` offline:** Regressed to `13.9 fps` and `+549 MB` VRAM over-budget. --- ## Pass 3 — VRAM, Textures, Aliases & Visual Correctness (Verified Post-`#281`) ### 1. [Tier-1 Correctness — `#150` Root Cause] Dual Visual Bug Still Present on `main` (`fd5a4206`) - **Where:** - **Bug A (BC7 confetti/specks):** `crates/victory-formats/src/bcpack.rs:519-524` (and reference test `bcpack.rs:1942-1945`). - **Bug B (Decoration-bake colored noise blocks):** `crates/victory-gpu/src/list/thin.rs` + `crates/victory-gpu/src/draw.rs:340, 2762, 2884-2970, 3045-3114`. - **Proof & Telemetry:** - **Bug A:** While `rotation()` (`bcpack.rs:1290`) is already guarded to BC7 modes 4/5, dictionary table loading at `bcpack.rs:519-524` still skips a `u16` (`r.u16();`) and reads only `&mut ix.ix.as_flattened_mut()[..31]`. The format takes that word as pixel 0's index across all 32 `i16` slots (`ix.ix.as_flattened_mut()`), shifting every BC7 dictionary-coded block's pixel indices by 1 texel -> colored specks/confetti on textures. - **Bug B:** Under default-on `VICTORY_THIN=1`, decoration-bake draws have no cross-list ordering barrier. Any list recorded *after* a bake list can be picked up first by one of the 8 translation workers and claim due texture slots into its *later*-submitted command list; when the bake draw executes `early_textures()` + `bring_bake_sources()`, those slots are no longer due or still show a stand-in/stale bytes (baseline logs `other_bytes=13, showed_another_view=3`; longer sessions log `other_bytes=489, showed_another_view=117`), permanently baking colored noise blocks for the scene. - **Estimated Impact:** **Fixes both primary visual artifact classes tracked in `#150` (~0 ms steady-state cost; only ~2–6 bake draws/frame)**. - **Architectural Replacement:** 1. Remove `r.u16();` and populate all 32 slots (`for v in ix.ix.as_flattened_mut()`) in `bcpack.rs:519-524` (and `1942-1945`). 2. In `list/thin.rs`, detect bake-pipeline binds via `draw::bake_pipeline` (default-on, no switch bloat), drain prior recordings, and translate bake draws inline in submission order until another pipeline is bound. ### 2. [Tier-1 VRAM — `#149` Root Cause] Double Eviction Dead-End: `slot_evict()` Blocks 100% of Streamed Textures & `evict_idle_host()` Skips Pinned Unmapped Textures - **Where:** `crates/victory-gpu/src/descriptor/host.rs:3477` (`slots_showing_from_raws`), `descriptor/host.rs:3630-3634` (`tabled_lately`), `descriptor/host.rs:1113-1125` (`seen_since`), `crates/victory-gpu/src/descriptor.rs:1911-1968` (`evictable_slots`), `crates/victory-gpu/src/resource.rs:2672-2679` (`evict_idle_host`), `resource.rs:2880-2896, 2989` (`VICTORY_SLOT_EVICT` / `slot_evict`). - **Proof & Telemetry:** - `descriptor/host.rs:3477` computes `let ok = i < count && !sampler && tabled_lately(i);`. Every bindless texture picked by index (>95% of streamed VRAM textures) has `stamp == 0`, so `tabled_lately(i)` is **always `false`** -> `evictable_slots` classifies 100% of them as `blocked`. Even tabled textures idle `> 240` frames flip to `tabled_lately == false` (`blocked`), while newer ones hit `seen_since == true` (`kept`). - Sweep profiling confirms **`all=43109 raws=30393 evictable=0 kept=0 blocked=30393`** (`7.90 ms` spent finding 0 evictable slots), matching `#149`'s **`reclaim: 0`** over 19 minutes. - Independently, `evict_idle_host()` (`resource.rs:2679`) requires `references(&host.texture) == 1`, which is always `false` while any `HostHeap::kept[slot]` holds a COM reference (pinning unmapped placed textures indefinitely). Even with `#281`'s `poolsmall` cutting 60s VRAM `6,803 -> 6,030 MB`, longer sessions still fill VRAM monotonically to permanent `room=false` with zero reclaim. - **Estimated Impact:** **Unlocks `500–2,000+ MB` dynamic VRAM reclamation on 8–12 GiB GPUs (resolving `#149`), with zero overhead on 16+ GiB GPUs below budget**. - **Architectural Replacement:** Track bindless slot last-use frames independently of table-copy `stamp` (removing `tabled_lately(i)` from `ok`), run `slot_evict` automatically when DXGI `used > 85%` of budget (default-on reactive policy, no opt-in switch), and allow `evict_idle_host` on unmapped placed textures to reset their `HostHeap::kept` slot to null/neutral before releasing the resource. ### 3. Why `levels_on_demand` Regresses Both FPS (`-1.5 fps` / `+10 ms`) & VRAM (`+213 MB`) on Top of `#281`'s `poolsmall`, Plus `shadow` Card Budget Crowding 8 GiB Cards - **Where:** `crates/victory-gpu/src/tiles.rs:194-226` (`parse_floor_for` / `floor`), `tiles.rs:534-557` (`uploaded_on`), `tiles.rs:303` (`host::resident`); `crates/victory-gpu/src/shadow.rs:205-219` (`default_card_limits_mb`). - **Proof & Telemetry:** - Paired 60s A/B proves `poolsmall` alone achieves **`15.8 fps`, VRAM `6,030 MB`, `room_false=0%`, `final_waiting=2,178`**, whereas adding `levels_on_demand` regresses to **`14.3 fps`, `preparing +10 ms` (`heaps/sweep 7.1–9.3 ms`), VRAM `6,243 MB` (`+213 MB` worse), `final_waiting=3,310` (`+1,132` worse)**. - Cause: `tiles.rs:194` lowers the tiled floor to `256 KiB` on `<= 9 GiB` GPUs, pulling thousands of medium textures out of `#281`'s 4 KiB-packed `pool` into 64 KiB-tile `tiles::POOL` — losing sub-64 KiB packing, duplicating 64 MiB heap slack across two separate pools, and running serial `UpdateTileMappings` + `texture_views_remade()` on the submitting thread (`tiles.rs:534-557`). - Meanwhile, `shadow.rs:205-219` allows up to `1,474 MiB` of card-resident shadow buffers on an 8 GiB card (`1,356 MiB` observed = ~20% of 6.7 GiB DXGI budget), crowding out textures before tiled mips are even needed. - **Estimated Impact:** **`~200–600 MB` VRAM headroom on 8 GiB cards + prevents `+10 ms` `preparing` regression**. - **Architectural Replacement:** Raise `tiles::floor()` to `>= 2 MiB` (restricting tiled reserved resources to large 2K/4K mip-streamed textures while `< 2 MiB` stays in 4 KiB `poolsmall`), batch `UpdateTileMappings` per submission, and make `shadow` card-buffer limits dynamically reactive to DXGI texture headroom (demoting idle card shadows when texture pressure exceeds 80% of budget). ### 4. `21,648` Committed Buffers Driving `15,000` Synchronous `MakeResident` (`3.91s`) + `16,200` `mapped()` (`1.28s`) Stalls - **Where:** `crates/victory-gpu/src/ahead.rs:219, 227`; `crates/victory-gpu/src/host.rs:13441-13442` (`shared_buffer_with`), `host.rs:13531-13532` (`mapped_card_buffer`), `host.rs:13607-13608` (`uav_buffer_with`). - **Proof & Telemetry:** Diagnostics logs **`10,482` shared buffers (`5,265 MB`) + `11,166` card buffers (`1,958 MB`)** allocated as individual committed D3D12 resources. Even WITH `poolsmall` active (only 33 texture pool blocks), `mapped()` STILL runs **`16,200` times (`1,277.6 ms`)** and `resident()` runs **`15,000` times (`3,911.7 ms`, `28.06 ms/s`)** — **`5.18s`** of per-buffer WDDM residency + aside copy-queue fence waits, plus ~20k kernel residency allocations inflating Dxgkrnl submission overhead. - **Estimated Impact:** **`>95%` reduction in `MakeResident`/`mapped()` stalls (~4–5s/60s saved across threads + reduced WDDM `ExecuteCommandLists` overhead)**. - **Architectural Replacement:** Sub-allocate 64 KiB `ahead` buffers (and small `<= 4 MiB` shadow buffers) as placed resources inside 64 MiB `ID3D12Heap` blocks (mirroring `pool.rs`: 1 `MakeResident` + 1 `mapped()` per 1,024 buffers), or batch `MakeResident(32, ...)` + 1 `mapped()` fence per refill batch. ### Pass 3 Do-Not-Chase Kill List - **GPU compute detiling:** Previously proven 7.6–8× slower than CPU detile (`#235`). - **Enabling `VICTORY_LEVELS_ON_DEMAND=1` at 256 KiB floor on top of `#281`'s `poolsmall`:** Empirically regresses both VRAM (`+213 MB`) and FPS (`-1.5 fps`). - **`VICTORY_RENDER_XOR` & `VICTORY_UNORDERED_NOW_KB`:** Already implemented on `main` (`crates/victory-formats/src/texture.rs:576`, `crates/victory-gpu/src/resource.rs:1774, 4021`). --- ## Pass 4 — Concurrency, Deadlocks & HLE/Shader Structural Hazards ### 1. [Tier-1 Freeze/Deadlock Hazard — `#148`] Unprotected Critical GPU Pipeline Workers & Unbounded `WaitForSingleObject(INFINITE)` / `LINE_LANDED.wait()` - **Where:** `crates/victory-gpu/src/host.rs:5125-5142` (`wait_host_fence`: `WaitForSingleObject(event, INFINITE)`), `host.rs:5339-5399` (`relay_worker`: `line.settling = true` at `L5372`, `relay_land` at `L5388` with NO `catch_unwind` or RAII guard, cleared only at `L7253`), `host.rs:5260-5299` (`relay_wait_most`: unbounded `LINE_LANDED.wait(line)`, escape hatch at `L5282` requires `!line.settling`), `host.rs:5149-5199` (`late_helper`: no `catch_unwind`), `crates/victory-gpu/src/queue/behind.rs:275-312` (`Line::serve`: no `catch_unwind` while `drain()`/`wait_presents()` wait unbounded on `self.moved`), `host.rs:604` (`wait_asked`: `WaitForSingleObject(e, INFINITE)` under global `WAITING` mutex). - **Logical Proof:** Unlike `sender()` (`host.rs:4423`), `list/thin.rs:464`, and `descriptor.rs:344-377`, none of the three primary GPU completion/submission workers catch panics or clean up state on unwind. If any panic occurs inside `relay_land` (e.g., `texback::land`, `shadow::land_card`, `card_steps`), `line.settling` stays `true` forever, `relay_worker` silently exits, every `Late::Signal` stops, and every caller of `Host::settle` / `fence::block_until` hangs permanently at `LINE_LANDED.wait()` (`host.rs:5298`). Likewise, if a cross-queue/Streamline FG2x stall holds a fence without triggering OS TDR, `wait_host_fence` (`host.rs:5132`) blocks silently forever with zero timeout or diagnostic output while `xmem` keeps ticking `0 noted` — matching the exact `#148` symptom profile. - **Estimated Impact:** **Eliminates silent permanent mid-gameplay hangs (`#148`-class) and guarantees actionable DRED/queue-state diagnostics on any GPU fence stall**. - **Architectural Replacement:** Wrap `relay_worker`, `late_helper`, and `behind::Line::serve` in `catch_unwind` -> `host::fail(...)` plus an RAII `SettlingGuard` clearing `line.settling = false` and notifying `LINE_LANDED`; replace `INFINITE` in `wait_host_fence()` (`host.rs:5132`) and `wait_asked()` (`host.rs:604`) with a 5s polling wait loop that checks `GetDeviceRemovedReason()` and logs stalled fence/queue/flight state. ### 2. [Tier-1 Hang Hazard] Uncapped Per-Frame 10-Second Re-Stall on `screen` Pipelines - **Where:** `crates/victory-gpu/src/pipeline/make.rs:274` (`screen_budget = 10_000 ms`), `make.rs:441` (`if !screen && p.missed_wait.load(Ordering::Acquire)`), `make.rs:451` (`SPENT` resets every `frame`), `make.rs:475` (`if !screen && ... { p.missed_wait.store(true, ...); }`). - **Logical Proof:** Non-screen pipelines set `p.missed_wait = true` after missing one 80 ms frame wait so subsequent frames stop blocking. `screen` pipelines explicitly bypass `missed_wait` (`!screen`) and reset `SPENT` on every new frame (`L451`). If any `screen`-classified graphics or compute pipeline takes >10s (or stalls in the driver compiler), every subsequent frame blocks another **10,000 ms** indefinitely (0.1 FPS freeze -> trips the title's 30s hang watchdog). - **Estimated Impact:** **Eliminates infinite 10s/frame stall loops and 30s watchdog kills on slow/hung driver PSO compiles (0 ms steady-state cost)**. - **Architectural Replacement:** Track cumulative lifetime waited time (`waited_ms: AtomicU64`) on `Pending` and cap total waiting across frames at 10,000 ms even for `screen` pipelines (while allowing background compilation to finish asynchronously). ### 3. Cross-Crate Lock-Ordering Hazard: `texback::land` Calls `xmem::materialize_for` (`PHYSICAL` + `GUARDS`) Under `MAPPING.read()` + `TICKETS` - **Where:** `crates/victory-gpu/src/watch.rs:3168-3174` (invariant: *"Not to be taken twice by one thread, nor held across anything that maps title memory"*); `crates/victory-gpu/src/texback.rs:241-291` (`_mapping = title_memory_reading()` -> `_ticket_guard = TICKETS.lock()` -> `read_into` at `L254` and `copy_mapped(..., title_dst=true)` at `L291`); `crates/victory-gpu/src/host.rs:11674` (`watch::materialize` -> `crates/victory-hle/src/modules/xmem.rs:2977` `physical()` + `MapViewOfFile3` + `title_memory_made_real` -> `GUARDS`). - **Logical Proof:** `texback::land` runs on `relay_worker` holding `MAPPING.read()` + `TICKETS`, yet calls `copy_mapped(..., title_dst=true)` which materializes soft views via `xmem::materialize_for` (taking `PHYSICAL` -> `GUARDS` and calling `MapViewOfFile3` while `MAPPING.read()` is held). This creates a lock-order inversion (`TICKETS -> PHYSICAL` in `texback::land` vs `PHYSICAL -> TICKETS` in `xmem::map_lazy`/`map_as`/`unmap` -> `title_memory_remapped` -> `texback::remapped`) currently only masked because those `xmem` paths acquire `MAPPING.write()` before `PHYSICAL`. Any non-`MAPPING` `PHYSICAL` caller invalidating tickets or contention with a pending `MAPPING.write()` risks deadlocking `relay_worker` right inside `texback::land`. - **Estimated Impact:** **Eliminates a latent `relay_worker` lock-order inversion directly at the `#148` `texback` path and enforces `MAPPING`'s documented invariant**. - **Architectural Replacement:** Call `crate::watch::materialize(at, len)` *before* acquiring `title_memory_reading()` and `TICKETS` in `texback::land` (`texback.rs:241`), and copy ticket metadata out under `TICKETS` rather than holding `TICKETS` across `read_into`/`copy_mapped`. ### 4. Wave64-to-Wave32 Translation Failures (6 Dropped Compute Shaders, 2.89s Wasted Cold Compile) & LDS Spin-Barrier Overhead (`Lower::meet`) - **Where:** `crates/victory-shader/src/emit/mod.rs:748-868` (digest allowlist for `wide_on` + 5–7 full lowering retries before `"no wave32 lowering for this wave64 program"`); `crates/victory-shader/src/emit/lower.rs:1402, 4910-4955` (`Lower::meet`: `MEETING_POLLS = 4096` LDS `barrier(8)` + load + `waveReadLaneFirst` spin loop). - **Proof & Telemetry:** - Plain `--release` logs **6 compute shaders** failing identically with `no wave32 lowering for this wave64 program is not supported`: `6871d6e4b3ac9a10` (**`1,834 ms`**), `6b82bc7d22016cb5` (`603 ms`), `1f1fbd86759b3da2` (`182 ms`), `eae3498e6553afa8` (`137 ms`), `b8f3f7979d6bbc50` (`105 ms`), `a1bf269d5b19f025` (`29 ms`) — **`2.89s` wasted cold translation** and **`5.4+` dropped compute dispatches/frame** in diagnostics. - In `Lower::meet` (`lower.rs:4910-4955`), `pairs` mode emits a 4,096-iteration `barrier(8)` + LDS load + `waveReadLaneFirst` spin loop at every pair meeting even at uniform blocks where all threads in the group are guaranteed to reach the meeting (where a single hardware `GroupMemoryBarrierWithGroupSync` `barrier(9)` avoids spin-loop SM warp-slot starvation). - **Estimated Impact:** **Eliminates ~2.9s cold compile waste, recovers up to 5.4 dropped compute dispatches/frame on wave32 (NVIDIA) GPUs, and cuts warp spin-wait overhead in wave64-emulated compute passes**. - **Architectural Replacement:** Cache negative unsupported translation outcomes keyed by translator version; replace the digest allowlist at `emit/mod.rs:748-752` with a structural convergence + LDS-fit predicate for auto-widening; emit hardware `group_sync` (`barrier(9)`) in `Lower::meet` whenever the IR block is threadgroup-uniform (`all_lane_blocks` outside divergent loops), reserving the LDS spin-poll strictly for divergent-wave pair meetings. ### Pass 4 Do-Not-Chase Kill List - **`list/thin.rs:456-462` `PARKED_N` vs `WORK.wait(ready)`:** Rigorous trace shows the worker calling `park()` always stores `PARKED_N` before looping back to `wait_timeout(1ms)`, preventing an all-worker missed wakeup. - **`xmem.rs` `MAPPING` vs `PHYSICAL` in `map_pages`/`alias_as`/`map_aliases`/`scatter`:** Consistently ordered `MAPPING.write() -> PHYSICAL`, covered by unit test `xmem.rs:3772`. - **`dstorage.rs:1034` staging cap:** `self.staged == 0 || ...` prevents head-of-line deadlock on requests exceeding staging capacity. - **Shader `LOOP_LIMIT` constant-trip loop caps:** Already addressed by open PR `#266`. - **Replaced BVH structures (`memory.rs:756`):** Already handled via `replaced()` / `remove_packed()`.
Androtim commented 2026-12-02 14:56:38 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-02T14:56:38Z.


Follow-Up Deep Static Logic Audit (main @ baf967fc + Open PRs #302, #329–#333, #341–#343)

Fresh strictly read-only logic audit skipping items already covered above in #282 or fixed in #335/#336/#337. High-confidence confirmed bugs only.


Area 1 — New GPU & Memory Hot Paths (main @ baf967fc: #322, #324, #327, #328)

1. [P0] slot_evict Deadlocked Between 85% and ~98.3% VRAM on 12–24 GB GPUs (Primary Cause of Long-Session VRAM + Shared Spill Creep)

  • Location: crates/victory-gpu/src/resource.rs:2378-2380 (line_for), resource.rs:2764-2767, 2912 (let_go_idle), resource.rs:3073-3126 (slot_evict), crates/victory-gpu/src/host.rs:181-197 (vram_keep_below), compounded by crates/victory-gpu/src/host.rs:690-703 (ram_idle_ms).
  • Step-by-step failure sequence:
    1. On a 16 GB GPU (budget ≈ 15.1 GiB), line_for(budget) returns room_line = 95% (~14.3 GiB).
    2. let_go_idle() passes weighed(budget, used) (raw used minus fragmented pool::texture_room() + tiles::free_room(), often 500 MiB–1.5 GiB of un-evictable slack) into vram_keep_below(budget, weighed, line).
    3. While weighed < 93% (~14.0 GiB, which corresponds to raw used anywhere from 85% up to ~98.3%!), vram_keep_below returns KEPT_MS = 600_000 (10 minutes).
    4. let_go_idle() forwards idle_ms = 600_000 into slot_evict(memory, idle_ms, IDLE_FRAMES) (resource.rs:2912).
    5. slot_evict activates at 85% raw used, but RING only retains 120 seconds of frame timestamps (resource.rs:3084-3091). frame_at(&ring, now_ms - 600_000) returns None, so between 85% and 95% raw used, slot_evict returns early at resource.rs:3097-3104 performing zero evictions.
    6. Past 95% raw used, slot_evict falls back to frame - 4 for the table-frame cutoff, but resource.rs:3122 still filters every candidate with !crate::host::long_ago(stamp, idle_ms, frames) using idle_ms = 600_000, rejecting every texture touched in the last 10 minutes.
    7. Meanwhile, on >32 GB RAM hosts ram_idle_ms holds host staging/shadow caches for 5 minutes until residency::pressured() trips at avail_phys <= 3 GiB || avail_commit <= 4 GiB, allowing WDDM to spill VRAM heaps into shared memory and private commit (~15.3 GB VRAM + 8+ GB shared + 33 GB commit over ~36k frames).
  • Minimal fix: Compute slot_evict's effective idle_ms directly from raw used / budget and clamp it to <= 60_000 ms (well inside RING's 120 s history), e.g., 60_000 ms at 85% scaling down to 5_000 ms at >= 93%, completely decoupled from vram_keep_below's KEPT_MS = 600_000.

2. [P0] CardBumpPool (#322) Bump-Only 4 MiB VRAM Heap Pinning (Up to 64× Fragmentation Leak)

  • Location: crates/victory-gpu/src/ahead.rs:270, 434-533 (CARD_HEAP_KEY, CardBumpPool, CARD_POOL, alloc_pooled_card), called from host.rs:13982 (uav_buffer_with), host/uav_pool.rs:104, and ahead.rs:796.
  • Step-by-step failure sequence:
    1. Every device-local uav_buffer(size <= 1 MiB) allocates 64 KiB-aligned slots sequentially from 4 MiB ID3D12Heaps via CardBumpPool (ahead.rs:434-470), which has no free-bitset or slot recycling.
    2. Each placed ID3D12Resource attaches an owning COM reference to its entire 4 MiB ID3D12Heap via SetPrivateDataInterface(&CARD_HEAP_KEY, &heap_unk) (ahead.rs:527).
    3. Whenever the pool rotates heaps (install() drops old entries once active.len() >= 2 at ahead.rs:462-466, also abandoning remaining free slots under concurrent creation races), any single surviving 64 KiB allocation from that heap (a persistent Shadow, a cached UAV_SPARE entry, or a LIFO-bottom ahead::CARD entry) permanently pins the entire 4 MiB default heap in VRAM while the other 63 slots can never be reused.
  • Minimal fix: Replace CardBumpPool with a free-list / bitset + fence-gated slot retirement pool (mirroring SharedPool), and re-check take(slots) after re-acquiring CARD_POOL before allocating a fresh 4 MiB heap.

3. [P1] watch::ask_rest (#324) Stale j.ahead Clone & Unheld-Range Timestamp Advance Race (Silent Missed Write-Watch Refreshes)

  • Location: crates/victory-gpu/src/watch.rs:974-1019 (record_rest_pages, ask_rest), interacting with ask_ahead (watch.rs:605-659), ask_once_extend (watch.rs:949-958), and ask_once_end (watch.rs:1034-1041).
  • Step-by-step failure sequence:
    1. ask_rest clones journal().ahead at watch.rs:1007 before acquiring Askings::hold(to_hold) (watch.rs:1017), and to_hold excludes all ranges in ahead.
    2. Race A (missed writes): Because pages P ∈ ahead are not held by Askings::hold(to_hold), another thread can call GetWriteWatch(WRITE_WATCH_FLAG_RESET) on P at T2, after which the title writes P at T3. Then record_rest_pages (watch.rs:991-998) advances j.ahead_asked = next_asking() (T4 > T3) across the entire merged j.ahead without re-querying P. Subsequent refreshes see j.ahead_asked >= T3 and permanently miss the write at T3.
    3. Race B (resurrected cleared journal): If ask_once_end() clears j.ahead and sets j.kept = false between watch.rs:1007 and watch.rs:986, record_rest_pages (watch.rs:996-998) overwrites j.ahead with the stale pre-clear clone and sets j.kept = true.
  • Minimal fix: Add a monotonic ask_once epoch in Journal (aborting record_rest_pages if the epoch changed since ask_rest began), re-read j.ahead under journal_mut(), and track per-interval (first, last, asked_at) timestamps instead of advancing one global j.ahead_asked over unqueried ranges.

4. [P1] shadow::unregister Drops Arc<Shadow> Synchronously Without host::retire (In-Flight HASH_POOL Reuse -> 0x887A0006)

  • Location: crates/victory-gpu/src/shadow.rs:6630-6636 (unregister), shadow.rs:3803-3841 (Drop for Shadow), shadow.rs:566-572 (hash_give).
  • Step-by-step failure sequence:
    1. Unlike let_go_idle (shadow.rs:4253) and in_place_let_go (shadow.rs:6678), unregister() removes entry from BUFFERS and lets entry.shadow drop synchronously on the calling thread without passing it to crate::host::retire(shadow).
    2. HostHeap::kept retains only shadow.buffer, not Arc<Shadow>. If a title releases a buffer whose card.before hash buffer or shadow.buffer is still referenced by an in-flight submission or bindless descriptor slot, Shadow::drop runs immediately and calls hash_give(class, before.buffer, before.gpu) (shadow.rs:3836) with zero GPU fence wait.
    3. The next buffer allocation pops before.buffer from HASH_POOL and overwrites its GPUVA while the earlier command list is still executing on the GPU -> data corruption or DXGI_ERROR_DEVICE_HUNG (0x887A0006).
  • Minimal fix: Pass shadow to crate::host::retire(shadow) inside shadow::unregister after shadow.mark_retired().

5. [P2] Unbounded STATES Map Leak in host/lazy.rs (#327) & xmem::shows_slices Ignores LAZY Entries (#328)

  • Location: crates/victory-gpu/src/host/lazy.rs:239, 253-259 (STATES) and crates/victory-hle/src/modules/xmem.rs:949-977, 1798, 1905, 2995-3027 (shows_slices, map_lazy, LAZY).
  • Failure sequences:
    • host/lazy.rs: STATES inserts (shadow.id(), State) (each containing Vec<bool> / Vec<u32> per 64 KiB piece) for every >= 64 MiB shadow buffer, with no removal hook when a Shadow drops. Fix: add lazy::forget(self.id) and invoke it in Drop for Shadow.
    • xmem.rs: map_lazy records a MEM_RESERVE-only range in both LAZY and physical.views, while shows_slices checks only physical.views. A subsequent non-lazy XMemMapPhysicalPages / alias_as covering the same slices returns early thinking the host view is already materialized, leaving pages unmapped (MEM_RESERVE). Fix: have shows_slices return false if any entry in LAZY overlaps [base, base + len).

Area 2 — AMD RDNA 4 (RX 9060 XT, WaveLaneCountMin=32, Max=64) Shader Wave & Culling Logic (crates/victory-shader/ @ baf967fc)

6. [P0] Wave64 Compute Shaders Omitting [WaveSize(64)] Silently Execute as Wave32 on RDNA 4 (v_readfirstlane_b32 & Multi-Wave LDS Race — Explains Whole-Foliage Blinking & Split-Tile Artifacts)

  • Location: crates/victory-shader/src/emit/lower.rs:1863-1900, 1986-2003 (console_lanes, one_wave, s.wave_size).
  • Step-by-step failure sequence:
    1. On AMD RDNA 4 (host_max_wave() == 64, WaveLaneCountMin = 32, Max = 64), omitting DXIL [WaveSize(64)] (s.wave_size == None) causes the AMD driver to default compute shaders to Wave32. Because host_max_wave() != 32, lower.rs:1887 never activates split_lds or halves/pairs.
    2. Two omissions leave s.wave_size = None on console Wave64 compute shaders:
      • v_readfirstlane_b32 missing from console_lanes (lower.rs:1869): Only v_readlane_b32 | v_writelane_b32 are matched. Any Wave64 compute shader using v_readfirstlane_b32 without another listed cross-lane op compiles without [WaveSize(64)], executes as Wave32, and broadcasts lane 32's value to lanes 32..63 instead of lane 0's (corrupting base indices/cull flags for the upper half of every 64-thread console wave).
      • Multi-wave LDS compute shaders (group > 64 && s.lds_dwords > 0, lower.rs:1878, 2001): one_wave = group <= wave, so any Wave64 compute shader with group > 64 (e.g., 128 or 256 threads) that relies on implicit intra-wave 64-lane lockstep LDS sharing without s_barrier (and without another listed cross-lane op) gets s.wave_size = None! On RDNA 4, each 64-lane console wave splits into two asynchronously scheduled Wave32 wavefronts racing on intra-wave LDS writes/reads — producing non-deterministic intermittent whole-group culling drops (e.g., whole-foliage clusters blinking in/out frame-to-frame) and tile corruption.
  • Minimal fix: Include non-waterfall v_readfirstlane_b32 in console_lanes (lower.rs:1869), and replace one_wave && s.lds_dwords > 0 at lower.rs:1887 and lower.rs:2001 with s.lds_dwords > 0 && (group > 32 || !x.native.wave64) (so any Wave64 compute shader using LDS emits [WaveSize(64)] on RDNA 4 and enters the split_lds check on Wave32-only hosts).

7. [P0] scc_some Skips within_exec and all_lane_blocks_native Checks on Native Wave64 Hosts (AMD RDNA 4)

  • Location: crates/victory-shader/src/emit/lower.rs:5166-5188, 7249-7280 (scc_some, scc_in) + crates/victory-shader/src/structure.rs:917-922, 1287-1289.
  • Step-by-step failure sequence:
    1. structure.rs:917-922, 1287-1289 exports the SCC of every non-scc_every mask SOP into st.scc_some, including s_not_b64, s_or_b64, s_xor_b64, and s_andn2_b64, whose result mask holds bits in inactive lanes (!st.active).
    2. When an instruction reads SCC (s_cselect_b32/b64, src_scc, etc.), scc_in (lower.rs:7249-7252) delegates straight to scc_some(v), bypassing within_exec(v) (lower.rs:7261).
    3. Inside scc_some (lower.rs:5180-5188), waveAnyTrue(bit) is emitted over currently active host lanes. On NVIDIA (self.exchange.is_some()), lines 5185-5188 catch divergent defining blocks and return Err(DIVERGENT_MASK_EXCHANGE) so widen() widens the enclosing branch.
    4. On AMD RDNA 4 (self.exchange.is_none()), line 5182-5184 returns Ok(some) immediately without checking self.within_exec(scc) or all_lane_blocks_native(self.x.st)!
    5. Consequently, any SCC derived from inactive-lane mask bits inside a per-lane branch polls only active lanes on RDNA 4 and silently evaluates to false when set bits reside in masked-out lanes — inverting culling/tile-visibility s_cselect decisions specifically on native Wave64 hosts.
  • Minimal fix: Mirror mask_dword inside scc_some (lower.rs:5172-5184): before emitting waveAnyTrue, if !self.within_exec(scc) and !made.is_none_or(|b| all_lane_blocks_native(self.x.st).is_some_and(|all| all[b])), call need(made.unwrap_or(0)) and return Err(MASK_ELSEWHERE) so widen() widens the enclosing branch on native Wave64 too.

8. [P0] s_cbranch_vccz / s_cbranch_vccnz Incorrectly Intersects VCC with Current EXEC (Sharp-Boundary Tile/Culling Drop)

  • Location: crates/victory-shader/src/structure.rs:1407-1418.
  • Step-by-step failure sequence:
    1. Per GFX10/RDNA ISA, s_cbranch_vccz / s_cbranch_vccnz tests raw VCC == 0 / VCC != 0, not (VCC & EXEC) == 0 / != 0.
    2. structure.rs:1412 computes let any = self.b.and(vcc, exec);, masking out all VCC bits belonging to lanes outside current EXEC.
    3. Whenever a shader builds VCC before narrowing EXEC (or manipulates VCC with s_or_b64 / s_andn2_b64 / s_not_b64 / s_mov_b64 vcc, ... while EXEC is narrowed — common in screen-space/horizon-frustum tile culling and water-tile loops), all inactive lanes' VCC bits are silently discarded. Both per-lane and wave_wide (waveAnyTrue/waveAllTrue) branches then take the wrong target once active lanes cross a sharp threshold (e.g., screen-horizon / camera-pitch boundary), causing entire rows of tiles to skip/vanish along a sharp horizontal line.
  • Minimal fix: Remove self.b.and(vcc, exec) at structure.rs:1412 and test raw vcc directly (requiring widening via need() if vcc is not active at a divergent block).

9. [P1] ticket LDS Counter Overflows D3D12's 32 KiB TGSM Limit Unguarded

  • Location: crates/victory-shader/src/emit/lower.rs:1384, 1996-2000, 2762 (HOST_LDS_DWORDS, ticket).
  • Step-by-step failure sequence:
    1. On any multi-wave compute shader with console_lanes && group > wave && ticket_on() (e.g., Wave64 with group > 64 on RDNA 4, or Wave32 with group > 32 on any GPU), lower.rs:1998-1999 allocates ticket by incrementing s.lds_dwords += 1.
    2. If the console shader already uses the full 32 KiB TGSM (8192 dwords), s.lds_dwords becomes 8193 (32,772 > 32,768 bytes).
    3. The TGSM overflow guard at lower.rs:2762 checks if self.pairs.is_some() && self.s.lds_dwords > HOST_LDS_DWORDS, which is false when ticket (or halves/exchange without pairs) overflowed TGSM.
    4. DXIL is emitted with 8193 TGSM dwords -> D3D12 PSO creation fails and dispatches using that shader are silently dropped.
  • Minimal fix: Remove the self.pairs.is_some() && precondition at lower.rs:2762 (guard self.s.lds_dwords > HOST_LDS_DWORDS unconditionally), and skip allocating ticket when s.lds_dwords == HOST_LDS_DWORDS (falling back to linear flat / wave wave base for 1D group % wave == 0 or returning a clean Err).

10. [P1] Float Inclusive Wave Prefix Sum Emits Integer Bin::Add on f32 Operands & Hardcodes unsigned = 1

  • Location: crates/victory-shader/src/emit/lower.rs:2466-2479 (wavePrefixOp.f32).
  • Step-by-step failure sequence:
    1. For Op::AddF with prefix == Some(true) (inclusive float wave prefix sum), lower.rs:2467, 2474 hardcodes unsigned = i8(1) (k1) into dx.op.wavePrefixOp.f32 (compare u8::from(!float) at lower.rs:2495, 2532).
    2. Immediately below at lower.rs:2477, if inclusive { self.s.m.bin(c, Bin::Add, r, arg) } emits LLVM integer add (Bin::Add) on two f32 values (r and arg, type f32t) instead of Bin::FAdd -> malformed LLVM IR / instant DXIL validator rejection.
  • Minimal fix: Pass self.s.m.i8(u8::from(!float)) to wavePrefixOp and use if float { Bin::FAdd } else { Bin::Add } at lower.rs:2477.

11. [P2] DPP row_shl/row_shr Out-of-Bounds laneIndex UB & v_permlane fi:1 Loop-Latch Check

  • Location: crates/victory-shader/src/emit/lower.rs:9053-9065, 9098 (DPP 0x101..=0x11F) and lower.rs:9889-9896 (v_permlane16_b32 / v_permlanex16_b32).
  • Failure sequences:
    • lower.rs:9061, 9098: For row_shr:n at lane < n, lane - n wraps to 0xFFFF_FFFF..; for row_shl:n at lane >= wave - n, lane + n >= WaveGetLaneCount(). src is passed unclamped to dx.op.waveReadLaneAt.i32 before the inside select (lower.rs:9104) — out-of-range laneIndex is HLSL/DXIL UB (drivers may trap or return poison). Fix: clamp let safe = self.s.m.select(c, inside, src, lane); before read_lane (as v_permlane already does).
    • lower.rs:9891: v_permlane16/x16 with fetch_inactive (fi:1) checks all_lane_blocks(self.x.st) (loops = false) instead of all_lane_blocks_native(self.x.st) (loops = true), permitting fetch_inactive inside loops where some lanes already exited via a divergent latch. Fix: check all_lane_blocks_native(self.x.st).

Area 3 — Pre-Merge Logic Audit of Open PRs (#302, #329–#333, #341–#343)

12. [P0] PR #331 (11322318) — ReadMostly::read Re-Entrant Read Self-Deadlock on Windows SRWLOCK

  • Location: crates/victory-gpu/src/listcpu.rs:156-182 (ReadMostly::read, try_read, HELD).
  • Step-by-step failure sequence:
    1. ReadMostly::read explicitly supports nested reads on the same thread by storing (depth, first) in HELD TLS and returning at = first when depth > 0.
    2. On a nested call (depth > 0), line 158 (let held = self.locks[at].0.read()...) calls AcquireSRWLockShared a second time on the exact same std::sync::RwLock (SRWLOCK) already held by the outer guard on the same thread.
    3. On Windows, SRWLOCK is non-reentrant for shared acquisition in the presence of a waiting writer: if any writer calls ReadMostly::write() and blocks waiting for self.locks[at] between the outer read() and inner read(), Windows queues the second AcquireSRWLockShared behind the exclusive writer while the writer waits for the outer ReleaseSRWLockShared -> instant permanent self-deadlock.
  • Minimal fix: When depth > 0, do not re-acquire self.locks[at].0.read() (store Option<RwLockReadGuard<'a, ()>> in ReadGuard, or forbid nested read() with debug_assert_eq!(depth, 0) if guards can drop out of LIFO order, since storing None on inner guards is only sound if guards drop strictly LIFO or the outer guard moves the underlying RwLockReadGuard to TLS).

13. [P0] PR #342 (84ac527d, #339) — Dangling ID3D12Heap Tile Mappings on Error Paths in by_address_in / map_buffer_tiles (GPU Page Fault / 0x887A0006)

  • Location: crates/victory-gpu/src/shadow.rs:7151-7175 (by_address_in) and crates/victory-gpu/src/host/reserved.rs:58-158 (map_buffer_tiles).
  • Step-by-step failure sequence:
    1. by_address_in calls host.map_buffer_tiles(&reserved, card_offset, len) (shadow.rs:7166), which creates an ID3D12Heap, issues UpdateTileMappings binding [card_offset, card_offset + len) of the shared ArenaPool.buffer reserved resource to that heap, and returns heap.
    2. Immediately afterward (shadow.rs:7168), by_address_in calls host.shared_buffer_staging(len). If staging allocation fails (e.g., under commit pressure), by_address_in returns None, dropping heap immediately without unmapping those tiles from reserved!
    3. Similarly, inside map_buffer_tiles (reserved.rs:146-158), if queue.Signal, SetEventOnCompletion, or WaitForSingleObject fails after UpdateTileMappings has been queued, map_buffer_tiles returns None and drops heap while UpdateTileMappings is still in flight on the GPU.
    4. Any subsequent GPU access to that offset of reserved (or executing the queued UpdateTileMappings) dereferences a destroyed ID3D12Heap -> GPU page fault / 0x887A0006.
  • Minimal fix: Allocate shared_buffer_staging(len) before calling map_buffer_tiles, and on any error after UpdateTileMappings in map_buffer_tiles, unmap the tile range (D3D12_TILE_RANGE_FLAG_NULL) and retire heap via crate::host::retire(heap) rather than dropping it synchronously.

14. [P0] PR #342 (84ac527d, #339) — Memory::bring_up Skips Refreshing Static / Submit-Time-Allocated Chunks (Stale/Zero BVH Data)

  • Location: crates/victory-gpu/src/memory.rs:1467-1485 (Memory::bring_up, DIRTY_WINDOW, free_pages).
  • Step-by-step failure sequence:
    1. bring_up(list, has_land) runs at recording time and registers shadow.refresh() on chunk c only when (has_land && chunk.free_pages > 0) || self.frame <= chunk.dirty_frame + DIRTY_WINDOW (DIRTY_WINDOW = 8).
    2. Failure A (submit-time land() mismatch): m.land(at) runs later at submit time via list.defer_host(...). If a full static chunk (free_pages == 0, dirty_frame < frame - 8) frees pages before submit time, if land() overwrites existing pages of a replaced packed structure inside a full chunk, or if land() calls another_pooled() allocating a brand-new chunk at submit time, bring_up already skipped that chunk at recording time -> shadow.refresh() is never scheduled and the GPU reads stale/zero BVH bytes.
    3. Failure B (arbitrary frame-age cutoff): Even without land(), if a chunk is dirtied at frame F and no RT dispatch records until frame F + 9 (e.g., menu/loading/pause or cutscenes without RT dispatches), self.frame <= chunk.dirty_frame + 8 evaluates to false and the dirty upload is permanently skipped.
  • Minimal fix: Replace the heuristic DIRTY_WINDOW / free_pages > 0 filter with a per-chunk (dirty_epoch: u64, refreshed_epoch: u64) pair (refresh whenever dirty_epoch != refreshed_epoch, advancing refreshed_epoch only when a refresh actually runs), and ensure submit-time m.land(at) explicitly triggers shadow.refresh() on every chunk it touches or allocates.

15. [P1] PR #302 (e3065e2a) — Relocated Partially-Mapped / Non-level0 Textures Never Update Host SRVs, Stranding Draining Blocks & Duplicating VRAM

  • Location: crates/victory-gpu/src/resource.rs:2934-3004 (drain_moves), crates/victory-gpu/src/descriptor/host.rs:3208-3227 (texture_slots_regrow), crates/victory-gpu/src/texture.rs:1128, 1231, 2359 (staging.first == staging.level0), and crates/victory-gpu/src/draw.rs:3865-3880.
  • Step-by-step failure sequence:
    1. drain_moves() (resource.rs:2996-3002) sets r.host.grown = true, removes r.host.made (moving old into REPLACED), and relies on texture.rs:1128, 1231, 2359 calling levels_changed_after(start) -> texture_views_remade() to switch existing HostHeap SRV slots from old to the newly allocated copy in a non-draining block.
    2. All three texture.rs sites gate levels_changed_after on if staging.first == staging.level0 && copy.grown.swap(false, Relaxed). Whenever a relocated texture is partially streamed (read_from(&layout, first) > copy.base, i.e., staging.first > staging.level0) or its view starts below level0, the condition is false: levels_changed_after is never called.
    3. HostHeap::mirror (descriptor/host.rs:4702-4708, 4726) sees shown == key and returns without rewriting the descriptor. As a result, HostHeap::kept[slot] keeps holding old indefinitely in the draining block while r.host.made holds a brand-new duplicate texture in a non-draining block — doubling VRAM for those textures and preventing the draining block from emptying until DRAIN_GIVE_UP_MS (30 s) expires.
    4. Additionally, when !room and existing_only (draw.rs:3874) rejects a relocated texture because no non-draining hole fits it, r.host.made was already cleared eagerly in drain_moves(), so any concurrent non-bindless caller (host_resource outside existing_only) allocates a fresh 64 MiB block via Grow::Yes/Grow::Must while VRAM is already over budget.
  • Minimal fix: Introduce a separate relocated: AtomicBool on HostTexture (or remove the staging.first == staging.level0 gate for relocations) so levels_changed_after(start) fires unconditionally once the relocated copy uploads any level; and skip drain_moves for textures with host.base < first_mapped_mip or verify/reserve the destination block via existing_only before taking r.host.made.

16. [P1] PR #341 (cdf16541, #339) — memory_smem Hardcodes NonUniformIndex = false for SLOT_MEMORY Heap Handles

  • Location: crates/victory-shader/src/emit/lower.rs:4453 (memory_smem -> memory_view_with(slot, start, lo, false)).
  • Step-by-step failure sequence:
    1. memory_smem lowers s_load_dword* from title memory (resource::MEMORY) and now calls self.memory_view_with(slot, start, lo, /*nonuniform=*/false) unconditionally.
    2. In victory-shader, SGPRs become per-lane SSA values in DXIL whenever an s_load_dword* address is produced by a flattened waterfall v_readfirstlane_b32 (lower.rs:10032) or by an SGPR PHI / s_cselect inside a per-lane lowered branch or loop where lanes diverge on iteration count.
    3. When two active lanes of a host wave hold title addresses in different 64 MiB SLOT_MEMORY arenas, slot is dynamically non-uniform; passing NonUniformIndex = false to dx.op.createHandleFromHeap causes D3D12/GPU hardware to broadcast lane 0's arena buffer descriptor across the wave, silently reading corrupt bytes from the wrong arena.
  • Minimal fix: Keep nonuniform = true in memory_smem unless the defining block is proven wave-uniform (all_lane_blocks_native) and (lo, hi) is not derived from waterfall.reads or a divergent SGPR PHI.

17. [P1] PR #343 (de84a1e1, #339) — has_pending_sizes Permanent Per-Frame Full Drain, SIZES_QUEUED/THIN_DONE Load-Order Race, & Quiet::wake Early Return

  • Location: crates/victory-gpu/src/queue.rs:958-964, crates/victory-gpu/src/queue/behind.rs:548-550, 784-789 (has_pending_sizes), crates/victory-gpu/src/memory.rs:1266, 1314, 1468 (SIZES_SEEN), and crates/victory-gpu/src/quiet.rs:90-103 (Quiet::wake).
  • Step-by-step failure sequences:
    1. Permanent per-frame full behind::drain(): SIZES_SEEN is a permanent one-way latch. Once any BVH compacted-size query occurs, has_pending_sizes() (behind.rs:784-789) returns true whenever THIN_DONE < THIN_QUEUED — which is true at almost every present() when async thin recordings (Job::Lists) are in flight. queue.rs:961-963 therefore calls behind::drain() on virtually every frame, stalling the title thread until all async translation/submission finishes and nullifying behind::on() / #330 (VICTORY_PRESENT_RELEASE).
    2. Atomic load-order race (missed size query): In Job::Lists (behind.rs:548-549), the worker writes SIZES_QUEUED before THIN_DONE. In has_pending_sizes() (behind.rs:785-787), present() reads SIZES_QUEUED before THIN_DONE. Interleaving: (a) present() reads SIZES_DONE == 0, SIZES_QUEUED == 0 -> false; (b) worker executes note_queued_sizes (SIZES_QUEUED = 1) and THIN_DONE = 1; (c) present() reads THIN_DONE == 1, THIN_QUEUED == 1 -> false. has_pending_sizes() returns false while a SIZES job is still pending in LANE, skipping both behind::drain() and settle_sizes_for_present().
    3. Quiet::wake near-threshold bypass (quiet.rs:90-91): When self.ready is false (e.g., state.streak == QUIET_AFTER - 1), wake() returns immediately without resetting state.streak = 0, allowing the very next unchanged compare to mute the size-query buffer right before a BVH size write lands.
  • Minimal fix: (1) Detect has_sizes during thin recording (e.g., a flag on Recording set when a SIZES dispatch is recorded) so only thin batches containing a size query increment SIZES_QUEUED (dropping SIZES_SEEN and THIN_QUEUED/THIN_DONE entirely, which fixes both the per-frame drain and the two-counter load-order race simultaneously); (2) in Quiet::wake, always lock self.state and reset state.streak = 0; state.audit = 0; state.range = None; self.ready.store(false, Release).

Verified Clean Open PRs (No Confirmed P0–P2 Soundness/Logic Bugs)

  • PR #329 (527b51a9, title_free.rs), PR #330 (097d2c45, wait_presents_ahead — step() notifies moved.notify_all() after every item), PR #332 (c062035e, VICTORY_FFX_RENDER_ALIGN — write_if_changed handles patched bytes cleanly), and PR #333 (34a8ac8a, diagnostics-only VICTORY_FRAMEGEN_OFF AB switch).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7349410307 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7349410307). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-02T14:56:38Z. --- ## Follow-Up Deep Static Logic Audit (`main` @ `baf967fc` + Open PRs `#302`, `#329`–`#333`, `#341`–`#343`) Fresh strictly read-only logic audit skipping items already covered above in `#282` or fixed in `#335`/`#336`/`#337`. High-confidence confirmed bugs only. --- ### Area 1 — New GPU & Memory Hot Paths (`main` @ `baf967fc`: `#322`, `#324`, `#327`, `#328`) #### 1. [P0] `slot_evict` Deadlocked Between 85% and ~98.3% VRAM on 12–24 GB GPUs (Primary Cause of Long-Session VRAM + Shared Spill Creep) - **Location:** `crates/victory-gpu/src/resource.rs:2378-2380` (`line_for`), `resource.rs:2764-2767, 2912` (`let_go_idle`), `resource.rs:3073-3126` (`slot_evict`), `crates/victory-gpu/src/host.rs:181-197` (`vram_keep_below`), compounded by `crates/victory-gpu/src/host.rs:690-703` (`ram_idle_ms`). - **Step-by-step failure sequence:** 1. On a 16 GB GPU (`budget ≈ 15.1 GiB`), `line_for(budget)` returns `room_line = 95%` (`~14.3 GiB`). 2. `let_go_idle()` passes `weighed(budget, used)` (raw `used` minus fragmented `pool::texture_room() + tiles::free_room()`, often 500 MiB–1.5 GiB of un-evictable slack) into `vram_keep_below(budget, weighed, line)`. 3. While `weighed < 93%` (`~14.0 GiB`, which corresponds to raw `used` anywhere from `85%` up to `~98.3%`!), `vram_keep_below` returns `KEPT_MS = 600_000` (10 minutes). 4. `let_go_idle()` forwards `idle_ms = 600_000` into `slot_evict(memory, idle_ms, IDLE_FRAMES)` (`resource.rs:2912`). 5. `slot_evict` activates at 85% raw `used`, but `RING` only retains 120 seconds of frame timestamps (`resource.rs:3084-3091`). `frame_at(&ring, now_ms - 600_000)` returns `None`, so between 85% and 95% raw `used`, `slot_evict` returns early at `resource.rs:3097-3104` performing **zero evictions**. 6. Past 95% raw `used`, `slot_evict` falls back to `frame - 4` for the table-frame cutoff, **but `resource.rs:3122` still filters every candidate with `!crate::host::long_ago(stamp, idle_ms, frames)` using `idle_ms = 600_000`**, rejecting every texture touched in the last 10 minutes. 7. Meanwhile, on >32 GB RAM hosts `ram_idle_ms` holds host staging/shadow caches for 5 minutes until `residency::pressured()` trips at `avail_phys <= 3 GiB || avail_commit <= 4 GiB`, allowing WDDM to spill VRAM heaps into shared memory and private commit (~15.3 GB VRAM + 8+ GB shared + 33 GB commit over ~36k frames). - **Minimal fix:** Compute `slot_evict`'s effective `idle_ms` directly from raw `used / budget` and clamp it to `<= 60_000 ms` (well inside `RING`'s 120 s history), e.g., `60_000 ms` at `85%` scaling down to `5_000 ms` at `>= 93%`, completely decoupled from `vram_keep_below`'s `KEPT_MS = 600_000`. #### 2. [P0] `CardBumpPool` (`#322`) Bump-Only 4 MiB VRAM Heap Pinning (Up to 64× Fragmentation Leak) - **Location:** `crates/victory-gpu/src/ahead.rs:270, 434-533` (`CARD_HEAP_KEY`, `CardBumpPool`, `CARD_POOL`, `alloc_pooled_card`), called from `host.rs:13982` (`uav_buffer_with`), `host/uav_pool.rs:104`, and `ahead.rs:796`. - **Step-by-step failure sequence:** 1. Every device-local `uav_buffer(size <= 1 MiB)` allocates 64 KiB-aligned slots sequentially from 4 MiB `ID3D12Heap`s via `CardBumpPool` (`ahead.rs:434-470`), which has **no free-bitset or slot recycling**. 2. Each placed `ID3D12Resource` attaches an owning COM reference to its entire 4 MiB `ID3D12Heap` via `SetPrivateDataInterface(&CARD_HEAP_KEY, &heap_unk)` (`ahead.rs:527`). 3. Whenever the pool rotates heaps (`install()` drops old entries once `active.len() >= 2` at `ahead.rs:462-466`, also abandoning remaining free slots under concurrent creation races), any **single** surviving 64 KiB allocation from that heap (a persistent `Shadow`, a cached `UAV_SPARE` entry, or a LIFO-bottom `ahead::CARD` entry) permanently pins the entire **4 MiB** default heap in VRAM while the other 63 slots can never be reused. - **Minimal fix:** Replace `CardBumpPool` with a free-list / bitset + fence-gated slot retirement pool (mirroring `SharedPool`), and re-check `take(slots)` after re-acquiring `CARD_POOL` before allocating a fresh 4 MiB heap. #### 3. [P1] `watch::ask_rest` (`#324`) Stale `j.ahead` Clone & Unheld-Range Timestamp Advance Race (Silent Missed Write-Watch Refreshes) - **Location:** `crates/victory-gpu/src/watch.rs:974-1019` (`record_rest_pages`, `ask_rest`), interacting with `ask_ahead` (`watch.rs:605-659`), `ask_once_extend` (`watch.rs:949-958`), and `ask_once_end` (`watch.rs:1034-1041`). - **Step-by-step failure sequence:** 1. `ask_rest` clones `journal().ahead` at `watch.rs:1007` **before** acquiring `Askings::hold(to_hold)` (`watch.rs:1017`), and `to_hold` excludes all ranges in `ahead`. 2. **Race A (missed writes):** Because pages `P ∈ ahead` are not held by `Askings::hold(to_hold)`, another thread can call `GetWriteWatch(WRITE_WATCH_FLAG_RESET)` on `P` at `T2`, after which the title writes `P` at `T3`. Then `record_rest_pages` (`watch.rs:991-998`) advances `j.ahead_asked = next_asking()` (`T4 > T3`) across the entire merged `j.ahead` without re-querying `P`. Subsequent refreshes see `j.ahead_asked >= T3` and permanently miss the write at `T3`. 3. **Race B (resurrected cleared journal):** If `ask_once_end()` clears `j.ahead` and sets `j.kept = false` between `watch.rs:1007` and `watch.rs:986`, `record_rest_pages` (`watch.rs:996-998`) overwrites `j.ahead` with the stale pre-clear clone and sets `j.kept = true`. - **Minimal fix:** Add a monotonic `ask_once` epoch in `Journal` (aborting `record_rest_pages` if the epoch changed since `ask_rest` began), re-read `j.ahead` under `journal_mut()`, and track per-interval `(first, last, asked_at)` timestamps instead of advancing one global `j.ahead_asked` over unqueried ranges. #### 4. [P1] `shadow::unregister` Drops `Arc<Shadow>` Synchronously Without `host::retire` (In-Flight `HASH_POOL` Reuse -> `0x887A0006`) - **Location:** `crates/victory-gpu/src/shadow.rs:6630-6636` (`unregister`), `shadow.rs:3803-3841` (`Drop for Shadow`), `shadow.rs:566-572` (`hash_give`). - **Step-by-step failure sequence:** 1. Unlike `let_go_idle` (`shadow.rs:4253`) and `in_place_let_go` (`shadow.rs:6678`), `unregister()` removes `entry` from `BUFFERS` and lets `entry.shadow` drop synchronously on the calling thread without passing it to `crate::host::retire(shadow)`. 2. `HostHeap::kept` retains only `shadow.buffer`, not `Arc<Shadow>`. If a title releases a buffer whose `card.before` hash buffer or `shadow.buffer` is still referenced by an in-flight submission or bindless descriptor slot, `Shadow::drop` runs immediately and calls `hash_give(class, before.buffer, before.gpu)` (`shadow.rs:3836`) with **zero GPU fence wait**. 3. The next buffer allocation pops `before.buffer` from `HASH_POOL` and overwrites its GPUVA while the earlier command list is still executing on the GPU -> data corruption or `DXGI_ERROR_DEVICE_HUNG` (`0x887A0006`). - **Minimal fix:** Pass `shadow` to `crate::host::retire(shadow)` inside `shadow::unregister` after `shadow.mark_retired()`. #### 5. [P2] Unbounded `STATES` Map Leak in `host/lazy.rs` (`#327`) & `xmem::shows_slices` Ignores `LAZY` Entries (`#328`) - **Location:** `crates/victory-gpu/src/host/lazy.rs:239, 253-259` (`STATES`) and `crates/victory-hle/src/modules/xmem.rs:949-977, 1798, 1905, 2995-3027` (`shows_slices`, `map_lazy`, `LAZY`). - **Failure sequences:** - `host/lazy.rs`: `STATES` inserts `(shadow.id(), State)` (each containing `Vec<bool>` / `Vec<u32>` per 64 KiB piece) for every `>= 64 MiB` shadow buffer, with no removal hook when a `Shadow` drops. Fix: add `lazy::forget(self.id)` and invoke it in `Drop for Shadow`. - `xmem.rs`: `map_lazy` records a `MEM_RESERVE`-only range in both `LAZY` and `physical.views`, while `shows_slices` checks only `physical.views`. A subsequent non-lazy `XMemMapPhysicalPages` / `alias_as` covering the same slices returns early thinking the host view is already materialized, leaving pages unmapped (`MEM_RESERVE`). Fix: have `shows_slices` return `false` if any entry in `LAZY` overlaps `[base, base + len)`. --- ### Area 2 — AMD RDNA 4 (`RX 9060 XT`, `WaveLaneCountMin=32, Max=64`) Shader Wave & Culling Logic (`crates/victory-shader/` @ `baf967fc`) #### 6. [P0] Wave64 Compute Shaders Omitting `[WaveSize(64)]` Silently Execute as Wave32 on RDNA 4 (`v_readfirstlane_b32` & Multi-Wave LDS Race — Explains Whole-Foliage Blinking & Split-Tile Artifacts) - **Location:** `crates/victory-shader/src/emit/lower.rs:1863-1900, 1986-2003` (`console_lanes`, `one_wave`, `s.wave_size`). - **Step-by-step failure sequence:** 1. On AMD RDNA 4 (`host_max_wave() == 64`, `WaveLaneCountMin = 32, Max = 64`), omitting DXIL `[WaveSize(64)]` (`s.wave_size == None`) causes the AMD driver to default compute shaders to **Wave32**. Because `host_max_wave() != 32`, `lower.rs:1887` never activates `split_lds` or `halves`/`pairs`. 2. Two omissions leave `s.wave_size = None` on console Wave64 compute shaders: - **`v_readfirstlane_b32` missing from `console_lanes` (`lower.rs:1869`):** Only `v_readlane_b32 | v_writelane_b32` are matched. Any Wave64 compute shader using `v_readfirstlane_b32` without another listed cross-lane op compiles without `[WaveSize(64)]`, executes as Wave32, and broadcasts lane 32's value to lanes 32..63 instead of lane 0's (corrupting base indices/cull flags for the upper half of every 64-thread console wave). - **Multi-wave LDS compute shaders (`group > 64 && s.lds_dwords > 0`, `lower.rs:1878, 2001`):** `one_wave = group <= wave`, so any Wave64 compute shader with `group > 64` (e.g., 128 or 256 threads) that relies on implicit intra-wave 64-lane lockstep LDS sharing without `s_barrier` (and without another listed cross-lane op) gets `s.wave_size = None`! On RDNA 4, each 64-lane console wave splits into two asynchronously scheduled Wave32 wavefronts racing on intra-wave LDS writes/reads — producing non-deterministic intermittent whole-group culling drops (e.g., whole-foliage clusters blinking in/out frame-to-frame) and tile corruption. - **Minimal fix:** Include non-waterfall `v_readfirstlane_b32` in `console_lanes` (`lower.rs:1869`), and replace `one_wave && s.lds_dwords > 0` at `lower.rs:1887` and `lower.rs:2001` with `s.lds_dwords > 0 && (group > 32 || !x.native.wave64)` (so any Wave64 compute shader using LDS emits `[WaveSize(64)]` on RDNA 4 and enters the `split_lds` check on Wave32-only hosts). #### 7. [P0] `scc_some` Skips `within_exec` and `all_lane_blocks_native` Checks on Native Wave64 Hosts (AMD RDNA 4) - **Location:** `crates/victory-shader/src/emit/lower.rs:5166-5188, 7249-7280` (`scc_some`, `scc_in`) + `crates/victory-shader/src/structure.rs:917-922, 1287-1289`. - **Step-by-step failure sequence:** 1. `structure.rs:917-922, 1287-1289` exports the SCC of **every** non-`scc_every` mask SOP into `st.scc_some`, including `s_not_b64`, `s_or_b64`, `s_xor_b64`, and `s_andn2_b64`, whose result mask holds bits in **inactive lanes** (`!st.active`). 2. When an instruction reads SCC (`s_cselect_b32/b64`, `src_scc`, etc.), `scc_in` (`lower.rs:7249-7252`) delegates straight to `scc_some(v)`, bypassing `within_exec(v)` (`lower.rs:7261`). 3. Inside `scc_some` (`lower.rs:5180-5188`), `waveAnyTrue(bit)` is emitted over currently active host lanes. On NVIDIA (`self.exchange.is_some()`), lines `5185-5188` catch divergent defining blocks and return `Err(DIVERGENT_MASK_EXCHANGE)` so `widen()` widens the enclosing branch. 4. On **AMD RDNA 4 (`self.exchange.is_none()`)**, line `5182-5184` returns `Ok(some)` **immediately** without checking `self.within_exec(scc)` or `all_lane_blocks_native(self.x.st)`! 5. Consequently, any SCC derived from inactive-lane mask bits inside a per-lane branch polls only active lanes on RDNA 4 and silently evaluates to `false` when set bits reside in masked-out lanes — inverting culling/tile-visibility `s_cselect` decisions specifically on native Wave64 hosts. - **Minimal fix:** Mirror `mask_dword` inside `scc_some` (`lower.rs:5172-5184`): before emitting `waveAnyTrue`, if `!self.within_exec(scc)` and `!made.is_none_or(|b| all_lane_blocks_native(self.x.st).is_some_and(|all| all[b]))`, call `need(made.unwrap_or(0))` and return `Err(MASK_ELSEWHERE)` so `widen()` widens the enclosing branch on native Wave64 too. #### 8. [P0] `s_cbranch_vccz` / `s_cbranch_vccnz` Incorrectly Intersects `VCC` with Current `EXEC` (Sharp-Boundary Tile/Culling Drop) - **Location:** `crates/victory-shader/src/structure.rs:1407-1418`. - **Step-by-step failure sequence:** 1. Per GFX10/RDNA ISA, `s_cbranch_vccz` / `s_cbranch_vccnz` tests raw `VCC == 0` / `VCC != 0`, **not** `(VCC & EXEC) == 0` / `!= 0`. 2. `structure.rs:1412` computes `let any = self.b.and(vcc, exec);`, masking out all `VCC` bits belonging to lanes outside current `EXEC`. 3. Whenever a shader builds `VCC` before narrowing `EXEC` (or manipulates `VCC` with `s_or_b64` / `s_andn2_b64` / `s_not_b64` / `s_mov_b64 vcc, ...` while `EXEC` is narrowed — common in screen-space/horizon-frustum tile culling and water-tile loops), all inactive lanes' `VCC` bits are silently discarded. Both per-lane and `wave_wide` (`waveAnyTrue`/`waveAllTrue`) branches then take the wrong target once active lanes cross a sharp threshold (e.g., screen-horizon / camera-pitch boundary), causing entire rows of tiles to skip/vanish along a sharp horizontal line. - **Minimal fix:** Remove `self.b.and(vcc, exec)` at `structure.rs:1412` and test raw `vcc` directly (requiring widening via `need()` if `vcc` is not `active` at a divergent block). #### 9. [P1] `ticket` LDS Counter Overflows D3D12's 32 KiB TGSM Limit Unguarded - **Location:** `crates/victory-shader/src/emit/lower.rs:1384, 1996-2000, 2762` (`HOST_LDS_DWORDS`, `ticket`). - **Step-by-step failure sequence:** 1. On any multi-wave compute shader with `console_lanes && group > wave && ticket_on()` (e.g., Wave64 with `group > 64` on RDNA 4, or Wave32 with `group > 32` on any GPU), `lower.rs:1998-1999` allocates `ticket` by incrementing `s.lds_dwords += 1`. 2. If the console shader already uses the full 32 KiB TGSM (`8192` dwords), `s.lds_dwords` becomes `8193` (`32,772 > 32,768` bytes). 3. The TGSM overflow guard at `lower.rs:2762` checks `if self.pairs.is_some() && self.s.lds_dwords > HOST_LDS_DWORDS`, which is **`false`** when `ticket` (or `halves`/`exchange` without `pairs`) overflowed TGSM. 4. DXIL is emitted with `8193` TGSM dwords -> D3D12 PSO creation fails and dispatches using that shader are silently dropped. - **Minimal fix:** Remove the `self.pairs.is_some() &&` precondition at `lower.rs:2762` (guard `self.s.lds_dwords > HOST_LDS_DWORDS` unconditionally), and skip allocating `ticket` when `s.lds_dwords == HOST_LDS_DWORDS` (falling back to linear `flat / wave` wave base for 1D `group % wave == 0` or returning a clean `Err`). #### 10. [P1] Float Inclusive Wave Prefix Sum Emits Integer `Bin::Add` on `f32` Operands & Hardcodes `unsigned = 1` - **Location:** `crates/victory-shader/src/emit/lower.rs:2466-2479` (`wavePrefixOp.f32`). - **Step-by-step failure sequence:** 1. For `Op::AddF` with `prefix == Some(true)` (inclusive float wave prefix sum), `lower.rs:2467, 2474` hardcodes `unsigned = i8(1)` (`k1`) into `dx.op.wavePrefixOp.f32` (compare `u8::from(!float)` at `lower.rs:2495, 2532`). 2. Immediately below at `lower.rs:2477`, `if inclusive { self.s.m.bin(c, Bin::Add, r, arg) }` emits LLVM integer **`add`** (`Bin::Add`) on two **`f32`** values (`r` and `arg`, type `f32t`) instead of `Bin::FAdd` -> malformed LLVM IR / instant DXIL validator rejection. - **Minimal fix:** Pass `self.s.m.i8(u8::from(!float))` to `wavePrefixOp` and use `if float { Bin::FAdd } else { Bin::Add }` at `lower.rs:2477`. #### 11. [P2] DPP `row_shl`/`row_shr` Out-of-Bounds `laneIndex` UB & `v_permlane` `fi:1` Loop-Latch Check - **Location:** `crates/victory-shader/src/emit/lower.rs:9053-9065, 9098` (DPP `0x101..=0x11F`) and `lower.rs:9889-9896` (`v_permlane16_b32` / `v_permlanex16_b32`). - **Failure sequences:** - `lower.rs:9061, 9098`: For `row_shr:n` at `lane < n`, `lane - n` wraps to `0xFFFF_FFFF..`; for `row_shl:n` at `lane >= wave - n`, `lane + n >= WaveGetLaneCount()`. `src` is passed unclamped to `dx.op.waveReadLaneAt.i32` before the `inside` select (`lower.rs:9104`) — out-of-range `laneIndex` is HLSL/DXIL UB (drivers may trap or return poison). Fix: clamp `let safe = self.s.m.select(c, inside, src, lane);` before `read_lane` (as `v_permlane` already does). - `lower.rs:9891`: `v_permlane16/x16` with `fetch_inactive` (`fi:1`) checks `all_lane_blocks(self.x.st)` (`loops = false`) instead of `all_lane_blocks_native(self.x.st)` (`loops = true`), permitting `fetch_inactive` inside loops where some lanes already exited via a divergent latch. Fix: check `all_lane_blocks_native(self.x.st)`. --- ### Area 3 — Pre-Merge Logic Audit of Open PRs (`#302`, `#329`–`#333`, `#341`–`#343`) #### 12. [P0] PR `#331` (`11322318`) — `ReadMostly::read` Re-Entrant Read Self-Deadlock on Windows `SRWLOCK` - **Location:** `crates/victory-gpu/src/listcpu.rs:156-182` (`ReadMostly::read`, `try_read`, `HELD`). - **Step-by-step failure sequence:** 1. `ReadMostly::read` explicitly supports nested reads on the same thread by storing `(depth, first)` in `HELD` TLS and returning `at = first` when `depth > 0`. 2. On a nested call (`depth > 0`), line `158` (`let held = self.locks[at].0.read()...`) calls `AcquireSRWLockShared` a **second time** on the exact same `std::sync::RwLock` (`SRWLOCK`) already held by the outer guard on the same thread. 3. On Windows, `SRWLOCK` is **non-reentrant** for shared acquisition in the presence of a waiting writer: if any writer calls `ReadMostly::write()` and blocks waiting for `self.locks[at]` between the outer `read()` and inner `read()`, Windows queues the second `AcquireSRWLockShared` behind the exclusive writer while the writer waits for the outer `ReleaseSRWLockShared` -> **instant permanent self-deadlock**. - **Minimal fix:** When `depth > 0`, do not re-acquire `self.locks[at].0.read()` (store `Option<RwLockReadGuard<'a, ()>>` in `ReadGuard`, or forbid nested `read()` with `debug_assert_eq!(depth, 0)` if guards can drop out of LIFO order, since storing `None` on inner guards is only sound if guards drop strictly LIFO or the outer guard moves the underlying `RwLockReadGuard` to TLS). #### 13. [P0] PR `#342` (`84ac527d`, `#339`) — Dangling `ID3D12Heap` Tile Mappings on Error Paths in `by_address_in` / `map_buffer_tiles` (GPU Page Fault / `0x887A0006`) - **Location:** `crates/victory-gpu/src/shadow.rs:7151-7175` (`by_address_in`) and `crates/victory-gpu/src/host/reserved.rs:58-158` (`map_buffer_tiles`). - **Step-by-step failure sequence:** 1. `by_address_in` calls `host.map_buffer_tiles(&reserved, card_offset, len)` (`shadow.rs:7166`), which creates an `ID3D12Heap`, issues `UpdateTileMappings` binding `[card_offset, card_offset + len)` of the shared `ArenaPool.buffer` reserved resource to that heap, and returns `heap`. 2. Immediately afterward (`shadow.rs:7168`), `by_address_in` calls `host.shared_buffer_staging(len)`. If staging allocation fails (e.g., under commit pressure), `by_address_in` returns `None`, **dropping `heap` immediately without unmapping those tiles from `reserved`**! 3. Similarly, inside `map_buffer_tiles` (`reserved.rs:146-158`), if `queue.Signal`, `SetEventOnCompletion`, or `WaitForSingleObject` fails after `UpdateTileMappings` has been queued, `map_buffer_tiles` returns `None` and **drops `heap` while `UpdateTileMappings` is still in flight on the GPU**. 4. Any subsequent GPU access to that offset of `reserved` (or executing the queued `UpdateTileMappings`) dereferences a destroyed `ID3D12Heap` -> GPU page fault / `0x887A0006`. - **Minimal fix:** Allocate `shared_buffer_staging(len)` **before** calling `map_buffer_tiles`, and on any error after `UpdateTileMappings` in `map_buffer_tiles`, unmap the tile range (`D3D12_TILE_RANGE_FLAG_NULL`) and retire `heap` via `crate::host::retire(heap)` rather than dropping it synchronously. #### 14. [P0] PR `#342` (`84ac527d`, `#339`) — `Memory::bring_up` Skips Refreshing Static / Submit-Time-Allocated Chunks (Stale/Zero BVH Data) - **Location:** `crates/victory-gpu/src/memory.rs:1467-1485` (`Memory::bring_up`, `DIRTY_WINDOW`, `free_pages`). - **Step-by-step failure sequence:** 1. `bring_up(list, has_land)` runs at **recording time** and registers `shadow.refresh()` on chunk `c` only when `(has_land && chunk.free_pages > 0) || self.frame <= chunk.dirty_frame + DIRTY_WINDOW` (`DIRTY_WINDOW = 8`). 2. **Failure A (submit-time `land()` mismatch):** `m.land(at)` runs **later at submit time** via `list.defer_host(...)`. If a full static chunk (`free_pages == 0`, `dirty_frame < frame - 8`) frees pages before submit time, if `land()` overwrites existing pages of a replaced packed structure inside a full chunk, or if `land()` calls `another_pooled()` allocating a **brand-new chunk** at submit time, `bring_up` already skipped that chunk at recording time -> `shadow.refresh()` is never scheduled and the GPU reads stale/zero BVH bytes. 3. **Failure B (arbitrary frame-age cutoff):** Even without `land()`, if a chunk is dirtied at frame `F` and no RT dispatch records until frame `F + 9` (e.g., menu/loading/pause or cutscenes without RT dispatches), `self.frame <= chunk.dirty_frame + 8` evaluates to `false` and the dirty upload is permanently skipped. - **Minimal fix:** Replace the heuristic `DIRTY_WINDOW` / `free_pages > 0` filter with a per-chunk `(dirty_epoch: u64, refreshed_epoch: u64)` pair (refresh whenever `dirty_epoch != refreshed_epoch`, advancing `refreshed_epoch` only when a refresh actually runs), and ensure submit-time `m.land(at)` explicitly triggers `shadow.refresh()` on every chunk it touches or allocates. #### 15. [P1] PR `#302` (`e3065e2a`) — Relocated Partially-Mapped / Non-`level0` Textures Never Update Host SRVs, Stranding Draining Blocks & Duplicating VRAM - **Location:** `crates/victory-gpu/src/resource.rs:2934-3004` (`drain_moves`), `crates/victory-gpu/src/descriptor/host.rs:3208-3227` (`texture_slots_regrow`), `crates/victory-gpu/src/texture.rs:1128, 1231, 2359` (`staging.first == staging.level0`), and `crates/victory-gpu/src/draw.rs:3865-3880`. - **Step-by-step failure sequence:** 1. `drain_moves()` (`resource.rs:2996-3002`) sets `r.host.grown = true`, removes `r.host.made` (moving `old` into `REPLACED`), and relies on `texture.rs:1128, 1231, 2359` calling `levels_changed_after(start)` -> `texture_views_remade()` to switch existing `HostHeap` SRV slots from `old` to the newly allocated copy in a non-draining block. 2. All three `texture.rs` sites gate `levels_changed_after` on **`if staging.first == staging.level0 && copy.grown.swap(false, Relaxed)`**. Whenever a relocated texture is partially streamed (`read_from(&layout, first) > copy.base`, i.e., `staging.first > staging.level0`) or its view starts below `level0`, the condition is `false`: `levels_changed_after` is **never called**. 3. `HostHeap::mirror` (`descriptor/host.rs:4702-4708, 4726`) sees `shown == key` and returns without rewriting the descriptor. As a result, `HostHeap::kept[slot]` keeps holding `old` indefinitely in the draining block while `r.host.made` holds a brand-new duplicate texture in a non-draining block — **doubling VRAM** for those textures and preventing the draining block from emptying until `DRAIN_GIVE_UP_MS` (30 s) expires. 4. Additionally, when `!room` and `existing_only` (`draw.rs:3874`) rejects a relocated texture because no non-draining hole fits it, `r.host.made` was already cleared eagerly in `drain_moves()`, so any concurrent non-bindless caller (`host_resource` outside `existing_only`) allocates a fresh 64 MiB block via `Grow::Yes`/`Grow::Must` while VRAM is already over budget. - **Minimal fix:** Introduce a separate `relocated: AtomicBool` on `HostTexture` (or remove the `staging.first == staging.level0` gate for relocations) so `levels_changed_after(start)` fires unconditionally once the relocated copy uploads any level; and skip `drain_moves` for textures with `host.base < first_mapped_mip` or verify/reserve the destination block via `existing_only` before taking `r.host.made`. #### 16. [P1] PR `#341` (`cdf16541`, `#339`) — `memory_smem` Hardcodes `NonUniformIndex = false` for `SLOT_MEMORY` Heap Handles - **Location:** `crates/victory-shader/src/emit/lower.rs:4453` (`memory_smem` -> `memory_view_with(slot, start, lo, false)`). - **Step-by-step failure sequence:** 1. `memory_smem` lowers `s_load_dword*` from title memory (`resource::MEMORY`) and now calls `self.memory_view_with(slot, start, lo, /*nonuniform=*/false)` unconditionally. 2. In `victory-shader`, SGPRs become **per-lane SSA values** in DXIL whenever an `s_load_dword*` address is produced by a flattened waterfall `v_readfirstlane_b32` (`lower.rs:10032`) or by an SGPR PHI / `s_cselect` inside a per-lane lowered branch or loop where lanes diverge on iteration count. 3. When two active lanes of a host wave hold title addresses in different 64 MiB `SLOT_MEMORY` arenas, `slot` is dynamically non-uniform; passing `NonUniformIndex = false` to `dx.op.createHandleFromHeap` causes D3D12/GPU hardware to broadcast lane 0's arena buffer descriptor across the wave, silently reading corrupt bytes from the wrong arena. - **Minimal fix:** Keep `nonuniform = true` in `memory_smem` unless the defining block is proven wave-uniform (`all_lane_blocks_native`) and `(lo, hi)` is not derived from `waterfall.reads` or a divergent SGPR PHI. #### 17. [P1] PR `#343` (`de84a1e1`, `#339`) — `has_pending_sizes` Permanent Per-Frame Full Drain, `SIZES_QUEUED`/`THIN_DONE` Load-Order Race, & `Quiet::wake` Early Return - **Location:** `crates/victory-gpu/src/queue.rs:958-964`, `crates/victory-gpu/src/queue/behind.rs:548-550, 784-789` (`has_pending_sizes`), `crates/victory-gpu/src/memory.rs:1266, 1314, 1468` (`SIZES_SEEN`), and `crates/victory-gpu/src/quiet.rs:90-103` (`Quiet::wake`). - **Step-by-step failure sequences:** 1. **Permanent per-frame full `behind::drain()`:** `SIZES_SEEN` is a permanent one-way latch. Once any BVH compacted-size query occurs, `has_pending_sizes()` (`behind.rs:784-789`) returns `true` whenever `THIN_DONE < THIN_QUEUED` — which is true at almost every `present()` when async thin recordings (`Job::Lists`) are in flight. `queue.rs:961-963` therefore calls `behind::drain()` on virtually **every frame**, stalling the title thread until all async translation/submission finishes and nullifying `behind::on()` / `#330` (`VICTORY_PRESENT_RELEASE`). 2. **Atomic load-order race (missed size query):** In `Job::Lists` (`behind.rs:548-549`), the worker writes `SIZES_QUEUED` **before** `THIN_DONE`. In `has_pending_sizes()` (`behind.rs:785-787`), `present()` reads `SIZES_QUEUED` **before** `THIN_DONE`. Interleaving: (a) `present()` reads `SIZES_DONE == 0`, `SIZES_QUEUED == 0` -> false; (b) worker executes `note_queued_sizes` (`SIZES_QUEUED = 1`) and `THIN_DONE = 1`; (c) `present()` reads `THIN_DONE == 1`, `THIN_QUEUED == 1` -> false. `has_pending_sizes()` returns **`false`** while a `SIZES` job is still pending in `LANE`, skipping both `behind::drain()` and `settle_sizes_for_present()`. 3. **`Quiet::wake` near-threshold bypass (`quiet.rs:90-91`):** When `self.ready` is `false` (e.g., `state.streak == QUIET_AFTER - 1`), `wake()` returns immediately without resetting `state.streak = 0`, allowing the very next unchanged compare to mute the size-query buffer right before a BVH size write lands. - **Minimal fix:** (1) Detect `has_sizes` during thin recording (e.g., a flag on `Recording` set when a `SIZES` dispatch is recorded) so only thin batches containing a size query increment `SIZES_QUEUED` (dropping `SIZES_SEEN` and `THIN_QUEUED`/`THIN_DONE` entirely, which fixes both the per-frame drain and the two-counter load-order race simultaneously); (2) in `Quiet::wake`, always lock `self.state` and reset `state.streak = 0; state.audit = 0; state.range = None; self.ready.store(false, Release)`. #### Verified Clean Open PRs (No Confirmed P0–P2 Soundness/Logic Bugs) - **PR `#329`** (`527b51a9`, `title_free.rs`), **PR `#330`** (`097d2c45`, `wait_presents_ahead` — `step()` notifies `moved.notify_all()` after every item), **PR `#332`** (`c062035e`, `VICTORY_FFX_RENDER_ALIGN` — `write_if_changed` handles patched bytes cleanly), and **PR `#333`** (`34a8ac8a`, diagnostics-only `VICTORY_FRAMEGEN_OFF` AB switch).
Androtim commented 2026-12-02 16:57:04 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-02T16:57:04Z.


Deep Static Logic Audit — Pass #2 (main @ 3efe907)

Read-only logic audit covering:

  1. Native DXR 1.1 RayQuery Phase 2 & 3 PRs (#347, #349, merged #352, #354, #357)
  2. Pre-merge verification of .09 bugfix PRs (#355, #356, #358, #359)
  3. Re-check of #341, #342, #343 against Pass #1 findings #13, #14, #16, #17

(All items already covered in Pass #1 comment 7349410307 are omitted except the requested re-check of #341–#343.)


Merge-Readiness Summary

Status PRs Notes
Verified Clean (Green Light to Merge) #352 (already merged), #358, #359, #341, #342 Zero P0/P1/P2 defects found. Pass #1 findings #13, #14, #16 are cleanly resolved.
Needs Fixes Before Merge #347, #349, #354, #357, #355, #356, #343 Confirmed P0/P1 bugs detailed below (#357 is a strict superset of #347 + #349; #343 is unchanged since Pass #1).

Zero-Impact Check (VICTORY_HW_RT Unset or 0)

  • #347, #349, #352, #357: Verified zero behavioral impact when VICTORY_HW_RT is unset or 0 — all HLE/GPU/descriptor/pipeline/cache branches are gated behind hwrt::requested() (which defaults to false), and no DXR device objects or queues are created. (One tiny hygiene note: hwrt::note_dispatch in #357 at crates/victory-gpu/src/hwrt.rs:2971 should early-return on if !requested() to match note_program, though q.queries.is_empty() already prevents entering it when off.)
  • #354 (standalone merge hazard — see Finding #10): victory-shader itself produces bit-for-bit identical DXIL when VICTORY_HW_RT is unset/0, but #354 alone does not include VICTORY_HW_RT in shader_cache::build() and drops ray_queries on cache deserialize. Merging #354 without #357's shader_cache.rs changes will poison shared disk caches across =1 -> =0 runs and break PSO creation on =1 cache hits.

Target 1A — DXR 1.1 GPU / HLE Runtime (#347, #349, #357)

(Note: #357 (679283a2) is stacked strictly on top of #347 (5e532641) + #349 (c2017ae5). Line numbers below reference #357 unless noted otherwise.)

1. [P0] #347, #349, #357 — Arc::strong_count(existing) == 1 Always True -> In-Place Overwrite of In-Flight TLAS & BLAS Buffers (+ Unbuilt TLAS Published at Recording Time)

  • Location: crates/victory-gpu/src/hwrt.rs:956 (alloc_or_reuse_as), hwrt.rs:1404, 1415 (flush_blas_waves), hwrt.rs:2860 (tlas_gpu_va), hwrt.rs:2878 (tlas_for_descriptor).
  • Failure sequence:
    1. alloc_or_reuse_as and flush_blas_waves guard in-place reuse of an existing Arc<HostAs> with Arc::strong_count(existing) == 1.
    2. However, every single consumer clones entry.buffer: ID3D12Resource, never Arc<HostAs> (list.keep(&entry.buffer), Shown, BlasRefs::held, tlas_gpu_va, tlas_for_descriptor). Thus Arc::strong_count(existing) in as_map is always 1, even while frame N-1's RayQuery dispatches or a second queue (VICTORY_TWO_QUEUES) are actively reading existing.buffer.
    3. Frame N rebuilds the TLAS (or refits/rebuilds a BLAS) in-place into the same ID3D12Resource without cross-queue/frame synchronization -> BVH node corruption and DXGI_ERROR_DEVICE_HUNG (0x887A0006).
    4. Additionally, alloc_or_reuse_as inserts a newly created TLAS into as_map during command-list recording (before submission). Under parallel recording, another worker calling tlas_gpu_va / tlas_for_descriptor immediately sees and binds the unbuilt, uninitialized TLAS GPU VA.
  • Minimal fix:
    • Keep Arc<HostAs> (not just ID3D12Resource) in list.hold(...), Shown, and BlasRefs — or explicitly double/triple-buffer TLAS allocations per frame gated on GPU fence completion (host::submissions().1).
    • Publish newly built TLAS entries into shown at submit time via list.defer_host(...) (matching BLAS publication) and resolve tlas_gpu_va / tlas_for_descriptor from shown rather than recording-time as_map.

2. [P1] #347, #349, #357 — emit_postbuild Leaves Shadow::buffer in COPY_DEST (Missing COPY_DEST -> COMMON Barrier & Shared-Heap Read-Before-Write Hazard)

  • Location: crates/victory-gpu/src/hwrt.rs:2482, 2506 (emit_postbuild; #347 hwrt.rs:2236, 2260).
  • Failure sequence:
    1. Both WriteBufferImmediate (hwrt.rs:2482, despite the comment claiming Shadow::buffer stays in COMMON) and CopyBufferRegion(&sh.buffer, ...) (hwrt.rs:2506) implicitly promote sh.buffer from COMMON to D3D12_RESOURCE_STATE_COPY_DEST.
    2. Neither path transitions sh.buffer back to COMMON afterward, nor barriers against prior reads of the same shared-heap Shadow::buffer earlier in the same command list.
    3. Subsequent shader/copy uses of sh.buffer on the same command list violate D3D12 resource state tracking or read stale postbuild size/compaction metadata.
  • Minimal fix: Emit a COPY_DEST -> COMMON transition on &sh.buffer immediately after both WriteBufferImmediate and CopyBufferRegion (and a prior transition/UAV flush if sh.buffer was previously read/written on the same list).

3. [P1] #347, #349, #357 — execute_op Gates mgr.blas_work Behind if !blas.is_empty(), Permanently Starving Deferred BLAS Backlogs & LRU Rebuilds

  • Location: crates/victory-gpu/src/hwrt.rs:2834-2835 (execute_op; #347 hwrt.rs:2585).
  • Failure sequence:
    1. blas_work is the sole caller of budget.roll(frame), lru.take_wanted(), evict_over_budget(), and waiting.take(budget).
    2. After a streaming burst overflows the per-frame BLAS budget (or after an evicted BLAS is re-referenced by a TLAS and queued in lru.wanted), steady-state TLAS-only frames arrive with blas.is_empty() == true.
    3. Because if !blas.is_empty() skips blas_work, deferred BLASes in queue.waiting and re-requested BLASes in lru.wanted are never built, remaining permanently masked out (missing RT geometry) until an unrelated title BLAS build occurs.
  • Minimal fix: Remove if !blas.is_empty() and call mgr.blas_work(list, &mut bound, blas); unconditionally before the for b in tlas loop (returning early inside blas_work only after checking blas.is_empty() && waiting.is_empty() && wanted.is_empty() and rolling the frame budget).

4. [P1] #347, #349, #357 — execute_copy + copy_waiting Silently Drop Copies From LRU-Evicted Source BLASes

  • Location: crates/victory-gpu/src/hwrt.rs:1680 (copy_waiting), hwrt.rs:2516-2539 (execute_copy; #347 hwrt.rs:1586, 2270-2292), crates/victory-gpu/src/hwrt/budget.rs:158-162 (BlasLru::copied).
  • Failure sequence:
    1. A source BLAS src is evicted by evict_over_budget() (removed from as_map, its rebuild recipe moved to lru.evicted).
    2. The title later executes CopyRaytracingAccelerationStructure(dest, src) (e.g., compaction).
    3. execute_copy looks up map.get(&src) (None), leaves is_blas = false, and returns without calling lru.copied(dest, src, frame) (making BlasLru::copied's evicted branch dead code).
    4. dest receives neither a live HostAs nor a rebuild recipe; once src is freed, all TLAS instances pointing to dest are permanently invisible.
  • Minimal fix: Check lru.evicted in copy_waiting / execute_copy, call lru.copied(dest, src, frame) whenever src is present in lru.recipes or lru.evicted (queuing dest for rebuild if needed), and bump as_map_version.

5. [P1] #357 — HostHeap::mirror Permanently Pins Stale / Empty TLAS SRVs in Shader-Visible Descriptor Heaps

  • Location: crates/victory-gpu/src/descriptor/host.rs:4193, 5793-5809, interacting with HostHeap::mirror (4702-4867) & is_texture_view (1925); also crates/victory-gpu/src/hwrt.rs:997 (TODO(phase3)).
  • Failure sequence:
    1. When a shader accesses a TLAS via a shader-visible SRV descriptor table (non-root-SRV path), HostHeap::mirror translates the console descriptor via hwrt::tlas_for_descriptor(console_va) and caches the resulting descriptor in self.made and self.quick keyed solely by title descriptor [tag, i, generation].
    2. If the SRV is written before the first TLAS build (returning empty_tlas) — or if the TLAS later grows beyond its current allocation (e.g. >4 MiB) and reallocates at a new host GPU VA — the title descriptor bytes do not change.
    3. HostHeap::mirror hits its cache forever and keeps the stale/freed (or empty) TLAS GPU VA pinned in the shader-visible heap -> missing RT hits or GPU page fault (0x887A0006).
    4. Additionally, is_texture_view returns true for View::Shader(0, Some(tlas_desc)), misrouting TLAS descriptor slots into texture handling. (The dedicated root-SRV stage.tlas_srvs path in draw.rs is unaffected.)
  • Minimal fix: Exclude D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE from is_texture_view, defer TLAS mirroring until draw/dispatch (later = !for_draw), and bypass quick/key caching for RTAS SRVs (or include a hwrt::tlas_generation() bumped whenever a TLAS buffer is created/reallocated).

6. [P1] #347, #349, #357 — Unsound unsafe { std::env::set_var(...) } From Parallel Precompile Workers + Shader-Cache Key Mismatch

  • Location: crates/victory-gpu/src/hwrt.rs:57-66 (requested), crates/victory-gpu/src/shader_cache.rs:113-116 (build).
  • Failure sequence:
    1. victory shaders / victory translate --warm invoke shader_cache::build() concurrently across std::thread::scope workers without first running modules::all().
    2. If both VICTORY_HW_RT=1 and VICTORY_BVH_BUILDER=1 are set in the environment (e.g., toggled via the F1 menu), the first worker entering hwrt::requested() executes unsafe { std::env::set_var("VICTORY_BVH_BUILDER", "0") } concurrently with sibling threads calling std::env::var_os(...) -> Rust UB / process env data race.
    3. Furthermore, shader_cache::build() hashes VICTORY_BVH_BUILDER before hwrt::requested() mutates it, producing different cache keys between precompile (=1) and runtime (=0) -> 100% cache miss.
  • Minimal fix: Delete unsafe { std::env::set_var(...) } from hwrt::requested(). Gate VICTORY_BVH_BUILDER consumers on !crate::hwrt::requested() and normalize the VICTORY_BVH_BUILDER cache key entry identically inside shader_cache::build().

7. [P1] #349, #357 — TOCTOU Unhandled Access Violation + Aliasing/Alignment UB Reading Live Title Memory Directly

  • Location: crates/victory-gpu/src/hwrt.rs:2008-2026, 2142 (prepare_triangles), crates/victory-gpu/src/hwrt/decoders.rs:139-276, 315-360.
  • Failure sequence:
    1. Under VICTORY_THIN=1 or deferred/evicted BLAS rebuilds (queue.waiting / lru.wanted), prepare_triangles and decoders.rs run asynchronously after the title thread has moved on.
    2. They probe with title_readable() (VirtualQuery) and then dereference raw title pointers (std::slice::from_raw_parts in prepare_triangles; raw read_unaligned loops in decoders.rs) without SEH protection (host::read_into).
    3. If the title concurrently frees/unmaps that allocation between VirtualQuery and the read, the process crashes with an unhandled STATUS_ACCESS_VIOLATION. Creating &[u16]/&[u32] over live concurrently-mutated and potentially unaligned title addresses in prepare_triangles is also Rust UB.
  • Minimal fix: Copy title index/vertex/transform spans into a scratch Vec<u8> via fault-safe crate::host::read_into / read_there and decode from the owned copy.

8. [P1] #347, #349, #357 — execute_build (TLAS): Missing Pre-Build UAV Barrier on n == 0, dst_inst_buf Leaked in NON_PIXEL_SHADER_RESOURCE on Early Return, & &[u32] UB on GPU-Written stats_rb

  • Location: crates/victory-gpu/src/hwrt.rs:2200-2415 (execute_build).
  • Failure sequence:
    1. When n == 0 or instance_descs_va == 0, the compute remap dispatch and its trailing uav_barrier() are skipped, leaving an in-place TLAS build with no pre-build UAV barrier against earlier BLAS/TLAS work (WAR/WAW hazard).
    2. dst_inst_buf is transitioned to D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE (hwrt.rs:2296) before lease(scratch) and alloc_or_reuse_as(...). If either returns None, Lease::drop returns dst_inst_buf to LeasePool stuck in NON_PIXEL_SHADER_RESOURCE instead of UNORDERED_ACCESS, corrupting the next frame's remap compute UAV write.
    3. Reading pool.stats_rb creates a shared &[u32] via slice::from_raw_parts over persistently mapped readback memory concurrently written by GPU CopyBufferRegion(&pool.stats) (and pool.stats is shared unsynchronized across concurrent lists) -> Rust data-race UB.
  • Minimal fix: Emit the pre-build UAV barrier unconditionally; lease scratch and allocate tlas before transitioning dst_inst_buf; read stats_rb via ptr::read_volatile (or guard per-list / read after fence).

9. [P2] #347, #349, #357 — DXR 1.1 Validation & Corner-Case Defects

  • Locations & issues:
    • prepare_aabbs stride validation (hwrt.rs:1797-1816): D3D12 requires AABBs.StrideInBytes to be a multiple of 8 and >= 24; unaligned/small strides are passed straight to BuildRaytracingAccelerationStructure.
    • prebuild_info index count 1..=2 (hwrt.rs:2573-2635): Clamping IndexCount (1..=2 -> 0) without clearing IndexFormat to DXGI_FORMAT_UNKNOWN fails D3D12 validation (IndexBuffer non-zero / non-UNKNOWN format with IndexCount == 0). Also raw pointer derefs in read_geometries/prebuild_info lack alignment/SEH guards.
    • pipeline/host.rs:639: tlas_srvs root descriptors pass D3D12_ROOT_DESCRIPTOR_FLAG_NONE (D3D12 DXR spec recommends DATA_STATIC or DATA_STATIC_WHILE_SET_AT_EXECUTE / proper volatility annotation, and NONE triggers debug-layer warnings on root SRV RTAS bindings on some drivers; verify DATA_VOLATILE is disallowed for RTAS while NONE defaults to DATA_STATIC_WHILE_SET_AT_EXECUTE only in root sig 1.1 — explicitly set D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC or DATA_STATIC_WHILE_SET_AT_EXECUTE).
    • sanitize.rs:410 (SANITIZE_MOST = 65_535 * 64): Valid meshes with eff_vc > SANITIZE_MOST are dropped wholesale instead of chunked/passed through when indices are clean.

Target 1B — DXR 1.1 Traversal-Loop Lifter (#354) & SM 6.6 Emitter (#352)

  • PR #352 (1cf49ae0, MERGED): Verified Clean — SM 6.6 RayQuery opcodes 178..=212, NoUnwind/ReadOnly attributes, RAYTRACING_TIER_1_1 (1 << 25 -> SFI0 0x10_0000), annotateHandle(16, 0), dx.resources {0, 4}, and PSV0 Binding { kind: 4, dxil_kind: 16 } are all valid and pass dxil.dll.

10. [P0] #354 (Standalone Merge Hazard) — Disk Shader Cache Collides Across VICTORY_HW_RT=0/1 & Drops HostShader::ray_queries on Cache Hit

  • Location: crates/victory-gpu/src/shader_cache.rs:394, 430 (pr354.patch).
  • Failure sequence:
    1. #354 leaves shader_cache::build() without VICTORY_HW_RT and sets ray_queries: Default::default() on cache decode.
    2. Run 1 with VICTORY_HW_RT=1 writes SM 6.6 RayQuery DXIL to disk; Run 2 with VICTORY_HW_RT=0 hits that cache entry and loads RayQuery DXIL with empty tlas_srvs -> CreateComputePipelineState fails (E_INVALIDARG) and breaks VICTORY_HW_RT=0 users.
    3. Run 2 with VICTORY_HW_RT=1 also hits the cache with ray_queries = empty, causing PSO creation failure because the root signature omits the tlas_srvs descriptors referenced by the cached DXIL.
  • Minimal fix: Merge #357's shader_cache.rs key + ray_queries binary serialization before or atomically with #354 (never merge #354 standalone).

11. [P0] #354 — CallbackKind::Blocks Emits Malformed DXIL PHIs in blocks[0] and SSA Dominance Violations / Dropped Branch Arms at cb_commit_blk

  • Location: crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:348-450, crates/victory-shader/src/emit/lower/rayquery/analyze.rs:3149-3195, 4175-4226 (find_callback_accumulator_next).
  • Failure sequence:
    1. Missing PHI predecessor in blocks[0]: When blocks[0] has PHIs (e.g., an inner waterfall loop header), its original predecessor search_blk was skipped (self.tail[search_blk] == None), so emit_rq omits the incoming (cb_body, value) edge when lowering blocks[0]'s PHIs -> dxil.dll validation failure.
    2. Non-dominating SSA values & dropped arms at cb_commit_blk: emit_rq.rs:348-350 redirects *merge_block to cb_commit_blk without materializing *merge_block's PHIs. Meanwhile find_callback_accumulator_next (analyze.rs:4196-4215) walks upward from out_v, pops the first callback def/PHI it encounters, and immediately breaks. For any multi-arm callback branching into *merge_block, self.i32_of(acc.next_val) (emit_rq.rs:428) references a value defined in only one branch arm (which does not dominate cb_commit_blk -> bitcode.rs panic or dxil.dll dominance error) and silently drops updates from the other branch arm(s).
  • Minimal fix: (a) Bind self.tail[search_blk] = Some(cb_body) (or explicitly feed cb_body for external predecessors of blocks[0]) while lowering blocks; (b) materialize *merge_block's PHIs in cb_commit_blk (mapping each callback predecessor's self.tail[pred] to its incoming value) and bind acc.next_val / commit_cond to those materialized PHIs rather than single-arm defs.

12. [P0] #354 — Non-Opaque Callbacks With EXEC-Masked / Branched Commits or hit_tri-Only Shadow Commits Silently Lift as CommitDecision::Never (or Always)

  • Location: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:2553-2607 (find_triangle_hit_info).
  • Failure sequence:
    1. find_triangle_hit_info only recognizes v_cndmask_b32 selecting between v_t and tmax_old to produce CommitDecision::Mask.
    2. Non-opaque callbacks that commit via EXEC-masked control flow (divergent branch skipping the v_mov commit) or shadow/any-hit callbacks that only update a hit flag / hit_tri register without updating tmax fall through to CommitDecision::Never (analyze.rs:2604) — causing all alpha-tested geometry / alpha shadows to vanish completely.
    3. Conversely, an opaque-bypass v_mov path can match CommitDecision::Always (analyze.rs:2602), bypassing the alpha test entirely.
  • Minimal fix: Track the block/EXEC reachability predicate from cb_entry to the actual commit store/PHI update (including hit_tri/state-only commits in shadow queries), and bail out of lifting (fall back to software BVH traversal) whenever the commit predicate cannot be proved exact, instead of defaulting to CommitDecision::Never.

13. [P1] #354 — Loop-Invariant TMax (tmax_phi == None) Misidentified as TMin, Emitting Zero-Length Rays [TMax, TMax]

  • Location: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:2253-2311, 3003-3054.
  • Failure sequence:
    1. Any-hit / shadow queries with RAY_FLAG_ACCEPT_FIRST_HIT_AND_END_SEARCH do not shorten tmax inside the loop, so tmax_phi is None.
    2. At analyze.rs:2254, tmax_phi.is_some() && ... evaluates to false, causing the tmax operand in the intersection comparison to be classified as tmin instead of tmax.
    3. TraceRayInline is emitted with TMin = tmax_val, TMax = tmax_val (zero-length ray -> 100% miss rate) and inverted callback guards.
  • Minimal fix: Match the invariant tmax_val directly against the image_bvh_intersect_ray tmax source SSA value even when tmax_phi.is_none(), before treating the other comparison operand as tmin.

14. [P1] #354 — InstanceInclusionMask Extraction Truncates 0xFF, Multi-Bit, and Dynamic Masks to 0x01

  • Location: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:1722-1730, 1879-1907.
  • Failure sequence:
    1. When the instance block shifts inst_dw0 (v_lshrrev_b32 / s_lshr_b32 by 24..=31), the extractor treats a single-bit check or arbitrary shift+mask pattern by folding to a constant 1 << (shift - 24) or 0x01 without verifying that the following AND/compare tests only a single constant bit.
    2. Multi-bit masks, dynamic SGPR/VGPR masks, or full 0xFF tests are silently truncated to a single-bit mask (e.g. 0x01), dropping all TLAS instances whose inclusion mask uses other bits.
  • Minimal fix: Require proving the exact bitmask (either a constant 8-bit and mask or a dynamic InstanceMask SSA value wired through TraceRayInline's InstanceInclusionMask operand); bail out to software traversal if the pattern is unrecognized.

15. [P1] #354 — is_pure_bvh_internal_scratch Silently Zeroes Live-Out Ray origin/dir Header PHIs

  • Location: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:3990-3995, 4083-4120.
  • Failure sequence:
    1. is_pure_bvh_internal_scratch (analyze.rs:4097-4106) treats any loop-header PHI whose in-loop back-edge def lies inside loop_blocks \ hit_and_cb_blocks (such as ray origin/dir overwritten with object-space ray during TLAS->BLAS descent in inst_blk) as "pure BVH internal scratch", ignoring that its pre-loop incoming value is live-out across the loop (e.g., world-space ray origin/dir used after the query for lighting/reflections).
    2. When such a PHI is live-out at q.exit, the lifter replaces it with constant 0, corrupting post-trace shading math.
  • Minimal fix: Exclude the ray origin/dir/tmin/tmax header PHIs from is_pure_bvh_internal_scratch (any live-out register holding a pre-loop value restored on BLAS pop must resolve to its pre-loop incoming value or bail out, never 0).

16. [P1] #354 — emit_ray_query Omits Outer-Loop Counter PHI Back-Edge When rpo[q.exit] <= rpo[q.latch] (dxil.dll Failure)

  • Location: crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:590-595, crates/victory-shader/src/emit/lower.rs:2864-2876.
  • Failure sequence:
    1. When a lifted ray query sits at the tail of an enclosing outer loop whose exit branches back to an outer header (rpo[q.exit] <= rpo[q.latch]), emit_rq.rs:591 (if self.rpo[q.exit] > self.rpo[q.latch]) skips self.enter_loop(q.latch, q.exit, final_blk).
    2. The outer loop's iteration-counter PHI (and loop-carried PHIs) miss the incoming edge from final_blk -> malformed DXIL PHI rejected by dxil.dll.
  • Minimal fix: Call self.branch_edge / self.enter_loop unconditionally (or handle back-edge counter increment via the same helper Lower uses for normal back-edges when self.rpo[q.exit] <= self.rpo[q.latch]).

17. [P1] #354 — Template B (bvh32) Multi-Exit latch Selection (max_by_key(rpo)) Drops Hits When Highest-RPO Exit Is an Early-Miss Block

  • Location: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:737-767, crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:590.
  • Failure sequence:
    1. Template B picks q.latch as the predecessor of q.exit with max_by_key(|&b| ir.rpo[b]).
    2. When a loop has multiple exits (e.g., normal hit/done exit + an early-miss/null-root trampoline placed later in RPO), emit_rq masquerades final_blk as q.latch (self.tail[q.latch] = Some(final_blk)).
    3. q.exit's PHIs select the incoming value from the early-miss trampoline (typically hit = 0 / sentinel) instead of the hit-bearing exit -> all hits silently dropped.
  • Minimal fix: Require all loop-exit edges into q.exit to agree on live-out hit/accumulator values (or explicitly classify the hit-bearing exit edge vs early-miss edge and reject ambiguous multi-exit layouts).

18. [P1] #354 — trace_tlas_from_shr Drops addr.dynamic2, Ignores Non-Zero Offset in Coalesced s_load_dwordx8/x16, Hardcodes nonuniform = false, & Unconditionally Zeroes Shared load_site

  • Location: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:330, 1209-1268, crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:60-71.
  • Failure sequence:
    1. trace_tlas_from_shr inspects addr.dynamic but ignores addr.dynamic2 (two-term dynamic indexing) and assumes the TLAS VA sits at dword offset 0 inside a coalesced s_load_dwordx8/x16, binding the wrong root/table dword.
    2. nonuniform is hardcoded to false even when the TLAS descriptor index is VGPR-divergent (NonUniformResourceIndex required by DXIL SM 6.6 -> UB / GPU hang on divergent TLAS arrays).
    3. Adding the coalesced s_load_dwordxN load_site to dead_sites zeroes all dwords written by that coalesced load, clobbering adjacent non-TLAS constants packed into the same s_load_dwordx8/x16.
  • Minimal fix: Bail out when addr.dynamic2.is_some() or when the TLAS load is part of a multi-field coalesced s_load whose other dwords have non-BVH uses; propagate lane-divergence to nonuniform = true (annotateHandle with NonUniformResourceIndex).

19. [P1] #354 — dead_sites Ignores Lane Guard, AttrSource::Single Calls Committed*() Unconditionally Under Lane Guard, & Inline Callback Truncates at First Nested s_mov exec

  • Locations: crates/victory-shader/src/emit/lower.rs:6557-6562, crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:752-761, crates/victory-shader/src/emit/lower/rayquery/analyze.rs:3292-3310.
  • Failure sequence:
    1. lower.rs:6557-6562 executes self.write(inst, reg, c, None) (guard = None) for dead_sites, clobbering inactive lanes' values in reg to 0 instead of preserving them under the current EXEC guard.
    2. emit_rq.rs:752-761 (AttrSource::Single) emits CommittedTriangleBarycentrics / CommittedInstanceID / CommittedPrimitiveIndex unconditionally without gating on CommittedStatus() == COMMITTED_TRIANGLE_HIT (and executes even on lanes that never called TraceRayInline when the query was lane-guarded -> DXR 1.1 undefined behavior / TDR).
    3. analyze.rs:3292-3310 terminates CallbackKind::Inline at the first s_mov_b32/b64 exec, ... after the non-opaque branch; any nested if inside the inline callback restores exec early and truncates the callback mid-body.
  • Minimal fix: Pass self.guard() to self.write in lower.rs:6560; gate Committed*() getters on CommittedStatus() == COMMITTED_TRIANGLE_HIT (returning 0/default otherwise); match the exact saved exec SSA value from the callback entry s_and_saveexec (not the first s_mov exec).

20. [P2] #354 — Opacity Polarity / FORCE_OPAQUE With dyn_ray_flags, & Plan::is_eliminated Hiding CallbackKind::Inline Ops From Lower::new

  • Locations: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:386-393, 615-629, 916-930, 2452-2465, crates/victory-shader/src/emit/lower/rayquery.rs:365-373.
  • Failure sequence:
    1. Non-cmpx opacity flag checks do not validate branch polarity, and FORCE_OPAQUE can be ORed unconditionally even when dyn_ray_flags dynamically requests non-opaque traversal.
    2. Plan::is_eliminated skips CallbackKind::Inline instructions (only exempting CallbackKind::Blocks), causing Lower::new to omit resources/barriers/wave requirements needed only inside an inline non-opaque callback.
  • Minimal fix: Validate non-cmpx branch polarity (bail if ambiguous), omit static FORCE_OPAQUE whenever dyn_ray_flags can clear it, and exempt CallbackKind::Inline (block, start..end) sites in Plan::is_eliminated.

Target 2 — Pre-Merge Verification of .09 Bugfix PRs (#355, #356, #358, #359)

  • #358 (e2282e17) — VERIFIED CLEAN (Green Light to Merge):
    • 32 KiB TGSM ticket guard (s.lds_dwords < HOST_LDS_DWORDS when 1D group is wave-aligned), f32 wavePrefixOp.f32 unsigned flag u8::from(!float) (bitcode.rs:73-74, 912 maps Bin::Add to fadd on TypeDef::Float), DPP lane clamping, and v_permlane all_lane_blocks_native are all sound.
  • #359 (38d58eb9) — VERIFIED CLEAN (Green Light to Merge):
    • watch::ask_rest per-interval (first, last, asked_at) + ahead_epoch + insert_ahead_interval/advance_ahead_range, shadow::unregister unlocking BUFFERS before host::retire, lazy::forget in Drop for Shadow, and xmem::shows_slices -> has_lazy_overlap (verified lock order PHYSICAL -> LAZY across all callers in xmem.rs, zero AB-BA cycles) are all sound.

21. [P1] #355 (b86ec6b6) — card_retire_fence() Under-Counts Unfolded Thin-Mode Job::Lists Batches & Lacks bury_lag, Allowing Concurrent COPY-Queue Zeroing / Heap Drop Over In-Flight Buffers

  • Location: crates/victory-gpu/src/ahead.rs:159-160, 209-212, 270-272, 332-336, 395-401, 582-609 (card_retire_fence, take_fenced, trim_fenced, CardZeroer::zero), interacting with crates/victory-gpu/src/queue/behind.rs:543-554, 904-914 and crates/victory-gpu/src/host.rs:844-856.
  • Failure sequence:
    1. card_retire_fence() (ahead.rs:332-336) returns started + queued, and CARD_POOL immediately recycles slots (and trim_card_pool drops empty heaps) as soon as retire_fence <= finished.
    2. Thin-mode Job::Lists under-count: Under default VICTORY_THIN=1, behind::submit (behind.rs:909) increments QUEUED by 1 for a folded Job::Lists(queue, recordings) batch, which Job::unfold (behind.rs:550-552) later expands into runs > 1 GPU submissions (advancing STARTED by runs). Any CARD_POOL buffer whose COM refcount reaches 0 while that Job::Lists is queued (e.g., uav_pool::give_uavs dropping overflow buffers, transient detile/resource/texture uav_buffers, or VICTORY_BURY_LAG=0) gets stamped retire_fence = started + 1.
    3. As soon as the first unfolded submission finishes (finished >= started + 1), alloc_pooled_card places a new buffer at the same ID3D12Heap offset and executes CardZeroer::zero (CopyBufferRegion on its dedicated COPY queue) — or trim_card_pool drops the ID3D12Heap — while submissions started + 2..started + runs are still executing on DIRECT/COMPUTE -> D3D12 placed-resource aliasing UB / GPU page fault (0x887A0006).
    4. Zero bury_lag / idle-list gap: When started == finished && queued == 0 (idle queue or recorded-but-unsubmitted command lists that reference the buffer by GPU VA, explicitly noted in host.rs:844-850), card_retire_fence() returns started == finished, recycling/zeroing immediately with zero grace window.
  • Minimal fix: Gate CARD_POOL slot retirement and heap trimming on both fence <= finished (with retire_fence = started + queued + crate::host::bury_lag().max(1) — host::bury_lag() is already pub(crate) in #359) and now_ms.saturating_sub(freed_ms) >= REST_MS (matching SharedPool's 500 ms rest window). (Verified: CardZeroer::zero's crate::host::settle() only waits on LATER async MakeResident, not GPU queues, so it does not deadlock.)

22. [P1] #356 (c96f79d5) — lds_wave Forces split_lds + halves/pairs on ALL Multi-Wave Wave64 LDS Compute Shaders on NVIDIA (host_max_wave() == 32), Breaking 32 KiB TGSM Shaders & Un-Widenable Shaders

  • Location: crates/victory-shader/src/emit/lower.rs:1922, 1931, 1973-1974, 2023-2032, 2045 (pr356.patch:34, 43, 52).
  • Failure sequence:
    1. #356 changes one_wave && s.lds_dwords > 0 to let lds_wave = s.lds_dwords > 0 && (one_wave || x.native.wave64); (lower.rs:1922) to keep Wave64 on AMD RDNA 4 (host_max_wave() == 64) for multi-wave Wave64 LDS shaders.
    2. On NVIDIA (host_max_wave() == 32), however, every multi-wave (group > 64) Wave64 LDS compute shader with console_lanes == false (including shaders that use explicit s_barriers and zero unbarriered intra-wave LDS!) now enters lower.rs:1931 (if wave == 64 && host_max_wave() == 32 && (console_lanes || lds_wave)):
      • Failure Mode A (32 KiB TGSM overflow -> shader dropped): When lds_ok == true, lower.rs:1974 sets wave = 32; split_lds = s.lds_dwords > 0 && group > 32; unconditionally (even if lds_no_meeting excluded every LDS access). Then lower.rs:2023-2031 adds halves (+1 dword) + pairs (+9 * (group / 64) = +18..+144 dwords). Any multi-wave Wave64 compute shader using > 8192 - (1 + 9 * (group / 64)) dwords of TGSM (including 32 KiB / 8192-dword shaders; #358 only guarded ticket, not halves/pairs) now exceeds HOST_LDS_DWORDS (8192) at lower.rs:2808 and fails to compile on NVIDIA.
      • Failure Mode B (Illegal [WaveSize(64)] on NVIDIA): If the shader has an indirect exit (all_lane_blocks == None) or un-widenable divergent LDS (lds_ok == false), wave stays 64 and lower.rs:2045 emits s.wave_size = Some(64) ([WaveSize(64)]), which NVIDIA D3D12 rejects at PSO creation.
      • Even shaders that fit pay unnecessary halves + pairs + group-wide split_lds barriers on NVIDIA despite needing none.
  • Minimal fix: Restrict the multi-wave x.native.wave64 expansion of lds_wave to hosts that actually support 64-lane waves (host_max_wave() >= 64), OR on host_max_wave() == 32 only enter split_lds for !one_wave && !console_lanes when the shader actually has unbarriered intra-wave LDS accesses (not in lds_no_meeting), lds_ok == true, and s.lds_dwords + 1 + 9 * (group / 64) <= HOST_LDS_DWORDS (never emitting s.wave_size = Some(64) on a Wave32-only host when !console_lanes). (Note: #356's scc_some widening and raw VCC branch fixes are verified clean.)

Target 3 — Re-Check of #341, #342, #343 (Pass #1 Findings #13, #14, #16, #17)

  • #341 (3bf8fad1) — Finding #16 RESOLVED -> VERIFIED CLEAN (Green Light to Merge):
    • Added uniform_scalars() in crates/victory-shader/src/emit/lower.rs tracking wave-uniform SGPRs/SCC across uniform blocks while explicitly excluding v_readfirstlane, waterfall.reads, waterfall.loads, masks, and divergent Atom::Uniform regions; memory_smem now passes !uniform_addr to memory_view_with.
  • #342 (f204e9cb) — Findings #13 & #14 RESOLVED -> VERIFIED CLEAN (Green Light to Merge):
    • Finding #13 fixed: by_address_in allocates shared_buffer_staging(len) before map_buffer_tiles, and crates/victory-gpu/src/host/reserved.rs adds unmap_and_retire (D3D12_TILE_RANGE_FLAG_NULL + synchronous SetEventOnCompletion wait + host::retire(heap)) on signal/wait error paths.
    • Finding #14 fixed: Replaced the DIRTY_WINDOW / free_pages heuristic with monotonic (dirty_epoch, refreshed_epoch) (refresh_if_dirty advances refreshed_epoch only at submission via defer_host) plus land_and_refresh / SUBMIT_REFRESHES -> batch.add_fresh() (and memory.rs place/take already call watch::wrote).
  • #343 (de84a1e1) — Finding #17 STILL OPEN (Unchanged Since Pass #1):
    • Commit de84a1e1 is identical to Pass #1: permanent per-frame full behind::drain() via SIZES_SEEN + THIN_DONE < THIN_QUEUED, the SIZES_QUEUED / THIN_DONE load-order race in has_pending_sizes(), and Quiet::wake near-threshold early return all remain unresolved.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7352688269 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7352688269). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-02T16:57:04Z. --- ## Deep Static Logic Audit — Pass #2 (`main` @ `3efe907`) Read-only logic audit covering: 1. **Native DXR 1.1 `RayQuery` Phase 2 & 3 PRs** (`#347`, `#349`, merged `#352`, `#354`, `#357`) 2. **Pre-merge verification of `.09` bugfix PRs** (`#355`, `#356`, `#358`, `#359`) 3. **Re-check of `#341`, `#342`, `#343`** against Pass #1 findings `#13`, `#14`, `#16`, `#17` *(All items already covered in Pass #1 comment `7349410307` are omitted except the requested re-check of `#341`–`#343`.)* --- ### Merge-Readiness Summary | Status | PRs | Notes | | --- | --- | --- | | **Verified Clean (Green Light to Merge)** | **`#352`** *(already merged)*, **`#358`**, **`#359`**, **`#341`**, **`#342`** | Zero P0/P1/P2 defects found. Pass #1 findings `#13`, `#14`, `#16` are cleanly resolved. | | **Needs Fixes Before Merge** | **`#347`**, **`#349`**, **`#354`**, **`#357`**, **`#355`**, **`#356`**, **`#343`** | Confirmed P0/P1 bugs detailed below (`#357` is a strict superset of `#347` + `#349`; `#343` is unchanged since Pass #1). | --- ### Zero-Impact Check (`VICTORY_HW_RT` Unset or `0`) - **`#347`, `#349`, `#352`, `#357`:** **Verified zero behavioral impact** when `VICTORY_HW_RT` is unset or `0` — all HLE/GPU/descriptor/pipeline/cache branches are gated behind `hwrt::requested()` (which defaults to `false`), and no DXR device objects or queues are created. *(One tiny hygiene note: `hwrt::note_dispatch` in `#357` at `crates/victory-gpu/src/hwrt.rs:2971` should early-return on `if !requested()` to match `note_program`, though `q.queries.is_empty()` already prevents entering it when off.)* - **`#354` (standalone merge hazard — see Finding #10):** `victory-shader` itself produces bit-for-bit identical DXIL when `VICTORY_HW_RT` is unset/`0`, **but `#354` alone does not include `VICTORY_HW_RT` in `shader_cache::build()` and drops `ray_queries` on cache deserialize**. Merging `#354` without `#357`'s `shader_cache.rs` changes will poison shared disk caches across `=1` -> `=0` runs and break PSO creation on `=1` cache hits. --- ### Target 1A — DXR 1.1 GPU / HLE Runtime (`#347`, `#349`, `#357`) *(Note: `#357` (`679283a2`) is stacked strictly on top of `#347` (`5e532641`) + `#349` (`c2017ae5`). Line numbers below reference `#357` unless noted otherwise.)* #### 1. `[P0]` `#347`, `#349`, `#357` — `Arc::strong_count(existing) == 1` Always True -> In-Place Overwrite of In-Flight TLAS & BLAS Buffers (+ Unbuilt TLAS Published at Recording Time) - **Location:** `crates/victory-gpu/src/hwrt.rs:956` (`alloc_or_reuse_as`), `hwrt.rs:1404, 1415` (`flush_blas_waves`), `hwrt.rs:2860` (`tlas_gpu_va`), `hwrt.rs:2878` (`tlas_for_descriptor`). - **Failure sequence:** 1. `alloc_or_reuse_as` and `flush_blas_waves` guard in-place reuse of an existing `Arc<HostAs>` with `Arc::strong_count(existing) == 1`. 2. However, **every single consumer clones `entry.buffer: ID3D12Resource`, never `Arc<HostAs>`** (`list.keep(&entry.buffer)`, `Shown`, `BlasRefs::held`, `tlas_gpu_va`, `tlas_for_descriptor`). Thus `Arc::strong_count(existing)` in `as_map` is **always `1`**, even while frame `N-1`'s `RayQuery` dispatches or a second queue (`VICTORY_TWO_QUEUES`) are actively reading `existing.buffer`. 3. Frame `N` rebuilds the TLAS (or refits/rebuilds a BLAS) in-place into the same `ID3D12Resource` without cross-queue/frame synchronization -> BVH node corruption and `DXGI_ERROR_DEVICE_HUNG` (`0x887A0006`). 4. Additionally, `alloc_or_reuse_as` inserts a newly created TLAS into `as_map` during command-list **recording** (before submission). Under parallel recording, another worker calling `tlas_gpu_va` / `tlas_for_descriptor` immediately sees and binds the unbuilt, uninitialized TLAS GPU VA. - **Minimal fix:** - Keep `Arc<HostAs>` (not just `ID3D12Resource`) in `list.hold(...)`, `Shown`, and `BlasRefs` — or explicitly double/triple-buffer TLAS allocations per frame gated on GPU fence completion (`host::submissions().1`). - Publish newly built TLAS entries into `shown` at submit time via `list.defer_host(...)` (matching BLAS publication) and resolve `tlas_gpu_va` / `tlas_for_descriptor` from `shown` rather than recording-time `as_map`. #### 2. `[P1]` `#347`, `#349`, `#357` — `emit_postbuild` Leaves `Shadow::buffer` in `COPY_DEST` (Missing `COPY_DEST -> COMMON` Barrier & Shared-Heap Read-Before-Write Hazard) - **Location:** `crates/victory-gpu/src/hwrt.rs:2482, 2506` (`emit_postbuild`; `#347` `hwrt.rs:2236, 2260`). - **Failure sequence:** 1. Both `WriteBufferImmediate` (`hwrt.rs:2482`, despite the comment claiming `Shadow::buffer` stays in `COMMON`) and `CopyBufferRegion(&sh.buffer, ...)` (`hwrt.rs:2506`) implicitly promote `sh.buffer` from `COMMON` to `D3D12_RESOURCE_STATE_COPY_DEST`. 2. Neither path transitions `sh.buffer` back to `COMMON` afterward, nor barriers against prior reads of the same shared-heap `Shadow::buffer` earlier in the same command list. 3. Subsequent shader/copy uses of `sh.buffer` on the same command list violate D3D12 resource state tracking or read stale postbuild size/compaction metadata. - **Minimal fix:** Emit a `COPY_DEST -> COMMON` transition on `&sh.buffer` immediately after both `WriteBufferImmediate` and `CopyBufferRegion` (and a prior transition/UAV flush if `sh.buffer` was previously read/written on the same list). #### 3. `[P1]` `#347`, `#349`, `#357` — `execute_op` Gates `mgr.blas_work` Behind `if !blas.is_empty()`, Permanently Starving Deferred BLAS Backlogs & LRU Rebuilds - **Location:** `crates/victory-gpu/src/hwrt.rs:2834-2835` (`execute_op`; `#347` `hwrt.rs:2585`). - **Failure sequence:** 1. `blas_work` is the sole caller of `budget.roll(frame)`, `lru.take_wanted()`, `evict_over_budget()`, and `waiting.take(budget)`. 2. After a streaming burst overflows the per-frame BLAS budget (or after an evicted BLAS is re-referenced by a TLAS and queued in `lru.wanted`), steady-state TLAS-only frames arrive with `blas.is_empty() == true`. 3. Because `if !blas.is_empty()` skips `blas_work`, deferred BLASes in `queue.waiting` and re-requested BLASes in `lru.wanted` are **never built**, remaining permanently masked out (missing RT geometry) until an unrelated title BLAS build occurs. - **Minimal fix:** Remove `if !blas.is_empty()` and call `mgr.blas_work(list, &mut bound, blas);` unconditionally before the `for b in tlas` loop (returning early inside `blas_work` only after checking `blas.is_empty() && waiting.is_empty() && wanted.is_empty()` and rolling the frame budget). #### 4. `[P1]` `#347`, `#349`, `#357` — `execute_copy` + `copy_waiting` Silently Drop Copies From LRU-Evicted Source BLASes - **Location:** `crates/victory-gpu/src/hwrt.rs:1680` (`copy_waiting`), `hwrt.rs:2516-2539` (`execute_copy`; `#347` `hwrt.rs:1586, 2270-2292`), `crates/victory-gpu/src/hwrt/budget.rs:158-162` (`BlasLru::copied`). - **Failure sequence:** 1. A source BLAS `src` is evicted by `evict_over_budget()` (removed from `as_map`, its rebuild recipe moved to `lru.evicted`). 2. The title later executes `CopyRaytracingAccelerationStructure(dest, src)` (e.g., compaction). 3. `execute_copy` looks up `map.get(&src)` (`None`), leaves `is_blas = false`, and returns without calling `lru.copied(dest, src, frame)` (making `BlasLru::copied`'s `evicted` branch dead code). 4. `dest` receives neither a live `HostAs` nor a rebuild recipe; once `src` is freed, all TLAS instances pointing to `dest` are permanently invisible. - **Minimal fix:** Check `lru.evicted` in `copy_waiting` / `execute_copy`, call `lru.copied(dest, src, frame)` whenever `src` is present in `lru.recipes` or `lru.evicted` (queuing `dest` for rebuild if needed), and bump `as_map_version`. #### 5. `[P1]` `#357` — `HostHeap::mirror` Permanently Pins Stale / Empty TLAS SRVs in Shader-Visible Descriptor Heaps - **Location:** `crates/victory-gpu/src/descriptor/host.rs:4193, 5793-5809`, interacting with `HostHeap::mirror` (`4702-4867`) & `is_texture_view` (`1925`); also `crates/victory-gpu/src/hwrt.rs:997` (`TODO(phase3)`). - **Failure sequence:** 1. When a shader accesses a TLAS via a shader-visible SRV descriptor table (non-root-SRV path), `HostHeap::mirror` translates the console descriptor via `hwrt::tlas_for_descriptor(console_va)` and caches the resulting descriptor in `self.made` and `self.quick` keyed solely by title descriptor `[tag, i, generation]`. 2. If the SRV is written before the first TLAS build (returning `empty_tlas`) — or if the TLAS later grows beyond its current allocation (e.g. >4 MiB) and reallocates at a new host GPU VA — the title descriptor bytes do not change. 3. `HostHeap::mirror` hits its cache forever and keeps the stale/freed (or empty) TLAS GPU VA pinned in the shader-visible heap -> missing RT hits or GPU page fault (`0x887A0006`). 4. Additionally, `is_texture_view` returns `true` for `View::Shader(0, Some(tlas_desc))`, misrouting TLAS descriptor slots into texture handling. *(The dedicated root-SRV `stage.tlas_srvs` path in `draw.rs` is unaffected.)* - **Minimal fix:** Exclude `D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE` from `is_texture_view`, defer TLAS mirroring until draw/dispatch (`later = !for_draw`), and bypass `quick`/key caching for RTAS SRVs (or include a `hwrt::tlas_generation()` bumped whenever a TLAS buffer is created/reallocated). #### 6. `[P1]` `#347`, `#349`, `#357` — Unsound `unsafe { std::env::set_var(...) }` From Parallel Precompile Workers + Shader-Cache Key Mismatch - **Location:** `crates/victory-gpu/src/hwrt.rs:57-66` (`requested`), `crates/victory-gpu/src/shader_cache.rs:113-116` (`build`). - **Failure sequence:** 1. `victory shaders` / `victory translate --warm` invoke `shader_cache::build()` concurrently across `std::thread::scope` workers without first running `modules::all()`. 2. If both `VICTORY_HW_RT=1` and `VICTORY_BVH_BUILDER=1` are set in the environment (e.g., toggled via the F1 menu), the first worker entering `hwrt::requested()` executes `unsafe { std::env::set_var("VICTORY_BVH_BUILDER", "0") }` concurrently with sibling threads calling `std::env::var_os(...)` -> **Rust UB / process env data race**. 3. Furthermore, `shader_cache::build()` hashes `VICTORY_BVH_BUILDER` before `hwrt::requested()` mutates it, producing different cache keys between precompile (`=1`) and runtime (`=0`) -> 100% cache miss. - **Minimal fix:** Delete `unsafe { std::env::set_var(...) }` from `hwrt::requested()`. Gate `VICTORY_BVH_BUILDER` consumers on `!crate::hwrt::requested()` and normalize the `VICTORY_BVH_BUILDER` cache key entry identically inside `shader_cache::build()`. #### 7. `[P1]` `#349`, `#357` — TOCTOU Unhandled Access Violation + Aliasing/Alignment UB Reading Live Title Memory Directly - **Location:** `crates/victory-gpu/src/hwrt.rs:2008-2026, 2142` (`prepare_triangles`), `crates/victory-gpu/src/hwrt/decoders.rs:139-276, 315-360`. - **Failure sequence:** 1. Under `VICTORY_THIN=1` or deferred/evicted BLAS rebuilds (`queue.waiting` / `lru.wanted`), `prepare_triangles` and `decoders.rs` run asynchronously after the title thread has moved on. 2. They probe with `title_readable()` (`VirtualQuery`) and then dereference raw title pointers (`std::slice::from_raw_parts` in `prepare_triangles`; raw `read_unaligned` loops in `decoders.rs`) without SEH protection (`host::read_into`). 3. If the title concurrently frees/unmaps that allocation between `VirtualQuery` and the read, the process crashes with an unhandled `STATUS_ACCESS_VIOLATION`. Creating `&[u16]`/`&[u32]` over live concurrently-mutated and potentially unaligned title addresses in `prepare_triangles` is also Rust UB. - **Minimal fix:** Copy title index/vertex/transform spans into a scratch `Vec<u8>` via fault-safe `crate::host::read_into` / `read_there` and decode from the owned copy. #### 8. `[P1]` `#347`, `#349`, `#357` — `execute_build` (TLAS): Missing Pre-Build UAV Barrier on `n == 0`, `dst_inst_buf` Leaked in `NON_PIXEL_SHADER_RESOURCE` on Early Return, & `&[u32]` UB on GPU-Written `stats_rb` - **Location:** `crates/victory-gpu/src/hwrt.rs:2200-2415` (`execute_build`). - **Failure sequence:** 1. When `n == 0` or `instance_descs_va == 0`, the compute remap dispatch and its trailing `uav_barrier()` are skipped, leaving an in-place TLAS build with no pre-build UAV barrier against earlier BLAS/TLAS work (WAR/WAW hazard). 2. `dst_inst_buf` is transitioned to `D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE` (`hwrt.rs:2296`) *before* `lease(scratch)` and `alloc_or_reuse_as(...)`. If either returns `None`, `Lease::drop` returns `dst_inst_buf` to `LeasePool` stuck in `NON_PIXEL_SHADER_RESOURCE` instead of `UNORDERED_ACCESS`, corrupting the next frame's remap compute UAV write. 3. Reading `pool.stats_rb` creates a shared `&[u32]` via `slice::from_raw_parts` over persistently mapped readback memory concurrently written by GPU `CopyBufferRegion(&pool.stats)` (and `pool.stats` is shared unsynchronized across concurrent lists) -> Rust data-race UB. - **Minimal fix:** Emit the pre-build UAV barrier unconditionally; lease `scratch` and allocate `tlas` *before* transitioning `dst_inst_buf`; read `stats_rb` via `ptr::read_volatile` (or guard per-list / read after fence). #### 9. `[P2]` `#347`, `#349`, `#357` — DXR 1.1 Validation & Corner-Case Defects - **Locations & issues:** - **`prepare_aabbs` stride validation (`hwrt.rs:1797-1816`):** D3D12 requires `AABBs.StrideInBytes` to be a multiple of 8 and `>= 24`; unaligned/small strides are passed straight to `BuildRaytracingAccelerationStructure`. - **`prebuild_info` index count `1..=2` (`hwrt.rs:2573-2635`):** Clamping `IndexCount` (`1..=2 -> 0`) without clearing `IndexFormat` to `DXGI_FORMAT_UNKNOWN` fails D3D12 validation (`IndexBuffer` non-zero / non-UNKNOWN format with `IndexCount == 0`). Also raw pointer derefs in `read_geometries`/`prebuild_info` lack alignment/SEH guards. - **`pipeline/host.rs:639`:** `tlas_srvs` root descriptors pass `D3D12_ROOT_DESCRIPTOR_FLAG_NONE` (D3D12 DXR spec recommends `DATA_STATIC` or `DATA_STATIC_WHILE_SET_AT_EXECUTE` / proper volatility annotation, and `NONE` triggers debug-layer warnings on root SRV RTAS bindings on some drivers; verify `DATA_VOLATILE` is disallowed for RTAS while `NONE` defaults to `DATA_STATIC_WHILE_SET_AT_EXECUTE` only in root sig 1.1 — explicitly set `D3D12_ROOT_DESCRIPTOR_FLAG_DATA_STATIC` or `DATA_STATIC_WHILE_SET_AT_EXECUTE`). - **`sanitize.rs:410` (`SANITIZE_MOST = 65_535 * 64`):** Valid meshes with `eff_vc > SANITIZE_MOST` are dropped wholesale instead of chunked/passed through when indices are clean. --- ### Target 1B — DXR 1.1 Traversal-Loop Lifter (`#354`) & SM 6.6 Emitter (`#352`) - **PR `#352` (`1cf49ae0`, MERGED):** **Verified Clean** — SM 6.6 `RayQuery` opcodes `178..=212`, `NoUnwind`/`ReadOnly` attributes, `RAYTRACING_TIER_1_1` (`1 << 25` -> `SFI0 0x10_0000`), `annotateHandle(16, 0)`, `dx.resources` `{0, 4}`, and `PSV0` `Binding { kind: 4, dxil_kind: 16 }` are all valid and pass `dxil.dll`. #### 10. `[P0]` `#354` (Standalone Merge Hazard) — Disk Shader Cache Collides Across `VICTORY_HW_RT=0/1` & Drops `HostShader::ray_queries` on Cache Hit - **Location:** `crates/victory-gpu/src/shader_cache.rs:394, 430` (`pr354.patch`). - **Failure sequence:** 1. `#354` leaves `shader_cache::build()` without `VICTORY_HW_RT` and sets `ray_queries: Default::default()` on cache decode. 2. Run 1 with `VICTORY_HW_RT=1` writes SM 6.6 `RayQuery` DXIL to disk; Run 2 with `VICTORY_HW_RT=0` hits that cache entry and loads `RayQuery` DXIL with empty `tlas_srvs` -> `CreateComputePipelineState` fails (`E_INVALIDARG`) and breaks `VICTORY_HW_RT=0` users. 3. Run 2 with `VICTORY_HW_RT=1` also hits the cache with `ray_queries = empty`, causing PSO creation failure because the root signature omits the `tlas_srvs` descriptors referenced by the cached DXIL. - **Minimal fix:** Merge `#357`'s `shader_cache.rs` key + `ray_queries` binary serialization **before or atomically with `#354`** (never merge `#354` standalone). #### 11. `[P0]` `#354` — `CallbackKind::Blocks` Emits Malformed DXIL PHIs in `blocks[0]` and SSA Dominance Violations / Dropped Branch Arms at `cb_commit_blk` - **Location:** `crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:348-450`, `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:3149-3195, 4175-4226` (`find_callback_accumulator_next`). - **Failure sequence:** 1. **Missing PHI predecessor in `blocks[0]`:** When `blocks[0]` has PHIs (e.g., an inner waterfall loop header), its original predecessor `search_blk` was skipped (`self.tail[search_blk] == None`), so `emit_rq` omits the incoming `(cb_body, value)` edge when lowering `blocks[0]`'s PHIs -> `dxil.dll` validation failure. 2. **Non-dominating SSA values & dropped arms at `cb_commit_blk`:** `emit_rq.rs:348-350` redirects `*merge_block` to `cb_commit_blk` without materializing `*merge_block`'s PHIs. Meanwhile `find_callback_accumulator_next` (`analyze.rs:4196-4215`) walks upward from `out_v`, pops the **first** callback def/PHI it encounters, and immediately `break`s. For any multi-arm callback branching into `*merge_block`, `self.i32_of(acc.next_val)` (`emit_rq.rs:428`) references a value defined in only one branch arm (which does **not** dominate `cb_commit_blk` -> `bitcode.rs` panic or `dxil.dll` dominance error) and silently drops updates from the other branch arm(s). - **Minimal fix:** (a) Bind `self.tail[search_blk] = Some(cb_body)` (or explicitly feed `cb_body` for external predecessors of `blocks[0]`) while lowering `blocks`; (b) materialize `*merge_block`'s PHIs in `cb_commit_blk` (mapping each callback predecessor's `self.tail[pred]` to its incoming value) and bind `acc.next_val` / `commit_cond` to those materialized PHIs rather than single-arm defs. #### 12. `[P0]` `#354` — Non-Opaque Callbacks With EXEC-Masked / Branched Commits or `hit_tri`-Only Shadow Commits Silently Lift as `CommitDecision::Never` (or `Always`) - **Location:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:2553-2607` (`find_triangle_hit_info`). - **Failure sequence:** 1. `find_triangle_hit_info` only recognizes `v_cndmask_b32` selecting between `v_t` and `tmax_old` to produce `CommitDecision::Mask`. 2. Non-opaque callbacks that commit via EXEC-masked control flow (divergent branch skipping the `v_mov` commit) or shadow/any-hit callbacks that only update a hit flag / `hit_tri` register without updating `tmax` fall through to `CommitDecision::Never` (`analyze.rs:2604`) — **causing all alpha-tested geometry / alpha shadows to vanish completely**. 3. Conversely, an opaque-bypass `v_mov` path can match `CommitDecision::Always` (`analyze.rs:2602`), bypassing the alpha test entirely. - **Minimal fix:** Track the block/EXEC reachability predicate from `cb_entry` to the actual commit store/PHI update (including `hit_tri`/state-only commits in shadow queries), and **bail out of lifting** (fall back to software BVH traversal) whenever the commit predicate cannot be proved exact, instead of defaulting to `CommitDecision::Never`. #### 13. `[P1]` `#354` — Loop-Invariant `TMax` (`tmax_phi == None`) Misidentified as `TMin`, Emitting Zero-Length Rays `[TMax, TMax]` - **Location:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:2253-2311, 3003-3054`. - **Failure sequence:** 1. Any-hit / shadow queries with `RAY_FLAG_ACCEPT_FIRST_HIT_AND_END_SEARCH` do not shorten `tmax` inside the loop, so `tmax_phi` is `None`. 2. At `analyze.rs:2254`, `tmax_phi.is_some() && ...` evaluates to `false`, causing the `tmax` operand in the intersection comparison to be classified as `tmin` instead of `tmax`. 3. `TraceRayInline` is emitted with `TMin = tmax_val, TMax = tmax_val` (zero-length ray -> 100% miss rate) and inverted callback guards. - **Minimal fix:** Match the invariant `tmax_val` directly against the `image_bvh_intersect_ray` `tmax` source SSA value even when `tmax_phi.is_none()`, before treating the other comparison operand as `tmin`. #### 14. `[P1]` `#354` — `InstanceInclusionMask` Extraction Truncates `0xFF`, Multi-Bit, and Dynamic Masks to `0x01` - **Location:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:1722-1730, 1879-1907`. - **Failure sequence:** 1. When the instance block shifts `inst_dw0` (`v_lshrrev_b32` / `s_lshr_b32` by `24..=31`), the extractor treats a single-bit check or arbitrary shift+mask pattern by folding to a constant `1 << (shift - 24)` or `0x01` without verifying that the following AND/compare tests only a single constant bit. 2. Multi-bit masks, dynamic SGPR/VGPR masks, or full `0xFF` tests are silently truncated to a single-bit mask (e.g. `0x01`), dropping all TLAS instances whose inclusion mask uses other bits. - **Minimal fix:** Require proving the exact bitmask (either a constant 8-bit `and` mask or a dynamic `InstanceMask` SSA value wired through `TraceRayInline`'s `InstanceInclusionMask` operand); bail out to software traversal if the pattern is unrecognized. #### 15. `[P1]` `#354` — `is_pure_bvh_internal_scratch` Silently Zeroes Live-Out Ray `origin`/`dir` Header PHIs - **Location:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:3990-3995, 4083-4120`. - **Failure sequence:** 1. `is_pure_bvh_internal_scratch` (`analyze.rs:4097-4106`) treats any loop-header PHI whose in-loop back-edge def lies inside `loop_blocks \ hit_and_cb_blocks` (such as ray `origin`/`dir` overwritten with object-space ray during TLAS->BLAS descent in `inst_blk`) as "pure BVH internal scratch", ignoring that its pre-loop incoming value is live-out across the loop (e.g., world-space ray origin/dir used after the query for lighting/reflections). 2. When such a PHI is live-out at `q.exit`, the lifter replaces it with constant `0`, corrupting post-trace shading math. - **Minimal fix:** Exclude the ray `origin`/`dir`/`tmin`/`tmax` header PHIs from `is_pure_bvh_internal_scratch` (any live-out register holding a pre-loop value restored on BLAS pop must resolve to its pre-loop incoming value or bail out, never `0`). #### 16. `[P1]` `#354` — `emit_ray_query` Omits Outer-Loop Counter PHI Back-Edge When `rpo[q.exit] <= rpo[q.latch]` (`dxil.dll` Failure) - **Location:** `crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:590-595`, `crates/victory-shader/src/emit/lower.rs:2864-2876`. - **Failure sequence:** 1. When a lifted ray query sits at the tail of an enclosing outer loop whose exit branches back to an outer header (`rpo[q.exit] <= rpo[q.latch]`), `emit_rq.rs:591` (`if self.rpo[q.exit] > self.rpo[q.latch]`) skips `self.enter_loop(q.latch, q.exit, final_blk)`. 2. The outer loop's iteration-counter PHI (and loop-carried PHIs) miss the incoming edge from `final_blk` -> malformed DXIL PHI rejected by `dxil.dll`. - **Minimal fix:** Call `self.branch_edge` / `self.enter_loop` unconditionally (or handle back-edge counter increment via the same helper `Lower` uses for normal back-edges when `self.rpo[q.exit] <= self.rpo[q.latch]`). #### 17. `[P1]` `#354` — Template B (`bvh32`) Multi-Exit `latch` Selection (`max_by_key(rpo)`) Drops Hits When Highest-RPO Exit Is an Early-Miss Block - **Location:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:737-767`, `crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:590`. - **Failure sequence:** 1. Template B picks `q.latch` as the predecessor of `q.exit` with `max_by_key(|&b| ir.rpo[b])`. 2. When a loop has multiple exits (e.g., normal hit/done exit + an early-miss/null-root trampoline placed later in RPO), `emit_rq` masquerades `final_blk` as `q.latch` (`self.tail[q.latch] = Some(final_blk)`). 3. `q.exit`'s PHIs select the incoming value from the early-miss trampoline (typically `hit = 0` / sentinel) instead of the hit-bearing exit -> all hits silently dropped. - **Minimal fix:** Require all loop-exit edges into `q.exit` to agree on live-out hit/accumulator values (or explicitly classify the hit-bearing exit edge vs early-miss edge and reject ambiguous multi-exit layouts). #### 18. `[P1]` `#354` — `trace_tlas_from_shr` Drops `addr.dynamic2`, Ignores Non-Zero Offset in Coalesced `s_load_dwordx8/x16`, Hardcodes `nonuniform = false`, & Unconditionally Zeroes Shared `load_site` - **Location:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:330, 1209-1268`, `crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:60-71`. - **Failure sequence:** 1. `trace_tlas_from_shr` inspects `addr.dynamic` but ignores `addr.dynamic2` (two-term dynamic indexing) and assumes the TLAS VA sits at dword offset `0` inside a coalesced `s_load_dwordx8`/`x16`, binding the wrong root/table dword. 2. `nonuniform` is hardcoded to `false` even when the TLAS descriptor index is VGPR-divergent (`NonUniformResourceIndex` required by DXIL SM 6.6 -> UB / GPU hang on divergent TLAS arrays). 3. Adding the coalesced `s_load_dwordxN` `load_site` to `dead_sites` zeroes **all** dwords written by that coalesced load, clobbering adjacent non-TLAS constants packed into the same `s_load_dwordx8`/`x16`. - **Minimal fix:** Bail out when `addr.dynamic2.is_some()` or when the TLAS load is part of a multi-field coalesced `s_load` whose other dwords have non-BVH uses; propagate lane-divergence to `nonuniform = true` (`annotateHandle` with `NonUniformResourceIndex`). #### 19. `[P1]` `#354` — `dead_sites` Ignores Lane Guard, `AttrSource::Single` Calls `Committed*()` Unconditionally Under Lane Guard, & Inline Callback Truncates at First Nested `s_mov exec` - **Locations:** `crates/victory-shader/src/emit/lower.rs:6557-6562`, `crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:752-761`, `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:3292-3310`. - **Failure sequence:** 1. `lower.rs:6557-6562` executes `self.write(inst, reg, c, None)` (`guard = None`) for `dead_sites`, clobbering inactive lanes' values in `reg` to `0` instead of preserving them under the current EXEC guard. 2. `emit_rq.rs:752-761` (`AttrSource::Single`) emits `CommittedTriangleBarycentrics` / `CommittedInstanceID` / `CommittedPrimitiveIndex` unconditionally without gating on `CommittedStatus() == COMMITTED_TRIANGLE_HIT` (and executes even on lanes that never called `TraceRayInline` when the query was lane-guarded -> DXR 1.1 undefined behavior / TDR). 3. `analyze.rs:3292-3310` terminates `CallbackKind::Inline` at the **first** `s_mov_b32/b64 exec, ...` after the non-opaque branch; any nested `if` inside the inline callback restores `exec` early and truncates the callback mid-body. - **Minimal fix:** Pass `self.guard()` to `self.write` in `lower.rs:6560`; gate `Committed*()` getters on `CommittedStatus() == COMMITTED_TRIANGLE_HIT` (returning `0`/default otherwise); match the exact saved `exec` SSA value from the callback entry `s_and_saveexec` (not the first `s_mov exec`). #### 20. `[P2]` `#354` — Opacity Polarity / `FORCE_OPAQUE` With `dyn_ray_flags`, & `Plan::is_eliminated` Hiding `CallbackKind::Inline` Ops From `Lower::new` - **Locations:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:386-393, 615-629, 916-930, 2452-2465`, `crates/victory-shader/src/emit/lower/rayquery.rs:365-373`. - **Failure sequence:** 1. Non-`cmpx` opacity flag checks do not validate branch polarity, and `FORCE_OPAQUE` can be ORed unconditionally even when `dyn_ray_flags` dynamically requests non-opaque traversal. 2. `Plan::is_eliminated` skips `CallbackKind::Inline` instructions (only exempting `CallbackKind::Blocks`), causing `Lower::new` to omit resources/barriers/wave requirements needed only inside an inline non-opaque callback. - **Minimal fix:** Validate non-`cmpx` branch polarity (bail if ambiguous), omit static `FORCE_OPAQUE` whenever `dyn_ray_flags` can clear it, and exempt `CallbackKind::Inline` `(block, start..end)` sites in `Plan::is_eliminated`. --- ### Target 2 — Pre-Merge Verification of `.09` Bugfix PRs (`#355`, `#356`, `#358`, `#359`) - **`#358` (`e2282e17`) — VERIFIED CLEAN (Green Light to Merge):** - 32 KiB TGSM `ticket` guard (`s.lds_dwords < HOST_LDS_DWORDS` when 1D group is wave-aligned), `f32` `wavePrefixOp.f32` unsigned flag `u8::from(!float)` (`bitcode.rs:73-74, 912` maps `Bin::Add` to `fadd` on `TypeDef::Float`), DPP lane clamping, and `v_permlane` `all_lane_blocks_native` are all sound. - **`#359` (`38d58eb9`) — VERIFIED CLEAN (Green Light to Merge):** - `watch::ask_rest` per-interval `(first, last, asked_at)` + `ahead_epoch` + `insert_ahead_interval`/`advance_ahead_range`, `shadow::unregister` unlocking `BUFFERS` before `host::retire`, `lazy::forget` in `Drop for Shadow`, and `xmem::shows_slices` -> `has_lazy_overlap` (verified lock order `PHYSICAL -> LAZY` across all callers in `xmem.rs`, zero AB-BA cycles) are all sound. #### 21. `[P1]` `#355` (`b86ec6b6`) — `card_retire_fence()` Under-Counts Unfolded Thin-Mode `Job::Lists` Batches & Lacks `bury_lag`, Allowing Concurrent COPY-Queue Zeroing / Heap Drop Over In-Flight Buffers - **Location:** `crates/victory-gpu/src/ahead.rs:159-160, 209-212, 270-272, 332-336, 395-401, 582-609` (`card_retire_fence`, `take_fenced`, `trim_fenced`, `CardZeroer::zero`), interacting with `crates/victory-gpu/src/queue/behind.rs:543-554, 904-914` and `crates/victory-gpu/src/host.rs:844-856`. - **Failure sequence:** 1. `card_retire_fence()` (`ahead.rs:332-336`) returns `started + queued`, and `CARD_POOL` immediately recycles slots (and `trim_card_pool` drops empty heaps) as soon as `retire_fence <= finished`. 2. **Thin-mode `Job::Lists` under-count:** Under default `VICTORY_THIN=1`, `behind::submit` (`behind.rs:909`) increments `QUEUED` by **1** for a folded `Job::Lists(queue, recordings)` batch, which `Job::unfold` (`behind.rs:550-552`) later expands into **`runs > 1` GPU submissions** (advancing `STARTED` by `runs`). Any `CARD_POOL` buffer whose COM refcount reaches `0` while that `Job::Lists` is queued (e.g., `uav_pool::give_uavs` dropping overflow buffers, transient `detile`/`resource`/`texture` `uav_buffer`s, or `VICTORY_BURY_LAG=0`) gets stamped `retire_fence = started + 1`. 3. As soon as the first unfolded submission finishes (`finished >= started + 1`), `alloc_pooled_card` places a new buffer at the **same `ID3D12Heap` offset** and executes `CardZeroer::zero` (`CopyBufferRegion` on its dedicated COPY queue) — or `trim_card_pool` drops the `ID3D12Heap` — while submissions `started + 2..started + runs` are **still executing on DIRECT/COMPUTE** -> D3D12 placed-resource aliasing UB / GPU page fault (`0x887A0006`). 4. **Zero `bury_lag` / idle-list gap:** When `started == finished && queued == 0` (idle queue or recorded-but-unsubmitted command lists that reference the buffer by GPU VA, explicitly noted in `host.rs:844-850`), `card_retire_fence()` returns `started == finished`, recycling/zeroing immediately with zero grace window. - **Minimal fix:** Gate `CARD_POOL` slot retirement and heap trimming on **both** `fence <= finished` (with `retire_fence = started + queued + crate::host::bury_lag().max(1)` — `host::bury_lag()` is already `pub(crate)` in `#359`) **and** `now_ms.saturating_sub(freed_ms) >= REST_MS` (matching `SharedPool`'s 500 ms rest window). *(Verified: `CardZeroer::zero`'s `crate::host::settle()` only waits on `LATER` async `MakeResident`, not GPU queues, so it does not deadlock.)* #### 22. `[P1]` `#356` (`c96f79d5`) — `lds_wave` Forces `split_lds` + `halves`/`pairs` on ALL Multi-Wave Wave64 LDS Compute Shaders on NVIDIA (`host_max_wave() == 32`), Breaking 32 KiB TGSM Shaders & Un-Widenable Shaders - **Location:** `crates/victory-shader/src/emit/lower.rs:1922, 1931, 1973-1974, 2023-2032, 2045` (`pr356.patch:34, 43, 52`). - **Failure sequence:** 1. `#356` changes `one_wave && s.lds_dwords > 0` to `let lds_wave = s.lds_dwords > 0 && (one_wave || x.native.wave64);` (`lower.rs:1922`) to keep Wave64 on AMD RDNA 4 (`host_max_wave() == 64`) for multi-wave Wave64 LDS shaders. 2. On **NVIDIA (`host_max_wave() == 32`)**, however, every multi-wave (`group > 64`) Wave64 LDS compute shader with `console_lanes == false` (including shaders that use explicit `s_barrier`s and zero unbarriered intra-wave LDS!) now enters `lower.rs:1931` (`if wave == 64 && host_max_wave() == 32 && (console_lanes || lds_wave)`): - **Failure Mode A (32 KiB TGSM overflow -> shader dropped):** When `lds_ok == true`, `lower.rs:1974` sets `wave = 32; split_lds = s.lds_dwords > 0 && group > 32;` unconditionally (even if `lds_no_meeting` excluded every LDS access). Then `lower.rs:2023-2031` adds `halves` (`+1` dword) + `pairs` (`+9 * (group / 64)` = `+18..+144` dwords). Any multi-wave Wave64 compute shader using `> 8192 - (1 + 9 * (group / 64))` dwords of TGSM (including 32 KiB / `8192`-dword shaders; `#358` only guarded `ticket`, not `halves`/`pairs`) now exceeds `HOST_LDS_DWORDS` (8192) at `lower.rs:2808` and **fails to compile on NVIDIA**. - **Failure Mode B (Illegal `[WaveSize(64)]` on NVIDIA):** If the shader has an indirect exit (`all_lane_blocks == None`) or un-widenable divergent LDS (`lds_ok == false`), `wave` stays `64` and `lower.rs:2045` emits `s.wave_size = Some(64)` (`[WaveSize(64)]`), which NVIDIA D3D12 rejects at PSO creation. - Even shaders that fit pay unnecessary `halves` + `pairs` + group-wide `split_lds` barriers on NVIDIA despite needing none. - **Minimal fix:** Restrict the multi-wave `x.native.wave64` expansion of `lds_wave` to hosts that actually support 64-lane waves (`host_max_wave() >= 64`), OR on `host_max_wave() == 32` only enter `split_lds` for `!one_wave && !console_lanes` when the shader actually has unbarriered intra-wave LDS accesses (not in `lds_no_meeting`), `lds_ok == true`, and `s.lds_dwords + 1 + 9 * (group / 64) <= HOST_LDS_DWORDS` (never emitting `s.wave_size = Some(64)` on a Wave32-only host when `!console_lanes`). *(Note: `#356`'s `scc_some` widening and raw `VCC` branch fixes are verified clean.)* --- ### Target 3 — Re-Check of `#341`, `#342`, `#343` (Pass #1 Findings `#13`, `#14`, `#16`, `#17`) - **`#341` (`3bf8fad1`) — Finding #16 RESOLVED -> VERIFIED CLEAN (Green Light to Merge):** - Added `uniform_scalars()` in `crates/victory-shader/src/emit/lower.rs` tracking wave-uniform SGPRs/SCC across uniform blocks while explicitly excluding `v_readfirstlane`, `waterfall.reads`, `waterfall.loads`, masks, and divergent `Atom::Uniform` regions; `memory_smem` now passes `!uniform_addr` to `memory_view_with`. - **`#342` (`f204e9cb`) — Findings #13 & #14 RESOLVED -> VERIFIED CLEAN (Green Light to Merge):** - **Finding #13 fixed:** `by_address_in` allocates `shared_buffer_staging(len)` *before* `map_buffer_tiles`, and `crates/victory-gpu/src/host/reserved.rs` adds `unmap_and_retire` (`D3D12_TILE_RANGE_FLAG_NULL` + synchronous `SetEventOnCompletion` wait + `host::retire(heap)`) on signal/wait error paths. - **Finding #14 fixed:** Replaced the `DIRTY_WINDOW` / `free_pages` heuristic with monotonic `(dirty_epoch, refreshed_epoch)` (`refresh_if_dirty` advances `refreshed_epoch` only at submission via `defer_host`) plus `land_and_refresh` / `SUBMIT_REFRESHES` -> `batch.add_fresh()` (and `memory.rs` `place`/`take` already call `watch::wrote`). - **`#343` (`de84a1e1`) — Finding #17 STILL OPEN (Unchanged Since Pass #1):** - Commit `de84a1e1` is identical to Pass #1: permanent per-frame full `behind::drain()` via `SIZES_SEEN` + `THIN_DONE < THIN_QUEUED`, the `SIZES_QUEUED` / `THIN_DONE` load-order race in `has_pending_sizes()`, and `Quiet::wake` near-threshold early return all remain unresolved.
Androtim commented 2026-12-02 19:11:04 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-02T19:11:04Z.


Deep Static Logic Audit — Pass #3 (Final Pre-Merge Verification)

Strictly read-only verification of the updated HW-RT stack (#343, #347, #349, #354, #357), .10 release candidates (#356, #360), and newly merged performance PRs (#363, #365).


Merge-Readiness Table

PR Head Verdict Summary
#343 6b9c8435 VERIFIED CLEAN (Green Light) Pass #1 Finding #17 cleanly resolved (per-recording has_sizes, Acquire/Release handoff, unconditional Quiet::wake reset).
#356 b56e2809 VERIFIED CLEAN (Green Light) Pass #2 Finding #22 cleanly resolved (host_max_wave() >= 64 guard); zero NVIDIA Wave32 regressions.
#360 6a8d28d5 NEEDS FIX (1 tiny [P2]) D3D12 barriers, fence capture, swapchain lifetimes, and PNG encoding are clean; 3-line [P2] stale-event fence-wait check in wait_for_fence.
#347 5140ce43 NEEDS FIX (1 [P1]) Pass #2 #1, #3, #4, #6, #8, #9 cleanly resolved. #2 (emit_postbuild / read_shadows) has 4 RESOURCE_BARRIER_BEFORE_AFTER_MISMATCH paths.
#349 769d11c2 NEEDS FIX (1 [P1], 2 [P2]) Pass #2 #7 cleanly resolved. Inherits #347 emit_postbuild [P1], plus unbounded vec![0u8; ...] OOM-abort in decoders.rs ([P2]) and standalone shader_cache.rs vs intersect.rs mismatch ([P2]).
#354 7ae7398d NEEDS FIX (2 [P0], 3 [P1], 4 [P2]) Pass #2 #10, #13, #14, #16, #17 cleanly resolved + standalone cache safety & zero RT-off impact confirmed. Remaining/new bugs in CallbackKind::Blocks Pattern C & PHI resolution, live-out origin/dir zeroing, opacity polarity (st.reach), and Pattern A invalid break.
#357 be6135ac NEEDS FIX (2 [P1], 2 [P2]) Pass #2 #1 (AS reuse/publish), #3, #4, #6, #7, #8, #9 cleanly resolved. Remaining [P1]s: bindless TlasSource::Heap stale/null RTAS SRVs + GPU BLAS UAF via HostHeap::kept + submit-time sync_heaps lag; inherited #347 emit_postbuild [P1].
#363 (merged) 60a88573 VERIFIED CLEAN Offloaded victory-sweep thread, bury_lag=16 / landed_lag=8, pool::REST=500ms — zero P0/P1 concurrency or ordering bugs.
#365 (merged) 6042ed29 VERIFIED CLEAN Coalesced CBV descriptor batches ((index/64)%parts) + fused FillsOnly card_steps — zero P0/P1 concurrency or ordering bugs.

Zero-Impact Verification (VICTORY_HW_RT Unset or 0)

  • #347, #349, #354, #357: CONFIRMED strictly zero behavioral impact when VICTORY_HW_RT is unset or 0 — including standalone #354 disk shader cache safety (shader_cache.rs now keys VICTORY_HW_RT=1/VICTORY_HW_RT_LIFT=0, normalizes VICTORY_BVH_BUILDER, and round-trips HostShader::ray_queries with zero extra bytes written when off).
  • (Minor rebase note: tlas_for_descriptor returns Some(empty_tlas) on miss in #347/#349 vs None in #357; align to None before merging.)

Section 1 — Verified Clean Sign-Offs (#343, #356, #363, #365)

  • #343 (6b9c8435) — Pass #1 Finding #17 RESOLVED:
    • Replaced global SIZES_SEEN / THIN_QUEUED/THIN_DONE with per-pipeline pipeline::maybe_size_query (threads == [1,1,1], SLOT_MEMORY, builder || (stores && stores_by_address)) + Recording::has_sizes + THIN_SIZES_QUEUED/THIN_SIZES_DONE, eliminating per-frame behind::drain() on frames without size queries.
    • Strictly ordered Release/Acquire handoff across Job::unfold (SIZES_QUEUED -> THIN_SIZES_DONE), Job::Run/Job::Joined (PENDING_FLIGHT -> SIZES_DONE), and has_pending_sizes() (THIN_SIZES_DONE -> THIN_SIZES_QUEUED -> SIZES_DONE -> SIZES_QUEUED).
    • Quiet::wake() unconditionally locks self.state and clears streak/audit/range even for near-threshold streaks.
  • #356 (b56e2809) — Pass #2 Finding #22 RESOLVED:
    • let lds_wave = s.lds_dwords > 0 && (one_wave || (x.native.wave64 && host_max_wave() >= 64)); (lower.rs:1930) cleanly restricts multi-wave Wave64 LDS WaveSize(64) to 64-lane hosts (RDNA 4), leaving NVIDIA (host_max_wave() == 32) untouched (wave_size = None, split_lds = false, full 32 KiB HOST_LDS_DWORDS intact, verified by new unit tests).
  • #363 (60a88573, merged) — Sanity Check CLEAN:
    • Every eviction in sweep_once() retires GPU resources via host::retire or drop_aside (after strong_count == 1 && references == 1 && long_ago), and resource::let_go_idle/slot_evict release textures() before descriptor calls (no AB-BA cycle with HostHeap::mirror). pool::REST = 500ms runs strictly after bury_lag drop; landed_lag = 8 only drains already GPU-completed line.landed flights.
  • #365 (6042ed29, merged) — Sanity Check CLEAN:
    • bucket_constant_ops partitions disjoint 64-slot blocks per worker ((index / 64) % parts); HostHeap::constant_slots_batch splits before duplicate slot indices (cbv_chunk_len), guards !self.twins.is_empty() / self.sampler, and uses linear self.cpu_inner(idx, true) with per-thread disjoint 64-slot CPU staging slices. card_steps::scan_and_take falls back immediately to take_steps_full on any Step::Copy/Placed/Run and mirrors blocked_by + copied_read exactly on FillsOnly submissions.

Section 2 — Remaining / New Bugs in #347, #349, #357 (HW-RT GPU/HLE)

(Pass #2 findings #3, #4, #6 (in #347/#357), #7, #8, #9, and #1's AS pool/refit/submit-time publication are all cleanly resolved.)

1. [P1] #357 — Bindless (ResourceDescriptorHeap[]) RTAS SRVs Stay Permanently Null/Stale, Risk GPU BLAS UAF via HostHeap::kept, & Lag Behind Same-Submission TLAS Builds

  • Locations: crates/victory-gpu/src/hwrt.rs:304-316 (HostAs::drop), hwrt.rs:3193-3206 (tlas_for_descriptor); crates/victory-gpu/src/descriptor/host.rs:4752-4943 (HostHeap::mirror), descriptor.rs:493-738 (sync_heaps); crates/victory-gpu/src/host.rs:8144-8290 (Host::submit).
  • Failure sequence:
    1. #354 lowers dynamic TLAS descriptors to TlasSource::Heap (ResourceDescriptorHeap[...]). A title creates a persistent RTAS SRV at shader-visible heap slot S pointing to console_tlas_va once and never rewrites slot S's bytes.
    2. Stuck null: If slot S is mirrored before the first TLAS build submits, tlas_for_descriptor returns None (writing Location: 0). Neither draw.rs (only mirrors root tables) nor sync_heaps() (only scans dirty title-memory heap pages and CONSTANT | PLACED before slots) ever re-calls HostHeap::mirror(S, ...) after TLAS_GENERATION bumps -> slot S remains null forever.
    3. Stale TLAS + GPU BLAS UAF: tlas_for_descriptor returns only ID3D12Resource (T1.buffer) to HostHeap::kept[S], not Arc<HostAs>. On Frame 2+, execute_build publishes T2 (T2.gpu_va != T1.gpu_va) and retires Shown(T1). Slot S is never refreshed (still exposes T1.gpu_va). Once Shown(T1) drops past bury_lag, HostAs::drop runs for T1 and retires T1.refs (Arc<BlasRefs>). While is_sole_com_owner keeps T1.buffer out of as_pool, nothing keeps T1.refs alive — rebuilt/evicted BLASes drop their last Arc<HostAs>, enter as_pool, and are overwritten/freed while ResourceDescriptorHeap[S] still traverses T1.gpu_va into their GPU VAs -> GPU page fault / TDR.
    4. Same-submission lag: Host::submit runs begin_sync_heaps() before list.run_deferred() (which runs show()), and draw.rs mirrors table slots at recording time before show(), so heap-mirrored RTAS SRVs see None on Frame 1 and T_prev on Frame N whenever TLAS build and trace share a submission.
  • Minimal fix: Track active RTAS SRV slots (index, handle) per HostHeap and retain Arc<HostAs> (e.g., via an opaque Box<dyn Any + Send> pin retired alongside kept) so T1.refs remains alive while any slot exposes T1. Immediately after list.run_deferred() in Host::submit (whenever TLAS_GENERATION changed), refresh tracked RTAS slots across SHADER_HEAPS before ExecuteCommandLists.

2. [P1] #347, #349, #357 — emit_postbuild + Local read_shadows Emits D3D12 RESOURCE_BARRIER_BEFORE_AFTER_MISMATCH

  • Locations: #347 crates/victory-gpu/src/hwrt.rs:1739, 1865, 1954, 1986, 2053, 2232, 2248, 2418-2521; #357 crates/victory-gpu/src/hwrt.rs:1837, 1963, 2079, 2145, 2207, 2290, 2469, 2485, 2655-2758 (prepare_aabbs, prepare_triangles, execute_blas_batch, execute_build, emit_postbuild).
  • Failure sequence (4 concrete paths):
    1. Multi-wave batch sharing a shadow buffer: prepare_* inserts sh.buffer once into read_shadows for the whole batch. Wave 1's emit_postbuild removes sh.buffer and emits NON_PIXEL_SHADER_RESOURCE -> COPY_DEST -> COMMON. Wave 2 reads sh.buffer (implicitly promoting COMMON -> NON_PIXEL_SHADER_RESOURCE), then Wave 2's emit_postbuild sees read_shadows.remove == false and emits COMMON -> COPY_DEST while sh.buffer is in NON_PIXEL_SHADER_RESOURCE.
    2. Wave 2 read / Wave 1 postbuild: Non-sanitized geometries insert sh.buffer during prep before Wave 1 executes; if Wave 1 writes postbuild to sh.buffer while only Wave 2 reads it, Wave 1 emits NON_PIXEL_SHADER_RESOURCE -> COPY_DEST on a buffer still in COMMON.
    3. Early return None after read_shadows.insert: prepare_aabbs (#357 hwrt.rs:1963) and prepare_triangles (#357 hwrt.rs:2079, 2145) insert sh.buffer before alignment/IB/work() checks that can return None, leaving sh.buffer in COMMON while emit_postbuild transitions from NON_PIXEL_SHADER_RESOURCE.
    4. Cross-chunk / BLAS->TLAS / prior draw on the same HostList: read_shadows is created fresh per execute_blas_batch chunk and per execute_build; any sh.buffer already promoted to NON_PIXEL_SHADER_RESOURCE / GENERIC_READ earlier on list gets transitioned from COMMON.
  • Minimal fix: Track shadow buffer state per HostList (populated only at the exact point a sanitize dispatch or BuildRaytracingAccelerationStructure wave actually records a read of sh.buffer, re-inserted on every subsequent wave/chunk read, and reset to COMMON after emit_postbuild), or use Enhanced Barriers D3D12_GLOBAL_BARRIER (SYNC_ALL / ACCESS_COMMON) when supported.

3. [P2] #349, #357 — Unbounded vec![0u8; ...] Allocations Before read_into in decoders.rs Can OOM-Abort

  • Locations: crates/victory-gpu/src/hwrt/decoders.rs:206-210 (decode_title_meshlet_ib), decoders.rs:315-325 (decode_title_quant24_vb).
  • Failure sequence: Corrupt/recycled title memory values for num_packed_tris (w1) or vcount * actual_stride allocate multi-GiB/TiB vec![0u8; ...] buffers before crate::host::read_into gets a chance to reject the unmapped range, triggering an OOM abort.
  • Minimal fix: Cap vertex_indices_off and vbytes to a sane ceiling (e.g. 64 << 20) and/or use Vec::try_reserve_exact, returning None on failure.

4. [P2] #349 (standalone, before #354) — shader_cache.rs Normalizes VICTORY_BVH_BUILDER=1 -> "0" While intersect.rs Still Reads Raw Env

  • Locations: #349 crates/victory-gpu/src/shader_cache.rs:48-57, 111-116 vs crates/victory-shader/src/emit/intersect.rs:105, 120.
  • Failure sequence: Merging #349 alone (before #354) hashes VICTORY_BVH_BUILDER=0 under VICTORY_HW_RT=1 VICTORY_BVH_BUILDER=1 VICTORY_BVH_MISS=1, while victory-shader/src/emit/intersect.rs still reads raw VICTORY_BVH_BUILDER=1, storing software-BVH shaders under the =0 cache key. (Already fixed in #357 via #354.)
  • Minimal fix: Add the 2-line VICTORY_HW_RT=1 check to intersect.rs in #349 (or defer normalizing VICTORY_BVH_BUILDER in shader_cache.rs until #354).

5. [P2] #357 — null_rtas_view & should_pin_descriptor Gate on hwrt::requested() Instead of hwrt::active()

  • Locations: crates/victory-gpu/src/descriptor/host.rs:4905-4910, 6564-6574.
  • Failure sequence: On a non-DXR-1.1 host GPU with VICTORY_HW_RT=1 (requested() == true, active() == false), null_rtas_view calls CreateShaderResourceView(None, &RAYTRACING_ACCELERATION_STRUCTURE, at) on a non-DXR device, and should_pin_descriptor returns false, repeating the invalid call on every draw.
  • Minimal fix: Replace crate::hwrt::requested() with crate::hwrt::active() at descriptor/host.rs:4908, 6565.

Section 3 — Remaining / New Bugs in #354 (7ae7398d, DXR 1.1 Traversal Lifter)

(Pass #2 findings #10, #13, #14, #16, #17 are cleanly resolved; #11, #12, #15, #18, #19, #20 are mostly resolved with the specific remaining/introduced defects below.)

6. [P0] #354 — find_triangle_hit_info Pattern C Miscompiles EXEC-Masked CallbackKind::Blocks Commits AND Opaque-Only tri_merge_block Commits as CommitDecision::Always

  • Locations: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:3528, 3530-3552 (find_triangle_hit_info).
  • Failure sequence:
    1. EXEC-masked CallbackKind::Blocks (:3528): Hardcodes CallbackKind::Blocks { .. } => Some(CommitDecision::Always) without inspecting st.guards[site.0][site.1]. Any multi-block callback whose dominating block narrows EXEC via s_and_saveexec/v_cmpx before v_mov_b32 v_tmax, v_t (or v_state = 0 / v_hit_tri = cur_tri) emits unconditional CommitNonOpaqueTriangleHit.
    2. Opaque-only commit moves in tri_merge_block[merge_start..] (:3530-3552): Candidate values (v_t, cur_tri, cur_inst, cand_u/v/ff) are defined before the callback (!cb_site_set.contains(&def_site)), so src_guard is always None and :3550 unconditionally yields Some(CommitDecision::Always) without checking st.guards[tri_merge_block][j]. A CommitDecision::Never (always-reject) callback followed by an opaque-only s_andn2 commit move silently lifts as CommitDecision::Always (committing every non-opaque hit).
  • Minimal fix: At :3528, inspect st.guards[site.0][site.1]: emit CommitDecision::GuardBool(gb) (requiring bool_dominates_cb_commit(gb), else Err) when Some(gb), and Always only when None. For !cb_site_set.contains(&site), test (st.reach[tri_merge_block], st.guards[tri_merge_block][j]) against the non-opaque entry mask nonop_bool: skip setting guard_commit_decision when disjoint (opaque-only), bail on partial overlap, and emit Always only if all non-opaque exit lanes execute it.

7. [P0] #354 — CallbackKind::Blocks PHI Resolution Silently Zeroes Live Lazy-Param/Missing Arms AND Aborts Lowering on Unread Lane-Mask/Scc PHIs

  • Locations: crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:469-505 (cb_data_phis), emit_rq.rs:510-572 (merge_block PHIs).
  • Failure sequence:
    1. Silent zeroing (:493, :542): Both loops match (Some(Val::Missing(_)) | None, false) if numbers => self.s.m.i32(0) without resolving lazy user-data root constants (self.params, never eagerly inserted into self.vals) and without checking self.dead(arg, ...) or !self.read_phis.contains(&phi.value) (unlike Lower::fill_phis at lower.rs:14056-14069). Any live callback or merge_block accumulator PHI joining an I32 arm with an unread self.params SGPR silently replaces that arm with 0.
    2. Broken lowering on valid multi-block callbacks (:496-498, :545-547): emit_rq.rs:388-408 creates a data_phi for every non-EXEC PHI in blocks (including vcc_lo/lane-mask SGPRs and Reg::Scc), and :510-572 iterates every non-EXEC PHI in *merge_block regardless of accumulator use. Because v_cmp_*/v_add_co_* store Val::Missing("a lane mask read as data") and st.masks.contains_key sets numbers = false, any multi-block callback whose branches write vcc/lane-mask/Scc fails at :496 or :545, aborting lifting for the entire shader.
  • Minimal fix: Mirror Lower::fill_phis in cb_data_phis (resolve self.params/self.lazy_barycentric; substitute 0/false only when !self.read_phis.contains(&phi.value) or (numbers && self.dead(arg, ...))). In merge_block PHIs (:510-572), materialize only PHIs referenced by q.accumulators, resolving self.params and never zeroing live missing arms.

8. [P1] #354 — is_pure_bvh_internal_scratch Still Zeroes Mutated Live-Out origin/dir Back-Edge Values

  • Locations: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:5093-5126 (classify_live_outs), analyze.rs:5363-5410 (is_pure_bvh_internal_scratch).
  • Failure sequence: In Template A (bvh64), entering a BLAS transforms origin/dir into object space and popping back to TLAS restores world-space origin/dir via v_cndmask_b32 (v_orig_next). ray_input_vals (:5093-5100) only expands mov/PHIs (not v_cndmask_b32), so v_orig_next misses ray_input_vals, hits def_inst in loop_blocks \ hit_and_cb_blocks, sets saw_bvh_internal_def = true (with touches_preloop_or_header discarded at :5405), and silently emits LiveOutKind::DeadZero (0.0) for post-loop origin/dir.
  • Minimal fix: In classify_live_outs (:5115), forbid is_pure_bvh_internal_scratch whenever header_phi.is_some_and(|hp| ray_input_vals.contains(&hp)), and inside is_pure_bvh_internal_scratch return false for any def_inst whose explicit reads reach ray_input_vals.

9. [P1] #354 — Non-Callback Opacity Culling Polarity Drops st.reach[search_blk] When st.guards[search_blk][ci] Is Some(...)

  • Locations: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:2908, 3057-3071 (find_triangle_hit_info).
  • Failure sequence: structure.rs:865 factors st.reach[b] out of st.guards[b][i]. Using st.guards[search_blk][ci].unwrap_or(st.reach[search_blk]) (:2908) discards st.reach[search_blk] whenever an instruction has an inner EXEC guard (v_cmpx/s_and_saveexec), causing q_true/q_false to miss branch-carried CULL_OPAQUE/CULL_NON_OPAQUE predicates and fall back to RAY_FLAG_FORCE_OPAQUE.
  • Minimal fix: Store (st.reach[search_blk], st.guards[search_blk][ci], extra) in commit_conds and include (reach, true) alongside guard in both q_true and q_false.

10. [P1] #354 — Pattern A (MergeEdges) Early break on invalid Silently Drops Inconsistent Merge PHIs

  • Location: crates/victory-shader/src/emit/lower/rayquery/analyze.rs:3307-3317 (find_triangle_hit_info).
  • Failure sequence: If cb_preds = [B_weird, B_commit] hits an unrecognized expression on pred 0 (B_weird), invalid = true; break; runs while commits is still empty, making if invalid && !commits.is_empty() (:3313) false and skipping the PHI instead of returning Err. A second PHI matching [B_weird -> old, B_commit -> cur] can then succeed and drop B_weird's commit effect.
  • Minimal fix: Continue scanning remaining cb_preds (collecting any committing preds) instead of breaking on invalid = true, then fail at :3313 whenever invalid && !commits.is_empty().

11. [P2] #354 — Remaining Edge Cases

  • Duplicate orphaned counter PHI (emit_rq.rs:367-379 vs lower.rs:2899-2916): Lower::run already allocates a counter PHI for inner loops in callback_blocks; emit_rq.rs:376 allocates a second one and overwrites self.counters[b], leaving the first with 0 incoming edges (dxil.dll failure under VICTORY_SHADER_OPT=0). Fix: if is_hdr && !self.counters.contains_key(&b).
  • bool_dominates_cb_commit omits Atom::Uniform (analyze.rs:3206-3212): Atom::Uniform(av) falls into _ => true, risking DXIL SSA dominance violation in cb_commit_blk. Fix: check val_dominates_cb_commit(av).
  • Heap TLAS load_site dead-site check (analyze.rs:434-451): no_external_uses tests all_lifted_blocks (which includes callback_blocks, inline_callbacks, and header), potentially zeroing a sibling value loaded in the same coalesced s_load and used inside a callback/header PHI. Fix: test plan.is_eliminated(u.0, u.1) and plan.skipped_blocks.contains(&pb) && !plan.callback_blocks.contains(&pb).
  • Minor helper guards: find_invariant_preloop_source (analyze.rs:5302) uses continue instead of return None when seen.len() > 128; extract_callback_region Case 2 (analyze.rs:4386-4391) should require saved_exec.is_some() so an inner s_mov tmp, exec; v_cmpx; s_mov exec, tmp cannot truncate early.

Section 4 — .10 Release Candidate #360 (6a8d28d5, Native F12 Screenshots)

All D3D12 backbuffer state transitions (COPY_DEST -> COPY_SOURCE -> PRESENT on both composed and non-composed paths), execute_own_with_fence fence capture (*submitted on self.queue), swapchain slot lifetime (p.ahead[i].1 = flown), non-stalling background PNG encoding, MAX_IN_FLIGHT = 4, and RGBA8/BGRA8/BGRX8/R10G10B10A2/R16G16B16A16_FLOAT conversions are verified clean.

12. [P2] #360 — wait_for_fence Trusts WAIT_OBJECT_0 Without Re-Checking GetCompletedValue() >= target on Reused Auto-Reset Event

  • Location: crates/victory-gpu/src/host/screenshot.rs:441-461 (wait_for_fence), called from worker_loop (screenshot.rs:465-470).
  • Failure sequence:
    1. worker_loop creates a single EventHandle (:466) reused across all screenshot jobs.
    2. If Screenshot #1 times out after 30 s (:460, e.g. during a heavy shader compile/stall), fence.SetEventOnCompletion(target1, event.0) remains armed; when target1 finishes shortly afterward, event.0 becomes signaled.
    3. Screenshot #2 (target2 > target1) calls SetEventOnCompletion(target2, event.0) and WaitForSingleObject(event.0, 5_000), which returns WAIT_OBJECT_0 immediately from target1's stale signal before target2 completes.
    4. Line :443 (WAIT_OBJECT_0 => return fence.GetCompletedValue() != u64::MAX) returns true without checking >= target, so process_job maps and reads pending.buffer while the GPU is still executing CopyTextureRegion.
  • Minimal fix: On WAIT_OBJECT_0, check let now = fence.GetCompletedValue(); if now == u64::MAX { return false; } if now >= target { return true; } and continue the wait loop (re-arming SetEventOnCompletion if needed) until now >= target.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7355749301 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7355749301). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-02T19:11:04Z. --- ## Deep Static Logic Audit — Pass #3 (Final Pre-Merge Verification) Strictly read-only verification of the updated HW-RT stack (`#343`, `#347`, `#349`, `#354`, `#357`), `.10` release candidates (`#356`, `#360`), and newly merged performance PRs (`#363`, `#365`). --- ### Merge-Readiness Table | PR | Head | Verdict | Summary | | --- | --- | --- | --- | | **`#343`** | `6b9c8435` | **VERIFIED CLEAN (Green Light)** | Pass #1 Finding `#17` cleanly resolved (per-recording `has_sizes`, Acquire/Release handoff, unconditional `Quiet::wake` reset). | | **`#356`** | `b56e2809` | **VERIFIED CLEAN (Green Light)** | Pass #2 Finding `#22` cleanly resolved (`host_max_wave() >= 64` guard); zero NVIDIA Wave32 regressions. | | **`#360`** | `6a8d28d5` | **NEEDS FIX** *(1 tiny `[P2]`)* | D3D12 barriers, fence capture, swapchain lifetimes, and PNG encoding are clean; 3-line `[P2]` stale-event fence-wait check in `wait_for_fence`. | | **`#347`** | `5140ce43` | **NEEDS FIX** *(1 `[P1]`)* | Pass #2 `#1`, `#3`, `#4`, `#6`, `#8`, `#9` cleanly resolved. `#2` (`emit_postbuild` / `read_shadows`) has 4 `RESOURCE_BARRIER_BEFORE_AFTER_MISMATCH` paths. | | **`#349`** | `769d11c2` | **NEEDS FIX** *(1 `[P1]`, 2 `[P2]`)* | Pass #2 `#7` cleanly resolved. Inherits `#347` `emit_postbuild` `[P1]`, plus unbounded `vec![0u8; ...]` OOM-abort in `decoders.rs` (`[P2]`) and standalone `shader_cache.rs` vs `intersect.rs` mismatch (`[P2]`). | | **`#354`** | `7ae7398d` | **NEEDS FIX** *(2 `[P0]`, 3 `[P1]`, 4 `[P2]`)* | Pass #2 `#10`, `#13`, `#14`, `#16`, `#17` cleanly resolved + **standalone cache safety & zero RT-off impact confirmed**. Remaining/new bugs in `CallbackKind::Blocks` Pattern C & PHI resolution, live-out `origin`/`dir` zeroing, opacity polarity (`st.reach`), and Pattern A `invalid` break. | | **`#357`** | `be6135ac` | **NEEDS FIX** *(2 `[P1]`, 2 `[P2]`)* | Pass #2 `#1` (AS reuse/publish), `#3`, `#4`, `#6`, `#7`, `#8`, `#9` cleanly resolved. Remaining `[P1]`s: bindless `TlasSource::Heap` stale/null RTAS SRVs + GPU BLAS UAF via `HostHeap::kept` + submit-time `sync_heaps` lag; inherited `#347` `emit_postbuild` `[P1]`. | | **`#363`** *(merged)* | `60a88573` | **VERIFIED CLEAN** | Offloaded `victory-sweep` thread, `bury_lag=16` / `landed_lag=8`, `pool::REST=500ms` — zero P0/P1 concurrency or ordering bugs. | | **`#365`** *(merged)* | `6042ed29` | **VERIFIED CLEAN** | Coalesced CBV descriptor batches (`(index/64)%parts`) + fused `FillsOnly` `card_steps` — zero P0/P1 concurrency or ordering bugs. | --- ### Zero-Impact Verification (`VICTORY_HW_RT` Unset or `0`) - **`#347`, `#349`, `#354`, `#357`:** **CONFIRMED strictly zero behavioral impact** when `VICTORY_HW_RT` is unset or `0` — including standalone `#354` disk shader cache safety (`shader_cache.rs` now keys `VICTORY_HW_RT=1`/`VICTORY_HW_RT_LIFT=0`, normalizes `VICTORY_BVH_BUILDER`, and round-trips `HostShader::ray_queries` with zero extra bytes written when off). - *(Minor rebase note: `tlas_for_descriptor` returns `Some(empty_tlas)` on miss in `#347`/`#349` vs `None` in `#357`; align to `None` before merging.)* --- ### Section 1 — Verified Clean Sign-Offs (`#343`, `#356`, `#363`, `#365`) - **`#343` (`6b9c8435`) — Pass #1 Finding `#17` RESOLVED:** - Replaced global `SIZES_SEEN` / `THIN_QUEUED`/`THIN_DONE` with per-pipeline `pipeline::maybe_size_query` (`threads == [1,1,1]`, `SLOT_MEMORY`, `builder || (stores && stores_by_address)`) + `Recording::has_sizes` + `THIN_SIZES_QUEUED`/`THIN_SIZES_DONE`, eliminating per-frame `behind::drain()` on frames without size queries. - Strictly ordered Release/Acquire handoff across `Job::unfold` (`SIZES_QUEUED` -> `THIN_SIZES_DONE`), `Job::Run`/`Job::Joined` (`PENDING_FLIGHT` -> `SIZES_DONE`), and `has_pending_sizes()` (`THIN_SIZES_DONE` -> `THIN_SIZES_QUEUED` -> `SIZES_DONE` -> `SIZES_QUEUED`). - `Quiet::wake()` unconditionally locks `self.state` and clears `streak`/`audit`/`range` even for near-threshold streaks. - **`#356` (`b56e2809`) — Pass #2 Finding `#22` RESOLVED:** - `let lds_wave = s.lds_dwords > 0 && (one_wave || (x.native.wave64 && host_max_wave() >= 64));` (`lower.rs:1930`) cleanly restricts multi-wave Wave64 LDS `WaveSize(64)` to 64-lane hosts (RDNA 4), leaving NVIDIA (`host_max_wave() == 32`) untouched (`wave_size = None`, `split_lds = false`, full 32 KiB `HOST_LDS_DWORDS` intact, verified by new unit tests). - **`#363` (`60a88573`, merged) — Sanity Check CLEAN:** - Every eviction in `sweep_once()` retires GPU resources via `host::retire` or `drop_aside` (after `strong_count == 1 && references == 1 && long_ago`), and `resource::let_go_idle`/`slot_evict` release `textures()` before descriptor calls (no AB-BA cycle with `HostHeap::mirror`). `pool::REST = 500ms` runs strictly after `bury_lag` drop; `landed_lag = 8` only drains already GPU-completed `line.landed` flights. - **`#365` (`6042ed29`, merged) — Sanity Check CLEAN:** - `bucket_constant_ops` partitions disjoint 64-slot blocks per worker (`(index / 64) % parts`); `HostHeap::constant_slots_batch` splits before duplicate slot indices (`cbv_chunk_len`), guards `!self.twins.is_empty()` / `self.sampler`, and uses linear `self.cpu_inner(idx, true)` with per-thread disjoint 64-slot CPU staging slices. `card_steps::scan_and_take` falls back immediately to `take_steps_full` on any `Step::Copy`/`Placed`/`Run` and mirrors `blocked_by` + `copied_read` exactly on `FillsOnly` submissions. --- ### Section 2 — Remaining / New Bugs in `#347`, `#349`, `#357` (HW-RT GPU/HLE) *(Pass #2 findings `#3`, `#4`, `#6` (in `#347`/`#357`), `#7`, `#8`, `#9`, and `#1`'s AS pool/refit/submit-time publication are all cleanly resolved.)* #### 1. `[P1]` `#357` — Bindless (`ResourceDescriptorHeap[]`) RTAS SRVs Stay Permanently Null/Stale, Risk GPU BLAS UAF via `HostHeap::kept`, & Lag Behind Same-Submission TLAS Builds - **Locations:** `crates/victory-gpu/src/hwrt.rs:304-316` (`HostAs::drop`), `hwrt.rs:3193-3206` (`tlas_for_descriptor`); `crates/victory-gpu/src/descriptor/host.rs:4752-4943` (`HostHeap::mirror`), `descriptor.rs:493-738` (`sync_heaps`); `crates/victory-gpu/src/host.rs:8144-8290` (`Host::submit`). - **Failure sequence:** 1. `#354` lowers dynamic TLAS descriptors to `TlasSource::Heap` (`ResourceDescriptorHeap[...]`). A title creates a persistent RTAS SRV at shader-visible heap slot `S` pointing to `console_tlas_va` once and never rewrites slot `S`'s bytes. 2. **Stuck null:** If slot `S` is mirrored before the first TLAS build submits, `tlas_for_descriptor` returns `None` (writing `Location: 0`). Neither `draw.rs` (only mirrors root tables) nor `sync_heaps()` (only scans dirty title-memory heap pages and `CONSTANT | PLACED` `before` slots) ever re-calls `HostHeap::mirror(S, ...)` after `TLAS_GENERATION` bumps -> slot `S` remains null forever. 3. **Stale TLAS + GPU BLAS UAF:** `tlas_for_descriptor` returns only `ID3D12Resource` (`T1.buffer`) to `HostHeap::kept[S]`, **not** `Arc<HostAs>`. On Frame 2+, `execute_build` publishes `T2` (`T2.gpu_va != T1.gpu_va`) and retires `Shown(T1)`. Slot `S` is never refreshed (still exposes `T1.gpu_va`). Once `Shown(T1)` drops past `bury_lag`, `HostAs::drop` runs for `T1` and retires `T1.refs` (`Arc<BlasRefs>`). While `is_sole_com_owner` keeps `T1.buffer` out of `as_pool`, **nothing keeps `T1.refs` alive** — rebuilt/evicted BLASes drop their last `Arc<HostAs>`, enter `as_pool`, and are overwritten/freed while `ResourceDescriptorHeap[S]` still traverses `T1.gpu_va` into their GPU VAs -> GPU page fault / TDR. 4. **Same-submission lag:** `Host::submit` runs `begin_sync_heaps()` *before* `list.run_deferred()` (which runs `show()`), and `draw.rs` mirrors table slots at recording time before `show()`, so heap-mirrored RTAS SRVs see `None` on Frame 1 and `T_prev` on Frame `N` whenever TLAS build and trace share a submission. - **Minimal fix:** Track active RTAS SRV slots `(index, handle)` per `HostHeap` and retain `Arc<HostAs>` (e.g., via an opaque `Box<dyn Any + Send>` pin retired alongside `kept`) so `T1.refs` remains alive while any slot exposes `T1`. Immediately after `list.run_deferred()` in `Host::submit` (whenever `TLAS_GENERATION` changed), refresh tracked RTAS slots across `SHADER_HEAPS` before `ExecuteCommandLists`. #### 2. `[P1]` `#347`, `#349`, `#357` — `emit_postbuild` + Local `read_shadows` Emits D3D12 `RESOURCE_BARRIER_BEFORE_AFTER_MISMATCH` - **Locations:** `#347` `crates/victory-gpu/src/hwrt.rs:1739, 1865, 1954, 1986, 2053, 2232, 2248, 2418-2521`; `#357` `crates/victory-gpu/src/hwrt.rs:1837, 1963, 2079, 2145, 2207, 2290, 2469, 2485, 2655-2758` (`prepare_aabbs`, `prepare_triangles`, `execute_blas_batch`, `execute_build`, `emit_postbuild`). - **Failure sequence (4 concrete paths):** 1. **Multi-wave batch sharing a shadow buffer:** `prepare_*` inserts `sh.buffer` once into `read_shadows` for the whole batch. Wave 1's `emit_postbuild` removes `sh.buffer` and emits `NON_PIXEL_SHADER_RESOURCE -> COPY_DEST -> COMMON`. Wave 2 reads `sh.buffer` (implicitly promoting `COMMON -> NON_PIXEL_SHADER_RESOURCE`), then Wave 2's `emit_postbuild` sees `read_shadows.remove == false` and emits **`COMMON -> COPY_DEST`** while `sh.buffer` is in `NON_PIXEL_SHADER_RESOURCE`. 2. **Wave 2 read / Wave 1 postbuild:** Non-sanitized geometries insert `sh.buffer` during prep before Wave 1 executes; if Wave 1 writes postbuild to `sh.buffer` while only Wave 2 reads it, Wave 1 emits **`NON_PIXEL_SHADER_RESOURCE -> COPY_DEST`** on a buffer still in `COMMON`. 3. **Early `return None` after `read_shadows.insert`:** `prepare_aabbs` (`#357 hwrt.rs:1963`) and `prepare_triangles` (`#357 hwrt.rs:2079, 2145`) insert `sh.buffer` before alignment/IB/`work()` checks that can `return None`, leaving `sh.buffer` in `COMMON` while `emit_postbuild` transitions from `NON_PIXEL_SHADER_RESOURCE`. 4. **Cross-chunk / BLAS->TLAS / prior draw on the same `HostList`:** `read_shadows` is created fresh per `execute_blas_batch` chunk and per `execute_build`; any `sh.buffer` already promoted to `NON_PIXEL_SHADER_RESOURCE` / `GENERIC_READ` earlier on `list` gets transitioned from `COMMON`. - **Minimal fix:** Track shadow buffer state per `HostList` (populated only at the exact point a sanitize dispatch or `BuildRaytracingAccelerationStructure` wave actually records a read of `sh.buffer`, re-inserted on every subsequent wave/chunk read, and reset to `COMMON` after `emit_postbuild`), or use Enhanced Barriers `D3D12_GLOBAL_BARRIER` (`SYNC_ALL / ACCESS_COMMON`) when supported. #### 3. `[P2]` `#349`, `#357` — Unbounded `vec![0u8; ...]` Allocations Before `read_into` in `decoders.rs` Can OOM-Abort - **Locations:** `crates/victory-gpu/src/hwrt/decoders.rs:206-210` (`decode_title_meshlet_ib`), `decoders.rs:315-325` (`decode_title_quant24_vb`). - **Failure sequence:** Corrupt/recycled title memory values for `num_packed_tris` (`w1`) or `vcount * actual_stride` allocate multi-GiB/TiB `vec![0u8; ...]` buffers before `crate::host::read_into` gets a chance to reject the unmapped range, triggering an OOM abort. - **Minimal fix:** Cap `vertex_indices_off` and `vbytes` to a sane ceiling (e.g. `64 << 20`) and/or use `Vec::try_reserve_exact`, returning `None` on failure. #### 4. `[P2]` `#349` (standalone, before `#354`) — `shader_cache.rs` Normalizes `VICTORY_BVH_BUILDER=1 -> "0"` While `intersect.rs` Still Reads Raw Env - **Locations:** `#349` `crates/victory-gpu/src/shader_cache.rs:48-57, 111-116` vs `crates/victory-shader/src/emit/intersect.rs:105, 120`. - **Failure sequence:** Merging `#349` alone (before `#354`) hashes `VICTORY_BVH_BUILDER=0` under `VICTORY_HW_RT=1 VICTORY_BVH_BUILDER=1 VICTORY_BVH_MISS=1`, while `victory-shader/src/emit/intersect.rs` still reads raw `VICTORY_BVH_BUILDER=1`, storing software-BVH shaders under the `=0` cache key. *(Already fixed in `#357` via `#354`.)* - **Minimal fix:** Add the 2-line `VICTORY_HW_RT=1` check to `intersect.rs` in `#349` (or defer normalizing `VICTORY_BVH_BUILDER` in `shader_cache.rs` until `#354`). #### 5. `[P2]` `#357` — `null_rtas_view` & `should_pin_descriptor` Gate on `hwrt::requested()` Instead of `hwrt::active()` - **Locations:** `crates/victory-gpu/src/descriptor/host.rs:4905-4910, 6564-6574`. - **Failure sequence:** On a non-DXR-1.1 host GPU with `VICTORY_HW_RT=1` (`requested() == true`, `active() == false`), `null_rtas_view` calls `CreateShaderResourceView(None, &RAYTRACING_ACCELERATION_STRUCTURE, at)` on a non-DXR device, and `should_pin_descriptor` returns `false`, repeating the invalid call on every draw. - **Minimal fix:** Replace `crate::hwrt::requested()` with `crate::hwrt::active()` at `descriptor/host.rs:4908, 6565`. --- ### Section 3 — Remaining / New Bugs in `#354` (`7ae7398d`, DXR 1.1 Traversal Lifter) *(Pass #2 findings `#10`, `#13`, `#14`, `#16`, `#17` are cleanly resolved; `#11`, `#12`, `#15`, `#18`, `#19`, `#20` are mostly resolved with the specific remaining/introduced defects below.)* #### 6. `[P0]` `#354` — `find_triangle_hit_info` Pattern C Miscompiles EXEC-Masked `CallbackKind::Blocks` Commits AND Opaque-Only `tri_merge_block` Commits as `CommitDecision::Always` - **Locations:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:3528, 3530-3552` (`find_triangle_hit_info`). - **Failure sequence:** 1. **EXEC-masked `CallbackKind::Blocks` (`:3528`):** Hardcodes `CallbackKind::Blocks { .. } => Some(CommitDecision::Always)` without inspecting `st.guards[site.0][site.1]`. Any multi-block callback whose dominating block narrows `EXEC` via `s_and_saveexec`/`v_cmpx` before `v_mov_b32 v_tmax, v_t` (or `v_state = 0` / `v_hit_tri = cur_tri`) emits unconditional `CommitNonOpaqueTriangleHit`. 2. **Opaque-only commit moves in `tri_merge_block[merge_start..]` (`:3530-3552`):** Candidate values (`v_t`, `cur_tri`, `cur_inst`, `cand_u/v/ff`) are defined *before* the callback (`!cb_site_set.contains(&def_site)`), so `src_guard` is always `None` and `:3550` unconditionally yields `Some(CommitDecision::Always)` without checking `st.guards[tri_merge_block][j]`. A `CommitDecision::Never` (always-reject) callback followed by an opaque-only `s_andn2` commit move silently lifts as `CommitDecision::Always` (committing every non-opaque hit). - **Minimal fix:** At `:3528`, inspect `st.guards[site.0][site.1]`: emit `CommitDecision::GuardBool(gb)` (requiring `bool_dominates_cb_commit(gb)`, else `Err`) when `Some(gb)`, and `Always` only when `None`. For `!cb_site_set.contains(&site)`, test `(st.reach[tri_merge_block], st.guards[tri_merge_block][j])` against the non-opaque entry mask `nonop_bool`: skip setting `guard_commit_decision` when disjoint (opaque-only), bail on partial overlap, and emit `Always` only if all non-opaque exit lanes execute it. #### 7. `[P0]` `#354` — `CallbackKind::Blocks` PHI Resolution Silently Zeroes Live Lazy-Param/Missing Arms AND Aborts Lowering on Unread Lane-Mask/`Scc` PHIs - **Locations:** `crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:469-505` (`cb_data_phis`), `emit_rq.rs:510-572` (`merge_block` PHIs). - **Failure sequence:** 1. **Silent zeroing (`:493`, `:542`):** Both loops match `(Some(Val::Missing(_)) | None, false) if numbers => self.s.m.i32(0)` without resolving lazy user-data root constants (`self.params`, never eagerly inserted into `self.vals`) and without checking `self.dead(arg, ...)` or `!self.read_phis.contains(&phi.value)` (unlike `Lower::fill_phis` at `lower.rs:14056-14069`). Any live callback or `merge_block` accumulator PHI joining an I32 arm with an unread `self.params` SGPR silently replaces that arm with `0`. 2. **Broken lowering on valid multi-block callbacks (`:496-498`, `:545-547`):** `emit_rq.rs:388-408` creates a `data_phi` for every non-EXEC PHI in `blocks` (including `vcc_lo`/lane-mask SGPRs and `Reg::Scc`), and `:510-572` iterates *every* non-EXEC PHI in `*merge_block` regardless of accumulator use. Because `v_cmp_*`/`v_add_co_*` store `Val::Missing("a lane mask read as data")` and `st.masks.contains_key` sets `numbers = false`, any multi-block callback whose branches write `vcc`/lane-mask/`Scc` fails at `:496` or `:545`, aborting lifting for the entire shader. - **Minimal fix:** Mirror `Lower::fill_phis` in `cb_data_phis` (resolve `self.params`/`self.lazy_barycentric`; substitute `0`/`false` only when `!self.read_phis.contains(&phi.value)` or `(numbers && self.dead(arg, ...))`). In `merge_block` PHIs (`:510-572`), materialize *only* PHIs referenced by `q.accumulators`, resolving `self.params` and never zeroing live missing arms. #### 8. `[P1]` `#354` — `is_pure_bvh_internal_scratch` Still Zeroes Mutated Live-Out `origin`/`dir` Back-Edge Values - **Locations:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:5093-5126` (`classify_live_outs`), `analyze.rs:5363-5410` (`is_pure_bvh_internal_scratch`). - **Failure sequence:** In Template A (`bvh64`), entering a BLAS transforms `origin`/`dir` into object space and popping back to TLAS restores world-space `origin`/`dir` via `v_cndmask_b32` (`v_orig_next`). `ray_input_vals` (`:5093-5100`) only expands `mov`/PHIs (not `v_cndmask_b32`), so `v_orig_next` misses `ray_input_vals`, hits `def_inst` in `loop_blocks \ hit_and_cb_blocks`, sets `saw_bvh_internal_def = true` (with `touches_preloop_or_header` discarded at `:5405`), and silently emits `LiveOutKind::DeadZero` (`0.0`) for post-loop `origin`/`dir`. - **Minimal fix:** In `classify_live_outs` (`:5115`), forbid `is_pure_bvh_internal_scratch` whenever `header_phi.is_some_and(|hp| ray_input_vals.contains(&hp))`, and inside `is_pure_bvh_internal_scratch` return `false` for any `def_inst` whose explicit reads reach `ray_input_vals`. #### 9. `[P1]` `#354` — Non-Callback Opacity Culling Polarity Drops `st.reach[search_blk]` When `st.guards[search_blk][ci]` Is `Some(...)` - **Locations:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:2908, 3057-3071` (`find_triangle_hit_info`). - **Failure sequence:** `structure.rs:865` factors `st.reach[b]` out of `st.guards[b][i]`. Using `st.guards[search_blk][ci].unwrap_or(st.reach[search_blk])` (`:2908`) discards `st.reach[search_blk]` whenever an instruction has an inner EXEC guard (`v_cmpx`/`s_and_saveexec`), causing `q_true`/`q_false` to miss branch-carried `CULL_OPAQUE`/`CULL_NON_OPAQUE` predicates and fall back to `RAY_FLAG_FORCE_OPAQUE`. - **Minimal fix:** Store `(st.reach[search_blk], st.guards[search_blk][ci], extra)` in `commit_conds` and include `(reach, true)` alongside `guard` in both `q_true` and `q_false`. #### 10. `[P1]` `#354` — Pattern A (`MergeEdges`) Early `break` on `invalid` Silently Drops Inconsistent Merge PHIs - **Location:** `crates/victory-shader/src/emit/lower/rayquery/analyze.rs:3307-3317` (`find_triangle_hit_info`). - **Failure sequence:** If `cb_preds = [B_weird, B_commit]` hits an unrecognized expression on `pred 0` (`B_weird`), `invalid = true; break;` runs while `commits` is still empty, making `if invalid && !commits.is_empty()` (`:3313`) false and skipping the PHI instead of returning `Err`. A second PHI matching `[B_weird -> old, B_commit -> cur]` can then succeed and drop `B_weird`'s commit effect. - **Minimal fix:** Continue scanning remaining `cb_preds` (collecting any committing preds) instead of `break`ing on `invalid = true`, then fail at `:3313` whenever `invalid && !commits.is_empty()`. #### 11. `[P2]` `#354` — Remaining Edge Cases - **Duplicate orphaned counter PHI (`emit_rq.rs:367-379` vs `lower.rs:2899-2916`):** `Lower::run` already allocates a counter PHI for inner loops in `callback_blocks`; `emit_rq.rs:376` allocates a second one and overwrites `self.counters[b]`, leaving the first with 0 incoming edges (`dxil.dll` failure under `VICTORY_SHADER_OPT=0`). Fix: `if is_hdr && !self.counters.contains_key(&b)`. - **`bool_dominates_cb_commit` omits `Atom::Uniform` (`analyze.rs:3206-3212`):** `Atom::Uniform(av)` falls into `_ => true`, risking DXIL SSA dominance violation in `cb_commit_blk`. Fix: check `val_dominates_cb_commit(av)`. - **Heap TLAS `load_site` dead-site check (`analyze.rs:434-451`):** `no_external_uses` tests `all_lifted_blocks` (which includes `callback_blocks`, `inline_callbacks`, and `header`), potentially zeroing a sibling value loaded in the same coalesced `s_load` and used inside a callback/header PHI. Fix: test `plan.is_eliminated(u.0, u.1)` and `plan.skipped_blocks.contains(&pb) && !plan.callback_blocks.contains(&pb)`. - **Minor helper guards:** `find_invariant_preloop_source` (`analyze.rs:5302`) uses `continue` instead of `return None` when `seen.len() > 128`; `extract_callback_region` Case 2 (`analyze.rs:4386-4391`) should require `saved_exec.is_some()` so an inner `s_mov tmp, exec; v_cmpx; s_mov exec, tmp` cannot truncate early. --- ### Section 4 — `.10` Release Candidate `#360` (`6a8d28d5`, Native `F12` Screenshots) All D3D12 backbuffer state transitions (`COPY_DEST -> COPY_SOURCE -> PRESENT` on both `composed` and non-`composed` paths), `execute_own_with_fence` fence capture (`*submitted` on `self.queue`), swapchain slot lifetime (`p.ahead[i].1 = flown`), non-stalling background PNG encoding, `MAX_IN_FLIGHT = 4`, and `RGBA8`/`BGRA8`/`BGRX8`/`R10G10B10A2`/`R16G16B16A16_FLOAT` conversions are verified clean. #### 12. `[P2]` `#360` — `wait_for_fence` Trusts `WAIT_OBJECT_0` Without Re-Checking `GetCompletedValue() >= target` on Reused Auto-Reset Event - **Location:** `crates/victory-gpu/src/host/screenshot.rs:441-461` (`wait_for_fence`), called from `worker_loop` (`screenshot.rs:465-470`). - **Failure sequence:** 1. `worker_loop` creates a single `EventHandle` (`:466`) reused across all screenshot jobs. 2. If Screenshot #1 times out after 30 s (`:460`, e.g. during a heavy shader compile/stall), `fence.SetEventOnCompletion(target1, event.0)` remains armed; when `target1` finishes shortly afterward, `event.0` becomes signaled. 3. Screenshot #2 (`target2 > target1`) calls `SetEventOnCompletion(target2, event.0)` and `WaitForSingleObject(event.0, 5_000)`, which returns `WAIT_OBJECT_0` **immediately from `target1`'s stale signal** before `target2` completes. 4. Line `:443` (`WAIT_OBJECT_0 => return fence.GetCompletedValue() != u64::MAX`) returns `true` without checking `>= target`, so `process_job` maps and reads `pending.buffer` while the GPU is still executing `CopyTextureRegion`. - **Minimal fix:** On `WAIT_OBJECT_0`, check `let now = fence.GetCompletedValue(); if now == u64::MAX { return false; } if now >= target { return true; }` and continue the wait loop (re-arming `SetEventOnCompletion` if needed) until `now >= target`.
Androtim commented 2026-12-02 21:55:01 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-02T21:55:01Z.


Deep Static Logic Audit — Pass #4 (Final Quick Sign-Off)

Strictly read-only verification of:

  1. Native DXR 1.1 RayQuery superset PR #357 (363edc51, incorporating #347, #349, and #354 5b974f32) against Pass #3 findings #1–#11 (7355749301)
  2. Updated PR #331 (100015c0) against Pass #1 finding #12

Merge-Readiness Table

PR Head Verdict Summary
#331 100015c0 VERIFIED CLEAN (Green Light) Pass #1 Finding #12 cleanly resolved (ReadMostly thread-local HELD re-entrant guard tracking, !Send ReadGuard, strict 0..=SHARDS write lock ordering, PLACED_TEXTURES append-only verified). Zero soundness or deadlock issues.
#357 (superset incl. #347+#349+#354) 363edc51 NEEDS FIX (1 [P0] regression + 1 minor [P2]) Pass #3 Findings #1 and #3–#11 are all cleanly resolved (#354 5b974f32 has zero P0/P1 blockers). However, commit a4aab821's ungated HostList::shadow_to / shadows_common breaks the VICTORY_HW_RT=0/unset zero-impact guarantee and leaves Shadow::buffer in COPY_DEST / UNORDERED_ACCESS / GENERIC_READ across untracked descriptor-table, root-SRV/CBV, and texture.rs accesses.

Target 1 — PR #357 (363edc51) Verification of Pass #3 Findings #1–#11

Pass #3 # Status Verified Post-Patch Evidence
#1 [P1] (#357 bindless RTAS refresh + BLAS pins + submit-time lag) RESOLVED tlas_for_descriptor (hwrt.rs:3167-3185) returns (gpu_va, resource, Arc<HostAs> pin); HostHeap::kept_pins + rtas_slots retain/retire pins across keep_view, unmake, make_null_settled, release, and release_batch; descriptor::refresh_rtas_heaps() runs in host.rs:8159, 8585 right after drop(h.heaps) / drop(heaps_synced) and before ExecuteCommandLists.
#2 [P1] (emit_postbuild barrier mismatches) REPLACED BY NEW [P0] read_shadows was replaced with HostList::shadow_to (a4aab821), which fixes intra-hwrt transitions but introduces the [P0] ungated state-tracking regression below.
#3 [P2] (decoders.rs OOM-abort allocs) RESOLVED MAX_DECODE_READ_BYTES = 64 << 20, alloc_zeroed + try_reserve_exact, try_reserve_stage, and checked multiplies (hwrt/decoders.rs:146-366).
#4 [P2] (shader_cache.rs vs intersect.rs) RESOLVED intersect.rs:93-127 (bvh_override_active) matches shader_cache.rs normalization in lockstep.
#5 [P2] (hwrt::active() gating) RESOLVED null_rtas_view, should_pin_descriptor, tlas_gen, ListViews, make_at_inner, and mirror now gate on crate::hwrt::active().
#6 [P0] (#354 Pattern C EXEC-masked & opaque-only commits) RESOLVED blocks_site_decision + tri_merge_block guard/complement BDD checks (analyze.rs:3504-3779) properly emit GuardBool, OpaqueOnly, or bail on ambiguity (dxil.dll-validated tests added).
#7 [P0] (#354 CallbackKind::Blocks PHI resolution) RESOLVED (1 minor [P2]) collect_rq_needed_vals, resolve_lazy_rq_phi_input, and resolve_rq_phi_arm (emit_rq.rs:492-615, 1126-1255) resolve lazy self.params/lazy_barycentric, avoid aborting on unread vcc/Scc PHIs, and bail on live missing arms. (See minor [P2] #2 below.)
#8 [P1] (#354 mutated live-out origin/dir) RESOLVED classify_live_outs adds ray-input header PHI back-edges to ray_input_vals, skips is_pure_bvh_internal_scratch on ray_input_vals header PHIs, and traces mov/cndmask/cselect reads (analyze.rs:5238-5276, 5546-5558).
#9 [P1] (#354 opacity polarity st.reach) RESOLVED commit_conds carries (st.reach[search_blk], st.guards[search_blk][ci], extra) into q_true/q_false (analyze.rs:2897-3065).
#10 [P1] (#354 Pattern A invalid break) RESOLVED Early breaks removed (analyze.rs:3294-3316), so inconsistent merge PHIs reliably return Err.
#11 [P2] (#354 4 helper edge cases) RESOLVED Duplicate counter PHI guarded (emit_rq.rs:374), Atom::Uniform added to bool_dominates_cb_commit (analyze.rs:3209), heap TLAS dead-site check uses plan.is_eliminated (analyze.rs:437-441), seen.len() > 128 returns None (analyze.rs:5456), and extract_callback_region requires saved_exec.is_some() (analyze.rs:4524-4531).

Blocking & Remaining Findings on #357

1. [P0] #357 — Ungated HostList::shadow_to / shadows_common Breaks VICTORY_HW_RT=0 Zero-Impact & Causes D3D12 State Mismatches Across Untracked Shadow::buffer Accesses

  • Locations:
    • crates/victory-gpu/src/host/place.rs:231, 237, 242, 243, 249, 284, 309-370 (HostList::shadow_to, HostList::shadows_common)
    • crates/victory-gpu/src/draw.rs:2131, 2150, 2596, 5995
    • crates/victory-gpu/src/indirect.rs:539, 541, 644, 652
    • crates/victory-gpu/src/host.rs:9196 (HostList::close)
  • Failure sequence (impacts BOTH VICTORY_HW_RT unset/0 AND VICTORY_HW_RT=1):
    1. Zero-impact violation when VICTORY_HW_RT is unset/0: shadow_to and shadows_common are not gated on crate::hwrt::active(). Every VB bind, IB bind, root UAV bind, indirect clamp/batch, and place.rs copy on every frame locks self.deferred(), hashes into shadow_states, clones ID3D12Resource, and emits explicit ResourceBarriers (plus a shadows_common() barrier batch at list.close()).
    2. Broken D3D12 state tracking across untracked Shadow::buffer consumers (on VICTORY_HW_RT=0 AND =1): Previously, Shadow::buffer remained in D3D12_RESOURCE_STATE_COMMON (relying on implicit buffer promotion, with explicit copy paths like texture.rs:463-475 and card_steps.rs:2528 returning to COMMON immediately). Because descriptor-table SRVs/CBVs/UAVs (HostHeap), root SRVs/CBVs (draw.rs:2376-2489), texture.rs:463-475, and list.rs copies do not call shadow_to:
      • place.rs COPY_DEST trap (place.rs:237, 243, 249): Any placed copy transitions to.buffer to COPY_DEST and leaves it stuck there until list.close(). Any subsequent shader SRV/CBV/UAV (table or root) on to.buffer accesses a resource explicitly in COPY_DEST (D3D12 error / stale GPU reads), and texture.rs:463 (COMMON -> COPY_DEST) hits RESOURCE_BARRIER_BEFORE_AFTER_MISMATCH.
      • draw.rs:2596 UNORDERED_ACCESS trap: bind_root_uav leaves s.buffer in UNORDERED_ACCESS until list.close(); subsequent descriptor-table SRVs/CBVs, root SRVs/CBVs, or texture.rs:463 read a buffer explicitly locked in UNORDERED_ACCESS without a barrier.
      • draw.rs / indirect.rs GENERIC_READ trap: VB/IB/indirect bindings leave s.buffer in GENERIC_READ (disabling implicit promotion from COMMON), so any subsequent descriptor-table UAV write hits a resource explicitly locked in GENERIC_READ.
  • Minimal fix:
    • Revert all shadow_to / shadows_common hooks in draw.rs, host/place.rs, indirect.rs, and host.rs:9196 so Shadow::buffer stays in COMMON outside hwrt and VICTORY_HW_RT=0/unset has strictly zero behavioral or performance impact.
    • Inside hwrt.rs (hwrt::active() only), eliminate legacy COPY_DEST barriers on sh.buffer in emit_postbuild (hwrt.rs:2699-2736) by writing the 8–16 byte postbuild result into sh.buffer via a tiny 1-thread compute shader (SetComputeRootUnorderedAccessView on sh.gpu(dest_va) + plain UAV barrier — Shadow::buffer always has ALLOW_UNORDERED_ACCESS and works cleanly from COMMON/implicit promotion with zero BEFORE_AFTER mismatch against prior draws), or via Enhanced Barriers (ID3D12GraphicsCommandList7::Barrier D3D12_GLOBAL_BARRIER) where supported.

2. [P2] #357 (inherited from #354) — collect_rq_needed_vals Does Not Seed From self.read_phis

  • Location: crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:1126-1198 (collect_rq_needed_vals), emit_rq.rs:503-552 (cb_data_phis).
  • Failure sequence: Lower::fill_phis's transitive read_phis closure (lower.rs:14018-14032) has not run yet when emit_ray_query resolves cb_data_phis. Inside a multi-block CallbackKind::Blocks callback, if PHI P2 (taking a lazy self.params arm) feeds only PHI P1, and P1 is read only by an instruction (not directly via PHIs into acc.next_val / commit_decision), self.read_phis contains P1 but not P2, so P2 has needed == false and silently zeroes its lazy self.params arm at emit_rq.rs:551.
  • Minimal fix: Seed collect_rq_needed_vals's work queue with all phi.value in cb_set/merge_block where self.read_phis.contains(&phi.value) so PHI-to-PHI chains inside callbacks propagate transitively.

Target 2 — PR #331 (100015c0) Verification of Pass #1 Finding #12

  • Status: VERIFIED CLEAN (Green Light)
  • Verification:
    • crates/victory-gpu/src/listcpu.rs:204-377 (Held, HELD, ReadMostly::reading, Drop for ReadGuard): re-entrant read() / try_read() on the same ReadMostly (h.of == me) increments h.guards in TLS HELD and returns ReadGuard { own: None, ... } without re-acquiring any Windows SRWLOCK, eliminating self-deadlock behind waiting writers (even when sharded() flips via VICTORY_AB).
    • ReadGuard<'a, T> contains Option<RwLockReadGuard<'a, ()>>, keeping it !Send; dropping guards in any order decrements h.guards and releases _lock outside the RefCell borrow only when h.guards == 0. TLS-teardown / ID-collision paths safely fall back to own: Some(lock).
    • write() and try_write() acquire locks[0..=SHARDS] in strict ascending order; production ReadMostly IDs are disjoint (0 = VIEWS, 1 = BUFFERS, 2 = LOOSE).
    • VICTORY_PLACED_SEEN (resource.rs:607-624): verified PLACED_TEXTURES is strictly append-only across victory-gpu (no .remove()/.clear()), so thread-local Remembered entries cannot dangle.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7359964895 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7359964895). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-02T21:55:01Z. --- ## Deep Static Logic Audit — Pass #4 (Final Quick Sign-Off) Strictly read-only verification of: 1. **Native DXR 1.1 `RayQuery` superset PR `#357`** (`363edc51`, incorporating `#347`, `#349`, and `#354` `5b974f32`) against Pass #3 findings `#1–#11` (`7355749301`) 2. **Updated PR `#331`** (`100015c0`) against Pass #1 finding `#12` --- ### Merge-Readiness Table | PR | Head | Verdict | Summary | | --- | --- | --- | --- | | **`#331`** | `100015c0` | **VERIFIED CLEAN (Green Light)** | Pass #1 Finding `#12` cleanly resolved (`ReadMostly` thread-local `HELD` re-entrant guard tracking, `!Send` `ReadGuard`, strict `0..=SHARDS` write lock ordering, `PLACED_TEXTURES` append-only verified). Zero soundness or deadlock issues. | | **`#357`** *(superset incl. `#347`+`#349`+`#354`)* | `363edc51` | **NEEDS FIX** *(1 `[P0]` regression + 1 minor `[P2]`)* | Pass #3 Findings `#1` and `#3–#11` are **all cleanly resolved** (`#354` `5b974f32` has zero P0/P1 blockers). However, commit `a4aab821`'s ungated `HostList::shadow_to` / `shadows_common` breaks the `VICTORY_HW_RT=0`/unset zero-impact guarantee and leaves `Shadow::buffer` in `COPY_DEST` / `UNORDERED_ACCESS` / `GENERIC_READ` across untracked descriptor-table, root-SRV/CBV, and `texture.rs` accesses. | --- ### Target 1 — PR `#357` (`363edc51`) Verification of Pass #3 Findings `#1–#11` | Pass #3 # | Status | Verified Post-Patch Evidence | | --- | --- | --- | | **#1** `[P1]` (`#357` bindless RTAS refresh + BLAS pins + submit-time lag) | **RESOLVED** | `tlas_for_descriptor` (`hwrt.rs:3167-3185`) returns `(gpu_va, resource, Arc<HostAs> pin)`; `HostHeap::kept_pins` + `rtas_slots` retain/retire pins across `keep_view`, `unmake`, `make_null_settled`, `release`, and `release_batch`; `descriptor::refresh_rtas_heaps()` runs in `host.rs:8159, 8585` right after `drop(h.heaps)` / `drop(heaps_synced)` and before `ExecuteCommandLists`. | | **#2** `[P1]` (`emit_postbuild` barrier mismatches) | **REPLACED BY NEW `[P0]`** | `read_shadows` was replaced with `HostList::shadow_to` (`a4aab821`), which fixes intra-`hwrt` transitions **but** introduces the `[P0]` ungated state-tracking regression below. | | **#3** `[P2]` (`decoders.rs` OOM-abort allocs) | **RESOLVED** | `MAX_DECODE_READ_BYTES = 64 << 20`, `alloc_zeroed` + `try_reserve_exact`, `try_reserve_stage`, and checked multiplies (`hwrt/decoders.rs:146-366`). | | **#4** `[P2]` (`shader_cache.rs` vs `intersect.rs`) | **RESOLVED** | `intersect.rs:93-127` (`bvh_override_active`) matches `shader_cache.rs` normalization in lockstep. | | **#5** `[P2]` (`hwrt::active()` gating) | **RESOLVED** | `null_rtas_view`, `should_pin_descriptor`, `tlas_gen`, `ListViews`, `make_at_inner`, and `mirror` now gate on `crate::hwrt::active()`. | | **#6** `[P0]` (`#354` Pattern C EXEC-masked & opaque-only commits) | **RESOLVED** | `blocks_site_decision` + `tri_merge_block` guard/complement BDD checks (`analyze.rs:3504-3779`) properly emit `GuardBool`, `OpaqueOnly`, or bail on ambiguity (`dxil.dll`-validated tests added). | | **#7** `[P0]` (`#354` `CallbackKind::Blocks` PHI resolution) | **RESOLVED** *(1 minor `[P2]`)* | `collect_rq_needed_vals`, `resolve_lazy_rq_phi_input`, and `resolve_rq_phi_arm` (`emit_rq.rs:492-615, 1126-1255`) resolve lazy `self.params`/`lazy_barycentric`, avoid aborting on unread `vcc`/`Scc` PHIs, and bail on live missing arms. *(See minor `[P2]` #2 below.)* | | **#8** `[P1]` (`#354` mutated live-out `origin`/`dir`) | **RESOLVED** | `classify_live_outs` adds ray-input header PHI back-edges to `ray_input_vals`, skips `is_pure_bvh_internal_scratch` on `ray_input_vals` header PHIs, and traces `mov`/`cndmask`/`cselect` reads (`analyze.rs:5238-5276, 5546-5558`). | | **#9** `[P1]` (`#354` opacity polarity `st.reach`) | **RESOLVED** | `commit_conds` carries `(st.reach[search_blk], st.guards[search_blk][ci], extra)` into `q_true`/`q_false` (`analyze.rs:2897-3065`). | | **#10** `[P1]` (`#354` Pattern A `invalid` break) | **RESOLVED** | Early `break`s removed (`analyze.rs:3294-3316`), so inconsistent merge PHIs reliably return `Err`. | | **#11** `[P2]` (`#354` 4 helper edge cases) | **RESOLVED** | Duplicate counter PHI guarded (`emit_rq.rs:374`), `Atom::Uniform` added to `bool_dominates_cb_commit` (`analyze.rs:3209`), heap TLAS dead-site check uses `plan.is_eliminated` (`analyze.rs:437-441`), `seen.len() > 128` returns `None` (`analyze.rs:5456`), and `extract_callback_region` requires `saved_exec.is_some()` (`analyze.rs:4524-4531`). | --- ### Blocking & Remaining Findings on `#357` #### 1. `[P0]` `#357` — Ungated `HostList::shadow_to` / `shadows_common` Breaks `VICTORY_HW_RT=0` Zero-Impact & Causes D3D12 State Mismatches Across Untracked `Shadow::buffer` Accesses - **Locations:** - `crates/victory-gpu/src/host/place.rs:231, 237, 242, 243, 249, 284, 309-370` (`HostList::shadow_to`, `HostList::shadows_common`) - `crates/victory-gpu/src/draw.rs:2131, 2150, 2596, 5995` - `crates/victory-gpu/src/indirect.rs:539, 541, 644, 652` - `crates/victory-gpu/src/host.rs:9196` (`HostList::close`) - **Failure sequence (impacts BOTH `VICTORY_HW_RT` unset/`0` AND `VICTORY_HW_RT=1`):** 1. **Zero-impact violation when `VICTORY_HW_RT` is unset/`0`:** `shadow_to` and `shadows_common` are not gated on `crate::hwrt::active()`. Every VB bind, IB bind, root UAV bind, indirect clamp/batch, and `place.rs` copy on every frame locks `self.deferred()`, hashes into `shadow_states`, clones `ID3D12Resource`, and emits explicit `ResourceBarrier`s (plus a `shadows_common()` barrier batch at `list.close()`). 2. **Broken D3D12 state tracking across untracked `Shadow::buffer` consumers (on `VICTORY_HW_RT=0` AND `=1`):** Previously, `Shadow::buffer` remained in `D3D12_RESOURCE_STATE_COMMON` (relying on implicit buffer promotion, with explicit copy paths like `texture.rs:463-475` and `card_steps.rs:2528` returning to `COMMON` immediately). Because descriptor-table SRVs/CBVs/UAVs (`HostHeap`), root SRVs/CBVs (`draw.rs:2376-2489`), `texture.rs:463-475`, and `list.rs` copies do **not** call `shadow_to`: - **`place.rs` `COPY_DEST` trap (`place.rs:237, 243, 249`):** Any placed copy transitions `to.buffer` to `COPY_DEST` and leaves it stuck there until `list.close()`. Any subsequent shader SRV/CBV/UAV (table or root) on `to.buffer` accesses a resource explicitly in `COPY_DEST` (D3D12 error / stale GPU reads), and `texture.rs:463` (`COMMON -> COPY_DEST`) hits `RESOURCE_BARRIER_BEFORE_AFTER_MISMATCH`. - **`draw.rs:2596` `UNORDERED_ACCESS` trap:** `bind_root_uav` leaves `s.buffer` in `UNORDERED_ACCESS` until `list.close()`; subsequent descriptor-table SRVs/CBVs, root SRVs/CBVs, or `texture.rs:463` read a buffer explicitly locked in `UNORDERED_ACCESS` without a barrier. - **`draw.rs` / `indirect.rs` `GENERIC_READ` trap:** VB/IB/indirect bindings leave `s.buffer` in `GENERIC_READ` (disabling implicit promotion from `COMMON`), so any subsequent descriptor-table UAV write hits a resource explicitly locked in `GENERIC_READ`. - **Minimal fix:** - **Revert all `shadow_to` / `shadows_common` hooks in `draw.rs`, `host/place.rs`, `indirect.rs`, and `host.rs:9196`** so `Shadow::buffer` stays in `COMMON` outside `hwrt` and `VICTORY_HW_RT=0`/unset has **strictly zero behavioral or performance impact**. - Inside `hwrt.rs` (`hwrt::active()` only), eliminate legacy `COPY_DEST` barriers on `sh.buffer` in `emit_postbuild` (`hwrt.rs:2699-2736`) by writing the 8–16 byte postbuild result into `sh.buffer` via a tiny 1-thread compute shader (`SetComputeRootUnorderedAccessView` on `sh.gpu(dest_va)` + plain `UAV` barrier — `Shadow::buffer` always has `ALLOW_UNORDERED_ACCESS` and works cleanly from `COMMON`/implicit promotion with zero `BEFORE_AFTER` mismatch against prior draws), or via Enhanced Barriers (`ID3D12GraphicsCommandList7::Barrier` `D3D12_GLOBAL_BARRIER`) where supported. #### 2. `[P2]` `#357` (inherited from `#354`) — `collect_rq_needed_vals` Does Not Seed From `self.read_phis` - **Location:** `crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:1126-1198` (`collect_rq_needed_vals`), `emit_rq.rs:503-552` (`cb_data_phis`). - **Failure sequence:** `Lower::fill_phis`'s transitive `read_phis` closure (`lower.rs:14018-14032`) has not run yet when `emit_ray_query` resolves `cb_data_phis`. Inside a multi-block `CallbackKind::Blocks` callback, if PHI `P2` (taking a lazy `self.params` arm) feeds only PHI `P1`, and `P1` is read only by an instruction (not directly via PHIs into `acc.next_val` / `commit_decision`), `self.read_phis` contains `P1` but not `P2`, so `P2` has `needed == false` and silently zeroes its lazy `self.params` arm at `emit_rq.rs:551`. - **Minimal fix:** Seed `collect_rq_needed_vals`'s `work` queue with all `phi.value` in `cb_set`/`merge_block` where `self.read_phis.contains(&phi.value)` so PHI-to-PHI chains inside callbacks propagate transitively. --- ### Target 2 — PR `#331` (`100015c0`) Verification of Pass #1 Finding `#12` - **Status:** **VERIFIED CLEAN (Green Light)** - **Verification:** - `crates/victory-gpu/src/listcpu.rs:204-377` (`Held`, `HELD`, `ReadMostly::reading`, `Drop for ReadGuard`): re-entrant `read()` / `try_read()` on the same `ReadMostly` (`h.of == me`) increments `h.guards` in TLS `HELD` and returns `ReadGuard { own: None, ... }` without re-acquiring any Windows `SRWLOCK`, eliminating self-deadlock behind waiting writers (even when `sharded()` flips via `VICTORY_AB`). - `ReadGuard<'a, T>` contains `Option<RwLockReadGuard<'a, ()>>`, keeping it `!Send`; dropping guards in any order decrements `h.guards` and releases `_lock` outside the `RefCell` borrow only when `h.guards == 0`. TLS-teardown / ID-collision paths safely fall back to `own: Some(lock)`. - `write()` and `try_write()` acquire `locks[0..=SHARDS]` in strict ascending order; production `ReadMostly` IDs are disjoint (`0 = VIEWS`, `1 = BUFFERS`, `2 = LOOSE`). - `VICTORY_PLACED_SEEN` (`resource.rs:607-624`): verified `PLACED_TEXTURES` is strictly append-only across `victory-gpu` (no `.remove()`/`.clear()`), so thread-local `Remembered` entries cannot dangle.
Androtim commented 2026-12-02 23:54:27 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-02T23:54:27Z.


Deep Static Logic Audit — Pass #5


Target 1: Final Merge Sign-Off on PR #357 (feat/hw-rt-phase3-gpu-dispatch-binding @ 5d0eedb)

Audit covers d065fff, 65e3d13, e680116, and merge commits 5a50f8f, 4f07a71, 344b0c1, 7cc5837, 5d0eedb against origin/main (5bfc066). Both remaining items from Pass #4 (#282 comment 7359964895) are resolved cleanly:

  1. [VERIFIED FIXED — Pass #4 [P0]] Revert shadow_to/shadows_common hooks & compute-UAV emit_postbuild (d065fff):

    • Zero non-RT impact (VICTORY_HW_RT=0 / unset): Repo-wide search for shadow_to, shadows_common, and shadow_states returns 0 matches. crates/victory-gpu/src/host/place.rs and crates/victory-gpu/src/indirect.rs have zero diff against origin/main, and non-RT paths in draw.rs / host.rs carry zero extra shadow-state tracking (hwrt::requested() -> false, manager() -> None).
    • Compute root signature & PSO (crates/victory-gpu/src/hwrt.rs:559-573, crates/victory-gpu/src/hwrt/sanitize.rs:461-484): HwRtManager::new compiles POSTBUILD_HLSL (write_postbuild, [numthreads(1, 1, 1)], cs_5_1) via host::compile (crates/victory-gpu/src/host.rs:2080-2124) with embedded root signature "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)".
    • Alignment, offset math, barriers & state replay (crates/victory-gpu/src/hwrt.rs:2657-2737): Gated inside HwRtManager (hwrt::active()). Filters zero / non-4-byte-aligned dst_gpu, calls sh.refresh, sh.gpu_writes, and list.keep(&sh.buffer), passes params[2] = (dst_gpu & 15) as u32 (dst_bias) and binds dst_aligned = dst_gpu & !15 (16-byte-aligned VA for raw RWByteAddressBuffer u0, with mode = 0 for inline u64 size or mode = dwords reading u1 after EmitRaytracingAccelerationStructurePostbuildInfo). Surrounds Dispatch(1, 1, 1) with uav_barrier and sets *bound = true, triggering state.replay(host) (crates/victory-gpu/src/list.rs:211-217, crates/victory-gpu/src/draw.rs:1825-1829) to restore title pipeline/root/heap bindings.
    • Post-merge [P2] hardening note (non-blocking): Unlike root_uav (crates/victory-gpu/src/draw.rs:2581-2586), emit_postbuild (crates/victory-gpu/src/hwrt.rs:2699-2703) does not check D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS on sh.buffer before SetComputeRootUnorderedAccessView(1, dst_aligned) (relevant only if a postbuild destination ever lands in a wc_mapped_for(size, false) non-UAV shadow via crates/victory-gpu/src/shadow.rs:7036-7039).
  2. [VERIFIED FIXED — Pass #4 [P2]] Transitive PHI-chain seeding in collect_rq_needed_vals (65e3d13, e680116):

    • collect_rq_needed_vals (crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:1191-1193) now seeds its backward work queue from self.read_phis across cb_set and merge_block.
    • resolve_rq_phi_arm (crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:1232-1236) inserts referenced phi_at PHI arguments into self.read_phis, ensuring outer header_block PHIs in data_phis are retained before Lower::fill_phis (crates/victory-shader/src/emit/lower.rs:14551).
    • e680116 (crates/victory-shader/src/emit/lower_tests.rs:2209) only populates ray_queries in the test HostShader initializer; --cc inspection of merge 7cc5837 shows zero conflict skew in victory-shader.

Target 1 Verdict: GREEN LIGHT — #357 (5d0eedb) is verified clean to merge behind VICTORY_HW_RT=1.


Target 2: .09 -> .12 Regression Sweep (8ff2a82..5bfc066) & fix/thin-hostlist-leak

Audited all 9 commits between v2026.12.02.09 (8ff2a82) and v2026.12.02.12 (5bfc066) (#363, #365, #360, #366, #368, #356, #341, #343, #331), prior .09-era shader/HLE changes (#329, #332, #346, #358), and the fix/thin-hostlist-leak branch diff:

1. Memory / Commit / VRAM Leaks

  • [P0] .12 Runaway ~100 MB/s private_commit Leak (persists with VICTORY_SWEEP_ASYNC=0) — list/thin.rs BACKS overflow -> release_boxed no-op:
    • back_list() (crates/victory-gpu/src/list/thin.rs:659-668) creates backing List objects via Box::into_raw, leaving Object.refs == 0.
    • Once BACKS.len() >= BACKS_CAP (256), Recording::drop (crates/victory-gpu/src/list/thin.rs:620-625) calls crate::object::release_boxed::<List>(inner.back as This). release_boxed (crates/victory-gpu/src/object.rs:146-167) uses refs.fetch_update(..., |n| n.checked_sub(1)), which sees 0, returns Err(()) => 0, and never frees the Box<List>.
    • Because detach / detach_parts (crates/victory-gpu/src/list.rs:637, 712) replaces back.host with a fresh_list() HostList, every leaked Box<List> retains a live HostList (command allocator, command list, and lazily attached scratch/budget/UAV buffers).
  • fix/thin-hostlist-leak Branch Verification — SOUND & RACE-FREE:
    • crates/victory-gpu/src/list/thin.rs:430-439, 572-631: Adds Recording::return_back(), reclaim_back() (Box::from_raw, returning boxed.host and boxed.earlier via list::return_idle_host), and recycle_back() (BACKS_CAP = 512). Recording::return_back atomically detaches inner.back under the inner mutex (std::mem::replace(&mut inner.back, 0) only if inner.closed && inner.back != 0), making concurrent/duplicate calls idempotent and disjoint from Recording::drop.
    • crates/victory-gpu/src/queue/behind.rs:586-590: Job::unfold calls r.return_back() immediately after jobs_of(queue, &lists), releasing back instead of keeping HostLists pinned until the next List::Reset.
    • crates/victory-gpu/src/list.rs:430-469, 835: return_idle_host calls host.reset() and returns the HostList to IDLE up to idle_most() / IDLE_MOST.1 (256 MiB); boxed(thin=false) draws warm lists from fresh_list().
    • [P2] minor notes on fix/thin-hostlist-leak:
      1. Because detach/detach_parts leaves a fresh HostList in back.host, up to BACKS_CAP = 512 backing shells sitting in BACKS still retain up to 512 HostLists outside list::IDLE, invisible to list::trim_on_pressure / list::trim_stale_idle.
      2. If a title were to execute the exact same closed thin command list across two separate ExecuteCommandLists calls without a Reset between them, the second unfold sees r.back() == null after the first return_back() rather than taking detach's empty-run path (list.rs:715).
  • [P0] #363 (VICTORY_SWEEP_ASYNC=1) Dedicated/Shared/Commit Surge (t+3m -> t+5m) & 858 ms list::thin CPU:
    • Starved BelowNormal workers + unbounded GRAVE channel: Both victory-sweep (crates/victory-gpu/src/host/sweep.rs:46-52) and victory-graveyard (crates/victory-gpu/src/host.rs:812-844) run at THREAD_PRIORITY_BELOW_NORMAL. Once BACKS overflow pushes commit into pagefile thrash under ~25–35 NORMAL/ABOVE_NORMAL worker threads, trigger_sweep() stamps LAST = now before waking the worker (sweep.rs:28-36, 80-86), coalescing missed sweeps into a single pending flag, while graveyard() queues retired Shadows / HostTextures / ID3D12Resources / allocators into an unbounded mpsc::channel() (host.rs:816). Retired objects accumulate unreleased in GRAVE even while shadow::LOOSE (host copies) and pool::TEXTURES (texture blocks) already dropped them from active tracking. (By contrast, drop_aside at host.rs:3268-3294 uses a bounded sync_channel at NORMAL priority with inline fallback.)
    • Removed 1500 ms settle + concurrent LOOSE.write() lock contention (#363 + #331): When sweep_async_on() is true, Host::submit (crates/victory-gpu/src/host.rs:8320-8341) skips the periodic 1500 ms self.settle(&mut submitted, WHY_SYNC) (25-30 flights in air with 0.0 settles) and runs sweep_once() concurrently with the 8 victory-list-* translation threads. In .12, shadow::let_go_idle() (crates/victory-gpu/src/shadow.rs:4273) acquires LOOSE.write() — locking all 17 RwLock shards (0..=WHOLE) in ReadMostly (crates/victory-gpu/src/listcpu.rs) while iterating windows and calling host::references — stalling all victory-list-* readers (list::thin wall time climbing to 857.9 ms).
  • (Verified clean across remaining .09 -> .12 commits: #360 screenshot::Pending::drop decrements IN_FLIGHT and drops readback staging before PNG encoding; #331 Remembered is fixed-size; #365 staged_cbv_batch uses one static heap and MappedPages reuses a per-thread set.)

2. Broken / Missing Audio Regression

  • [P1] Priority inversion & CPU oversubscription (audio.rs, #368 land.rs, #329 title_free.rs):
    • victory XMA decoder (crates/victory-hle/src/modules/audio.rs:762-776) runs at default THREAD_PRIORITY_NORMAL pumping XMA rings every 2 ms. Meanwhile, every land::Pool thread (crates/victory-gpu/src/land.rs:240-257 -> cores::Priority::new() at cores.rs:147-159) as well as victory-wide (shadow.rs:2299-2301), victory-submit (queue/behind.rs:971), victory-host-submit (host.rs:4550), and victory-aside (host/aside.rs:72) runs at THREAD_PRIORITY_ABOVE_NORMAL, strictly preempting victory XMA decoder under load.
    • #368 spawned victory-wide-sub (crates/victory-gpu/src/land.rs:387-397, (cpus / 4).clamp(4, 8) additional ABOVE_NORMAL helper threads!) and lowered parallelism thresholds (FEW: 256 -> 32, wide_refresh >= 2 at host.rs:11774, 11975, 12002; LONG: 1 MiB -> 256 KiB, PART: 256 -> 128 KiB at shadow.rs:5793-5794), waking high-priority pools far more often.
    • #329 (crates/victory-hle/src/modules/title_free.rs:94-121, 170-200, landed at .09) unpins all affinitized title threads (SetThreadAffinityMask / SetThreadGroupAffinity) to the full process mask and forces SetProcessPriorityBoost(process, 0) (re-enabling dynamic priority boost), throwing the title's audio mixer thread (4 ms cadence per crates/victory-hle/src/runtime.rs:233-234) into the shared normal-priority contention pool underneath ~25+ ABOVE_NORMAL GPU workers — matching .09 minor crunching degrading into .12 total audio dropout once #368 + pagefile thrash landed. (Note also crates/victory-hle/src/modules/kernel.rs:435: when VICTORY_STARTUP_PRIORITIES is set, title asks 1..=15 remain capped at NORMAL for the entire run.)

3. Excessive Night Starburst Lens-Flare / Bloom Glare

  • [P1] Unsound finite_data rules in #346 (VICTORY_LEGACY_MUL=data, default) — 0.0 * Inf -> NaN (crates/victory-shader/src/emit/bitcode/finite.rs:50-65, crates/victory-shader/src/emit/lower.rs:5182-5196):
    • Module::finite_data (finite.rs:51-60) classifies Op::Extract(..), Op::Cast(Cast::Bitcast, i32 -> f32) (type_of(x) != type_of(v)), and LegacyF16ToF32 (131) as unconditionally finite, and ignores FP overflow in Add/Sub/Mul/FMa/FMad.
    • In DXIL, every texture sample/load, buffer load, and CBV load returns a struct read via Op::Extract. HDR light targets (FP16 max 65504 / R11G11B10F max 65024) from bright lights routinely carry +Inf (or LegacyF16ToF32 unpacks 0x7C00/0x7E00).
    • legacy_mul (lower.rs:5182-5196) elides the 0 * anything = 0 select guard whenever both factors report finite_data == true. In HDR bloom / starburst glare kernels, 0.0 * (+Inf) flips from 0.0 to NaN; notably clamp_hdr() (crates/victory-shader/src/emit/hdr.rs:132-143, lower.rs:14202, 14209) only runs on pixel shader color exports (not compute UAV bloom/starburst/adaptation passes), and compose.rs:30 (clean1, default VICTORY_COMPOSE_NAN=1) converts surviving NaNs into 1.0 full-bright white.
    • [P2] Cache key omission: crates/victory-gpu/src/shader_cache.rs:84-111 omits "VICTORY_LEGACY_MUL", so toggling VICTORY_LEGACY_MUL=0 without clearing the shader cache serves stale data-mode cached binaries.
  • [P2] Secondary compute-drop check (#358, crates/victory-shader/src/emit/lower.rs:2996): #358 changed if self.pairs.is_some() && self.s.lds_dwords > HOST_LDS_DWORDS to reject any shader with self.s.lds_dwords > 8192 (Err("LDS past the host's 32 KiB")). Worth checking .12 logs for "dropped ... without a host pipeline" / "LDS past the host's 32 KiB" to rule out dropped eye-adaptation / bloom compute passes alongside an A/B test of VICTORY_LEGACY_MUL=0 (with cleared shader cache) + VICTORY_COMPOSE_NAN=0.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7362568946 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7362568946). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-02T23:54:27Z. --- ## Deep Static Logic Audit — Pass #5 --- ### Target 1: Final Merge Sign-Off on PR `#357` (`feat/hw-rt-phase3-gpu-dispatch-binding` @ `5d0eedb`) Audit covers `d065fff`, `65e3d13`, `e680116`, and merge commits `5a50f8f`, `4f07a71`, `344b0c1`, `7cc5837`, `5d0eedb` against `origin/main` (`5bfc066`). Both remaining items from Pass #4 (`#282` comment `7359964895`) are resolved cleanly: 1. **[VERIFIED FIXED — Pass #4 `[P0]`] Revert `shadow_to`/`shadows_common` hooks & compute-UAV `emit_postbuild` (`d065fff`):** - **Zero non-RT impact (`VICTORY_HW_RT=0` / unset):** Repo-wide search for `shadow_to`, `shadows_common`, and `shadow_states` returns 0 matches. `crates/victory-gpu/src/host/place.rs` and `crates/victory-gpu/src/indirect.rs` have zero diff against `origin/main`, and non-RT paths in `draw.rs` / `host.rs` carry zero extra shadow-state tracking (`hwrt::requested()` -> `false`, `manager()` -> `None`). - **Compute root signature & PSO (`crates/victory-gpu/src/hwrt.rs:559-573`, `crates/victory-gpu/src/hwrt/sanitize.rs:461-484`):** `HwRtManager::new` compiles `POSTBUILD_HLSL` (`write_postbuild`, `[numthreads(1, 1, 1)]`, `cs_5_1`) via `host::compile` (`crates/victory-gpu/src/host.rs:2080-2124`) with embedded root signature `"RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)"`. - **Alignment, offset math, barriers & state replay (`crates/victory-gpu/src/hwrt.rs:2657-2737`):** Gated inside `HwRtManager` (`hwrt::active()`). Filters zero / non-4-byte-aligned `dst_gpu`, calls `sh.refresh`, `sh.gpu_writes`, and `list.keep(&sh.buffer)`, passes `params[2] = (dst_gpu & 15) as u32` (`dst_bias`) and binds `dst_aligned = dst_gpu & !15` (`16`-byte-aligned VA for raw `RWByteAddressBuffer` `u0`, with `mode = 0` for inline `u64` size or `mode = dwords` reading `u1` after `EmitRaytracingAccelerationStructurePostbuildInfo`). Surrounds `Dispatch(1, 1, 1)` with `uav_barrier` and sets `*bound = true`, triggering `state.replay(host)` (`crates/victory-gpu/src/list.rs:211-217`, `crates/victory-gpu/src/draw.rs:1825-1829`) to restore title pipeline/root/heap bindings. - **Post-merge `[P2]` hardening note (non-blocking):** Unlike `root_uav` (`crates/victory-gpu/src/draw.rs:2581-2586`), `emit_postbuild` (`crates/victory-gpu/src/hwrt.rs:2699-2703`) does not check `D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS` on `sh.buffer` before `SetComputeRootUnorderedAccessView(1, dst_aligned)` (relevant only if a postbuild destination ever lands in a `wc_mapped_for(size, false)` non-UAV shadow via `crates/victory-gpu/src/shadow.rs:7036-7039`). 2. **[VERIFIED FIXED — Pass #4 `[P2]`] Transitive PHI-chain seeding in `collect_rq_needed_vals` (`65e3d13`, `e680116`):** - `collect_rq_needed_vals` (`crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:1191-1193`) now seeds its backward work queue from `self.read_phis` across `cb_set` and `merge_block`. - `resolve_rq_phi_arm` (`crates/victory-shader/src/emit/lower/rayquery/emit_rq.rs:1232-1236`) inserts referenced `phi_at` PHI arguments into `self.read_phis`, ensuring outer `header_block` PHIs in `data_phis` are retained before `Lower::fill_phis` (`crates/victory-shader/src/emit/lower.rs:14551`). - `e680116` (`crates/victory-shader/src/emit/lower_tests.rs:2209`) only populates `ray_queries` in the test `HostShader` initializer; `--cc` inspection of merge `7cc5837` shows zero conflict skew in `victory-shader`. **Target 1 Verdict: GREEN LIGHT — `#357` (`5d0eedb`) is verified clean to merge behind `VICTORY_HW_RT=1`.** --- ### Target 2: `.09 -> .12` Regression Sweep (`8ff2a82..5bfc066`) & `fix/thin-hostlist-leak` Audited all 9 commits between `v2026.12.02.09` (`8ff2a82`) and `v2026.12.02.12` (`5bfc066`) (`#363`, `#365`, `#360`, `#366`, `#368`, `#356`, `#341`, `#343`, `#331`), prior `.09`-era shader/HLE changes (`#329`, `#332`, `#346`, `#358`), and the `fix/thin-hostlist-leak` branch diff: #### 1. Memory / Commit / VRAM Leaks - **`[P0]` `.12` Runaway ~100 MB/s `private_commit` Leak (persists with `VICTORY_SWEEP_ASYNC=0`) — `list/thin.rs` `BACKS` overflow -> `release_boxed` no-op:** - `back_list()` (`crates/victory-gpu/src/list/thin.rs:659-668`) creates backing `List` objects via `Box::into_raw`, leaving `Object.refs == 0`. - Once `BACKS.len() >= BACKS_CAP` (`256`), `Recording::drop` (`crates/victory-gpu/src/list/thin.rs:620-625`) calls `crate::object::release_boxed::<List>(inner.back as This)`. `release_boxed` (`crates/victory-gpu/src/object.rs:146-167`) uses `refs.fetch_update(..., |n| n.checked_sub(1))`, which sees `0`, returns `Err(()) => 0`, and never frees the `Box<List>`. - Because `detach` / `detach_parts` (`crates/victory-gpu/src/list.rs:637, 712`) replaces `back.host` with a `fresh_list()` `HostList`, every leaked `Box<List>` retains a live `HostList` (command allocator, command list, and lazily attached scratch/budget/UAV buffers). - **`fix/thin-hostlist-leak` Branch Verification — SOUND & RACE-FREE:** - `crates/victory-gpu/src/list/thin.rs:430-439, 572-631`: Adds `Recording::return_back()`, `reclaim_back()` (`Box::from_raw`, returning `boxed.host` and `boxed.earlier` via `list::return_idle_host`), and `recycle_back()` (`BACKS_CAP = 512`). `Recording::return_back` atomically detaches `inner.back` under the `inner` mutex (`std::mem::replace(&mut inner.back, 0)` only if `inner.closed && inner.back != 0`), making concurrent/duplicate calls idempotent and disjoint from `Recording::drop`. - `crates/victory-gpu/src/queue/behind.rs:586-590`: `Job::unfold` calls `r.return_back()` immediately after `jobs_of(queue, &lists)`, releasing `back` instead of keeping `HostList`s pinned until the next `List::Reset`. - `crates/victory-gpu/src/list.rs:430-469, 835`: `return_idle_host` calls `host.reset()` and returns the `HostList` to `IDLE` up to `idle_most()` / `IDLE_MOST.1` (`256 MiB`); `boxed(thin=false)` draws warm lists from `fresh_list()`. - **`[P2]` minor notes on `fix/thin-hostlist-leak`:** 1. Because `detach`/`detach_parts` leaves a fresh `HostList` in `back.host`, up to `BACKS_CAP = 512` backing shells sitting in `BACKS` still retain up to `512` `HostList`s outside `list::IDLE`, invisible to `list::trim_on_pressure` / `list::trim_stale_idle`. 2. If a title were to execute the exact same closed thin command list across two separate `ExecuteCommandLists` calls without a `Reset` between them, the second `unfold` sees `r.back() == null` after the first `return_back()` rather than taking `detach`'s empty-run path (`list.rs:715`). - **`[P0]` `#363` (`VICTORY_SWEEP_ASYNC=1`) Dedicated/Shared/Commit Surge (`t+3m -> t+5m`) & `858 ms` `list::thin` CPU:** - **Starved `BelowNormal` workers + unbounded `GRAVE` channel:** Both `victory-sweep` (`crates/victory-gpu/src/host/sweep.rs:46-52`) and `victory-graveyard` (`crates/victory-gpu/src/host.rs:812-844`) run at `THREAD_PRIORITY_BELOW_NORMAL`. Once `BACKS` overflow pushes commit into pagefile thrash under ~25–35 `NORMAL`/`ABOVE_NORMAL` worker threads, `trigger_sweep()` stamps `LAST = now` **before** waking the worker (`sweep.rs:28-36, 80-86`), coalescing missed sweeps into a single `pending` flag, while `graveyard()` queues retired `Shadow`s / `HostTexture`s / `ID3D12Resource`s / allocators into an **unbounded** `mpsc::channel()` (`host.rs:816`). Retired objects accumulate unreleased in `GRAVE` even while `shadow::LOOSE` (`host copies`) and `pool::TEXTURES` (`texture blocks`) already dropped them from active tracking. (By contrast, `drop_aside` at `host.rs:3268-3294` uses a bounded `sync_channel` at `NORMAL` priority with inline fallback.) - **Removed `1500 ms` settle + concurrent `LOOSE.write()` lock contention (`#363` + `#331`):** When `sweep_async_on()` is true, `Host::submit` (`crates/victory-gpu/src/host.rs:8320-8341`) skips the periodic `1500 ms` `self.settle(&mut submitted, WHY_SYNC)` (`25-30` flights in air with `0.0` settles) and runs `sweep_once()` concurrently with the `8` `victory-list-*` translation threads. In `.12`, `shadow::let_go_idle()` (`crates/victory-gpu/src/shadow.rs:4273`) acquires `LOOSE.write()` — locking all `17` `RwLock` shards (`0..=WHOLE`) in `ReadMostly` (`crates/victory-gpu/src/listcpu.rs`) while iterating windows and calling `host::references` — stalling all `victory-list-*` readers (`list::thin` wall time climbing to `857.9 ms`). - *(Verified clean across remaining `.09 -> .12` commits: `#360` `screenshot::Pending::drop` decrements `IN_FLIGHT` and drops readback staging before PNG encoding; `#331` `Remembered` is fixed-size; `#365` `staged_cbv_batch` uses one static heap and `MappedPages` reuses a per-thread set.)* #### 2. Broken / Missing Audio Regression - **`[P1]` Priority inversion & CPU oversubscription (`audio.rs`, `#368` `land.rs`, `#329` `title_free.rs`):** - `victory XMA decoder` (`crates/victory-hle/src/modules/audio.rs:762-776`) runs at default **`THREAD_PRIORITY_NORMAL`** pumping XMA rings every `2 ms`. Meanwhile, **every** `land::Pool` thread (`crates/victory-gpu/src/land.rs:240-257` -> `cores::Priority::new()` at `cores.rs:147-159`) as well as `victory-wide` (`shadow.rs:2299-2301`), `victory-submit` (`queue/behind.rs:971`), `victory-host-submit` (`host.rs:4550`), and `victory-aside` (`host/aside.rs:72`) runs at **`THREAD_PRIORITY_ABOVE_NORMAL`**, strictly preempting `victory XMA decoder` under load. - `#368` spawned **`victory-wide-sub`** (`crates/victory-gpu/src/land.rs:387-397`, `(cpus / 4).clamp(4, 8)` additional `ABOVE_NORMAL` helper threads!) and lowered parallelism thresholds (`FEW: 256 -> 32`, `wide_refresh >= 2` at `host.rs:11774, 11975, 12002`; `LONG: 1 MiB -> 256 KiB`, `PART: 256 -> 128 KiB` at `shadow.rs:5793-5794`), waking high-priority pools far more often. - `#329` (`crates/victory-hle/src/modules/title_free.rs:94-121, 170-200`, landed at `.09`) unpins all affinitized title threads (`SetThreadAffinityMask` / `SetThreadGroupAffinity`) to the full process mask and forces `SetProcessPriorityBoost(process, 0)` (re-enabling dynamic priority boost), throwing the title's audio mixer thread (4 ms cadence per `crates/victory-hle/src/runtime.rs:233-234`) into the shared normal-priority contention pool underneath ~25+ `ABOVE_NORMAL` GPU workers — matching `.09` minor crunching degrading into `.12` total audio dropout once `#368` + pagefile thrash landed. *(Note also `crates/victory-hle/src/modules/kernel.rs:435`: when `VICTORY_STARTUP_PRIORITIES` is set, title asks `1..=15` remain capped at `NORMAL` for the entire run.)* #### 3. Excessive Night Starburst Lens-Flare / Bloom Glare - **`[P1]` Unsound `finite_data` rules in `#346` (`VICTORY_LEGACY_MUL=data`, default) — `0.0 * Inf -> NaN` (`crates/victory-shader/src/emit/bitcode/finite.rs:50-65`, `crates/victory-shader/src/emit/lower.rs:5182-5196`):** - `Module::finite_data` (`finite.rs:51-60`) classifies `Op::Extract(..)`, `Op::Cast(Cast::Bitcast, i32 -> f32)` (`type_of(x) != type_of(v)`), and `LegacyF16ToF32` (`131`) as **unconditionally finite**, and ignores FP overflow in `Add`/`Sub`/`Mul`/`FMa`/`FMad`. - In DXIL, **every** texture sample/load, buffer load, and CBV load returns a struct read via `Op::Extract`. HDR light targets (FP16 max `65504` / `R11G11B10F` max `65024`) from bright lights routinely carry `+Inf` (or `LegacyF16ToF32` unpacks `0x7C00`/`0x7E00`). - `legacy_mul` (`lower.rs:5182-5196`) elides the `0 * anything = 0` select guard whenever both factors report `finite_data == true`. In HDR bloom / starburst glare kernels, `0.0 * (+Inf)` flips from **`0.0`** to **`NaN`**; notably `clamp_hdr()` (`crates/victory-shader/src/emit/hdr.rs:132-143`, `lower.rs:14202, 14209`) only runs on **pixel shader** color exports (not compute UAV bloom/starburst/adaptation passes), and `compose.rs:30` (`clean1`, default `VICTORY_COMPOSE_NAN=1`) converts surviving `NaN`s into `1.0` full-bright white. - **`[P2]` Cache key omission:** `crates/victory-gpu/src/shader_cache.rs:84-111` omits `"VICTORY_LEGACY_MUL"`, so toggling `VICTORY_LEGACY_MUL=0` without clearing the shader cache serves stale `data`-mode cached binaries. - **`[P2]` Secondary compute-drop check (`#358`, `crates/victory-shader/src/emit/lower.rs:2996`):** `#358` changed `if self.pairs.is_some() && self.s.lds_dwords > HOST_LDS_DWORDS` to reject any shader with `self.s.lds_dwords > 8192` (`Err("LDS past the host's 32 KiB")`). Worth checking `.12` logs for `"dropped ... without a host pipeline"` / `"LDS past the host's 32 KiB"` to rule out dropped eye-adaptation / bloom compute passes alongside an A/B test of `VICTORY_LEGACY_MUL=0` (with cleared shader cache) + `VICTORY_COMPOSE_NAN=0`.
Androtim commented 2026-12-03 04:27:07 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T04:27:07Z.


Deep Static Logic Audit — Pass #6 (Androtim/MiniVI#372 @ 90086b60)

Strictly read-only audit of PR #372 (fix/p0-visuals-cache-and-vram, CI check = SUCCESS).

Pass #6 Verdict Table

Area Files Verified Verdict Summary
Overall PR #372 90086b60 VERIFIED CLEAN (Green Light) 0 [P0], 0 [P1] blockers; 3 minor non-blocking [P2] hardening notes below.
1. Shader Cache & Build Tracking crates/victory-gpu/build.rs:7-49, crates/victory-gpu/src/shader_cache.rs:204-212 VERIFIED CLEAN SHADER_CACHE_VERSION = 2 feeds into Translate::version() and CacheKey::new (crates/victory-pipeline/src/cache.rs:17-24), strictly invalidating all v1 disk entries. build.rs emits cargo:rerun-if-changed recursively for all subdirectories under crates/victory-shader/src, strips \r, and hashes sorted paths deterministically across CI/release checkouts. VICTORY_HW_RT=0 / unset stays unaffected (hwrt::requested() is false, normalize_env_value leaves VICTORY_BVH_BUILDER unchanged).
2. Compositor NaN/Inf Scrubbing crates/victory-gpu/src/compose.rs:29-45, 362-442 VERIFIED CLEAN Bit-level clean1() ((asuint(x) & 0x7FFFFFFFu) > 0x7F800000u ? 0.0 : saturate(x)) flushes NaN to 0.0 (avoiding white blocks/blank white frames), keeps +Inf -> 1.0 and -Inf -> 0.0, preserves [0.0, 1.0] identically (no black crush), and compiles cleanly via D3DCompile (vs_5_1 / ps_5_1 DXBC with [RootSignature(RS)]). Pre-blend clean(o.rgb) / clean(s.rgb) / clean1(o.a) eliminates +Inf * 0 = NaN behind opaque overlays; Composer targets DXGI_FORMAT_R8G8B8A8_UNORM only (crates/victory-gpu/src/host.rs:13149-13150), so saturate causes no unintended HDR clipping.
3. Wave64 Compute / PostDom / vcc_unknown_exec crates/victory-shader/src/emit/lower.rs:614-891, 2188-2240, 5855-5874, crates/victory-shader/src/structure.rs:484-486, 741-785, 970 VERIFIED CLEAN Cooper-Harvey-Kennedy PostDom + Euler tin/tout + RegionWalker match the prior O(N^2 * W) bitset semantics (including dead-end loops where tin[node] == u32::MAX) and uniform_scalars !cleared[b] (lower.rs:876) is exact for loops = true, eliminating the compute compile hang. Gating lds_wave (:2192) and non-waterfall v_readfirstlane_b32 (:2206) on host_wave >= 64 (plus !lds_wave || group <= 32 at :2237) preserves RDNA 4 [WaveSize(64)] and Wave32 single-wave LDS while letting multi-wave 32 KiB LDS shaders lower on NVIDIA via waveReadLaneFirst without split_lds/pairs overflow or WaveSize(64) rejections. Forward-predecessor matching EXEC + vcc_unknown_exec eliminates false MASK_ELSEWHERE across scalar joins (s_cbranch_scc1) while keeping back-edge/join divergence guarded.
4. 8 GB Small-Card VRAM Headroom crates/victory-gpu/src/host.rs:1229-1267, 13706-13765, crates/victory-gpu/src/host/panel.rs:292, 462, crates/victory-gpu/src/host/telemetry.rs:128, apps/victory/src/play.rs:425-446, 464-473 VERIFIED CLEAN planned_budget() reserves 640 MiB (VICTORY_SMALL_CARD_HEADROOM_MB, clamped .min(2048) << 20) when 0 < system <= 7500 MiB (<= 8 GB / 6 GB adapters) with saturating_sub and .max(2048 MiB).min(system) (zero underflow/overflow from < 2 GiB up to 24 GB+). Explicit VICTORY_VRAM_BUDGET_MB and VICTORY_SMALL_CARD_HEADROOM_MB=0 override cleanly; 12 GB, 16 GB, and 24 GB cards (> 7500 MiB / vram_mb > 9216) are completely untouched. play.rs tightens 4K <= 8 GB thresholds (84 / 82 / 74) before applying menu and --set user overrides (:464-473), while panel.rs and telemetry.rs read Host::system_video_memory() so dedicated_mb stays strictly below reported budget_mb.
5. Scheduled Backbuffer Capture crates/victory-gpu/src/host/screenshot.rs:107-167 VERIFIED CLEAN Opt-in VICTORY_SCREENSHOT_AT_S deduplicates positive second thresholds via per-slot AtomicBool::swap(true) (OnceLock initialized when screenshots are enabled); zero overhead when unset.

Root-Cause Confirmation (Visual Regressions)

  • Blank white screen, dropped character shading, and night starburst glare are genuinely addressed end-to-end:
    1. PostDom (lower.rs:614-742) eliminates the worker hang on large compute shaders, and v_readfirstlane_b32 (:2206) + vcc_unknown_exec (structure.rs:486, 741-785, lower.rs:5868) recover the dropped Wave64 compute pipelines (post-process / adaptation / bloom / shading passes).
    2. compose.rs:32, 45 converts any surviving NaN (and prevents +Inf * (1 - 1) = NaN) to 0.0 instead of 1.0 full-bright white.
    3. SHADER_CACHE_VERSION = 2 (shader_cache.rs:204) forces automatic invalidation of stale v1 cached DXIL blobs so both #370 (finite_data / hdr.rs) and #372 codegen fixes take effect immediately without manual cache wipes.

Non-Blocking [P2] Hardening Notes

  1. [P2] structure.rs:741-785 — now propagation across rare non-wide, non-EXEC-modifying per-lane branches: If a block B0 ends in a non-wide per-lane branch that does not update EXEC (e.g., scc_lane s_cbranch_scc0/1) while an earlier vcc remains live across B0 -> B1 without redefining vcc in B1 (!vcc_in_block), now still carries end_exec[B0] into B1, so B1 is placed in neither vcc_outside_exec nor vcc_unknown_exec despite receiving only a subset of B0's lanes. Unlikely in compiler-generated s_and_saveexec/v_cmpx divergence, and easily hardened by carrying end_exec[q] into now only when q exits via Jump, wide, Atom::Uniform, or s_cbranch_exec*.
  2. [P2] host.rs:1229 — SMALL_CARD_BUDGET = 7500 << 20 edge on uncontended 8 GB adapters: If an 8 GB GPU initially reports an uncontended DXGI local budget slightly above 7,500 MiB (prior to DLSS/swapchain allocations), planned_budget() keeps full system until DXGI budget drops <= 7,500 MiB (at which point planned budget steps down by 640 MiB), though play.rs's LOW_VRAM_THRESHOLD_MB = 9216 (DedicatedVideoMemory) still applies the 4K 84% / 82%-74% guards independently.
  3. [P2] Pre-existing cache key omission (crates/victory-gpu/src/shader_cache.rs:42-70): TRANSLATOR_ENV_KEYS omits VICTORY_LDS_FIRST_INIT (crates/victory-shader/src/emit/lower.rs:6595), unrelated to #372's own switches (VICTORY_SMALL_CARD_HEADROOM_MB and VICTORY_SCREENSHOT_AT_S do not affect shader translation).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7367659732 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7367659732). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T04:27:07Z. --- ## Deep Static Logic Audit — Pass #6 (`Androtim/MiniVI#372` @ `90086b60`) Strictly read-only audit of PR `#372` (`fix/p0-visuals-cache-and-vram`, CI `check` = `SUCCESS`). ### Pass #6 Verdict Table | Area | Files Verified | Verdict | Summary | | --- | --- | --- | --- | | **Overall PR `#372`** | `90086b60` | **VERIFIED CLEAN (Green Light)** | **0 `[P0]`**, **0 `[P1]`** blockers; 3 minor non-blocking `[P2]` hardening notes below. | | **1. Shader Cache & Build Tracking** | `crates/victory-gpu/build.rs:7-49`, `crates/victory-gpu/src/shader_cache.rs:204-212` | **VERIFIED CLEAN** | `SHADER_CACHE_VERSION = 2` feeds into `Translate::version()` and `CacheKey::new` (`crates/victory-pipeline/src/cache.rs:17-24`), strictly invalidating all `v1` disk entries. `build.rs` emits `cargo:rerun-if-changed` recursively for all subdirectories under `crates/victory-shader/src`, strips `\r`, and hashes sorted paths deterministically across CI/release checkouts. `VICTORY_HW_RT=0` / unset stays unaffected (`hwrt::requested()` is `false`, `normalize_env_value` leaves `VICTORY_BVH_BUILDER` unchanged). | | **2. Compositor NaN/Inf Scrubbing** | `crates/victory-gpu/src/compose.rs:29-45, 362-442` | **VERIFIED CLEAN** | Bit-level `clean1()` (`(asuint(x) & 0x7FFFFFFFu) > 0x7F800000u ? 0.0 : saturate(x)`) flushes `NaN` to `0.0` (avoiding white blocks/blank white frames), keeps `+Inf -> 1.0` and `-Inf -> 0.0`, preserves `[0.0, 1.0]` identically (no black crush), and compiles cleanly via `D3DCompile` (`vs_5_1` / `ps_5_1` DXBC with `[RootSignature(RS)]`). Pre-blend `clean(o.rgb)` / `clean(s.rgb)` / `clean1(o.a)` eliminates `+Inf * 0 = NaN` behind opaque overlays; `Composer` targets `DXGI_FORMAT_R8G8B8A8_UNORM` only (`crates/victory-gpu/src/host.rs:13149-13150`), so `saturate` causes no unintended HDR clipping. | | **3. Wave64 Compute / `PostDom` / `vcc_unknown_exec`** | `crates/victory-shader/src/emit/lower.rs:614-891, 2188-2240, 5855-5874`, `crates/victory-shader/src/structure.rs:484-486, 741-785, 970` | **VERIFIED CLEAN** | Cooper-Harvey-Kennedy `PostDom` + Euler `tin`/`tout` + `RegionWalker` match the prior `O(N^2 * W)` bitset semantics (including dead-end loops where `tin[node] == u32::MAX`) and `uniform_scalars` `!cleared[b]` (`lower.rs:876`) is exact for `loops = true`, eliminating the compute compile hang. Gating `lds_wave` (`:2192`) and non-waterfall `v_readfirstlane_b32` (`:2206`) on `host_wave >= 64` (plus `!lds_wave \|\| group <= 32` at `:2237`) preserves RDNA 4 `[WaveSize(64)]` and Wave32 single-wave LDS while letting multi-wave 32 KiB LDS shaders lower on NVIDIA via `waveReadLaneFirst` without `split_lds`/`pairs` overflow or `WaveSize(64)` rejections. Forward-predecessor matching `EXEC` + `vcc_unknown_exec` eliminates false `MASK_ELSEWHERE` across scalar joins (`s_cbranch_scc1`) while keeping back-edge/join divergence guarded. | | **4. 8 GB Small-Card VRAM Headroom** | `crates/victory-gpu/src/host.rs:1229-1267, 13706-13765`, `crates/victory-gpu/src/host/panel.rs:292, 462`, `crates/victory-gpu/src/host/telemetry.rs:128`, `apps/victory/src/play.rs:425-446, 464-473` | **VERIFIED CLEAN** | `planned_budget()` reserves `640 MiB` (`VICTORY_SMALL_CARD_HEADROOM_MB`, clamped `.min(2048) << 20`) when `0 < system <= 7500 MiB` (`<= 8 GB` / `6 GB` adapters) with `saturating_sub` and `.max(2048 MiB).min(system)` (zero underflow/overflow from `< 2 GiB` up to `24 GB+`). Explicit `VICTORY_VRAM_BUDGET_MB` and `VICTORY_SMALL_CARD_HEADROOM_MB=0` override cleanly; `12 GB`, `16 GB`, and `24 GB` cards (`> 7500 MiB` / `vram_mb > 9216`) are completely untouched. `play.rs` tightens 4K `<= 8 GB` thresholds (`84` / `82` / `74`) before applying menu and `--set` user overrides (`:464-473`), while `panel.rs` and `telemetry.rs` read `Host::system_video_memory()` so `dedicated_mb` stays strictly below reported `budget_mb`. | | **5. Scheduled Backbuffer Capture** | `crates/victory-gpu/src/host/screenshot.rs:107-167` | **VERIFIED CLEAN** | Opt-in `VICTORY_SCREENSHOT_AT_S` deduplicates positive second thresholds via per-slot `AtomicBool::swap(true)` (`OnceLock` initialized when screenshots are enabled); zero overhead when unset. | --- ### Root-Cause Confirmation (Visual Regressions) - **Blank white screen, dropped character shading, and night starburst glare are genuinely addressed end-to-end:** 1. `PostDom` (`lower.rs:614-742`) eliminates the worker hang on large compute shaders, and `v_readfirstlane_b32` (`:2206`) + `vcc_unknown_exec` (`structure.rs:486, 741-785`, `lower.rs:5868`) recover the dropped Wave64 compute pipelines (post-process / adaptation / bloom / shading passes). 2. `compose.rs:32, 45` converts any surviving `NaN` (and prevents `+Inf * (1 - 1) = NaN`) to `0.0` instead of `1.0` full-bright white. 3. `SHADER_CACHE_VERSION = 2` (`shader_cache.rs:204`) forces automatic invalidation of stale `v1` cached DXIL blobs so both `#370` (`finite_data` / `hdr.rs`) and `#372` codegen fixes take effect immediately without manual cache wipes. --- ### Non-Blocking `[P2]` Hardening Notes 1. **`[P2]` `structure.rs:741-785` — `now` propagation across rare non-`wide`, non-`EXEC`-modifying per-lane branches:** If a block `B0` ends in a non-`wide` per-lane branch that does not update `EXEC` (e.g., `scc_lane` `s_cbranch_scc0/1`) while an earlier `vcc` remains live across `B0 -> B1` without redefining `vcc` in `B1` (`!vcc_in_block`), `now` still carries `end_exec[B0]` into `B1`, so `B1` is placed in neither `vcc_outside_exec` nor `vcc_unknown_exec` despite receiving only a subset of `B0`'s lanes. Unlikely in compiler-generated `s_and_saveexec`/`v_cmpx` divergence, and easily hardened by carrying `end_exec[q]` into `now` only when `q` exits via `Jump`, `wide`, `Atom::Uniform`, or `s_cbranch_exec*`. 2. **`[P2]` `host.rs:1229` — `SMALL_CARD_BUDGET = 7500 << 20` edge on uncontended 8 GB adapters:** If an 8 GB GPU initially reports an uncontended DXGI local budget slightly above `7,500 MiB` (prior to DLSS/swapchain allocations), `planned_budget()` keeps full `system` until DXGI budget drops `<= 7,500 MiB` (at which point planned budget steps down by `640 MiB`), though `play.rs`'s `LOW_VRAM_THRESHOLD_MB = 9216` (`DedicatedVideoMemory`) still applies the 4K `84%` / `82%-74%` guards independently. 3. **`[P2]` Pre-existing cache key omission (`crates/victory-gpu/src/shader_cache.rs:42-70`):** `TRANSLATOR_ENV_KEYS` omits `VICTORY_LDS_FIRST_INIT` (`crates/victory-shader/src/emit/lower.rs:6595`), unrelated to `#372`'s own switches (`VICTORY_SMALL_CARD_HEADROOM_MB` and `VICTORY_SCREENSHOT_AT_S` do not affect shader translation).
Androtim commented 2026-12-03 06:57:28 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T06:57:28Z.


Deep Static Logic Audit — Pass #7 (Androtim/MiniVI#373 @ 373b3ce2)

Strictly read-only audit of PR #373 (feat/p1-reflections-textures-and-hwrt, CI check = SUCCESS).

Pass #7 Verdict Table

Area Files Verified Verdict Summary
Overall PR #373 373b3ce2 NEEDS FIX 0 [P0], 3 [P1] blockers (fold.rs lane/CFG soundness x2; resource.rs waste_only idle_ms thrash); 5 non-blocking [P2] hardening/scope notes below.
1. Reflections Wide-Wave Fold & Cache crates/victory-shader/src/fold.rs, emit/mod.rs:790, 874, emit/lower.rs, crates/victory-gpu/src/shader_cache.rs:47, 205, 652, apps/victory/src/play.rs:116 NEEDS FIX (2 [P1], 2 [P2]) VICTORY_EXACT64=71883e40620a567a+7168dd781ca7efb9 cleanly targets the two temporal-resolve reflection shaders while leaving SSR pre-pass 34992f2b65a789a5 and AMD RDNA 4 Wave64 (host_max_wave() == 32 guard at emit/mod.rs:790) untouched. TRANSLATOR_ENV_KEYS includes "VICTORY_EXACT64" with SHADER_CACHE_VERSION = 2 (no stale DXIL collisions). However, fold.rs has two [P1] soundness bugs (v_writelane_b32 running under EXEC_LO = E.hi, and linear dirty/e_written state across branches/leaders).
2. Texture Stand-In & Submission Order crates/victory-gpu/src/descriptor/host.rs:627-634, 736, 3709-3795, 5374-5422, descriptor.rs:1140-1145, 2107-2118, texture/hoist.rs, texture.rs:1093, 1365, texture/ahead.rs:442-444, host/heap_order.rs, host.rs:8188, 8400-8438, 10297, draw.rs:2788-2817, 3566 VERIFIED CLEAN (1 [P2]) Zero deadlocks (Hoist<T> SeqCst 2-epoch protocol, HELD self-deadlock guard, bounded 50 ms wait_limit(), open_detached Drop cleanup), zero permanently stuck slots (UPLOAD_GIVE_UP = 600 submissions, UPLOAD_WAITS_MOST = 20_000, late = Some(frame), uploaded_in stamped across prelude/hoisted/record_upload/ahead::finish), and zero lock-ordering inversions (UPLOAD_WAITS/NEW_PENDING/FLIPS/views_read() are all leaf locks; slot_evict releases textures() first). One [P2] lifetime note for Heap::drop.
3. Park RAM/Commit Cap & Compaction crates/victory-gpu/src/residency.rs:68-167, pool.rs:45-64, 878, resource.rs:2734, 2769, 2916, 2967, 3098-3176, 3246, host.rs:181-197, apps/victory/src/play.rs:95-96 NEEDS FIX (1 [P1], 1 [P2]) shared_headroom uses saturating_sub across phys_floor (1 GiB), commit_floor (2 GiB), and 20% (<= 3 GiB) DXGI shared reserve with zero underflow/overflow on 6/8/16/24 GB GPUs and 16/32/64 GB RAM; block_waste_floor (1 GiB for <= 7500 MiB, 2 GiB above) is safe, and compaction is fence/retire-safe (evict_slots -> strong_count == 1 -> host::retire -> REST = 500 ms). However, slot_evict has a [P1] idle_ms vs evict_idle_ms mismatch that thrashes descriptor slots under VICTORY_PARK_COMPACT_WASTE=1 without compacting sparse blocks.
4. HW-RT DRED Policy & Snapshots crates/victory-gpu/src/host/dred.rs:37-88, host.rs:1317-1334, hwrt.rs:59-71, 2043-2104, 2125, 2166-2231, 2307-2315, 2829-2831, 2956, hwrt/sanitize.rs:103, 130-149, 223-238, 354-360, crates/victory-hle/src/modules/mod.rs:83-84 VERIFIED CLEAN (Scope Note [P2]) VICTORY_HW_RT=0 / unset has zero overhead or behavior change (dred_policy preserves prior DRED behavior, xboxbvh module is unregistered, and hwrt::active()/manager()/prebuild_info short-circuit on !requested()). Note: #373 implements Transform3x4 (tx_copy) snapshotting (48 B inline, 16-byte aligned in 16 MiB-bounded stage), not BLAS vertex/position buffer snapshotting.
5. GPL-3.0 Attribution & Clean-Room Full diff (33 files) + PR body/commits VERIFIED CLEAN All adapted files/hunks carry explicit GPL-3.0 credits (TrustNo1/Darner, linkoovosh/LinkoArts-build, skornuta/victory-memory-stack); zero local paths; zero retail game/character/location names.

[P1] Findings (Action Required)

  1. [P1] crates/victory-gpu/src/resource.rs:3123, 3146-3153, 3176, 3246 — VICTORY_PARK_COMPACT_WASTE Phase 2/Phase 3 idle_ms mismatch thrashes slots with zero compaction:

    • Under healthy VRAM (used < room_line - 2%), let_go_idle (resource.rs:2769, 2916, host.rs:182, 191) passes idle_ms = 600_000 ms into slot_evict. When need == 0, VICTORY_PARK_COMPACT_WASTE=1 sets waste_only = true, while evict_idle_ms = idle_ms.min(slot_evict_idle_ms(...)) clamps to <= 60_000 ms (:3123).
    • Phase 1 (:3176) selects sparse-block textures idle for >= evict_idle_ms (60 s), and Phase 2 evicts their descriptor slots to neutral, but Phase 3 (:3246) checks long_ago(r.host.used.load(Relaxed), idle_ms, frames) against unclamped 600_000 ms. Every sparse texture idle between 60 s and 600 s is slot-evicted and immediately re-made via restore on every sweep without reclaiming the block.
    • Minimal fix: Check evict_idle_ms instead of idle_ms at resource.rs:3246.
  2. [P1] crates/victory-shader/src/fold.rs:985-1034, 1106-1138, 1573, 1593-1595 — v_writelane_b32 runs under EXEC_LO = E.hi and gets masked off by lower.rs:

    • f.flush() (fold.rs:985-1001, 1022) leaves host EXEC_LO = E.hi (dirty = true), and f.lanes (v_writelane_b32, :1106-1138) neither settles EXEC_LO nor enables all lanes.
    • Because ir.rs:1797 marks all VALU ops as reading EXEC, structure.rs:751, 911 and emit/lower.rs:5885-5900, 5979, 9545, 9554, 10572-10590 gate v_writelane_b32 VGPR writes via guard. Writes to console lane k < 32 are silently dropped whenever lane k + 32 is inactive in E.hi (including all group <= 32 dispatches where E.hi == 0 at fold.rs:1573), whereas hardware v_writelane_b32 ignores EXEC.
    • Minimal fix: Set EXEC_LO = -1 (0xFFFF_FFFF) and self.dirty = true before v_writelane_b32 in fold.rs:1106-1138.
  3. [P1] crates/victory-shader/src/fold.rs:857-868, 1163-1186, 1523, 1579-1581, 1638-1645 — Linear dirty/e_written tracking causes stale EXEC_LO after branches:

    • Fold tracks dirty/e_written monotonically by offset; leaders.contains(&inst.offset) (:1579-1581) calls f.flush() without resetting dirty.
    • Taken edges from s_cbranch_vccz/vccnz (:1171-1174 leaves EXEC_LO = VCC_LO | VCC_HI), live-SCC s_cbranch_execz (:1183-1185), or live-SCC conditional branches after E writes (where settle(live_in[i]) at :858, 1638 is skipped) can reach a backward loop header or forward leader whose linear dirty flag became false. At that target, s_cbranch_execz/execnz (:1170, if lo != e || self.dirty) omits s_or_b32 exec_lo, e, e+1 and branches on VCC or stale pre-update EXEC_LO instead of E.
    • Minimal fix: Mark f.dirty = true (and f.e_written = true) at leaders in fold.rs:1579-1581.

Non-Blocking [P2] Notes

  1. [P2] crates/victory-shader/src/fold.rs:321-328, 385, 454, 492, 521, 966-970, 1006-1012 — v_cmpx WAR hazard in joins(): valu_copy sets t.exec = true for v_cmpx* without pushing EXEC_LO onto side.writes, allowing joins() to pair an earlier instruction whose Half::B reads EXEC_LO (data/source9 -> x.e) into the same run, so lower_copies (s_mov_b32 e, exec_lo) overwrites x.e before upper_copies reads it.
  2. [P2] crates/victory-shader/src/fold.rs:410-415 — mask9 negative inline constants 194..=208: 194..=208 (-2..-16) are returned unchanged on Half::B instead of 193 (-1, sign-extended high dword for lanes 32..63), flipping bits on lanes 32..35.
  3. [P2] crates/victory-gpu/src/hwrt.rs:2043-2104, 2125, 2166-2231 & hwrt/sanitize.rs:103, 223-238 — Snapshot scope (tx_copy only): PR #373 snapshots Transform3x4 (tx_copy), not BLAS vertex/position or index buffers; cross-frame deferred builds in Backlog still read live vertex/index memory if recycled before drain (tx_copy itself is memory-bounded, 16-byte aligned, and race-free).
  4. [P2] crates/victory-gpu/src/descriptor.rs:1140-1145 & descriptor/host.rs:627, 736, 3747: Heap::drop unregisters from SHADER_HEAPS but does not purge UPLOAD_WAITS, NEW_PENDING, or FLIPS, allowing lingering Arc<HostTexture> refs (up to 600 submissions) or ptr::from_ref(self) as usize reuse aliasing if a shader-visible heap is freed while uploads wait.
  5. [P2] crates/victory-gpu/src/resource.rs:2967, 3151: When VICTORY_SLOT_EVICT_MB is set to 16..=63 MiB (cap < BLOCK_BYTES), cap.min(free_blocks / 2).max(crate::pool::BLOCK_BYTES) exceeds cap.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7370427796 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7370427796). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T06:57:28Z. --- ## Deep Static Logic Audit — Pass #7 (`Androtim/MiniVI#373` @ `373b3ce2`) Strictly read-only audit of PR `#373` (`feat/p1-reflections-textures-and-hwrt`, CI `check` = `SUCCESS`). ### Pass #7 Verdict Table | Area | Files Verified | Verdict | Summary | | --- | --- | --- | --- | | **Overall PR `#373`** | `373b3ce2` | **NEEDS FIX** | **0 `[P0]`**, **3 `[P1]`** blockers (`fold.rs` lane/CFG soundness x2; `resource.rs` `waste_only` `idle_ms` thrash); 5 non-blocking `[P2]` hardening/scope notes below. | | **1. Reflections Wide-Wave Fold & Cache** | `crates/victory-shader/src/fold.rs`, `emit/mod.rs:790, 874`, `emit/lower.rs`, `crates/victory-gpu/src/shader_cache.rs:47, 205, 652`, `apps/victory/src/play.rs:116` | **NEEDS FIX (`2 [P1]`, `2 [P2]`)** | `VICTORY_EXACT64=71883e40620a567a+7168dd781ca7efb9` cleanly targets the two temporal-resolve reflection shaders while leaving SSR pre-pass `34992f2b65a789a5` and AMD RDNA 4 Wave64 (`host_max_wave() == 32` guard at `emit/mod.rs:790`) untouched. `TRANSLATOR_ENV_KEYS` includes `"VICTORY_EXACT64"` with `SHADER_CACHE_VERSION = 2` (no stale DXIL collisions). However, `fold.rs` has two `[P1]` soundness bugs (`v_writelane_b32` running under `EXEC_LO = E.hi`, and linear `dirty`/`e_written` state across branches/leaders). | | **2. Texture Stand-In & Submission Order** | `crates/victory-gpu/src/descriptor/host.rs:627-634, 736, 3709-3795, 5374-5422`, `descriptor.rs:1140-1145, 2107-2118`, `texture/hoist.rs`, `texture.rs:1093, 1365`, `texture/ahead.rs:442-444`, `host/heap_order.rs`, `host.rs:8188, 8400-8438, 10297`, `draw.rs:2788-2817, 3566` | **VERIFIED CLEAN (`1 [P2]`)** | Zero deadlocks (`Hoist<T>` `SeqCst` 2-epoch protocol, `HELD` self-deadlock guard, bounded `50 ms` `wait_limit()`, `open_detached` `Drop` cleanup), zero permanently stuck slots (`UPLOAD_GIVE_UP = 600` submissions, `UPLOAD_WAITS_MOST = 20_000`, `late = Some(frame)`, `uploaded_in` stamped across prelude/hoisted/`record_upload`/`ahead::finish`), and zero lock-ordering inversions (`UPLOAD_WAITS`/`NEW_PENDING`/`FLIPS`/`views_read()` are all leaf locks; `slot_evict` releases `textures()` first). One `[P2]` lifetime note for `Heap::drop`. | | **3. Park RAM/Commit Cap & Compaction** | `crates/victory-gpu/src/residency.rs:68-167`, `pool.rs:45-64, 878`, `resource.rs:2734, 2769, 2916, 2967, 3098-3176, 3246`, `host.rs:181-197`, `apps/victory/src/play.rs:95-96` | **NEEDS FIX (`1 [P1]`, `1 [P2]`)** | `shared_headroom` uses `saturating_sub` across `phys_floor` (`1 GiB`), `commit_floor` (`2 GiB`), and `20%` (`<= 3 GiB`) DXGI shared reserve with zero underflow/overflow on 6/8/16/24 GB GPUs and 16/32/64 GB RAM; `block_waste_floor` (`1 GiB` for `<= 7500 MiB`, `2 GiB` above) is safe, and compaction is fence/retire-safe (`evict_slots` -> `strong_count == 1` -> `host::retire` -> `REST = 500 ms`). However, `slot_evict` has a `[P1]` `idle_ms` vs `evict_idle_ms` mismatch that thrashes descriptor slots under `VICTORY_PARK_COMPACT_WASTE=1` without compacting sparse blocks. | | **4. HW-RT DRED Policy & Snapshots** | `crates/victory-gpu/src/host/dred.rs:37-88`, `host.rs:1317-1334`, `hwrt.rs:59-71, 2043-2104, 2125, 2166-2231, 2307-2315, 2829-2831, 2956`, `hwrt/sanitize.rs:103, 130-149, 223-238, 354-360`, `crates/victory-hle/src/modules/mod.rs:83-84` | **VERIFIED CLEAN (Scope Note `[P2]`)** | `VICTORY_HW_RT=0` / unset has zero overhead or behavior change (`dred_policy` preserves prior DRED behavior, `xboxbvh` module is unregistered, and `hwrt::active()`/`manager()`/`prebuild_info` short-circuit on `!requested()`). Note: `#373` implements **Transform3x4 (`tx_copy`)** snapshotting (`48 B` inline, 16-byte aligned in `16 MiB`-bounded `stage`), **not** BLAS vertex/position buffer snapshotting. | | **5. GPL-3.0 Attribution & Clean-Room** | Full diff (33 files) + PR body/commits | **VERIFIED CLEAN** | All adapted files/hunks carry explicit GPL-3.0 credits (`TrustNo1/Darner`, `linkoovosh/LinkoArts-build`, `skornuta/victory-memory-stack`); zero local paths; zero retail game/character/location names. | --- ### `[P1]` Findings (Action Required) 1. **`[P1]` `crates/victory-gpu/src/resource.rs:3123, 3146-3153, 3176, 3246` — `VICTORY_PARK_COMPACT_WASTE` Phase 2/Phase 3 `idle_ms` mismatch thrashes slots with zero compaction:** - Under healthy VRAM (`used < room_line - 2%`), `let_go_idle` (`resource.rs:2769, 2916`, `host.rs:182, 191`) passes `idle_ms = 600_000` ms into `slot_evict`. When `need == 0`, `VICTORY_PARK_COMPACT_WASTE=1` sets `waste_only = true`, while `evict_idle_ms = idle_ms.min(slot_evict_idle_ms(...))` clamps to `<= 60_000` ms (`:3123`). - Phase 1 (`:3176`) selects sparse-block textures idle for `>= evict_idle_ms` (`60 s`), and Phase 2 evicts their descriptor slots to neutral, but Phase 3 (`:3246`) checks `long_ago(r.host.used.load(Relaxed), idle_ms, frames)` against unclamped `600_000` ms. Every sparse texture idle between `60 s` and `600 s` is slot-evicted and immediately re-made via `restore` on every sweep without reclaiming the block. - **Minimal fix:** Check `evict_idle_ms` instead of `idle_ms` at `resource.rs:3246`. 2. **`[P1]` `crates/victory-shader/src/fold.rs:985-1034, 1106-1138, 1573, 1593-1595` — `v_writelane_b32` runs under `EXEC_LO = E.hi` and gets masked off by `lower.rs`:** - `f.flush()` (`fold.rs:985-1001, 1022`) leaves host `EXEC_LO = E.hi` (`dirty = true`), and `f.lanes` (`v_writelane_b32`, `:1106-1138`) neither settles `EXEC_LO` nor enables all lanes. - Because `ir.rs:1797` marks all VALU ops as reading `EXEC`, `structure.rs:751, 911` and `emit/lower.rs:5885-5900, 5979, 9545, 9554, 10572-10590` gate `v_writelane_b32` VGPR writes via `guard`. Writes to console lane `k < 32` are silently dropped whenever lane `k + 32` is inactive in `E.hi` (including all `group <= 32` dispatches where `E.hi == 0` at `fold.rs:1573`), whereas hardware `v_writelane_b32` ignores `EXEC`. - **Minimal fix:** Set `EXEC_LO = -1` (`0xFFFF_FFFF`) and `self.dirty = true` before `v_writelane_b32` in `fold.rs:1106-1138`. 3. **`[P1]` `crates/victory-shader/src/fold.rs:857-868, 1163-1186, 1523, 1579-1581, 1638-1645` — Linear `dirty`/`e_written` tracking causes stale `EXEC_LO` after branches:** - `Fold` tracks `dirty`/`e_written` monotonically by offset; `leaders.contains(&inst.offset)` (`:1579-1581`) calls `f.flush()` without resetting `dirty`. - Taken edges from `s_cbranch_vccz`/`vccnz` (`:1171-1174` leaves **`EXEC_LO = VCC_LO | VCC_HI`**), live-`SCC` `s_cbranch_execz` (`:1183-1185`), or live-`SCC` conditional branches after `E` writes (where `settle(live_in[i])` at `:858, 1638` is skipped) can reach a backward loop header or forward `leader` whose linear `dirty` flag became `false`. At that target, `s_cbranch_execz`/`execnz` (`:1170`, `if lo != e || self.dirty`) omits `s_or_b32 exec_lo, e, e+1` and branches on `VCC` or stale pre-update `EXEC_LO` instead of `E`. - **Minimal fix:** Mark `f.dirty = true` (and `f.e_written = true`) at `leaders` in `fold.rs:1579-1581`. --- ### Non-Blocking `[P2]` Notes 1. **`[P2]` `crates/victory-shader/src/fold.rs:321-328, 385, 454, 492, 521, 966-970, 1006-1012` — `v_cmpx` WAR hazard in `joins()`:** `valu_copy` sets `t.exec = true` for `v_cmpx*` without pushing `EXEC_LO` onto `side.writes`, allowing `joins()` to pair an earlier instruction whose `Half::B` reads `EXEC_LO` (`data`/`source9` -> `x.e`) into the same `run`, so `lower_copies` (`s_mov_b32 e, exec_lo`) overwrites `x.e` before `upper_copies` reads it. 2. **`[P2]` `crates/victory-shader/src/fold.rs:410-415` — `mask9` negative inline constants `194..=208`:** `194..=208` (`-2..-16`) are returned unchanged on `Half::B` instead of `193` (`-1`, sign-extended high dword for lanes `32..63`), flipping bits on lanes `32..35`. 3. **`[P2]` `crates/victory-gpu/src/hwrt.rs:2043-2104, 2125, 2166-2231` & `hwrt/sanitize.rs:103, 223-238` — Snapshot scope (`tx_copy` only):** PR `#373` snapshots `Transform3x4` (`tx_copy`), not BLAS vertex/position or index buffers; cross-frame deferred builds in `Backlog` still read live vertex/index memory if recycled before drain (`tx_copy` itself is memory-bounded, 16-byte aligned, and race-free). 4. **`[P2]` `crates/victory-gpu/src/descriptor.rs:1140-1145` & `descriptor/host.rs:627, 736, 3747`:** `Heap::drop` unregisters from `SHADER_HEAPS` but does not purge `UPLOAD_WAITS`, `NEW_PENDING`, or `FLIPS`, allowing lingering `Arc<HostTexture>` refs (up to `600` submissions) or `ptr::from_ref(self) as usize` reuse aliasing if a shader-visible heap is freed while uploads wait. 5. **`[P2]` `crates/victory-gpu/src/resource.rs:2967, 3151`:** When `VICTORY_SLOT_EVICT_MB` is set to `16..=63` MiB (`cap < BLOCK_BYTES`), `cap.min(free_blocks / 2).max(crate::pool::BLOCK_BYTES)` exceeds `cap`.
Androtim commented 2026-12-03 07:15:25 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T07:15:25Z.


Deep Static Logic Audit — Pass #8 (Androtim/MiniVI#374 @ 3c336ef6)

Strictly read-only static audit of PR #374 (perf/p1-speed-wins, CI check = SUCCESS).

Pass #8 Verdict Table

Area Files Verified Verdict Summary
Overall PR #374 3c336ef6 VERIFIED CLEAN (Green Light) 0 [P0], 0 [P1] blockers; 2 minor non-blocking [P2] observations below.
1. Shader WIDE 4-Dword Loads & Cache crates/victory-shader/src/emit/bitcode/opt.rs:62-70, emit/mod.rs:365-381, 440-461, 1615-1629, 2744-2894, emit/lower.rs:7981-8017, 8095-8188, 9222-9248, crates/victory-gpu/build.rs:7-50, crates/victory-gpu/src/shader_cache.rs:113, 150, 204-212 VERIFIED CLEAN opt::DEFAULT = ALL (127, opt-out via VICTORY_SHADER_OPT=63) enables raw_dwords() solely on scalar buffer loads (smem() s_buffer_load_dword* count in {1,2,4,8,16}, chunked to 1/2/4 dwords with align = 4, mask = 1/3/15). raw_twin (descriptor/host.rs:6075-6099) and root/memory SRVs bind R32_TYPELESS FLAG_RAW views with per-dword D3D12 OOB zeroing (verified across unaligned offsets and partial view-end straddling); count == 1 preserves builder_bounds size && root clamping (lower.rs:8145, 8159, 8181-8185), and picked CBVs (stride == 0) stay guarded behind is_buffer. victory-gpu/build.rs hashes opt.rs + mod.rs into VICTORY_TRANSLATOR, and shader_cache.rs:150 hashes shader_opt().to_le_bytes() alongside SHADER_CACHE_VERSION = 2 (zero pre-#374 or env-toggle cache collisions). Identical scalar SMEM semantics across NVIDIA Wave32 & AMD RDNA 4 Wave64.
2. Tiered Buffer Lookup (shadow.rs) crates/victory-gpu/src/shadow.rs:939-940, 6774-6886, 6894-6905, 6933-6959, 6968-7111, 7353-7372, 8069-8075, 8381-8435, crates/victory-gpu/src/listcpu.rs:125-296 VERIFIED CLEAN Buffers partitions keys (start, resource) across TIERS = [4 KiB, 64 KiB, 1 MiB, 16 MiB] + overflow (>16 MiB) with exact per-size live counts (sizes). insert strips all tiers before reinserting and updates sizes on overwrite; remove keeps map/tiers/sizes consistent; find computes lowest = end.saturating_sub(most) per non-empty tier (most = sizes.range(low..=high).next_back()), skips lowest > address, and takes best.max(found) — matching full-scan semantics across all boundary/empty/len == 0 cases (and avoiding prior .take(64) truncation misses). ReadMostly (id = 1) shard ordering, BUFFERS_CHANGED + FOUND TLS SeqCst fencing, host::retire outside lock, and BUFFERS/LOOSE separation (unregister, in_place_let_go, lookup, spans, near) remain deadlock- and race-free (near also switches from buffers() write lock to buffers_read()).
3. Title Priority Cap (TITLE_PRIORITY_MAX) crates/victory-hle/src/modules/kernel.rs:427-481, 600-622, 625-709, 1007-1021, apps/victory/src/play.rs:77-80, crates/victory-hle/src/modules/audio.rs:424-426, 760-788, crates/victory-hle/src/modules/xaudio2.rs:62-90 VERIFIED CLEAN play.rs:80 sets VICTORY_TITLE_PRIORITY_MAX=0 while leaving VICTORY_TITLE_PRIORITIES and VICTORY_STARTUP_PRIORITIES unset (cap = false). held_at() (kernel.rs:474-481) clamps non-time-critical HLE SetThreadPriority values (<= 2) to max (0 = THREAD_PRIORITY_NORMAL), strictly preserving TIME_CRITICAL (15: given != TIME_CRITICAL) for title mixer threads (audio.rs:426). #370's victory XMA decoder (audio.rs:760-788) calls host Win32 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) directly outside HLE kernel::SetThreadPriority, keeping it at HIGHEST (2) strictly above ABOVE_NORMAL (1) GPU pools and capped (0) title workers; host xaudio2_9.dll threads (xaudio2.rs:62-90) are likewise untouched. Clean opt-out via off or 2.
4. Descriptor KEPT_APART (Omitted) crates/victory-gpu/src/descriptor/host.rs:315-322, 4124-4182, 4416-4485 VERIFIED CLEAN Omission is justified: HostHeap already uses per-slot kept: Box<[Mutex<Option<ID3D12Resource>>]>, lock-free kept_raw: Box<[AtomicUsize]>, and rtas_slots/kept_pins, and calls crate::host::retire_resource(old) / crate::host::retire(pin) strictly outside slot (keep_inner:4476-4484) and next (release:4139-4142, release_batch:4178-4181) locks. Zero UAF or lock-held COM drops.
5. GPL-3.0 Attribution & Clean-Room Full diff (5 files) + commit 3c336ef6 + PR #374 body VERIFIED CLEAN Explicit GPL-3.0 credits in code comments, commit message, and PR body (linkoovosh/LinkoArts-build fd9443e/93c6311, TrustNo1/Darner 2a8566e); zero local Windows paths; zero retail game/character/location names.

Non-Blocking [P2] Observations

  1. [P2] crates/victory-hle/src/modules/kernel.rs:613, 646-648 (VICTORY_STARTUP_PRIORITIES + VICTORY_TITLE_PRIORITIES=0 edge): Under play.rs defaults (VICTORY_STARTUP_PRIORITIES unset), STARTUP_RAISED is inactive. Only if someone manually combines VICTORY_STARTUP_PRIORITIES=<sec> + VICTORY_TITLE_PRIORITIES=0 + VICTORY_TITLE_PRIORITY_MAX=0 does give_back_startup_raises() (:613) restore original asked values without held_at (while cap = true already suppressed should_raise on > 0 priorities at :646-648).
  2. [P2] apps/victory/src/play.rs:80 vs scripts/play.ps1: VICTORY_TITLE_PRIORITY_MAX=0 is wired into apps/victory/src/play.rs SETTINGS only (not scripts/play.ps1); intended for the default victory play launcher path.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7370778048 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7370778048). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T07:15:25Z. --- ## Deep Static Logic Audit — Pass #8 (`Androtim/MiniVI#374` @ `3c336ef6`) Strictly read-only static audit of PR `#374` (`perf/p1-speed-wins`, CI `check` = `SUCCESS`). ### Pass #8 Verdict Table | Area | Files Verified | Verdict | Summary | | --- | --- | --- | --- | | **Overall PR `#374`** | `3c336ef6` | **VERIFIED CLEAN (Green Light)** | **0 `[P0]`**, **0 `[P1]`** blockers; 2 minor non-blocking `[P2]` observations below. | | **1. Shader `WIDE` 4-Dword Loads & Cache** | `crates/victory-shader/src/emit/bitcode/opt.rs:62-70`, `emit/mod.rs:365-381, 440-461, 1615-1629, 2744-2894`, `emit/lower.rs:7981-8017, 8095-8188, 9222-9248`, `crates/victory-gpu/build.rs:7-50`, `crates/victory-gpu/src/shader_cache.rs:113, 150, 204-212` | **VERIFIED CLEAN** | `opt::DEFAULT = ALL` (`127`, opt-out via `VICTORY_SHADER_OPT=63`) enables `raw_dwords()` solely on scalar buffer loads (`smem()` `s_buffer_load_dword*` `count` in `{1,2,4,8,16}`, chunked to `1`/`2`/`4` dwords with `align = 4`, `mask = 1`/`3`/`15`). `raw_twin` (`descriptor/host.rs:6075-6099`) and root/memory SRVs bind `R32_TYPELESS` `FLAG_RAW` views with per-dword D3D12 OOB zeroing (verified across unaligned offsets and partial view-end straddling); `count == 1` preserves `builder_bounds` `size && root` clamping (`lower.rs:8145, 8159, 8181-8185`), and `picked` CBVs (`stride == 0`) stay guarded behind `is_buffer`. `victory-gpu/build.rs` hashes `opt.rs` + `mod.rs` into `VICTORY_TRANSLATOR`, and `shader_cache.rs:150` hashes `shader_opt().to_le_bytes()` alongside `SHADER_CACHE_VERSION = 2` (zero pre-`#374` or env-toggle cache collisions). Identical scalar SMEM semantics across NVIDIA Wave32 & AMD RDNA 4 Wave64. | | **2. Tiered Buffer Lookup (`shadow.rs`)** | `crates/victory-gpu/src/shadow.rs:939-940, 6774-6886, 6894-6905, 6933-6959, 6968-7111, 7353-7372, 8069-8075, 8381-8435`, `crates/victory-gpu/src/listcpu.rs:125-296` | **VERIFIED CLEAN** | `Buffers` partitions keys `(start, resource)` across `TIERS = [4 KiB, 64 KiB, 1 MiB, 16 MiB]` + overflow (`>16 MiB`) with exact per-size live counts (`sizes`). `insert` strips all tiers before reinserting and updates `sizes` on overwrite; `remove` keeps `map`/`tiers`/`sizes` consistent; `find` computes `lowest = end.saturating_sub(most)` per non-empty tier (`most = sizes.range(low..=high).next_back()`), skips `lowest > address`, and takes `best.max(found)` — matching full-scan semantics across all boundary/empty/`len == 0` cases (and avoiding prior `.take(64)` truncation misses). `ReadMostly` (`id = 1`) shard ordering, `BUFFERS_CHANGED` + `FOUND` TLS `SeqCst` fencing, `host::retire` outside lock, and `BUFFERS`/`LOOSE` separation (`unregister`, `in_place_let_go`, `lookup`, `spans`, `near`) remain deadlock- and race-free (`near` also switches from `buffers()` write lock to `buffers_read()`). | | **3. Title Priority Cap (`TITLE_PRIORITY_MAX`)** | `crates/victory-hle/src/modules/kernel.rs:427-481, 600-622, 625-709, 1007-1021`, `apps/victory/src/play.rs:77-80`, `crates/victory-hle/src/modules/audio.rs:424-426, 760-788`, `crates/victory-hle/src/modules/xaudio2.rs:62-90` | **VERIFIED CLEAN** | `play.rs:80` sets `VICTORY_TITLE_PRIORITY_MAX=0` while leaving `VICTORY_TITLE_PRIORITIES` and `VICTORY_STARTUP_PRIORITIES` unset (`cap = false`). `held_at()` (`kernel.rs:474-481`) clamps non-time-critical HLE `SetThreadPriority` values (`<= 2`) to `max` (`0` = `THREAD_PRIORITY_NORMAL`), strictly preserving `TIME_CRITICAL` (`15`: `given != TIME_CRITICAL`) for title mixer threads (`audio.rs:426`). `#370`'s `victory XMA decoder` (`audio.rs:760-788`) calls host Win32 `SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST)` directly outside HLE `kernel::SetThreadPriority`, keeping it at `HIGHEST` (`2`) strictly above `ABOVE_NORMAL` (`1`) GPU pools and capped (`0`) title workers; host `xaudio2_9.dll` threads (`xaudio2.rs:62-90`) are likewise untouched. Clean opt-out via `off` or `2`. | | **4. Descriptor `KEPT_APART` (Omitted)** | `crates/victory-gpu/src/descriptor/host.rs:315-322, 4124-4182, 4416-4485` | **VERIFIED CLEAN** | Omission is justified: `HostHeap` already uses per-slot `kept: Box<[Mutex<Option<ID3D12Resource>>]>`, lock-free `kept_raw: Box<[AtomicUsize]>`, and `rtas_slots`/`kept_pins`, and calls `crate::host::retire_resource(old)` / `crate::host::retire(pin)` strictly outside slot (`keep_inner:4476-4484`) and `next` (`release:4139-4142`, `release_batch:4178-4181`) locks. Zero UAF or lock-held COM drops. | | **5. GPL-3.0 Attribution & Clean-Room** | Full diff (5 files) + commit `3c336ef6` + PR `#374` body | **VERIFIED CLEAN** | Explicit GPL-3.0 credits in code comments, commit message, and PR body (`linkoovosh/LinkoArts-build` `fd9443e`/`93c6311`, `TrustNo1/Darner` `2a8566e`); zero local Windows paths; zero retail game/character/location names. | --- ### Non-Blocking `[P2]` Observations 1. **`[P2]` `crates/victory-hle/src/modules/kernel.rs:613, 646-648` (`VICTORY_STARTUP_PRIORITIES` + `VICTORY_TITLE_PRIORITIES=0` edge):** Under `play.rs` defaults (`VICTORY_STARTUP_PRIORITIES` unset), `STARTUP_RAISED` is inactive. Only if someone manually combines `VICTORY_STARTUP_PRIORITIES=<sec>` + `VICTORY_TITLE_PRIORITIES=0` + `VICTORY_TITLE_PRIORITY_MAX=0` does `give_back_startup_raises()` (`:613`) restore original `asked` values without `held_at` (while `cap = true` already suppressed `should_raise` on `> 0` priorities at `:646-648`). 2. **`[P2]` `apps/victory/src/play.rs:80` vs `scripts/play.ps1`:** `VICTORY_TITLE_PRIORITY_MAX=0` is wired into `apps/victory/src/play.rs` `SETTINGS` only (not `scripts/play.ps1`); intended for the default `victory play` launcher path.
Androtim commented 2026-12-03 07:17:17 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T07:17:17Z.


Targeted Sign-Off — Pass #7.5 (Androtim/MiniVI#373 @ 34a701f6)

Strictly read-only verification of follow-up commit 34a701f6 on PR #373 (feat/p1-reflections-textures-and-hwrt, CI check = pass in 4m30s).

Verdict: VERIFIED CLEAN (Green Light) — 0 [P0], 0 [P1] blockers

Pass #7 [P1] Item File & Lines Verified Status Verification Summary
1. v_writelane_b32 under EXEC_LO = E.hi crates/victory-shader/src/fold.rs:1117-1118 VERIFIED FIXED Emits s_mov_b32 exec_lo, -1 and sets self.dirty = true before both constant-lane and scalar-lane v_writelane_b32 expansions (structure.rs:1153-1160, 1323-1333 evaluates EXEC = Bool::TRUE -> guards[b][i] == None at structure.rs:911, so emit/lower.rs:5885-5900 never masks writes off); leaves SCC and x.e untouched.
2. Linear dirty/e_written across branches/leaders crates/victory-shader/src/fold.rs:1586-1591 VERIFIED FIXED Marks f.dirty = true and f.e_written = true after f.flush() at every CFG leader (branch/jump targets and post-branch fall-throughs, including offset 0 back-edge headers), forcing f.settle(false) (fold.rs:861-872) to re-emit s_or_b32 exec_lo, e, e+1 and s_and_b32 e/e+1, exec_lo when SCC is dead, and keeping dirty/e_written armed across live_in SCC regions.
3. slot_evict idle_ms vs evict_idle_ms thrash (VICTORY_PARK_COMPACT_WASTE=1) crates/victory-gpu/src/resource.rs:3119-3121, 3135, 3177, 3188, 3258 VERIFIED FIXED slot_evict_cutoff_ms clamps evict_idle_ms = idle_ms.min(slot_evict_idle_ms(...)) (<= 60_000 ms) and shares one is_idle closure (stamp != 0 && long_ago(stamp, evict_idle_ms, frames)) across both Phase 1 candidate selection and Phase 3 retirement, eliminating the 60 s vs 600 s slot-eviction thrash.

Additional [P2] Fixes Included in 34a701f6 & Remaining Notes

  • Resolved Pass #7 [P2]s (3 of 5): fold.rs:414 (mask9 sign-extends 193..=208 to 193 in upper half), fold.rs:456, 495, 525 (v_cmpx* pushes EXEC_LO/EXEC_HI onto side.writes for joins() and Twin::ordered()), and resource.rs:3125-3127, 3163 (waste_evict_need applies .min(cap) last so need <= cap even when VICTORY_SLOT_EVICT_MB is 16..=63 MiB), each covered by new unit tests in fold.rs and resource.rs.
  • Remaining non-blocking [P2] notes from Pass #7: hwrt.rs tx_copy-only snapshot scope and descriptor.rs Heap::drop queue purge (unchanged, non-blocking).
  • Clean-room check: Zero local paths, zero retail game/character/location names.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7370816301 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7370816301). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T07:17:17Z. --- ## Targeted Sign-Off — Pass #7.5 (`Androtim/MiniVI#373` @ `34a701f6`) Strictly read-only verification of follow-up commit `34a701f6` on PR `#373` (`feat/p1-reflections-textures-and-hwrt`, CI `check` = `pass` in `4m30s`). ### Verdict: **VERIFIED CLEAN (Green Light)** — **0 `[P0]`**, **0 `[P1]`** blockers | Pass #7 `[P1]` Item | File & Lines Verified | Status | Verification Summary | | --- | --- | --- | --- | | **1. `v_writelane_b32` under `EXEC_LO = E.hi`** | `crates/victory-shader/src/fold.rs:1117-1118` | **VERIFIED FIXED** | Emits `s_mov_b32 exec_lo, -1` and sets `self.dirty = true` before both constant-lane and scalar-lane `v_writelane_b32` expansions (`structure.rs:1153-1160, 1323-1333` evaluates `EXEC = Bool::TRUE` -> `guards[b][i] == None` at `structure.rs:911`, so `emit/lower.rs:5885-5900` never masks writes off); leaves `SCC` and `x.e` untouched. | | **2. Linear `dirty`/`e_written` across branches/leaders** | `crates/victory-shader/src/fold.rs:1586-1591` | **VERIFIED FIXED** | Marks `f.dirty = true` and `f.e_written = true` after `f.flush()` at every CFG `leader` (branch/jump targets and post-branch fall-throughs, including offset `0` back-edge headers), forcing `f.settle(false)` (`fold.rs:861-872`) to re-emit `s_or_b32 exec_lo, e, e+1` and `s_and_b32 e/e+1, exec_lo` when `SCC` is dead, and keeping `dirty`/`e_written` armed across `live_in` `SCC` regions. | | **3. `slot_evict` `idle_ms` vs `evict_idle_ms` thrash (`VICTORY_PARK_COMPACT_WASTE=1`)** | `crates/victory-gpu/src/resource.rs:3119-3121, 3135, 3177, 3188, 3258` | **VERIFIED FIXED** | `slot_evict_cutoff_ms` clamps `evict_idle_ms = idle_ms.min(slot_evict_idle_ms(...))` (`<= 60_000` ms) and shares one `is_idle` closure (`stamp != 0 && long_ago(stamp, evict_idle_ms, frames)`) across both Phase 1 candidate selection and Phase 3 retirement, eliminating the `60 s` vs `600 s` slot-eviction thrash. | ### Additional `[P2]` Fixes Included in `34a701f6` & Remaining Notes - **Resolved Pass #7 `[P2]`s (3 of 5):** `fold.rs:414` (`mask9` sign-extends `193..=208` to `193` in upper half), `fold.rs:456, 495, 525` (`v_cmpx*` pushes `EXEC_LO`/`EXEC_HI` onto `side.writes` for `joins()` and `Twin::ordered()`), and `resource.rs:3125-3127, 3163` (`waste_evict_need` applies `.min(cap)` last so `need <= cap` even when `VICTORY_SLOT_EVICT_MB` is `16..=63` MiB), each covered by new unit tests in `fold.rs` and `resource.rs`. - **Remaining non-blocking `[P2]` notes from Pass #7:** `hwrt.rs` `tx_copy`-only snapshot scope and `descriptor.rs` `Heap::drop` queue purge (unchanged, non-blocking). - **Clean-room check:** Zero local paths, zero retail game/character/location names.
Androtim commented 2026-12-03 08:58:48 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T08:58:48Z.


Reasoning Audit Pass #9 — PR #380 (46e38e1, feat/build-version-overlay)

  • Verdict: VERIFIED CLEAN (0 P0, 0 P1, 0 P2)
  • Scope: Compile-time BUILD_VERSION (crates/victory-gpu/build.rs, victory-gpu/src/lib.rs, victory-hle/src/lib.rs) + F3 stats overlay build version & RT mode (RT OFF / RT HW / RT SW) in panel.rs, window caption (host.rs), and log header (apps/victory/src/play.rs).
  • Pre-merge P2 catches fixed in 46e38e1:
    1. build.rs: watch worktree commondir branch refs & packed-ref parent dirs; gate git invocations on has_git.
    2. panel.rs: align RT SW detection with !hwrt::requested() && VICTORY_BVH_BUILDER == "1" so VICTORY_BVH_BUILDER="" (OFF) or suppressed SW-RT never mislabels as RT SW.
  • Gate 3 Live RTX 4060 Ti check: verified crisp 40-col MINIVI 50E503C (F3) ... F1: MENU, FRAME GEN OFF RT OFF, and # version=50e503c ... log line 1.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7373005042 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7373005042). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T08:58:48Z. --- ### Reasoning Audit Pass #9 — PR #380 (`46e38e1`, `feat/build-version-overlay`) - **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1, 0 P2)` - **Scope:** Compile-time `BUILD_VERSION` (`crates/victory-gpu/build.rs`, `victory-gpu/src/lib.rs`, `victory-hle/src/lib.rs`) + `F3` stats overlay build version & RT mode (`RT OFF` / `RT HW` / `RT SW`) in `panel.rs`, window caption (`host.rs`), and log header (`apps/victory/src/play.rs`). - **Pre-merge P2 catches fixed in `46e38e1`:** 1. `build.rs`: watch worktree `commondir` branch refs & packed-ref parent dirs; gate `git` invocations on `has_git`. 2. `panel.rs`: align `RT SW` detection with `!hwrt::requested() && VICTORY_BVH_BUILDER == "1"` so `VICTORY_BVH_BUILDER=""` (OFF) or suppressed SW-RT never mislabels as `RT SW`. - **Gate 3 Live RTX 4060 Ti check:** verified crisp 40-col `MINIVI 50E503C (F3) ... F1: MENU`, `FRAME GEN OFF RT OFF`, and `# version=50e503c ...` log line 1.
Androtim commented 2026-12-03 09:46:04 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T09:46:04Z.


Reasoning Audit Pass #10 — PR #382 (b5f6f82, fix/hwrt-refit-shown-source)

  • Verdict: VERIFIED CLEAN (0 P0, 0 P1, 0 P2)
  • Scope: crates/victory-gpu/src/hwrt.rs (flush_blas_waves + job_of, +10/-5 lines) — resolve BLAS PERFORM_UPDATE refit source_va from submitted self.shown instead of recording-time self.as_map.
  • Verified: Lock DAG cycle-free (blas_table -> queue -> lru -> shown -> recording_tlas), GPU timeline ordering guaranteed by defer_host + global UAV barrier on direct queue, lifetime safety via list.hold + RetiredAs + is_sole_com_owner, and all remaining self.as_map accesses audited (none emit GPU commands).
  • Gate 3 Live RTX 4060 Ti check: 1440 DLSS Quality VICTORY_HW_RT=1 (refits ON) ran full 70s gameplay (136.4s total) with 9,601 BLAS refits, 4,115 TLAS builds, 38 unsubmitted races safely converted to refit->rebuild, and 0 hangs / 0 DRED / 0 0x887A0006 (100% crash beforehand).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7374204403 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7374204403). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T09:46:04Z. --- ### Reasoning Audit Pass #10 — PR #382 (`b5f6f82`, `fix/hwrt-refit-shown-source`) - **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1, 0 P2)` - **Scope:** `crates/victory-gpu/src/hwrt.rs` (`flush_blas_waves` + `job_of`, +10/-5 lines) — resolve BLAS `PERFORM_UPDATE` refit `source_va` from submitted `self.shown` instead of recording-time `self.as_map`. - **Verified:** Lock DAG cycle-free (`blas_table -> queue -> lru -> shown -> recording_tlas`), GPU timeline ordering guaranteed by `defer_host` + global UAV barrier on direct queue, lifetime safety via `list.hold` + `RetiredAs` + `is_sole_com_owner`, and all remaining `self.as_map` accesses audited (none emit GPU commands). - **Gate 3 Live RTX 4060 Ti check:** `1440` DLSS Quality `VICTORY_HW_RT=1` (refits ON) ran full 70s gameplay (`136.4s` total) with **9,601 BLAS refits**, **4,115 TLAS builds**, **38 unsubmitted races safely converted to `refit->rebuild`**, and **0 hangs / 0 DRED / 0 `0x887A0006`** (100% crash beforehand).
Androtim commented 2026-12-03 10:01:48 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T10:01:48Z.


Reasoning Audit Pass #11 — PR #383 (fed6c13, perf/copy-filter-dedup)

  • Verdict: VERIFIED CLEAN (0 P0, 0 P1) (2 non-blocking P2 notes: 3.125% lazy filter RAM overhead on large single-sided buffers, and also runs on L0 write-back shared copies).
  • Scope: crates/victory-gpu/src/shadow.rs + host.rs (Shadow::copy_filtered, VICTORY_COPY_FILTER=0|1|check, adapted from ReZOnGithub/VIctory-lap 0388407, GPL-3.0).
  • Verified: Disjoint parallel refresh ranges, written Release/Acquire + filter_epoch invalidation, complete unfiltered() coverage across all single-sided writers, initial zeroing & alignment safety, clean-room + GPL-3.0 attribution.
  • Gate 3 Live RTX 4060 Ti check: 1440 DLSS Quality VICTORY_COPY_FILTER=check -> 0 byte mismatches across full gameplay; default VICTORY_COPY_FILTER=1 -> 8.8 fps (113.5 ms), VRAM 5.4 / 6.5 GB, clean visuals.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7374630503 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7374630503). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T10:01:48Z. --- ### Reasoning Audit Pass #11 — PR #383 (`fed6c13`, `perf/copy-filter-dedup`) - **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` (2 non-blocking P2 notes: 3.125% lazy filter RAM overhead on large single-sided buffers, and also runs on L0 write-back shared copies). - **Scope:** `crates/victory-gpu/src/shadow.rs` + `host.rs` (`Shadow::copy_filtered`, `VICTORY_COPY_FILTER=0|1|check`, adapted from `ReZOnGithub/VIctory-lap` `0388407`, GPL-3.0). - **Verified:** Disjoint parallel refresh ranges, `written` Release/Acquire + `filter_epoch` invalidation, complete `unfiltered()` coverage across all single-sided writers, initial zeroing & alignment safety, clean-room + GPL-3.0 attribution. - **Gate 3 Live RTX 4060 Ti check:** `1440` DLSS Quality `VICTORY_COPY_FILTER=check` -> **0 byte mismatches** across full gameplay; default `VICTORY_COPY_FILTER=1` -> `8.8 fps` (`113.5 ms`), `VRAM 5.4 / 6.5 GB`, clean visuals.
Androtim commented 2026-12-03 10:56:10 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T10:56:10Z.


Deep Reasoning Audit Pass #12 — PR #384 (perf/safe-working-set-trim, 5fe71eb)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Initial Audit (59e7e97) caught and fixed in 5fe71eb:

  • [P1] Fixed: Eliminated scan-to-unlock TOCTOU window between scan() and trim_gently() by adding OPEN_LOCK (RwLock<()>, write-guarded across inplace::open, read-guarded around each single <= 16 MiB VirtualUnlock step), monotonic STATE_GEN (Acquire/Release) bumped on TITLE/OPENED/WRITE_COMBINED changes, and live per-chunk VirtualQuery + exclusion re-verification (splitting around newly added exclusions).
  • [P2] Fixed: title_freed(at, len) now only removes at from TITLE on MEM_RELEASE (len == 0), keeping AllocationBase tracked across partial MEM_DECOMMIT (len > 0).
  • [P2] Fixed: shadow::write_combined_freed(at, len) now splits surviving sub-ranges on partial MEM_DECOMMIT (len > 0) and notifies trim::write_combined_changed().

Lock Order & Portability Verified:

  • Strict leaf lock hierarchy (OPEN_LOCK -> TITLE / OPENED / WRITE_COMBINED, never nested; zero cycles).
  • Full #[cfg(windows)] gating across lib.rs, residency.rs, inplace.rs, shadow.rs, watch.rs.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7375982314 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7375982314). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T10:56:10Z. --- ### Deep Reasoning Audit Pass #12 — PR #384 (`perf/safe-working-set-trim`, `5fe71eb`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` **Initial Audit (`59e7e97`) caught and fixed in `5fe71eb`:** - **[P1] Fixed:** Eliminated scan-to-unlock TOCTOU window between `scan()` and `trim_gently()` by adding `OPEN_LOCK` (`RwLock<()>`, write-guarded across `inplace::open`, read-guarded around each single `<= 16 MiB` `VirtualUnlock` step), monotonic `STATE_GEN` (`Acquire`/`Release`) bumped on `TITLE`/`OPENED`/`WRITE_COMBINED` changes, and live per-chunk `VirtualQuery` + exclusion re-verification (splitting around newly added exclusions). - **[P2] Fixed:** `title_freed(at, len)` now only removes `at` from `TITLE` on `MEM_RELEASE` (`len == 0`), keeping `AllocationBase` tracked across partial `MEM_DECOMMIT` (`len > 0`). - **[P2] Fixed:** `shadow::write_combined_freed(at, len)` now splits surviving sub-ranges on partial `MEM_DECOMMIT` (`len > 0`) and notifies `trim::write_combined_changed()`. **Lock Order & Portability Verified:** - Strict leaf lock hierarchy (`OPEN_LOCK` -> `TITLE` / `OPENED` / `WRITE_COMBINED`, never nested; zero cycles). - Full `#[cfg(windows)]` gating across `lib.rs`, `residency.rs`, `inplace.rs`, `shadow.rs`, `watch.rs`.
Androtim commented 2026-12-03 11:31:55 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T11:31:55Z.


Deep Reasoning Audit Pass #13 — PR #385 (fix/amd-buffer-size-nonuniform-handle, 8510813)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

  • Verified Lower::size_view_handle (crates/victory-shader/src/emit/lower/amd.rs) emits a dedicated SM 6.6 nonuniform = true heap handle strictly for uniform buffer descriptor_data (getDimensions) queries while leaving images and waterfall loads on self.handle(...).
  • Confirmed raw_twin remapping, VIEW_LIMIT clamping, error propagation, and nonuniform_handles -= 1 (non-underflowing because heap_handle_at unconditionally increments on nonuniform = true) are exact.
  • Confirmed SFI0/PSV0 flags remain standard RESOURCE_HEAP and victory-gpu/build.rs automatically updates VICTORY_TRANSLATOR across crates/victory-shader/src/emit/lower/amd.rs to invalidate cached translations cleanly.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7376828701 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7376828701). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T11:31:55Z. --- ### Deep Reasoning Audit Pass #13 — PR #385 (`fix/amd-buffer-size-nonuniform-handle`, `8510813`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` - Verified `Lower::size_view_handle` (`crates/victory-shader/src/emit/lower/amd.rs`) emits a dedicated SM 6.6 `nonuniform = true` heap handle strictly for uniform buffer `descriptor_data` (`getDimensions`) queries while leaving images and waterfall loads on `self.handle(...)`. - Confirmed `raw_twin` remapping, `VIEW_LIMIT` clamping, error propagation, and `nonuniform_handles -= 1` (non-underflowing because `heap_handle_at` unconditionally increments on `nonuniform = true`) are exact. - Confirmed `SFI0`/`PSV0` flags remain standard `RESOURCE_HEAP` and `victory-gpu/build.rs` automatically updates `VICTORY_TRANSLATOR` across `crates/victory-shader/src/emit/lower/amd.rs` to invalidate cached translations cleanly.
Androtim commented 2026-12-03 11:54:12 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T11:54:12Z.


Reasoning Audit Pass #14 — PR #386 (\perf/low-ram-tier-and-pressure-sweeps, head \dd0fb48)

  • Scope: \crates/victory-gpu/src/{ahead.rs,host.rs,host/sweep.rs,hwrt.rs,hwrt/budget.rs,list.rs,residency.rs}\
  • Pass 1 (\1993124): Found 1 [P1]\ (\hwrt::trim_on_pressure\ calling \manager()\ \OnceLock::get_or_init) + 3 [P2]\s (\give_prelude\ refill cap under pressure, non-critical VRAM \leases\ drain churn, \ iny\ physical recovery threshold \5.5 GiB).
  • Pass 2 (\dd0fb48): All 4 findings fixed (\MGR\ lifted to module scope with \MGR.get().and_then(Option::as_ref), non-critical HW-RT trim drains host
    eadbacks\ only while \leases/\s_pool\ require \critical, \give_prelude\ caps to \prelude_pressure_keep\ while pressured, \ iny\ hysteresis <= 3 GiB / < 4.5 GiB\ phys & <= 6 GiB / < 8 GiB\ commit).
  • Verdict: VERIFIED CLEAN (0 P0, 0 P1, 0 P2)
<!-- greyfinch-sync:Androtim/MiniVI:comment:7377330572 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7377330572). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T11:54:12Z. --- ### Reasoning Audit Pass #14 — PR #386 (\perf/low-ram-tier-and-pressure-sweeps\, head \dd0fb48\) - **Scope:** \crates/victory-gpu/src/{ahead.rs,host.rs,host/sweep.rs,hwrt.rs,hwrt/budget.rs,list.rs,residency.rs}\ - **Pass 1 (\1993124\):** Found 1 \[P1]\ (\hwrt::trim_on_pressure\ calling \manager()\ \OnceLock::get_or_init\) + 3 \[P2]\s (\give_prelude\ refill cap under pressure, non-critical VRAM \leases\ drain churn, \ iny\ physical recovery threshold \5.5 GiB\). - **Pass 2 (\dd0fb48\):** All 4 findings fixed (\MGR\ lifted to module scope with \MGR.get().and_then(Option::as_ref)\, non-critical HW-RT trim drains host \ eadbacks\ only while \leases\/\s_pool\ require \critical\, \give_prelude\ caps to \prelude_pressure_keep\ while pressured, \ iny\ hysteresis \<= 3 GiB / < 4.5 GiB\ phys & \<= 6 GiB / < 8 GiB\ commit). - **Verdict:** **VERIFIED CLEAN (0 P0, 0 P1, 0 P2)**
Androtim commented 2026-12-03 12:37:34 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T12:37:34Z.


Reasoning Audit Pass #15 — PR #388 (\perf/draw-hotpath-cache, commit \2d7c529)

  • Scope: \crates/victory-gpu/src/{host.rs,list.rs,draw.rs}\
  • Checks: Verified complete \state_epoch\ invalidation across every recording-time \states/\ wins\ mutation, \TESTED_DEPTH\ transitions, \State::set_targets\ bind-cache interaction, atomic \HostTexture/\Twin\ creation, \BATCH_USE/\WINDOW_USE\ \use_id\ equivalence across resets/cuts, immutable bindless heap tables, and #[cfg(windows)]\ Linux CI portability.
  • Verdict: VERIFIED CLEAN (0 P0, 0 P1, 0 P2)
<!-- greyfinch-sync:Androtim/MiniVI:comment:7378596391 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7378596391). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T12:37:34Z. --- ### Reasoning Audit Pass #15 — PR #388 (\perf/draw-hotpath-cache\, commit \2d7c529\) - **Scope:** \crates/victory-gpu/src/{host.rs,list.rs,draw.rs}\ - **Checks:** Verified complete \state_epoch\ invalidation across every recording-time \states\/\ wins\ mutation, \TESTED_DEPTH\ transitions, \State::set_targets\ bind-cache interaction, atomic \HostTexture\/\Twin\ creation, \BATCH_USE\/\WINDOW_USE\ \use_id\ equivalence across resets/cuts, immutable bindless heap tables, and \#[cfg(windows)]\ Linux CI portability. - **Verdict:** **VERIFIED CLEAN (0 P0, 0 P1, 0 P2)**
Androtim commented 2026-12-03 13:08:49 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T13:08:49Z.


Deep Reasoning Audit Pass #16 — PR #390 (perf/submit-lockfree-nothing-new, commit 0b700ca)

  • Scope: crates/victory-gpu/src/{host.rs,host/refresh_tests.rs,shadow.rs,watch.rs}
  • Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Verified Invariants:

  1. Batch pre-filtering & ask_ahead ordering (host.rs):
    • Batch::filter_unchanged and Batch::ask_ahead_and_filter share lock-free ahead_snapshot_into + Shadow::nothing_new_with filtering across Batch::refresh_front, Batch::flush_all, and Batch::refresh_ahead.
    • Prior Step::Run (batch.title_written() clears self.ahead + watch::ask_once_end() clears j.ahead and KEPT), Step::Copy (title_written() + watch::writing + watch::wrote), Step::Placed (title_written() + watch::writing + watch::wrote), concurrent CPU writes (PUBLISHED cleared on view faults, asked_ahead() / WRITTEN_EPOCHS monotonic on write-watched memory), unwatched shadows (!matches!(watched, 1 | GUARDED) returns false), and pending gaps are all retained.
    • kept (watch::is_kept()) / ask_ahead / ask_ahead_done pairing is preserved even if re-filtering reduces surviving spans to <= 1; synchronous ask_ahead populates WRITTEN_EPOCHS (Release) and j.ahead under journal_mut() before ahead_snapshot_into re-filters, so newly dirtied pages (now > copied.max(ranged)) cannot be dropped.
  2. Shadow::gaps_nothing_new, Shadow::nothing_new_with, and ranged_lockfree (shadow.rs):
    • Whole-range lock-free check_gap(from, to) fast-path before self.pending.lock() is sound: [a, b) ⊆ [from, to) implies published(a, b), ahead interval containment, and ranged_lockfree(a, b) >= ranged_lockfree(from, to), while ranges inside self.pending are skipped by Shadow::update anyway. On false, gaps_nothing_new locks pending, returns false if busy.is_empty() (concurrent copy_back_done), or checks each free gap.
    • ranged_lockfree SeqLock ordering (s1 Acquire even check, Relaxed slot loads + fence(Acquire) + Relaxed ranged_seq == s1 recheck) pairs with copy_stale's copy_lock-serialized seq + 1 -> fence(Release) -> slot stores -> seq + 2 (Release) after take_all and mark_copied. Both Shadow::nothing_new and Shadow::nothing_new_with enforce crate::watch::light().
  3. PageEpochs::all_within_with, watch::nothing_new_with, and watch::nothing_new_single (watch.rs):
    • Lazy ranged evaluation executes only inside WRITTEN_EPOCHS.all_within_with after published || ahead (contains_interval / ahead_asked_at) succeeds and any JOURNAL read guard is dropped, and only when needed (t0 == 0 || w > t0 on single-page fast path; !all_copied && any(taken == 0) or w != 0 && w > t on multi-page path).
    • all_copied (uncopied_pages.load(Acquire) == 0) synchronizes-with mark_copied's swap(AcqRel) -> fetch_sub(1, Release).
  4. Portability & CI:
    • All 4 files reside in #[cfg(windows)] modules (crates/victory-gpu/src/lib.rs), PageEpochs::all_within is gated #[cfg(test)], and PR #390 CI check (47111008969/job/144269478960 on windows-latest: clippy default + --all-features + workspace tests) passed on 0b700ca.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7379381558 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7379381558). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T13:08:49Z. --- ### Deep Reasoning Audit Pass #16 — PR #390 (`perf/submit-lockfree-nothing-new`, commit `0b700ca`) - **Scope:** `crates/victory-gpu/src/{host.rs,host/refresh_tests.rs,shadow.rs,watch.rs}` - **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` **Verified Invariants:** 1. **`Batch` pre-filtering & `ask_ahead` ordering (`host.rs`):** - `Batch::filter_unchanged` and `Batch::ask_ahead_and_filter` share lock-free `ahead_snapshot_into` + `Shadow::nothing_new_with` filtering across `Batch::refresh_front`, `Batch::flush_all`, and `Batch::refresh_ahead`. - Prior `Step::Run` (`batch.title_written()` clears `self.ahead` + `watch::ask_once_end()` clears `j.ahead` and `KEPT`), `Step::Copy` (`title_written()` + `watch::writing` + `watch::wrote`), `Step::Placed` (`title_written()` + `watch::writing` + `watch::wrote`), concurrent CPU writes (`PUBLISHED` cleared on view faults, `asked_ahead()` / `WRITTEN_EPOCHS` monotonic on write-watched memory), unwatched shadows (`!matches!(watched, 1 | GUARDED)` returns `false`), and pending gaps are all retained. - `kept` (`watch::is_kept()`) / `ask_ahead` / `ask_ahead_done` pairing is preserved even if re-filtering reduces surviving spans to `<= 1`; synchronous `ask_ahead` populates `WRITTEN_EPOCHS` (`Release`) and `j.ahead` under `journal_mut()` before `ahead_snapshot_into` re-filters, so newly dirtied pages (`now > copied.max(ranged)`) cannot be dropped. 2. **`Shadow::gaps_nothing_new`, `Shadow::nothing_new_with`, and `ranged_lockfree` (`shadow.rs`):** - Whole-range lock-free `check_gap(from, to)` fast-path before `self.pending.lock()` is sound: `[a, b) ⊆ [from, to)` implies `published(a, b)`, `ahead` interval containment, and `ranged_lockfree(a, b) >= ranged_lockfree(from, to)`, while ranges inside `self.pending` are skipped by `Shadow::update` anyway. On `false`, `gaps_nothing_new` locks `pending`, returns `false` if `busy.is_empty()` (concurrent `copy_back_done`), or checks each free gap. - `ranged_lockfree` SeqLock ordering (`s1` `Acquire` even check, `Relaxed` slot loads + `fence(Acquire)` + `Relaxed` `ranged_seq == s1` recheck) pairs with `copy_stale`'s `copy_lock`-serialized `seq + 1` -> `fence(Release)` -> slot stores -> `seq + 2` (`Release`) after `take_all` and `mark_copied`. Both `Shadow::nothing_new` and `Shadow::nothing_new_with` enforce `crate::watch::light()`. 3. **`PageEpochs::all_within_with`, `watch::nothing_new_with`, and `watch::nothing_new_single` (`watch.rs`):** - Lazy `ranged` evaluation executes only inside `WRITTEN_EPOCHS.all_within_with` after `published || ahead` (`contains_interval` / `ahead_asked_at`) succeeds and any `JOURNAL` read guard is dropped, and only when needed (`t0 == 0 || w > t0` on single-page fast path; `!all_copied && any(taken == 0)` or `w != 0 && w > t` on multi-page path). - `all_copied` (`uncopied_pages.load(Acquire) == 0`) synchronizes-with `mark_copied`'s `swap(AcqRel)` -> `fetch_sub(1, Release)`. 4. **Portability & CI:** - All 4 files reside in `#[cfg(windows)]` modules (`crates/victory-gpu/src/lib.rs`), `PageEpochs::all_within` is gated `#[cfg(test)]`, and PR #390 CI check (`47111008969/job/144269478960` on `windows-latest`: clippy default + `--all-features` + workspace tests) passed on `0b700ca`.
Androtim commented 2026-12-03 13:37:56 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T13:37:56Z.


Deep Reasoning Audit Pass #17 — PR #393 (perf/pending-copies-and-mirror-cache, commit 0008339)

  • Scope: crates/victory-gpu/src/{descriptor/host.rs,draw.rs} (merged cleanly against origin/main via git merge-tree; branch base 07b5b5c precedes #383/#388)
  • Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Verified Invariants:

  1. Coalescing Dynamic Table Copies (PendingCopies / CopyDescriptors):
    • PendingCopies partitions primary slots ([0..RAW_TWINS)) and raw twin slots ([RAW_TWINS..)) into separate CopyPartition buffers (PENDING_COPY_CAP = 64), backed by disjoint per-thread CPU-only PendingStage slices (PENDING_STAGE_CAP = 128, PENDING_STAGE_THREADS = 512).
    • CopyPartition::push_with flushes the prior partition before accepting duplicate dst_slot writes or overflowing PENDING_COPY_CAP, preserving write-after-write order and disjoint CopyDescriptors destination ranges.
    • coalesce_copy_entries merges only contiguous dst_slot / dst.ptr (dst_step-checked) and contiguous src handles matching both src_tag (SRC_TAG_STAGE vs SRC_TAG_LISTED) and src_step != 0.
    • Sampler heaps bypass PendingCopies (!self.sampler / heap.samplers() guards); PendingCopies::bind_heap flushes on heap switches; State::tables flushes copies.flush() before returning table offsets to State::bind (prior to draw/dispatch/indirect recording), with Drop flushing as a fallback; is_cpu_staging_twin restricts move_raw patching to CPU-only staging slots.
  2. Direct CBV Binding (HostHeap::commit_direct_cbv / inline_constant / root CBVs):
    • State::tables decodes inline constants via inline_constant (and fallback View::Constant via view_with_words), allocates 256-byte-aligned scratch via HostList::scratch_held_with_base (next_multiple_of(256) on committed upload buffers), queues defer_constants, and binds via commit_direct_cbv (falling back to make_null_settled on allocation failure).
    • commit_direct_cbv_inner clamps CBV size via constant_bytes(size) (<= 64 KiB, 256-byte multiple), creates/clears the raw SRV twin (self.raw + index) consistently with self.twins, clears write_stride/write_address and untrack_rtas, and preserves kept/RETIRED resource lifetimes via keep_inner (PinOp::Clear guarded by lock-free pin_slots, with kept_raw stored Release after pin_slots.put and pin_count.fetch_add). Root CBVs (root_view) enforce 256-byte alignment via shadow.gpu or 256-byte-aligned fill_scratch.
  3. TLS MirrorCache / HostHeap::mirror_for_table_with / view_with / listed_view_with:
    • MirrorCache (512 × 2-way sets per thread) never caches key == 0 or inline CONSTANT records, uses try_borrow/try_borrow_mut to avoid re-entrant RefCell panics, and validates non-inline entries via views_entry_alive under views_read(), evicting entries invalidated by descriptor::forget or free_ownerless.
    • mirror_for_table_with requires quick_mirror() && self.quick_key(index) == key && !self.tlas_gen_stale(index) (quick_is cleared on unmake/evict/remap/flip and tlas_gen_is ordered Release before quick_is), preventing stale hits on slot overwrites, heap replacements, or hwrt::tlas_generation() bumps. listed_view_with scopes entries to monotonic State::recording (reset on tables_done() and State::reset()).
  4. Title-Neutrality, Portability & Verification:
    • Diff is fully title-neutral and confined to #[cfg(windows)] modules (descriptor/host.rs, draw.rs).
    • Verified locally on 0008339: cargo +1.98.1-x86_64-pc-windows-gnu clippy -p victory-gpu --all-targets -- -D warnings (pass), --all-features -- -D warnings (pass), and test -p victory-gpu --lib -- --test-threads=1 (842 passed; 0 failed; 39 ignored, including pending_copies_tests and mirror_cache_tests), matching PR #393 CI check (47114145957/job/144280477638).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7380123412 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7380123412). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T13:37:56Z. --- ### Deep Reasoning Audit Pass #17 — PR #393 (`perf/pending-copies-and-mirror-cache`, commit `0008339`) - **Scope:** `crates/victory-gpu/src/{descriptor/host.rs,draw.rs}` (merged cleanly against `origin/main` via `git merge-tree`; branch base `07b5b5c` precedes `#383`/`#388`) - **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` **Verified Invariants:** 1. **Coalescing Dynamic Table Copies (`PendingCopies` / `CopyDescriptors`):** - `PendingCopies` partitions primary slots (`[0..RAW_TWINS)`) and raw twin slots (`[RAW_TWINS..)`) into separate `CopyPartition` buffers (`PENDING_COPY_CAP = 64`), backed by disjoint per-thread CPU-only `PendingStage` slices (`PENDING_STAGE_CAP = 128`, `PENDING_STAGE_THREADS = 512`). - `CopyPartition::push_with` flushes the prior partition before accepting duplicate `dst_slot` writes or overflowing `PENDING_COPY_CAP`, preserving write-after-write order and disjoint `CopyDescriptors` destination ranges. - `coalesce_copy_entries` merges only contiguous `dst_slot` / `dst.ptr` (`dst_step`-checked) and contiguous `src` handles matching both `src_tag` (`SRC_TAG_STAGE` vs `SRC_TAG_LISTED`) and `src_step != 0`. - Sampler heaps bypass `PendingCopies` (`!self.sampler` / `heap.samplers()` guards); `PendingCopies::bind_heap` flushes on heap switches; `State::tables` flushes `copies.flush()` before returning table offsets to `State::bind` (prior to draw/dispatch/indirect recording), with `Drop` flushing as a fallback; `is_cpu_staging_twin` restricts `move_raw` patching to CPU-only staging slots. 2. **Direct CBV Binding (`HostHeap::commit_direct_cbv` / `inline_constant` / root CBVs):** - `State::tables` decodes inline constants via `inline_constant` (and fallback `View::Constant` via `view_with_words`), allocates 256-byte-aligned scratch via `HostList::scratch_held_with_base` (`next_multiple_of(256)` on committed upload buffers), queues `defer_constants`, and binds via `commit_direct_cbv` (falling back to `make_null_settled` on allocation failure). - `commit_direct_cbv_inner` clamps CBV size via `constant_bytes(size)` (`<= 64 KiB`, 256-byte multiple), creates/clears the raw SRV twin (`self.raw + index`) consistently with `self.twins`, clears `write_stride`/`write_address` and `untrack_rtas`, and preserves `kept`/`RETIRED` resource lifetimes via `keep_inner` (`PinOp::Clear` guarded by lock-free `pin_slots`, with `kept_raw` stored `Release` after `pin_slots.put` and `pin_count.fetch_add`). Root CBVs (`root_view`) enforce 256-byte alignment via `shadow.gpu` or 256-byte-aligned `fill_scratch`. 3. **TLS `MirrorCache` / `HostHeap::mirror_for_table_with` / `view_with` / `listed_view_with`:** - `MirrorCache` (512 × 2-way sets per thread) never caches `key == 0` or inline `CONSTANT` records, uses `try_borrow`/`try_borrow_mut` to avoid re-entrant `RefCell` panics, and validates non-inline entries via `views_entry_alive` under `views_read()`, evicting entries invalidated by `descriptor::forget` or `free_ownerless`. - `mirror_for_table_with` requires `quick_mirror() && self.quick_key(index) == key && !self.tlas_gen_stale(index)` (`quick_is` cleared on unmake/evict/remap/flip and `tlas_gen_is` ordered `Release` before `quick_is`), preventing stale hits on slot overwrites, heap replacements, or `hwrt::tlas_generation()` bumps. `listed_view_with` scopes entries to monotonic `State::recording` (reset on `tables_done()` and `State::reset()`). 4. **Title-Neutrality, Portability & Verification:** - Diff is fully title-neutral and confined to `#[cfg(windows)]` modules (`descriptor/host.rs`, `draw.rs`). - Verified locally on `0008339`: `cargo +1.98.1-x86_64-pc-windows-gnu clippy -p victory-gpu --all-targets -- -D warnings` (pass), `--all-features -- -D warnings` (pass), and `test -p victory-gpu --lib -- --test-threads=1` (`842 passed; 0 failed; 39 ignored`, including `pending_copies_tests` and `mirror_cache_tests`), matching PR #393 CI `check` (`47114145957/job/144280477638`).
Androtim commented 2026-12-03 13:58:18 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T13:58:18Z.


Deep Reasoning Audit Pass #18 — PR #394 (feat/ambient-alpha-and-nort-preset, commit 35fe0c4)

  • Scope: apps/victory/src/run.rs, crates/victory-gpu/src/{ambient.rs,draw.rs,mirror.rs}, crates/victory-loader/src/{hooks.rs,lib.rs,rt_preset.rs} (re-audit of 1ce4e98..35fe0c4; merges cleanly against origin/main 931e127 via git merge-tree)
  • Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Verified Fixes & Invariants:

  1. [VERIFIED FIXED — Pass 1 P1] DXR 1.1 HW-RT (hwrt::active()) gating across ambient stand-ins, Role::Alpha, mirror lighting, and CS_RayMiss skip:
    • ambient::title_rt_active() (crates/victory-gpu/src/ambient.rs:175-177) combines pipeline::builder_runs() || hwrt::active(). standin_enabled / ambient::on() (ambient.rs:179-192), alpha_enabled / ambient::alpha_on() (ambient.rs:300-307), ambient::around() (ambient.rs:1111-1114), ambient::without_depth() (ambient.rs:1241-1245), ambient::role_decision() (ambient.rs:1309-1319), and mirror::light() (crates/victory-gpu/src/mirror.rs:284-286) all short-circuit when either SW-RT or DXR 1.1 HW-RT is active (preserving stand-in fallback when VICTORY_HW_RT=1 is requested without DXR 1.1 support).
    • State::sky_miss_left_out() (crates/victory-gpu/src/draw.rs:4384-4395) passes hwrt::active() to sky_miss_should_skip() (draw.rs:6888-6902), keeping CS_RayMiss enabled under active DXR 1.1 HW-RT.
    • Covered by unit tests ambient::tests::standin_and_alpha_stay_disabled_when_rt_active, draw::record_hash_tests::ambient_indirect_eligibility_covers_miss_and_alpha, and draw::record_hash_tests::sky_miss_skip_respects_builder_specular_and_kill_switch.
  2. [VERIFIED FIXED — Pass 1 P2] Single rt_preset::asked() evaluation:
    • rt_preset::apply_asked (crates/victory-loader/src/rt_preset.rs:301-305) returns Option<(Preset, Patched)> and apps/victory/src/run.rs:491-495 consumes both from one call, eliminating duplicate unknown-value warning logs.
  3. Retained Pass 1 Invariants:
    • Role::Alpha (CS_SpatialFilterAlpha, bound_alpha barrier/luma guards, indirect flush via unsettle_indirect), raise() sky skip reset, rt_preset Preset::NoRt layout & apply_at bounds/BLAKE3/VirtualProtect invariants, GPL-3.0 attributions, and title-neutrality remain intact with zero new regressions.
  4. Verification (35fe0c4):
    • PR #394 CI check (47119925658/job/144300901914): SUCCESS.
    • Local (+1.98.1-x86_64-pc-windows-gnu): clippy -p victory-gpu -p victory-loader -p victory --all-targets --locked -- -D warnings & --all-features -- -D warnings (pass), xtask policy (asset policy: 352 files ok), xtask (8 passed; 0 failed), victory-loader --lib (66 passed; 0 failed), victory-gpu --lib ambient (19 passed; 0 failed; 1 ignored), victory-gpu --lib draw::record_hash_tests (4 passed; 0 failed), victory-gpu --lib mirror (5 passed; 0 failed), and victory (47 passed; 0 failed + 2 passed; 0 failed census.rs).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7380680452 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7380680452). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T13:58:18Z. --- ### Deep Reasoning Audit Pass #18 — PR #394 (`feat/ambient-alpha-and-nort-preset`, commit `35fe0c4`) - **Scope:** `apps/victory/src/run.rs`, `crates/victory-gpu/src/{ambient.rs,draw.rs,mirror.rs}`, `crates/victory-loader/src/{hooks.rs,lib.rs,rt_preset.rs}` (re-audit of `1ce4e98..35fe0c4`; merges cleanly against `origin/main` `931e127` via `git merge-tree`) - **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` **Verified Fixes & Invariants:** 1. **`[VERIFIED FIXED — Pass 1 P1]` DXR 1.1 HW-RT (`hwrt::active()`) gating across ambient stand-ins, `Role::Alpha`, mirror lighting, and `CS_RayMiss` skip:** - `ambient::title_rt_active()` (`crates/victory-gpu/src/ambient.rs:175-177`) combines `pipeline::builder_runs() || hwrt::active()`. `standin_enabled` / `ambient::on()` (`ambient.rs:179-192`), `alpha_enabled` / `ambient::alpha_on()` (`ambient.rs:300-307`), `ambient::around()` (`ambient.rs:1111-1114`), `ambient::without_depth()` (`ambient.rs:1241-1245`), `ambient::role_decision()` (`ambient.rs:1309-1319`), and `mirror::light()` (`crates/victory-gpu/src/mirror.rs:284-286`) all short-circuit when either SW-RT or DXR 1.1 HW-RT is active (preserving stand-in fallback when `VICTORY_HW_RT=1` is requested without DXR 1.1 support). - `State::sky_miss_left_out()` (`crates/victory-gpu/src/draw.rs:4384-4395`) passes `hwrt::active()` to `sky_miss_should_skip()` (`draw.rs:6888-6902`), keeping `CS_RayMiss` enabled under active DXR 1.1 HW-RT. - Covered by unit tests `ambient::tests::standin_and_alpha_stay_disabled_when_rt_active`, `draw::record_hash_tests::ambient_indirect_eligibility_covers_miss_and_alpha`, and `draw::record_hash_tests::sky_miss_skip_respects_builder_specular_and_kill_switch`. 2. **`[VERIFIED FIXED — Pass 1 P2]` Single `rt_preset::asked()` evaluation:** - `rt_preset::apply_asked` (`crates/victory-loader/src/rt_preset.rs:301-305`) returns `Option<(Preset, Patched)>` and `apps/victory/src/run.rs:491-495` consumes both from one call, eliminating duplicate unknown-value warning logs. 3. **Retained Pass 1 Invariants:** - `Role::Alpha` (`CS_SpatialFilterAlpha`, `bound_alpha` barrier/luma guards, indirect flush via `unsettle_indirect`), `raise()` sky skip reset, `rt_preset` `Preset::NoRt` layout & `apply_at` bounds/BLAKE3/`VirtualProtect` invariants, GPL-3.0 attributions, and title-neutrality remain intact with zero new regressions. 4. **Verification (`35fe0c4`):** - PR #394 CI `check` (`47119925658/job/144300901914`): `SUCCESS`. - Local (`+1.98.1-x86_64-pc-windows-gnu`): `clippy -p victory-gpu -p victory-loader -p victory --all-targets --locked -- -D warnings` & `--all-features -- -D warnings` (pass), `xtask policy` (`asset policy: 352 files ok`), `xtask` (`8 passed; 0 failed`), `victory-loader --lib` (`66 passed; 0 failed`), `victory-gpu --lib ambient` (`19 passed; 0 failed; 1 ignored`), `victory-gpu --lib draw::record_hash_tests` (`4 passed; 0 failed`), `victory-gpu --lib mirror` (`5 passed; 0 failed`), and `victory` (`47 passed; 0 failed` + `2 passed; 0 failed` `census.rs`).
Androtim commented 2026-12-03 14:01:03 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T14:01:03Z.


Gate 2 Deep Reasoning Audit — Pass #19: PR #387 (feat/hwrt-rayquery-lift-all-patterns, 78bf1c5)

Verdict: VERIFIED CLEAN (0 P0, 0 P1) (4-pass adversarial audit by read-only pro auditor)

  • Closed all prior [P0]/[P1] soundness findings across crates/victory-shader/src/emit/lower/rayquery/analyze.rs:
    • Replaced unguarded ir.strip_mov/ir.const_val in candidate/commit recognition with is_plain_valu, strip_plain_mov, plain_const_val, and plain_const_val_in_guard so non-dominating guarded moves cannot drop EXEC guards into MergeEdges/Always.
    • Hardened is_dead_vgpr_exit_phi with unconditionally_overwrites_vgpr_32 and tightened is_explicit_read for 16-bit partial writes, DPP, SDWA dst_unused==2/dst_sel>6, cross-lane/RMW ops, M0-relative VGPR moves, and DS atomics.
    • Restricted tri_merge_block PHI handling to CallbackKind::Blocks, added validate_tri_merge_phi rejecting mixed masked/guarded + skip/raw callback arms (BlocksMixedMaskedAndOldArmBail) and nested callback-interior merge commits (BlocksNestedInnerMergeCommit), and made cb_val_reaches fail-closed.
  • Verification: clippy -p victory-shader --all-targets -- -D warnings clean (0 warnings), all 28/28 rayquery unit & negative regression tests green.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7380753342 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7380753342). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T14:01:03Z. --- ### Gate 2 Deep Reasoning Audit — Pass #19: PR #387 (`feat/hwrt-rayquery-lift-all-patterns`, `78bf1c5`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` (4-pass adversarial audit by read-only `pro` auditor) - **Closed all prior `[P0]`/`[P1]` soundness findings across `crates/victory-shader/src/emit/lower/rayquery/analyze.rs`:** - Replaced unguarded `ir.strip_mov`/`ir.const_val` in candidate/commit recognition with `is_plain_valu`, `strip_plain_mov`, `plain_const_val`, and `plain_const_val_in_guard` so non-dominating guarded moves cannot drop EXEC guards into `MergeEdges`/`Always`. - Hardened `is_dead_vgpr_exit_phi` with `unconditionally_overwrites_vgpr_32` and tightened `is_explicit_read` for 16-bit partial writes, DPP, SDWA `dst_unused==2`/`dst_sel>6`, cross-lane/RMW ops, M0-relative VGPR moves, and DS atomics. - Restricted `tri_merge_block` PHI handling to `CallbackKind::Blocks`, added `validate_tri_merge_phi` rejecting mixed masked/guarded + skip/raw callback arms (`BlocksMixedMaskedAndOldArmBail`) and nested callback-interior merge commits (`BlocksNestedInnerMergeCommit`), and made `cb_val_reaches` fail-closed. - **Verification:** `clippy -p victory-shader --all-targets -- -D warnings` clean (`0` warnings), all `28/28` `rayquery` unit & negative regression tests green.
Androtim commented 2026-12-03 14:02:21 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T14:02:21Z.


Gate 2 Deep Reasoning Audit — Pass #20: PR #392 (perf/ram-staging-commit-reduction, commit 87289a7)

Scope: Re-audit of bd171f1..87289a7 across crates/victory-gpu/src/{shadow.rs,texture.rs,texture/ahead.rs,texture_detile_tests.rs} (and full PR context origin/main...87289a7; merges cleanly against origin/main 931e127 via git merge-tree --write-tree).

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Closed Pass 1 Findings & Verified Invariants:

  1. [VERIFIED FIXED — Pass 1 P0] Staging::cpu publication vs forget()/refresh() and ensure_cpu lock-gap races:
    • CpuStaging now tracks monotonic id (NEXT_CPU_ID) and populated: AtomicBool (Release stored in Staging::detile only after mips_guard drops and all subresources succeed; Acquire checked via is_populated()).
    • Staging::refresh_timed checks self.current_cpu() under self.last.lock() (last -> cpu lock order) and invokes Last::reset_for_new_cpu whenever last.cpu_id != cpu.id || !cpu.is_populated(), eliminating out-of-lock staging.forget() races in upload_from, PreludeUpload::finish_refresh, and ahead::claim.
    • Staging::prepare_prelude_upload refreshes whenever !guard.cpu().is_populated() rather than gating on newly_made.
    • Staging::ensure_cpu acquires self.last before self.cpu (last -> cpu), setting dirty (Release), resetting written_mips (Release), installing cpu, and calling last.reset_for_new_cpu(cpu_id) atomically before unlocking self.cpu, closing the concurrent release_cpu_if_idle drop window.
  2. [VERIFIED FIXED — Pass 1 P1] Re-acquired zeroed CpuStaging on already-uploaded textures:
    • Staging::refresh_unlocked skips partial-page fill() when self.uploaded.load(Acquire) is true.
    • Staging::prepare_prelude_upload aborts without calling claim_upload (preserving dirty = true) when self.uploaded.load(Acquire) && !guard.cpu().is_populated().
    • Staging::prepare_direct_upload / upload_from synchronously calls self.refresh() when self.uploaded.load(Acquire) && !guard.cpu().is_populated(), returning DirectUpload::Unpopulated without recording CopyTextureRegion or clearing dirty if unpopulated.
    • ahead::Worker::copy / ahead::finish only records/commits/flips when !job.staging.uploaded.load(Acquire) || job.upload.cpu().is_populated(), falling back to LISTED (Then::Failed) otherwise.
  3. [VERIFIED FIXED — Pass 1 P2] shadow.rs length and partial-commit epoch tracking:
    • Shadow::stale_pages passes hi - lo length to shadow.card_held(lo - start, hi - lo).
    • Shadow::take / take_landed / copy / take_all / copy_stale propagate actual copied byte counts and missed intervals on CardMirror::ensure_committed failure, skipping mark_copied, self.ranged updates, and uncommitted slice dereferences/dirty tracking for uncommitted ranges.
  4. Concurrency, Memory Safety & Fence Lifetime:
    • Strict last -> cpu lock order across Staging, duplicate/taken dropped after unlocking, UploadGuard (pending_uploads: AtomicU32) held until post-fence HostList::reset() and post-SetEventOnCompletion ahead::finish, and pool::staging zeroes recycled pieces (again == true).

Verification (87289a7):

  • PR #392 CI check (47119796155/job/144300449855): pass.
  • Local (+1.98.1-x86_64-pc-windows-gnu): clippy -p victory-gpu --all-targets --locked -- -D warnings (pass), clippy -p victory-gpu --all-targets --all-features --locked -- -D warnings (pass), test -p victory-gpu --lib -- --test-threads=1 (850 passed; 0 failed; 39 ignored), and detile_fallback_tests -- --nocapture --test-threads=1 (6/6 passed on D3D12 WARP, including the new [P0]/[P1] regression tests plus shadow::card_staging_tests and pool::tests).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7380789268 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7380789268). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T14:02:21Z. --- ### Gate 2 Deep Reasoning Audit — Pass #20: PR #392 (`perf/ram-staging-commit-reduction`, commit `87289a7`) **Scope:** Re-audit of `bd171f1..87289a7` across `crates/victory-gpu/src/{shadow.rs,texture.rs,texture/ahead.rs,texture_detile_tests.rs}` (and full PR context `origin/main...87289a7`; merges cleanly against `origin/main` `931e127` via `git merge-tree --write-tree`). **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` **Closed Pass 1 Findings & Verified Invariants:** 1. **`[VERIFIED FIXED — Pass 1 P0]` `Staging::cpu` publication vs `forget()`/`refresh()` and `ensure_cpu` lock-gap races:** - `CpuStaging` now tracks monotonic `id` (`NEXT_CPU_ID`) and `populated: AtomicBool` (`Release` stored in `Staging::detile` only after `mips_guard` drops and all subresources succeed; `Acquire` checked via `is_populated()`). - `Staging::refresh_timed` checks `self.current_cpu()` under `self.last.lock()` (`last -> cpu` lock order) and invokes `Last::reset_for_new_cpu` whenever `last.cpu_id != cpu.id || !cpu.is_populated()`, eliminating out-of-lock `staging.forget()` races in `upload_from`, `PreludeUpload::finish_refresh`, and `ahead::claim`. - `Staging::prepare_prelude_upload` refreshes whenever `!guard.cpu().is_populated()` rather than gating on `newly_made`. - `Staging::ensure_cpu` acquires `self.last` before `self.cpu` (`last -> cpu`), setting `dirty` (`Release`), resetting `written_mips` (`Release`), installing `cpu`, and calling `last.reset_for_new_cpu(cpu_id)` atomically before unlocking `self.cpu`, closing the concurrent `release_cpu_if_idle` drop window. 2. **`[VERIFIED FIXED — Pass 1 P1]` Re-acquired zeroed `CpuStaging` on already-uploaded textures:** - `Staging::refresh_unlocked` skips partial-page `fill()` when `self.uploaded.load(Acquire)` is true. - `Staging::prepare_prelude_upload` aborts without calling `claim_upload` (preserving `dirty = true`) when `self.uploaded.load(Acquire) && !guard.cpu().is_populated()`. - `Staging::prepare_direct_upload` / `upload_from` synchronously calls `self.refresh()` when `self.uploaded.load(Acquire) && !guard.cpu().is_populated()`, returning `DirectUpload::Unpopulated` without recording `CopyTextureRegion` or clearing `dirty` if unpopulated. - `ahead::Worker::copy` / `ahead::finish` only records/commits/flips when `!job.staging.uploaded.load(Acquire) || job.upload.cpu().is_populated()`, falling back to `LISTED` (`Then::Failed`) otherwise. 3. **`[VERIFIED FIXED — Pass 1 P2]` `shadow.rs` length and partial-commit epoch tracking:** - `Shadow::stale_pages` passes `hi - lo` length to `shadow.card_held(lo - start, hi - lo)`. - `Shadow::take` / `take_landed` / `copy` / `take_all` / `copy_stale` propagate actual copied byte counts and `missed` intervals on `CardMirror::ensure_committed` failure, skipping `mark_copied`, `self.ranged` updates, and uncommitted slice dereferences/dirty tracking for uncommitted ranges. 4. **Concurrency, Memory Safety & Fence Lifetime:** - Strict `last -> cpu` lock order across `Staging`, `duplicate`/`taken` dropped after unlocking, `UploadGuard` (`pending_uploads: AtomicU32`) held until post-fence `HostList::reset()` and post-`SetEventOnCompletion` `ahead::finish`, and `pool::staging` zeroes recycled pieces (`again == true`). **Verification (`87289a7`):** - PR #392 CI `check` (`47119796155/job/144300449855`): `pass`. - Local (`+1.98.1-x86_64-pc-windows-gnu`): `clippy -p victory-gpu --all-targets --locked -- -D warnings` (pass), `clippy -p victory-gpu --all-targets --all-features --locked -- -D warnings` (pass), `test -p victory-gpu --lib -- --test-threads=1` (`850 passed; 0 failed; 39 ignored`), and `detile_fallback_tests -- --nocapture --test-threads=1` (`6/6` passed on D3D12 WARP, including the new `[P0]`/`[P1]` regression tests plus `shadow::card_staging_tests` and `pool::tests`).
Androtim commented 2026-12-03 14:06:16 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T14:06:16Z.


Gate 2 Deep Reasoning Audit — Pass #21: PR #396 (perf/shader-pure-load-and-srv-cse, commit 7e615e6)

Scope: Read-only audit of git diff origin/main...HEAD (commit 7e615e6a9a76840960a8c0f16eb9538a00825eed, merge-base 4f09e0582f7bdecde4d87cf5c8414712b04ab8c2, 5 files, +903/-17, clean git merge-tree --write-tree against origin/main) across crates/victory-shader/src/emit/{bitcode.rs,bitcode/opt.rs,lower.rs,lower_tests.rs,mod.rs}.

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Verified Compiler Soundness Invariants:

  1. pure_loads / mark_pure (SLOT_MEMORY page directory CSE):
    • Module::pure_loads (bitcode.rs:230-234) and Module::mark_pure (bitcode.rs:506-513) live inside private mod bitcode (emit/mod.rs) and are called only once — in Lower::memory_entry (lower.rs:3896-3911) on the rawBufferLoad.f32 lookup of root_srv_handle(SLOT_MEMORY). No UAV, RWStructuredBuffer, TGSM/LDS, scratch/stack, or aliased title-memory load is ever marked pure.
    • Lower::memory_entry clamps page to MEMORY_PAGES - 1 (Tag::Clamp) prior to shifting (lower.rs:3876-3896), preventing out-of-bounds directory indexing on divergent or fault-inducing branches. opt.rs merge() (1267-1304) never hoists instructions (repl[i] = Some(first) strictly under dominance), and class() (933-939) / has_effect() (1381-1383) allow CSE across SLOT_FAULTS stores/atomics without dropping those stores.
  2. DOM_LOADS (128, DEFAULT = ALL = 255) & srv_memory_regions (RawBuffer SRV CSE):
    • Domination & loops (opt.rs:1027-1086, 1267-1304): srv_memory_regions computes an RPO fixpoint over tree.order: blocks with conflicting predecessor exit regions (loop headers with back-edge global writes, or diamond joins with one writing branch) pin entry[b] = b, while loop-invariant SRVs and clean branches preserve the dominating region (repl[i] still requires first to dominate i in merge(), and loop-variant addresses differ in SSA Value/PHI operands).
    • Memory aliasing & barriers (opt.rs:978-1013, lower.rs:1988-1996, 7103): is_global_buffer_write treats only DXIL non-global writes (Op::Store/AtomicRmw/CmpXchg, shader outputs, discard, textureStore) as non-aliasing for RawBuffer SRVs; rawBufferStore, bufferStore, atomics, and RayQuery mutators advance region and clear intra-block read. Barriers invalidate whenever args.get(1) (int_k) is non-constant or (m & 6) != 0 (global UAV fence 2 or thread-group UAV fence 4); Lower::s_barrier (lower.rs:7103) sets bit 2 whenever writes_uavs is true.
    • Handle, offset, mask & typing (opt.rs:1093-1119): raw_srv_key matches only dx.op.rawBufferLoad.* on a dx.op.annotateHandle whose first resource-property word is exact i32 11 (Some((32, 11)) — excluding UAV 0x1000, ROV 0x2000, coherent 0x4000, structured, and typed resources; verified against shader.rs:495, lower.rs:3969, 4208, 13637). Key::BufferRead(region, *f, args.clone()) keys on exact function ID *f (opcode + overload return type) and full operand vector args (handle, index/offset, mask, alignment).
    • Cache key (mod.rs:462, shader_cache.rs:151): translation_fingerprint() hashes shader_opt().to_le_bytes().
  3. Attribution, Title-Neutrality & Tests:
    • Explicit GPL-3.0 attributions added for lobomfz/VIctory-xmem (PR #166, fd19a20) and ReTerryDavis/ReVIctory (40b5f9c). Diff is title-neutral (xtask policy: 351 files ok).
    • Positive & negative coverage in opt.rs:2064-2558 and lower_tests.rs:2623-2805 (non-dominance, branch/loop-header write invalidation, UAV store/atomic/DeviceMemoryBarrier invalidation, and dxil.dll validation).

Verification (7e615e6):

  • PR #396 CI check (47119014357, job 144297711208): pass (victory-shader: 417 passed; 0 failed; 6 ignored; victory-gpu: 840 passed; 0 failed; 39 ignored).
  • Local (+1.98.1-x86_64-pc-windows-gnu):
    • cargo +1.98.1-x86_64-pc-windows-gnu run ... --package xtask -- policy: asset policy: 351 files ok
    • cargo +1.98.1-x86_64-pc-windows-gnu test ... -p xtask --locked: 8 passed; 0 failed; 0 ignored
    • cargo +1.98.1-x86_64-pc-windows-gnu clippy ... -p victory-shader --all-targets -- -D warnings & --all-features: pass
    • cargo +1.98.1-x86_64-pc-windows-gnu clippy ... -p victory-gpu --all-targets -- -D warnings: pass
    • cargo +1.98.1-x86_64-pc-windows-gnu test ... -p victory-shader --lib -- --test-threads=1 bitcode::opt::tests the_clean_up_switch slot_memory_pure_load raw_srv_cse_in_lowered_shader: 21 passed; 0 failed; 0 ignored; 402 filtered out
<!-- greyfinch-sync:Androtim/MiniVI:comment:7380893922 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7380893922). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T14:06:16Z. --- ### Gate 2 Deep Reasoning Audit — Pass #21: PR #396 (`perf/shader-pure-load-and-srv-cse`, commit `7e615e6`) **Scope:** Read-only audit of `git diff origin/main...HEAD` (commit `7e615e6a9a76840960a8c0f16eb9538a00825eed`, merge-base `4f09e0582f7bdecde4d87cf5c8414712b04ab8c2`, 5 files, `+903/-17`, clean `git merge-tree --write-tree` against `origin/main`) across `crates/victory-shader/src/emit/{bitcode.rs,bitcode/opt.rs,lower.rs,lower_tests.rs,mod.rs}`. **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` **Verified Compiler Soundness Invariants:** 1. **`pure_loads` / `mark_pure` (`SLOT_MEMORY` page directory CSE):** - `Module::pure_loads` (`bitcode.rs:230-234`) and `Module::mark_pure` (`bitcode.rs:506-513`) live inside private `mod bitcode` (`emit/mod.rs`) and are called only once — in `Lower::memory_entry` (`lower.rs:3896-3911`) on the `rawBufferLoad.f32` lookup of `root_srv_handle(SLOT_MEMORY)`. No UAV, `RWStructuredBuffer`, TGSM/LDS, scratch/stack, or aliased title-memory load is ever marked pure. - `Lower::memory_entry` clamps `page` to `MEMORY_PAGES - 1` (`Tag::Clamp`) prior to shifting (`lower.rs:3876-3896`), preventing out-of-bounds directory indexing on divergent or fault-inducing branches. `opt.rs` `merge()` (`1267-1304`) never hoists instructions (`repl[i] = Some(first)` strictly under dominance), and `class()` (`933-939`) / `has_effect()` (`1381-1383`) allow CSE across `SLOT_FAULTS` stores/atomics without dropping those stores. 2. **`DOM_LOADS` (`128`, `DEFAULT = ALL = 255`) & `srv_memory_regions` (`RawBuffer` SRV CSE):** - **Domination & loops (`opt.rs:1027-1086`, `1267-1304`):** `srv_memory_regions` computes an RPO fixpoint over `tree.order`: blocks with conflicting predecessor exit regions (loop headers with back-edge global writes, or diamond joins with one writing branch) pin `entry[b] = b`, while loop-invariant SRVs and clean branches preserve the dominating region (`repl[i]` still requires `first` to dominate `i` in `merge()`, and loop-variant addresses differ in SSA `Value`/PHI operands). - **Memory aliasing & barriers (`opt.rs:978-1013`, `lower.rs:1988-1996`, `7103`):** `is_global_buffer_write` treats only DXIL non-global writes (`Op::Store`/`AtomicRmw`/`CmpXchg`, shader outputs, `discard`, `textureStore`) as non-aliasing for `RawBuffer` SRVs; `rawBufferStore`, `bufferStore`, atomics, and `RayQuery` mutators advance `region` and clear intra-block `read`. Barriers invalidate whenever `args.get(1)` (`int_k`) is non-constant or `(m & 6) != 0` (global UAV fence `2` or thread-group UAV fence `4`); `Lower::s_barrier` (`lower.rs:7103`) sets bit `2` whenever `writes_uavs` is true. - **Handle, offset, mask & typing (`opt.rs:1093-1119`):** `raw_srv_key` matches only `dx.op.rawBufferLoad.*` on a `dx.op.annotateHandle` whose first resource-property word is exact `i32 11` (`Some((32, 11))` — excluding UAV `0x1000`, ROV `0x2000`, coherent `0x4000`, structured, and typed resources; verified against `shader.rs:495`, `lower.rs:3969`, `4208`, `13637`). `Key::BufferRead(region, *f, args.clone())` keys on exact function ID `*f` (opcode + overload return type) and full operand vector `args` (handle, index/offset, mask, alignment). - **Cache key (`mod.rs:462`, `shader_cache.rs:151`):** `translation_fingerprint()` hashes `shader_opt().to_le_bytes()`. 3. **Attribution, Title-Neutrality & Tests:** - Explicit GPL-3.0 attributions added for `lobomfz/VIctory-xmem` (PR `#166`, `fd19a20`) and `ReTerryDavis/ReVIctory` (`40b5f9c`). Diff is title-neutral (`xtask policy`: `351 files ok`). - Positive & negative coverage in `opt.rs:2064-2558` and `lower_tests.rs:2623-2805` (non-dominance, branch/loop-header write invalidation, UAV store/atomic/`DeviceMemoryBarrier` invalidation, and `dxil.dll` validation). **Verification (`7e615e6`):** - PR #396 CI `check` (`47119014357`, job `144297711208`): `pass` (`victory-shader`: `417 passed; 0 failed; 6 ignored`; `victory-gpu`: `840 passed; 0 failed; 39 ignored`). - Local (`+1.98.1-x86_64-pc-windows-gnu`): - `cargo +1.98.1-x86_64-pc-windows-gnu run ... --package xtask -- policy`: `asset policy: 351 files ok` - `cargo +1.98.1-x86_64-pc-windows-gnu test ... -p xtask --locked`: `8 passed; 0 failed; 0 ignored` - `cargo +1.98.1-x86_64-pc-windows-gnu clippy ... -p victory-shader --all-targets -- -D warnings` & `--all-features`: `pass` - `cargo +1.98.1-x86_64-pc-windows-gnu clippy ... -p victory-gpu --all-targets -- -D warnings`: `pass` - `cargo +1.98.1-x86_64-pc-windows-gnu test ... -p victory-shader --lib -- --test-threads=1 bitcode::opt::tests the_clean_up_switch slot_memory_pure_load raw_srv_cse_in_lowered_shader`: `21 passed; 0 failed; 0 ignored; 402 filtered out`
Androtim commented 2026-12-03 14:20:48 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T14:20:48Z.


Gate 2 Deep Reasoning Audit — Pass #22: PR #395 (perf/thin-recording-root-cache, commit 564c9ac)

Scope: Re-audit of e1322a6..564c9ac (crates/victory-gpu/src/list.rs, crates/victory-gpu/src/list/thin.rs) and full PR context origin/main...564c9ac (6 files, +917/-265, clean git merge-tree --write-tree against origin/main).

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Closed Pass 1 [P1] (StateHold / whole-struct &mut List aliasing) & Verified Invariants:

  1. Stationary MutexGuard in StateHold::scope (list.rs:178-210, thin.rs:1212):
    • StateHold::scope projects only &(*this.cast::<List>()).state, keeps guard stationary on its stack frame after deriving ptr: *mut State = &mut *guard, stores (this as usize, ptr) in HELD_STATE, and declares _restore = Self { prev } after guard so HELD_STATE is restored before guard unlocks on return or unwind.
    • Nested StateHold::scope on the same this short-circuits without re-locking; with_locked_state (list.rs:215-234) clears HELD_STATE across f via an unwind-safe Restore guard and never re-enters with_locked_state/StateHold::scope on the same List (and State/HostList/hwrt::execute_op/streamline::{note,evaluate} callbacks never call back into crate::list::* state locks).
  2. Disjoint field projection in reset, cut, cut_to_fresh, and value_written (list.rs:617-671, 996-1006, 2811-2825):
    • Eliminated all whole-struct &mut List references on paths reachable during thin::translate; only disjoint fields ((*list).earlier, (*list).gate, (*list).host) are projected via raw pointer.
    • cut_to_fresh drops all &mut field borrows before taking &HostList via host_list_held(this) and calling with_locked_state(this, |s| s.replay(host)). detach_parts/cut_list/tables_done run only after Recording::wait() (done == true) when StateHold::scope has exited.
  3. Regression Coverage:
    • Added list::bc_copy_tests::state_hold_allows_reset_and_cut_across_held_state (list.rs:3281-3369) and list::thin::tests::translate_runs_reset_and_commands_under_state_hold (thin.rs:1816-1834), plus updated state_hold_reuses_held_mutex_across_calls_and_releases_on_drop (list.rs:3248-3277), exercising nested StateHold::scope, RESET/reset, untouched/touched cut, cut_to_fresh, value_written, and post-scope HELD_STATE/mutex cleanup.

Verification (564c9ac):

  • PR #395 CI check (47123882900, job 144314857719): pass (victory-gpu: 849 passed; 0 failed; 39 ignored; victory-shader: 410 passed; 0 failed; 6 ignored; xtask: 8 passed; 0 failed).
  • Local (+1.98.1-x86_64-pc-windows-gnu):
    • cargo test -p xtask --locked: 8 passed; 0 failed (incl. policy::tests::repository_passes_policy).
    • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings & --all-features -- -D warnings: pass (0 warnings).
    • cargo test -p victory-gpu --lib --locked -- --test-threads=1: 847 passed; 0 failed; 39 ignored on clean re-run (initial full run hit one unrelated pre-existing shadow-address reuse flake in descriptor::host::tests::views_off_their_elements_get_a_copy_of_their_bytes, which passed in isolation and on re-run).
    • cargo test -p victory-gpu --all-features --lib --locked -- --test-threads=1 state_hold translate_runs_reset rootcache listed_views_skip: 7 passed; 0 failed.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7381291689 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7381291689). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T14:20:48Z. --- ### Gate 2 Deep Reasoning Audit — Pass #22: PR #395 (`perf/thin-recording-root-cache`, commit `564c9ac`) **Scope:** Re-audit of `e1322a6..564c9ac` (`crates/victory-gpu/src/list.rs`, `crates/victory-gpu/src/list/thin.rs`) and full PR context `origin/main...564c9ac` (6 files, `+917/-265`, clean `git merge-tree --write-tree` against `origin/main`). **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` **Closed Pass 1 `[P1]` (`StateHold` / whole-struct `&mut List` aliasing) & Verified Invariants:** 1. **Stationary `MutexGuard` in `StateHold::scope` (`list.rs:178-210`, `thin.rs:1212`):** - `StateHold::scope` projects only `&(*this.cast::<List>()).state`, keeps `guard` stationary on its stack frame after deriving `ptr: *mut State = &mut *guard`, stores `(this as usize, ptr)` in `HELD_STATE`, and declares `_restore = Self { prev }` after `guard` so `HELD_STATE` is restored before `guard` unlocks on return or unwind. - Nested `StateHold::scope` on the same `this` short-circuits without re-locking; `with_locked_state` (`list.rs:215-234`) clears `HELD_STATE` across `f` via an unwind-safe `Restore` guard and never re-enters `with_locked_state`/`StateHold::scope` on the same `List` (and `State`/`HostList`/`hwrt::execute_op`/`streamline::{note,evaluate}` callbacks never call back into `crate::list::*` state locks). 2. **Disjoint field projection in `reset`, `cut`, `cut_to_fresh`, and `value_written` (`list.rs:617-671`, `996-1006`, `2811-2825`):** - Eliminated all whole-struct `&mut List` references on paths reachable during `thin::translate`; only disjoint fields (`(*list).earlier`, `(*list).gate`, `(*list).host`) are projected via raw pointer. - `cut_to_fresh` drops all `&mut` field borrows before taking `&HostList` via `host_list_held(this)` and calling `with_locked_state(this, |s| s.replay(host))`. `detach_parts`/`cut_list`/`tables_done` run only after `Recording::wait()` (`done == true`) when `StateHold::scope` has exited. 3. **Regression Coverage:** - Added `list::bc_copy_tests::state_hold_allows_reset_and_cut_across_held_state` (`list.rs:3281-3369`) and `list::thin::tests::translate_runs_reset_and_commands_under_state_hold` (`thin.rs:1816-1834`), plus updated `state_hold_reuses_held_mutex_across_calls_and_releases_on_drop` (`list.rs:3248-3277`), exercising nested `StateHold::scope`, `RESET`/`reset`, untouched/touched `cut`, `cut_to_fresh`, `value_written`, and post-scope `HELD_STATE`/mutex cleanup. **Verification (`564c9ac`):** - PR #395 CI `check` (`47123882900`, job `144314857719`): `pass` (`victory-gpu`: `849 passed; 0 failed; 39 ignored`; `victory-shader`: `410 passed; 0 failed; 6 ignored`; `xtask`: `8 passed; 0 failed`). - Local (`+1.98.1-x86_64-pc-windows-gnu`): - `cargo test -p xtask --locked`: `8 passed; 0 failed` (incl. `policy::tests::repository_passes_policy`). - `cargo clippy -p victory-gpu --all-targets --locked -- -D warnings` & `--all-features -- -D warnings`: `pass` (`0` warnings). - `cargo test -p victory-gpu --lib --locked -- --test-threads=1`: `847 passed; 0 failed; 39 ignored` on clean re-run (initial full run hit one unrelated pre-existing shadow-address reuse flake in `descriptor::host::tests::views_off_their_elements_get_a_copy_of_their_bytes`, which passed in isolation and on re-run). - `cargo test -p victory-gpu --all-features --lib --locked -- --test-threads=1 state_hold translate_runs_reset rootcache listed_views_skip`: `7 passed; 0 failed`.
Androtim commented 2026-12-03 16:40:43 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T16:40:43Z.


### Gate 2 Deep Reasoning Audit — Pass #23: PR #381 (fix/missing-character-head, commit 4d35a2b)

Scope: Read-only audit of gh pr diff 381 --repo Androtim/MiniVI (4d35a2b, base 1698b62c, 5 files, +208/-7, clean git merge-tree --write-tree against origin/main 21fcafd producing 142b5e99) across crates/victory-gpu/src/{pipeline/make.rs,shader_cache.rs} and crates/victory-shader/src/emit/{mod.rs,lower.rs,lower_tests.rs}.

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Verified Invariants:

  1. Early Head Blend-Shape Map Preparation (crates/victory-gpu/src/pipeline/make.rs):
    • HEAD_BLEND_SHAPE_MAP ("61e54e90adccaf6a", make.rs:148) is added to scene_input() (make.rs:153-166), setting scene_input = true and screen = true on Pending::new (make.rs:182-189).
    • pipeline::hand_out (pipeline.rs:672-676) calls make::early(&host) before returning the Pipeline object (object::hand_out), queuing it at REQUESTED priority into Queue::screen (ahead of EARLY / SLOW, serviced by dedicated SCREEN_WORKERS as well as general workers) and giving dispatch-time make::ready the separate screen_budget() (SPENT[1], default 10 s).
    • Synchronization, residency & memory: HostPipeline::new only translates immutable Shader::container bytes and compiles the D3D12 root signature + compute PSO (and immutable code_table_address upload chunk under POOL mutex if needed). Shader::dxil() holds an Arc<[u8]> (reloading transparently from shader_cache if previously trimmed by trim_shader_bytecode) across CreateComputePipelineState. Early preparation never touches title GPU buffers, CPU shadow memory, descriptor heaps, or eviction/residency paths, cannot race with GPU writes or title uploads, and adds only the 1 compute PSO the title dispatches.
  2. Scoped Face LDS Bounds Exemption (crates/victory-shader/src/emit/{mod.rs,lower.rs,lower_tests.rs} & crates/victory-gpu/src/shader_cache.rs):
    • Strict matching criteria (mod.rs:583-596, 641-691): FACE_PROGRAMS contains 25 unique, valid 16-hex-digit container hashes ("e4a7e088c7780ce8" is already in scene_input()). parse_lds_bounds_exempt and lds_bounds_exempt_matches enforce exact 16-hex ASCII case-insensitive equality (or explicit "all" / "0" / ""); short prefixes and malformed entries are placed in ignored and cannot broaden matching. Thread-local PROGRAM is scoped by with_program in emit::translate (mod.rs:704) and apps/victory/src/translate.rs:601 using an unwind-safe Restore Drop guard; empty PROGRAM never matches FACE_PROGRAMS or custom hashes.
    • Shader cache isolation (shader_cache.rs:65, 207): VICTORY_LDS_BOUNDS_EXEMPT is included in TRANSLATOR_ENV_KEYS and SHADER_CACHE_VERSION is bumped from 2 to 3, preventing reuse of stale v1/v2 cached DXIL blobs even when env defaults match (and pipeline::library::name keys on translated DXIL bytes).
    • dxil.dll soundness & title-neutrality: lds_bounds() (lower.rs:786-789) disables bounds clamping only when VICTORY_LDS_BOUNDS=0 or lds_bounds_exempt() matches, keeping clamping active for all other shaders (CS_SortRayTiles, etc.). Local dxil.dll (10.0.22000.0) accepts dynamic LDS indexing under the exemption (Ok(())), while static constant OOB GEPs (if ever constant-folded >= lds_dwords) remain rejected by dxil.dll (and Validator is offline/test-only, not runtime). Diff is completely title-neutral (xtask policy: 353 files ok) with clean TrustNo1/Darner (GPL-3.0) attributions.
  3. Compatibility with origin/main (21fcafd):
    • Clean merge onto origin/main (21fcafd) in an isolated temp clone; zero semantic conflicts with #392, #395, #396, #394, or #385.

Verification:

  • PR #381 CI check (47070308173, job 144127718140): pass (victory-shader: 410 passed; 0 failed; 6 ignored; victory-gpu: 836 passed; 0 failed; 39 ignored; xtask: 8 passed; 0 failed).
  • Local (+1.98.1-x86_64-pc-windows-gnu, pr-381 merged onto origin/main 21fcafd in isolated temp clone):
    • cargo +1.98.1-x86_64-pc-windows-gnu xtask policy: asset policy: 353 files ok
    • cargo +1.98.1-x86_64-pc-windows-gnu test -p xtask --locked: 8 passed; 0 failed; 0 ignored
    • cargo +1.98.1-x86_64-pc-windows-gnu clippy -p victory-shader -p victory-gpu --all-targets --locked -- -D warnings & --all-features -- -D warnings: pass (0 warnings)
    • cargo +1.98.1-x86_64-pc-windows-gnu test -p victory-gpu --lib --locked -- --test-threads=1: 865 passed; 0 failed; 39 ignored
    • cargo +1.98.1-x86_64-pc-windows-gnu test -p victory-shader --lib --locked -- --test-threads=1: 416 passed; 3 failed; 6 ignored (PR #381's lds_bounds_exempts_face_programs_from_clamping and lds_bounds_exempt_parsing_and_matching pass; the 3 PSV0 validation failures — first_half_values_render_on_hardware_and_warp, rectangles_are_drawn_whole, the_rectangle_stage_is_a_geometry_shader — are pre-existing local SDK 10.0.22000.0\x64\dxil.dll mismatches, confirmed identically failing on unmodified origin/main 21fcafd).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7385251261 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7385251261). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T16:40:43Z. --- ### Gate 2 Deep Reasoning Audit — Pass #23: PR #381 (`fix/missing-character-head`, commit `4d35a2b`) **Scope:** Read-only audit of `gh pr diff 381 --repo Androtim/MiniVI` (`4d35a2b`, base `1698b62c`, 5 files, `+208/-7`, clean `git merge-tree --write-tree` against `origin/main` `21fcafd` producing `142b5e99`) across `crates/victory-gpu/src/{pipeline/make.rs,shader_cache.rs}` and `crates/victory-shader/src/emit/{mod.rs,lower.rs,lower_tests.rs}`. **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` **Verified Invariants:** 1. **Early Head Blend-Shape Map Preparation (`crates/victory-gpu/src/pipeline/make.rs`):** - `HEAD_BLEND_SHAPE_MAP` (`"61e54e90adccaf6a"`, `make.rs:148`) is added to `scene_input()` (`make.rs:153-166`), setting `scene_input = true` and `screen = true` on `Pending::new` (`make.rs:182-189`). - `pipeline::hand_out` (`pipeline.rs:672-676`) calls `make::early(&host)` before returning the `Pipeline` object (`object::hand_out`), queuing it at `REQUESTED` priority into `Queue::screen` (ahead of `EARLY` / `SLOW`, serviced by dedicated `SCREEN_WORKERS` as well as general workers) and giving dispatch-time `make::ready` the separate `screen_budget()` (`SPENT[1]`, default 10 s). - **Synchronization, residency & memory:** `HostPipeline::new` only translates immutable `Shader::container` bytes and compiles the D3D12 root signature + compute PSO (and immutable `code_table_address` upload chunk under `POOL` mutex if needed). `Shader::dxil()` holds an `Arc<[u8]>` (reloading transparently from `shader_cache` if previously trimmed by `trim_shader_bytecode`) across `CreateComputePipelineState`. Early preparation never touches title GPU buffers, CPU shadow memory, descriptor heaps, or eviction/residency paths, cannot race with GPU writes or title uploads, and adds only the 1 compute PSO the title dispatches. 2. **Scoped Face LDS Bounds Exemption (`crates/victory-shader/src/emit/{mod.rs,lower.rs,lower_tests.rs}` & `crates/victory-gpu/src/shader_cache.rs`):** - **Strict matching criteria (`mod.rs:583-596, 641-691`):** `FACE_PROGRAMS` contains 25 unique, valid 16-hex-digit container hashes (`"e4a7e088c7780ce8"` is already in `scene_input()`). `parse_lds_bounds_exempt` and `lds_bounds_exempt_matches` enforce exact 16-hex ASCII case-insensitive equality (or explicit `"all"` / `"0"` / `""`); short prefixes and malformed entries are placed in `ignored` and cannot broaden matching. Thread-local `PROGRAM` is scoped by `with_program` in `emit::translate` (`mod.rs:704`) and `apps/victory/src/translate.rs:601` using an unwind-safe `Restore` `Drop` guard; empty `PROGRAM` never matches `FACE_PROGRAMS` or custom hashes. - **Shader cache isolation (`shader_cache.rs:65, 207`):** `VICTORY_LDS_BOUNDS_EXEMPT` is included in `TRANSLATOR_ENV_KEYS` and `SHADER_CACHE_VERSION` is bumped from `2` to `3`, preventing reuse of stale `v1`/`v2` cached DXIL blobs even when env defaults match (and `pipeline::library::name` keys on translated DXIL bytes). - **`dxil.dll` soundness & title-neutrality:** `lds_bounds()` (`lower.rs:786-789`) disables bounds clamping only when `VICTORY_LDS_BOUNDS=0` or `lds_bounds_exempt()` matches, keeping clamping active for all other shaders (`CS_SortRayTiles`, etc.). Local `dxil.dll` (`10.0.22000.0`) accepts dynamic LDS indexing under the exemption (`Ok(())`), while static constant OOB GEPs (if ever constant-folded `>= lds_dwords`) remain rejected by `dxil.dll` (and `Validator` is offline/test-only, not runtime). Diff is completely title-neutral (`xtask policy`: `353 files ok`) with clean `TrustNo1/Darner` (`GPL-3.0`) attributions. 3. **Compatibility with `origin/main` (`21fcafd`):** - Clean merge onto `origin/main` (`21fcafd`) in an isolated temp clone; zero semantic conflicts with `#392`, `#395`, `#396`, `#394`, or `#385`. **Verification:** - PR #381 CI `check` (`47070308173`, job `144127718140`): `pass` (`victory-shader`: `410 passed; 0 failed; 6 ignored`; `victory-gpu`: `836 passed; 0 failed; 39 ignored`; `xtask`: `8 passed; 0 failed`). - Local (`+1.98.1-x86_64-pc-windows-gnu`, `pr-381` merged onto `origin/main` `21fcafd` in isolated temp clone): - `cargo +1.98.1-x86_64-pc-windows-gnu xtask policy`: `asset policy: 353 files ok` - `cargo +1.98.1-x86_64-pc-windows-gnu test -p xtask --locked`: `8 passed; 0 failed; 0 ignored` - `cargo +1.98.1-x86_64-pc-windows-gnu clippy -p victory-shader -p victory-gpu --all-targets --locked -- -D warnings` & `--all-features -- -D warnings`: `pass` (`0` warnings) - `cargo +1.98.1-x86_64-pc-windows-gnu test -p victory-gpu --lib --locked -- --test-threads=1`: `865 passed; 0 failed; 39 ignored` - `cargo +1.98.1-x86_64-pc-windows-gnu test -p victory-shader --lib --locked -- --test-threads=1`: `416 passed; 3 failed; 6 ignored` (PR #381's `lds_bounds_exempts_face_programs_from_clamping` and `lds_bounds_exempt_parsing_and_matching` pass; the 3 PSV0 validation failures — `first_half_values_render_on_hardware_and_warp`, `rectangles_are_drawn_whole`, `the_rectangle_stage_is_a_geometry_shader` — are pre-existing local SDK `10.0.22000.0\x64\dxil.dll` mismatches, confirmed identically failing on unmodified `origin/main` `21fcafd`).
Androtim commented 2026-12-03 17:49:17 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T17:49:17Z.


Gate 2 Re-Audit (PR #387, \13ec537): VERIFIED CLEAN (\

<!-- greyfinch-sync:Androtim/MiniVI:comment:7387113309 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7387113309). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T17:49:17Z. --- Gate 2 Re-Audit (PR #387, \13ec537\): **VERIFIED CLEAN** (\
Androtim commented 2026-12-03 18:00:57 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T18:00:57Z.


Gate 2 Re-Audit — PR #399 (perf/xmem-hot-chunk-pinning, commit d5f4ddf)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Pure-reasoning re-audit of 5e3fd75..d5f4ddf (ab04297, d5f4ddf) against the earlier Gate 2 findings (memory.rs, draw.rs, host/check_cut.rs, and attributions already verified clean on 5e3fd75; CI SUCCESS on d5f4ddf):

  • [P0] 1 & [P0] 2 resolved (shadow.rs, host/quiet_tests.rs): gpu_writes_with_quiet, note_quiet_compared, and note_quiet_compared_address strictly gate Quiet to self.card.is_some() (and copy_back_with routes through self.note_quiet_compared inside the snapshot block). Non-carded (card.is_none()) buffers never activate or skip Quiet, preserving defer_gpu_write, Shadow::writing, line.written (late_met_known, blocked_by), and shadow.pending (stale_under_writes / Shadow::update) with no AUDIT_EVERY blindness.
  • [P1] 3 resolved (hwrt.rs, host/place.rs, host/card_steps.rs, host.rs, shadow.rs): Deterministic GPU writes (hwrt postbuild queries, place_copy, card_steps) use gpu_writes_always (allow_quiet = false) so they can never be muted even on carded buffers. RelayBack::merge, Host::card_back (gather_card_back_pieces + finish_card_back_ranges, excluding r.picked and setting changed before seen deduplication), and Shadow::copy_back_with all feed GPU-side change flags (usize::from(changed)) rather than written bytes.
  • Test & policy hygiene (d5f4ddf, list.rs, shadow.rs, host/quiet_tests.rs): #[cfg(test)] inline_snapshots on Shadow::unbacked keeps CPU-only Shadow::writing snapshots inline without touching global SNAPS or production codegen. New regression tests cover all 3 prior findings cleanly; zero title-neutrality or attribution regressions.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7387454859 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7387454859). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T18:00:57Z. --- ### Gate 2 Re-Audit — PR #399 (`perf/xmem-hot-chunk-pinning`, commit `d5f4ddf`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` Pure-reasoning re-audit of `5e3fd75..d5f4ddf` (`ab04297`, `d5f4ddf`) against the earlier Gate 2 findings (`memory.rs`, `draw.rs`, `host/check_cut.rs`, and attributions already verified clean on `5e3fd75`; CI `SUCCESS` on `d5f4ddf`): - **`[P0]` 1 & `[P0]` 2 resolved (`shadow.rs`, `host/quiet_tests.rs`):** `gpu_writes_with_quiet`, `note_quiet_compared`, and `note_quiet_compared_address` strictly gate `Quiet` to `self.card.is_some()` (and `copy_back_with` routes through `self.note_quiet_compared` inside the snapshot block). Non-carded (`card.is_none()`) buffers never activate or skip `Quiet`, preserving `defer_gpu_write`, `Shadow::writing`, `line.written` (`late_met_known`, `blocked_by`), and `shadow.pending` (`stale_under_writes` / `Shadow::update`) with no `AUDIT_EVERY` blindness. - **`[P1]` 3 resolved (`hwrt.rs`, `host/place.rs`, `host/card_steps.rs`, `host.rs`, `shadow.rs`):** Deterministic GPU writes (`hwrt` postbuild queries, `place_copy`, `card_steps`) use `gpu_writes_always` (`allow_quiet = false`) so they can never be muted even on carded buffers. `RelayBack::merge`, `Host::card_back` (`gather_card_back_pieces` + `finish_card_back_ranges`, excluding `r.picked` and setting `changed` before `seen` deduplication), and `Shadow::copy_back_with` all feed GPU-side change flags (`usize::from(changed)`) rather than `written` bytes. - **Test & policy hygiene (`d5f4ddf`, `list.rs`, `shadow.rs`, `host/quiet_tests.rs`):** `#[cfg(test)] inline_snapshots` on `Shadow::unbacked` keeps CPU-only `Shadow::writing` snapshots inline without touching global `SNAPS` or production codegen. New regression tests cover all 3 prior findings cleanly; zero title-neutrality or attribution regressions.
Androtim commented 2026-12-03 18:11:12 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T18:11:12Z.


Gate 2 Re-Audit: VERIFIED CLEAN (0 P0 / 0 P1)

  • PR: #400 (\ ix/vram-8gb-4k-eviction-headroom)
  • Commit: \a9b7f6\ (diff \de48b59..ba9b7f6, pure-reasoning read-only re-audit)
  • Resolved prior findings (3 P0, 2 P1):
    1. [P0] Lazy depth-twin sync (
      esource.rs, host/twins.rs, host/prelude.rs, host.rs, host/two_queues.rs):
      \Arc\ (\TwinCell::Retired(Weak)\ on \Drop), Dekker \SeqCst\ (\depth_written/\has_twin) + post-publish check under \TwinSlot::twin, and per-list \pending_depth_writes\ close both the same-list mid-list \depth -> twin\ copy drop and cross-list out-of-order sync race with an acyclic lock DAG (\states -> twins -> pending_depth_writes -> TwinSlot::twin).
    2. [P0] Pool quarantine (pool.rs): \draining_mask\ checks actual fit (\Ranges::fits) and preserves the fullest ripe candidate when no usable non-candidate exists; \ ake_ripe_with\ falls back to draining blocks for both \Grow::Yes\ and \Grow::Must\ before growing, and filters !draining[i]\ in the
      ipe.ahead > 0\ unripe path for \Grow::No.
    3. [P0] Bindless live eviction & \View::Placed\ restore (
      esource.rs, descriptor.rs):
      Tier 1b removed; \make_waiting()\ now resolves \View::Placed\ via \ iew_matches_resource\ / \placed_known.
    4. [P1] Tier 1a unmapped check & \WAITING\ handling (
      esource.rs, descriptor.rs):
      Tier 1a gates on full-footprint \is_fully_unmapped, evicts via \evict_unmapped_resource_slots\ (\use_waiting = false), and restores Phase-3 aborts via
      equeue_slots\ + \ exture_made.
    5. [P1] Invalid UAV barrier on depth resource (list.rs,
      esource.rs):
      \host_barrier\ (\kind == 2) skips emitting a UAV barrier when \existing_twin_resource\ is \None\ and \depth_and_unordered\ (now also guarding \dimension != BUFFER) is \ rue.
  • New regressions / title-neutrality: None found.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7387748774 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7387748774). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T18:11:12Z. --- ### Gate 2 Re-Audit: VERIFIED CLEAN (0 P0 / 0 P1) - **PR:** #400 (\ ix/vram-8gb-4k-eviction-headroom\) - **Commit:** \a9b7f6\ (diff \de48b59..ba9b7f6\, pure-reasoning read-only re-audit) - **Resolved prior findings (3 P0, 2 P1):** 1. **[P0] Lazy depth-twin sync ( esource.rs, host/twins.rs, host/prelude.rs, host.rs, host/two_queues.rs):** \Arc<TwinSlot>\ (\TwinCell::Retired(Weak)\ on \Drop\), Dekker \SeqCst\ (\depth_written\/\has_twin\) + post-publish check under \TwinSlot::twin\, and per-list \pending_depth_writes\ close both the same-list mid-list \depth -> twin\ copy drop and cross-list out-of-order sync race with an acyclic lock DAG (\states -> twins -> pending_depth_writes -> TwinSlot::twin\). 2. **[P0] Pool quarantine (pool.rs):** \draining_mask\ checks actual fit (\Ranges::fits\) and preserves the fullest ripe candidate when no usable non-candidate exists; \ ake_ripe_with\ falls back to draining blocks for both \Grow::Yes\ and \Grow::Must\ before growing, and filters \!draining[i]\ in the \ ipe.ahead > 0\ unripe path for \Grow::No\. 3. **[P0] Bindless live eviction & \View::Placed\ restore ( esource.rs, descriptor.rs):** Tier 1b removed; \make_waiting()\ now resolves \View::Placed\ via \ iew_matches_resource\ / \placed_known\. 4. **[P1] Tier 1a unmapped check & \WAITING\ handling ( esource.rs, descriptor.rs):** Tier 1a gates on full-footprint \is_fully_unmapped\, evicts via \evict_unmapped_resource_slots\ (\use_waiting = false\), and restores Phase-3 aborts via \ equeue_slots\ + \ exture_made\. 5. **[P1] Invalid UAV barrier on depth resource (list.rs, esource.rs):** \host_barrier\ (\kind == 2\) skips emitting a UAV barrier when \existing_twin_resource\ is \None\ and \depth_and_unordered\ (now also guarding \dimension != BUFFER\) is \ rue\. - **New regressions / title-neutrality:** None found.
Androtim commented 2026-12-03 18:24:09 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T18:24:09Z.


Gate 2 Re-Audit — PR #402 (fix/visuals-ghosting-and-pixelated-lighting, commit f87e3a4)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Pure-reasoning read-only re-audit of eb7d35b..f87e3a4 and full title-neutrality / path scan of origin/main...HEAD (all functional code previously verified 0 P0 / 0 technical P1 in the prior full audit):

  • Prior [P1] resolved (crates/victory-shader/src/emit/hdr.rs): git diff eb7d35b..f87e3a4 touches only the two doc-comment blocks in hdr.rs (nan_scrub_mode and Lower::scrub_nan), replacing the retail location reference with title-neutral upstream GPL-3.0 attributions (voidopcode/vilocity 598050b / 767369a, felicienradio/cold-project-vi ec62312, and aki-runtime 01f6f31 by Aki-Developer). Zero functional changes were introduced.
  • Full diff hygiene scan (origin/main...HEAD, 9 files / 946 added lines + commit message + PR #402 body): Zero retail game/character/location names and zero local paths found; clean git merge-tree against origin/main.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7388083139 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7388083139). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T18:24:09Z. --- ### Gate 2 Re-Audit — PR #402 (`fix/visuals-ghosting-and-pixelated-lighting`, commit `f87e3a4`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` Pure-reasoning read-only re-audit of `eb7d35b..f87e3a4` and full title-neutrality / path scan of `origin/main...HEAD` (all functional code previously verified `0 P0` / `0` technical `P1` in the prior full audit): - **Prior `[P1]` resolved (`crates/victory-shader/src/emit/hdr.rs`):** `git diff eb7d35b..f87e3a4` touches only the two doc-comment blocks in `hdr.rs` (`nan_scrub_mode` and `Lower::scrub_nan`), replacing the retail location reference with title-neutral upstream GPL-3.0 attributions (`voidopcode/vilocity` `598050b` / `767369a`, `felicienradio/cold-project-vi` `ec62312`, and `aki-runtime` `01f6f31` by `Aki-Developer`). Zero functional changes were introduced. - **Full diff hygiene scan (`origin/main...HEAD`, 9 files / 946 added lines + commit message + PR #402 body):** Zero retail game/character/location names and zero local paths found; clean `git merge-tree` against `origin/main`.
Androtim commented 2026-12-03 18:28:10 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T18:28:10Z.


Gate 2 Re-Audit — PR #401 (fix/dom-loads-pin-cuda-preload-chroma-bvh-stub, commit 35493b8)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Pure-reasoning read-only re-audit of ce60753..35493b8 (all production code previously verified 0 P0 in prior Gate 2 audits; only the unserialized upload::allocate_in_window unit-test race remained [P1]):

  • Prior [P1] resolved (crates/victory-gpu/src/upload.rs, crates/victory-gpu/src/list.rs, crates/victory-gpu/src/list/thin.rs): All four unit tests that allocate inside [4 GiB, 2^37) via upload::allocate_in_window (blocks_lie_below_40_bits_and_are_used_again_zeroed, the_pool_is_reserved_in_the_window_and_handed_out_once, every_inline_command_falls_back_to_the_table, and abandoned_upload_ops_reclaim_arena_slots) now acquire let _turn = crate::window::test_turn(); at function entry, serializing cleanly against window::tests::fence_reserves_title_window_and_releases_it_on_drop and streamline::tests::cuda_preload_holds_window_on_init_and_falls_back_cleanly_when_absent.
  • Exhaustive caller & lock-order verification: No other unit tests in crates/victory-gpu allocate in [4 GiB, 2^37) (an_unrepresentable_upload_returns_none and an_unrepresentable_pool_size_returns_none overflow and return None before reaching reserve/POOL; reserve_early defaults to 0 MB). window::test_turn() (TURN) has in-degree 0 in the lock graph (acquired strictly as the first statement of 6 single-threaded #[test] functions, never nested, never combined with warp_turn()), uses poison-recovering .unwrap_or_else(|e| e.into_inner()), and drops last in LIFO order — zero deadlocks.
  • Production impact & title-neutrality: Zero production changes (all 4 added lines are under #[cfg(test)]); commit message and diff are 100% title-neutral with zero clippy/warning regressions (_turn named binding avoids clippy::let_underscore_lock).
  • Non-blocking [P2] note: list.rs:2993 is in a module without #[cfg(windows)] (unlike upload.rs and list/thin.rs), though victory-gpu is already Windows-only on origin/main (mod ambient; unconditionally imports windows::Win32::*, and CI runs solely on windows-latest).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7388186212 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7388186212). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T18:28:10Z. --- ### Gate 2 Re-Audit — PR #401 (`fix/dom-loads-pin-cuda-preload-chroma-bvh-stub`, commit `35493b8`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` Pure-reasoning read-only re-audit of `ce60753..35493b8` (all production code previously verified `0 P0` in prior Gate 2 audits; only the unserialized `upload::allocate_in_window` unit-test race remained `[P1]`): - **Prior `[P1]` resolved (`crates/victory-gpu/src/upload.rs`, `crates/victory-gpu/src/list.rs`, `crates/victory-gpu/src/list/thin.rs`):** All four unit tests that allocate inside `[4 GiB, 2^37)` via `upload::allocate_in_window` (`blocks_lie_below_40_bits_and_are_used_again_zeroed`, `the_pool_is_reserved_in_the_window_and_handed_out_once`, `every_inline_command_falls_back_to_the_table`, and `abandoned_upload_ops_reclaim_arena_slots`) now acquire `let _turn = crate::window::test_turn();` at function entry, serializing cleanly against `window::tests::fence_reserves_title_window_and_releases_it_on_drop` and `streamline::tests::cuda_preload_holds_window_on_init_and_falls_back_cleanly_when_absent`. - **Exhaustive caller & lock-order verification:** No other unit tests in `crates/victory-gpu` allocate in `[4 GiB, 2^37)` (`an_unrepresentable_upload_returns_none` and `an_unrepresentable_pool_size_returns_none` overflow and return `None` before reaching `reserve`/`POOL`; `reserve_early` defaults to `0` MB). `window::test_turn()` (`TURN`) has in-degree 0 in the lock graph (acquired strictly as the first statement of 6 single-threaded `#[test]` functions, never nested, never combined with `warp_turn()`), uses poison-recovering `.unwrap_or_else(|e| e.into_inner())`, and drops last in LIFO order — **zero deadlocks**. - **Production impact & title-neutrality:** Zero production changes (all 4 added lines are under `#[cfg(test)]`); commit message and diff are 100% title-neutral with zero clippy/warning regressions (`_turn` named binding avoids `clippy::let_underscore_lock`). - **Non-blocking `[P2]` note:** `list.rs:2993` is in a module without `#[cfg(windows)]` (unlike `upload.rs` and `list/thin.rs`), though `victory-gpu` is already Windows-only on `origin/main` (`mod ambient;` unconditionally imports `windows::Win32::*`, and CI runs solely on `windows-latest`).
Androtim commented 2026-12-03 18:34:24 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T18:34:24Z.


Gate 2 Re-Audit — PR #403 (\perf/dstorage-cache-parts-one-call-dynamic-chunk, commit \e217efe)

Verdict: \VERIFIED CLEAN (0 P0, 0 P1)\

Pure-reasoning read-only re-audit of \df0efa2..e217efe\ (10 files, +388/-31 lines) verifying all 1 [P0]\ and 2 [P1]\ findings from the prior Gate 2 audit:

  • Prior [P0]\ resolved (\crates/victory-hle/src/modules/dstorage.rs):
    • \open_file\ now computes \File:🆔 Option\ via \decoded::file_id_for_handle(&kept, &file), querying \GetFileInformationByHandle\ (\FileStamp) and folding (dwVolumeSerialNumber, nFileIndexHigh, nFileIndexLow, ftLastWriteTime.dwHighDateTime, ftLastWriteTime.dwLowDateTime, nFileSizeHigh, nFileSizeLow)\ after a \
<!-- greyfinch-sync:Androtim/MiniVI:comment:7388346932 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7388346932). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T18:34:24Z. --- ### Gate 2 Re-Audit — PR #403 (\perf/dstorage-cache-parts-one-call-dynamic-chunk\, commit \e217efe\) **Verdict:** \VERIFIED CLEAN (0 P0, 0 P1)\ Pure-reasoning read-only re-audit of \df0efa2..e217efe\ (10 files, +388/-31 lines) verifying all 1 \[P0]\ and 2 \[P1]\ findings from the prior Gate 2 audit: - **Prior \[P0]\ resolved (\crates/victory-hle/src/modules/dstorage.rs\):** - \open_file\ now computes \File::id: Option<u128>\ via \decoded::file_id_for_handle(&kept, &file)\, querying \GetFileInformationByHandle\ (\FileStamp\) and folding \(dwVolumeSerialNumber, nFileIndexHigh, nFileIndexLow, ftLastWriteTime.dwHighDateTime, ftLastWriteTime.dwLowDateTime, nFileSizeHigh, nFileSizeLow)\ after a \
Androtim commented 2026-12-03 19:07:58 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T19:07:58Z.


Gate 2 Re-Audit — PR #404 (perf/interp-live-stream-bound-segment-tight, commit 8415763)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Pure-reasoning read-only re-audit of 63f0e19..8415763 (crates/victory-shader/src/io.rs, +169/-4 lines; all other files previously verified 0 P0, 0 P1 in prior re-audit of 63f0e19):

  • Prior [P0] resolved (crates/victory-shader/src/io.rs, InterpReach::value_reachable & live_non_folded_values):
    • InterpReach::value_reachable (lines 695–718) now propagates (w_out, next_avoided) along inactive (!gw) lanes whenever a non-full-overwrite instruction writes VGPR reg under guard = Some(gw) (inst.write(reg) == Some(w_out)), even when the active-lane meet(&check) returns false. It enforces the same next_avoided.len() >= 8 => true conservative cap, sort_unstable() canonicalization, pass_check ROBDD feasibility test, and seen deduplication as the full-overwrite branch.
    • live_non_folded_values (lines 890–894) now records (site, exec_epoch, w_out, val) in overwrites on the non-full-overwrite else branch whenever matches!(reg, Reg::V(_)) and inst.write(reg) is Some(w_out), ensuring downstream liveness outside (site.0, gw) / (site.0, w_epoch) propagates UseGuard::Mixed back through chained guarded RMW / partial VGPR writes to earlier guarded overwrites in both structured and unstructured modes while preserving lattice monotonicity and termination.
    • Verified test coverage (guarded_rmw_and_partial_write_after_guarded_overwrite_keep_first_half_weighted): covers both guarded RMW (v_add_f32 v2, 1.0, v2, VOP2 op 0x03) and guarded partial write (v_cvt_f16_f32 v2, v3, VOP1 op 0x0a) after guarded v_mov_b32 v2, 0 in both raise_structured and raise.
  • Prior [P1] resolved (crates/victory-shader/src/io.rs, reads_inactive_lanes):
    • reads_inactive_lanes (line 748) now includes v_readfirstlane_b32 (matches!(name, "v_readlane_b32" | "v_readfirstlane_b32")), preventing guarded overwrites from killing first-half values observable via WaveReadLaneFirst fallback (EXEC == 0) or pixel helper-lane first_lane ownership.
    • Cross-checked all cross-lane ops in emit/lower.rs (dpp, v_readlane_b32, v_readfirstlane_b32, v_permlane16_b32/v_permlanex16_b32, v_writelane_b32, ds_swizzle*, ds_*permute*) — no remaining unguarded inactive-lane readers.
    • Verified test coverage (Case C in inactive_lane_vgpr_readers_keep_first_half_weighted with v_readfirstlane_b32 s4, v2, VOP1 op 0x02) in both raise_structured and raise.
  • Title-neutrality & hygiene: 63f0e19..8415763 touches only crates/victory-shader/src/io.rs; zero title-neutrality violations, zero local paths, zero new issues. Confirmed 8415763885666f39bcab1a5f3faff7d7f0b30403 is PR #404's pushed HEAD.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7389200201 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7389200201). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T19:07:58Z. --- ### Gate 2 Re-Audit — PR #404 (`perf/interp-live-stream-bound-segment-tight`, commit `8415763`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` Pure-reasoning read-only re-audit of `63f0e19..8415763` (`crates/victory-shader/src/io.rs`, `+169/-4` lines; all other files previously verified `0 P0, 0 P1` in prior re-audit of `63f0e19`): - **Prior `[P0]` resolved (`crates/victory-shader/src/io.rs`, `InterpReach::value_reachable` & `live_non_folded_values`):** - `InterpReach::value_reachable` (lines 695–718) now propagates `(w_out, next_avoided)` along inactive (`!gw`) lanes whenever a non-full-overwrite instruction writes VGPR `reg` under `guard = Some(gw)` (`inst.write(reg) == Some(w_out)`), even when the active-lane `meet(&check)` returns `false`. It enforces the same `next_avoided.len() >= 8 => true` conservative cap, `sort_unstable()` canonicalization, `pass_check` ROBDD feasibility test, and `seen` deduplication as the full-overwrite branch. - `live_non_folded_values` (lines 890–894) now records `(site, exec_epoch, w_out, val)` in `overwrites` on the non-full-overwrite `else` branch whenever `matches!(reg, Reg::V(_))` and `inst.write(reg)` is `Some(w_out)`, ensuring downstream liveness outside `(site.0, gw)` / `(site.0, w_epoch)` propagates `UseGuard::Mixed` back through chained guarded RMW / partial VGPR writes to earlier guarded overwrites in both structured and unstructured modes while preserving lattice monotonicity and termination. - Verified test coverage (`guarded_rmw_and_partial_write_after_guarded_overwrite_keep_first_half_weighted`): covers both guarded RMW (`v_add_f32 v2, 1.0, v2`, VOP2 op `0x03`) and guarded partial write (`v_cvt_f16_f32 v2, v3`, VOP1 op `0x0a`) after guarded `v_mov_b32 v2, 0` in both `raise_structured` and `raise`. - **Prior `[P1]` resolved (`crates/victory-shader/src/io.rs`, `reads_inactive_lanes`):** - `reads_inactive_lanes` (line 748) now includes `v_readfirstlane_b32` (`matches!(name, "v_readlane_b32" | "v_readfirstlane_b32")`), preventing guarded overwrites from killing first-half values observable via `WaveReadLaneFirst` fallback (`EXEC == 0`) or pixel helper-lane `first_lane` ownership. - Cross-checked all cross-lane ops in `emit/lower.rs` (`dpp`, `v_readlane_b32`, `v_readfirstlane_b32`, `v_permlane16_b32`/`v_permlanex16_b32`, `v_writelane_b32`, `ds_swizzle*`, `ds_*permute*`) — no remaining unguarded inactive-lane readers. - Verified test coverage (Case C in `inactive_lane_vgpr_readers_keep_first_half_weighted` with `v_readfirstlane_b32 s4, v2`, VOP1 op `0x02`) in both `raise_structured` and `raise`. - **Title-neutrality & hygiene:** `63f0e19..8415763` touches only `crates/victory-shader/src/io.rs`; zero title-neutrality violations, zero local paths, zero new issues. Confirmed `8415763885666f39bcab1a5f3faff7d7f0b30403` is PR #404's pushed `HEAD`.
Androtim commented 2026-12-03 19:28:18 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T19:28:18Z.


Gate 2 Deep Audit — PR #407 (fix/silent-restart-headless-safety, commit 4cd20c2)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Pure-reasoning read-only audit of origin/main...HEAD (4cd20c2, 2 files, +76/-14 lines) verifying both findings from the prior PR #406 Gate 2 audit (audit_406.md):

  • Prior [P0] resolved (headless CREATE_NO_WINDOW stdin prompt deadlock):
    • apps/victory/src/play.rs (lines 602–636): adds has_console_window() (kernel32::GetConsoleWindow via Rust 2024 unsafe extern system, with #[cfg(not(windows))] fallback), pure is_interactive_console(stdin_is_terminal, no_console, has_console_window), and interactive_console().
    • All 5 stdin prompt sites across the repository (offer_dlss, offer_fsr, offer_mfg, check_shader_model, hold_window) now gate on interactive_console() instead of raw std::io::stdin().is_terminal(), preventing invisible blocks on CREATE_NO_WINDOW's CONIN$ or when VICTORY_NO_CONSOLE=1.
    • crates/victory-gpu/src/host/menu.rs (lines 244–249): headless restart_command_line now passes -NonInteractive to powershell.exe and pipes $null | & '{play}' {args} so the restarted child receives a closed anonymous stdin pipe (EOF, is_terminal() == false) instead of CONIN$, providing defense in depth even for non-MiniVI targets.
  • Prior [P1] resolved (stale VICTORY_RESTART_EXIT_CODE inherited across spawn_restart):
    • crates/victory-gpu/src/host/menu.rs (lines 242–255): both headless and console branches of restart_command_line now execute Remove-Item Env:VICTORY_RESTART_EXIT_CODE -ErrorAction SilentlyContinue; before launching {play}. Any self-spawned PowerShell child (such as post-preload == true restarts) therefore clears the stale parent-supervision exit code and cleanly reverts to self-relaunch on subsequent restarts while preserving VICTORY_NO_CONSOLE via KEPT.
  • FFI, quoting, tests, & title-neutrality:
    • GetConsoleWindow FFI signature (*mut std::ffi::c_void, extern system, #[link(name = kernel32)]) is ABI-accurate and only checked via .is_null().
    • New/updated unit tests (interactive_console_blocks_prompts_when_headless_or_non_tty in play.rs, restart_command_line_differs_between_console_and_headless_modes in menu.rs) cover all branches cleanly.
    • Zero new [P0]/[P1] bugs, zero title-neutrality violations, and zero local paths. Confirmed 4cd20c2db92d876677465e6d74117554712bdb9c is PR #407's pushed HEAD.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7389747537 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7389747537). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T19:28:18Z. --- ### Gate 2 Deep Audit — PR #407 (`fix/silent-restart-headless-safety`, commit `4cd20c2`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` Pure-reasoning read-only audit of `origin/main...HEAD` (`4cd20c2`, 2 files, `+76/-14` lines) verifying both findings from the prior PR #406 Gate 2 audit (`audit_406.md`): - **Prior `[P0]` resolved (headless `CREATE_NO_WINDOW` stdin prompt deadlock):** - `apps/victory/src/play.rs` (lines 602–636): adds `has_console_window()` (`kernel32::GetConsoleWindow` via Rust 2024 `unsafe extern system`, with `#[cfg(not(windows))]` fallback), pure `is_interactive_console(stdin_is_terminal, no_console, has_console_window)`, and `interactive_console()`. - All 5 stdin prompt sites across the repository (`offer_dlss`, `offer_fsr`, `offer_mfg`, `check_shader_model`, `hold_window`) now gate on `interactive_console()` instead of raw `std::io::stdin().is_terminal()`, preventing invisible blocks on `CREATE_NO_WINDOW`'s `CONIN$` or when `VICTORY_NO_CONSOLE=1`. - `crates/victory-gpu/src/host/menu.rs` (lines 244–249): headless `restart_command_line` now passes `-NonInteractive` to `powershell.exe` and pipes `$null | & '{play}' {args}` so the restarted child receives a closed anonymous stdin pipe (EOF, `is_terminal() == false`) instead of `CONIN$`, providing defense in depth even for non-`MiniVI` targets. - **Prior `[P1]` resolved (stale `VICTORY_RESTART_EXIT_CODE` inherited across `spawn_restart`):** - `crates/victory-gpu/src/host/menu.rs` (lines 242–255): both headless and console branches of `restart_command_line` now execute `Remove-Item Env:VICTORY_RESTART_EXIT_CODE -ErrorAction SilentlyContinue;` before launching `{play}`. Any self-spawned PowerShell child (such as post-`preload == true` restarts) therefore clears the stale parent-supervision exit code and cleanly reverts to self-relaunch on subsequent restarts while preserving `VICTORY_NO_CONSOLE` via `KEPT`. - **FFI, quoting, tests, & title-neutrality:** - `GetConsoleWindow` FFI signature (`*mut std::ffi::c_void`, `extern system`, `#[link(name = kernel32)]`) is ABI-accurate and only checked via `.is_null()`. - New/updated unit tests (`interactive_console_blocks_prompts_when_headless_or_non_tty` in `play.rs`, `restart_command_line_differs_between_console_and_headless_modes` in `menu.rs`) cover all branches cleanly. - Zero new `[P0]`/`[P1]` bugs, zero title-neutrality violations, and zero local paths. Confirmed `4cd20c2db92d876677465e6d74117554712bdb9c` is PR #407's pushed `HEAD`.
Androtim commented 2026-12-03 20:51:36 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T20:51:36Z.


Gate 2 Re-Audit — PR #408 (perf/placed-fill-card-and-list-fronts, commit 4ac99b5)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Pure-reasoning read-only re-audit of b69ec4f..4ac99b5 (crates/victory-gpu/src/host.rs, crates/victory-gpu/src/host/place.rs, +6/-27 lines; full origin/main..HEAD previously verified 0 P0 in prior Gate 2 audit of b69ec4f):

  • Prior [P1] resolved (crates/victory-gpu/src/host/place.rs & crates/victory-gpu/src/host.rs):
    • order_aware() (lines 194–197), fill_card() (lines 235–238), and fill_multi() (lines 243–246) now initialize directly from VICTORY_PLACED_ORDER_AWARE, VICTORY_PLACED_FILL_CARD, and VICTORY_PLACED_FILL_MULTI via per-function static ON: OnceLock<bool> getters (defaulting to enabled unless set to 0), matching on() and stale_fix().
    • Removed the stale ORDER_AWARE / FILL_CARD / FILL_MULTI AtomicBool::new(true) statics, fill_card_latch(), and its Host::submit() call site in crates/victory-gpu/src/host.rs (zero remaining references across the repository).
    • Pre-submit callers (such as early log_fills(), blocked_by(), read_by(), or left_stale() paths) now observe VICTORY_PLACED_*=0 immediately rather than falling back to unlatched true defaults.
  • Regression, concurrency, & hygiene checks:
    • Thread safety & consistency: std::sync::OnceLock::get_or_init guarantees race-free single initialization and immutable submission-wide agreement across all callers (blocked_by, read_by, read_by_left, left_stale, kept_fills, fills_stayed, fills_on_card, log_fills).
    • Flag gating & deadlock freedom: fill_multi() gates cleanly on fill_card() inside its initializer (fill_card() && ...) with a strict acyclic dependency (fill_multi -> fill_card), so VICTORY_PLACED_FILL_CARD=0 forces fill_multi() == false.
    • Imports, tests, attribution, & title-neutrality: No unused imports left behind (OnceLock and Ordering remain in active use); pure unit tests in place.rs remain self-contained; GPL-3.0 attributions in place.rs (vi-rdna4/VIctory-9070XT, 7b47335) and front.rs (ReTerryDavis/ReVIctory, ad297b1) are intact; zero title-neutrality violations and zero local paths. Confirmed 4ac99b56340be4aa0c102dd689edeb34cbde9b2b is PR #408's pushed HEAD.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7391913492 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7391913492). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T20:51:36Z. --- ### Gate 2 Re-Audit — PR #408 (`perf/placed-fill-card-and-list-fronts`, commit `4ac99b5`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` Pure-reasoning read-only re-audit of `b69ec4f..4ac99b5` (`crates/victory-gpu/src/host.rs`, `crates/victory-gpu/src/host/place.rs`, `+6/-27` lines; full `origin/main..HEAD` previously verified `0 P0` in prior Gate 2 audit of `b69ec4f`): - **Prior `[P1]` resolved (`crates/victory-gpu/src/host/place.rs` & `crates/victory-gpu/src/host.rs`):** - `order_aware()` (lines 194–197), `fill_card()` (lines 235–238), and `fill_multi()` (lines 243–246) now initialize directly from `VICTORY_PLACED_ORDER_AWARE`, `VICTORY_PLACED_FILL_CARD`, and `VICTORY_PLACED_FILL_MULTI` via per-function `static ON: OnceLock<bool>` getters (defaulting to enabled unless set to `0`), matching `on()` and `stale_fix()`. - Removed the stale `ORDER_AWARE` / `FILL_CARD` / `FILL_MULTI` `AtomicBool::new(true)` statics, `fill_card_latch()`, and its `Host::submit()` call site in `crates/victory-gpu/src/host.rs` (zero remaining references across the repository). - Pre-submit callers (such as early `log_fills()`, `blocked_by()`, `read_by()`, or `left_stale()` paths) now observe `VICTORY_PLACED_*=0` immediately rather than falling back to unlatched `true` defaults. - **Regression, concurrency, & hygiene checks:** - **Thread safety & consistency:** `std::sync::OnceLock::get_or_init` guarantees race-free single initialization and immutable submission-wide agreement across all callers (`blocked_by`, `read_by`, `read_by_left`, `left_stale`, `kept_fills`, `fills_stayed`, `fills_on_card`, `log_fills`). - **Flag gating & deadlock freedom:** `fill_multi()` gates cleanly on `fill_card()` inside its initializer (`fill_card() && ...`) with a strict acyclic dependency (`fill_multi -> fill_card`), so `VICTORY_PLACED_FILL_CARD=0` forces `fill_multi() == false`. - **Imports, tests, attribution, & title-neutrality:** No unused imports left behind (`OnceLock` and `Ordering` remain in active use); pure unit tests in `place.rs` remain self-contained; GPL-3.0 attributions in `place.rs` (`vi-rdna4/VIctory-9070XT`, `7b47335`) and `front.rs` (`ReTerryDavis/ReVIctory`, `ad297b1`) are intact; zero title-neutrality violations and zero local paths. Confirmed `4ac99b56340be4aa0c102dd689edeb34cbde9b2b` is PR #408's pushed `HEAD`.
Androtim commented 2026-12-03 21:00:30 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T21:00:30Z.


Gate 2 Deep Audit — PR #409 (fix/revert-broken-rt-skip-and-standin-defaults, commit 9de107b)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Pure-reasoning read-only audit of origin/main..HEAD (7fbc01d, 9de107b; 5 files, +220/-54 lines):

  • crates/victory-gpu/src/pipeline.rs & draw.rs:
    • VICTORY_RT_SKIP_RESOLVE and VICTORY_RT_SKIP_DEAD default OFF (strict opt-in =1 via is_some_and(|v| v.trim() == 1)) and remain disabled whenever any RT mode is active (hwrt || bvh_builder || rays).
    • CSComputeSkinning is excluded from DeadRt::Feeds so mesh skinning/deformation is never dropped.
    • Verified VICTORY_BVH_STUB (xboxbvh.rs), DOM_LOADS (bitcode/opt.rs), and VICTORY_CUDA_PRELOAD (streamline.rs) remain intact.
  • crates/victory-gpu/src/descriptor/host.rs:
    • VICTORY_STANDIN_OPAQUE defaults OFF via crate::asked_for! so neutral stand-ins use [0x80, 0x80, 0x80, 0x80] (0x80 alpha) instead of opaque 0xff alpha.
    • gray_fits() excludes single-channel mask formats (R8_UNORM, BC4_TYPELESS, BC4_UNORM) and HDR float/BC6H formats (R16G16B16A16_FLOAT, R11G11B10_FLOAT, BC6H_TYPELESS, BC6H_UF16, BC6H_SF16), falling back cleanly to typed null_for(view, at) descriptors reading (0,0,0,0) while preserving neutral gray stand-ins for color/YCbCr/BC5/BC7/RGBA8 textures.
  • crates/victory-gpu/src/ambient.rs:
    • GATHERED_FRAME (initialized to u64::MAX and updated on every place + gather in Role::Resolve and Role::Miss) ensures miss_needs_gather only reuses cells/points in Set::Estimate when already gathered on the current frame, preventing reflect_light from reading stale or uninitialized buffers.
    • without_depth (bound_light) gates gathered-point blending on gathered_points_fresh (current or immediately preceding frame), cleanly falling back to cells[CELLS].rgb otherwise.
    • Verified VICTORY_AMBIENT_RT band behavior under builder_runs=true (SW-RT): runs Role::Radiance and Role::Resolve (pass.raise with (least, most, level)) to lift unlit/starved blocks to found * least, preserve normal traced diffuse, and cap spikes to found * most, while skipping Role::Miss/Role::Air/Role::Alpha; under hwrt_active=true (HW-RT), standin_enabled is false and title_rt_active() is true.
  • crates/victory-gpu/src/pipeline/make.rs (commit 9de107b):
    • Tags CS_RaytracingResolve on Pending::rt_resolve, routes EARLY to Queue::slow and REQUESTED to Queue::requested_slow (even on a cold cache), and skips blocking wait() on rt_resolve so cold RT resolves never exhaust the shared 80 ms per-frame wait budget.
    • Verified Queue state machine & concurrency invariants: queue_state transitions monotonically (NOT_QUEUED < EARLY < REQUESTED < MAKING) under QUEUE mutex; screen -> requested -> early always drain ahead of requested_slow -> slow; unclaimed(..., REQUESTED) / unclaimed(..., EARLY) prevents double-popping or double-counting WAITING across EARLY -> REQUESTED promotions; slow_now increments/decrements strictly 1-to-1 with was_slow under QUEUE mutex (p.make() is catch_unwind-guarded) with AVAILABLE.notify_all() under the lock — zero leaks, underflow, missed wakeups, or deadlocks across slow_limit() == usize::MAX, >= 1, or multi-worker contention.
  • Title-neutrality & attribution: Zero retail game/character/location names, zero local paths, and all upstream GPL-3.0 attributions preserved. Confirmed 9de107b807f4e1d4d945b7e7edd3538b77d85a79 is PR #409's pushed HEAD.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7392141411 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7392141411). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T21:00:30Z. --- ### Gate 2 Deep Audit — PR #409 (`fix/revert-broken-rt-skip-and-standin-defaults`, commit `9de107b`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` Pure-reasoning read-only audit of `origin/main..HEAD` (`7fbc01d`, `9de107b`; 5 files, `+220/-54` lines): - **`crates/victory-gpu/src/pipeline.rs` & `draw.rs`:** - `VICTORY_RT_SKIP_RESOLVE` and `VICTORY_RT_SKIP_DEAD` default OFF (strict opt-in `=1` via `is_some_and(|v| v.trim() == 1)`) and remain disabled whenever any RT mode is active (`hwrt || bvh_builder || rays`). - `CSComputeSkinning` is excluded from `DeadRt::Feeds` so mesh skinning/deformation is never dropped. - Verified `VICTORY_BVH_STUB` (`xboxbvh.rs`), `DOM_LOADS` (`bitcode/opt.rs`), and `VICTORY_CUDA_PRELOAD` (`streamline.rs`) remain intact. - **`crates/victory-gpu/src/descriptor/host.rs`:** - `VICTORY_STANDIN_OPAQUE` defaults OFF via `crate::asked_for!` so neutral stand-ins use `[0x80, 0x80, 0x80, 0x80]` (0x80 alpha) instead of opaque 0xff alpha. - `gray_fits()` excludes single-channel mask formats (`R8_UNORM`, `BC4_TYPELESS`, `BC4_UNORM`) and HDR float/BC6H formats (`R16G16B16A16_FLOAT`, `R11G11B10_FLOAT`, `BC6H_TYPELESS`, `BC6H_UF16`, `BC6H_SF16`), falling back cleanly to typed `null_for(view, at)` descriptors reading `(0,0,0,0)` while preserving neutral gray stand-ins for color/YCbCr/BC5/BC7/RGBA8 textures. - **`crates/victory-gpu/src/ambient.rs`:** - `GATHERED_FRAME` (initialized to `u64::MAX` and updated on every `place` + `gather` in `Role::Resolve` and `Role::Miss`) ensures `miss_needs_gather` only reuses `cells`/`points` in `Set::Estimate` when already gathered on the current frame, preventing `reflect_light` from reading stale or uninitialized buffers. - `without_depth` (`bound_light`) gates gathered-point blending on `gathered_points_fresh` (current or immediately preceding frame), cleanly falling back to `cells[CELLS].rgb` otherwise. - Verified `VICTORY_AMBIENT_RT` band behavior under `builder_runs=true` (SW-RT): runs `Role::Radiance` and `Role::Resolve` (`pass.raise` with `(least, most, level)`) to lift unlit/starved blocks to `found * least`, preserve normal traced diffuse, and cap spikes to `found * most`, while skipping `Role::Miss`/`Role::Air`/`Role::Alpha`; under `hwrt_active=true` (HW-RT), `standin_enabled` is `false` and `title_rt_active()` is `true`. - **`crates/victory-gpu/src/pipeline/make.rs` (commit `9de107b`):** - Tags `CS_RaytracingResolve` on `Pending::rt_resolve`, routes `EARLY` to `Queue::slow` and `REQUESTED` to `Queue::requested_slow` (even on a cold cache), and skips blocking `wait()` on `rt_resolve` so cold RT resolves never exhaust the shared 80 ms per-frame wait budget. - Verified `Queue` state machine & concurrency invariants: `queue_state` transitions monotonically (`NOT_QUEUED < EARLY < REQUESTED < MAKING`) under `QUEUE` mutex; `screen -> requested -> early` always drain ahead of `requested_slow -> slow`; `unclaimed(..., REQUESTED)` / `unclaimed(..., EARLY)` prevents double-popping or double-counting `WAITING` across `EARLY -> REQUESTED` promotions; `slow_now` increments/decrements strictly 1-to-1 with `was_slow` under `QUEUE` mutex (`p.make()` is `catch_unwind`-guarded) with `AVAILABLE.notify_all()` under the lock — zero leaks, underflow, missed wakeups, or deadlocks across `slow_limit() == usize::MAX`, `>= 1`, or multi-worker contention. - **Title-neutrality & attribution:** Zero retail game/character/location names, zero local paths, and all upstream GPL-3.0 attributions preserved. Confirmed `9de107b807f4e1d4d945b7e7edd3538b77d85a79` is PR #409's pushed `HEAD`.
Androtim commented 2026-12-03 21:11:45 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T21:11:45Z.


Gate 2 Deep Audit — PR #410 (ci/atomic-draft-release, commit c729ad7)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Pure-reasoning read-only audit of origin/main..HEAD (c729ad7; .github/workflows/release.yml, +12/-0 lines):

  • Draft discovery (gh api repos/$env:GITHUB_REPOSITORY/releases?per_page=30):
    • Top-level permissions: contents: write paired with GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} grants write access so GitHub REST GET /repos/{owner}/{repo}/releases?per_page=30 returns both draft and published releases, with newly drafted releases at the top of page 1.
    • PowerShell string expansion repos/$env:GITHUB_REPOSITORY/releases?per_page=30 terminates $env:GITHUB_REPOSITORY cleanly at /.
  • Draft asset upload (gh release upload $tag target/release/MiniVI.exe MiniVI.exe.sha256 --clobber):
    • Verified against upstream cli/cli (pkg/cmd/release/upload/upload.go -> pkg/cmd/release/shared/fetch.go): shared.FetchRelease races REST /releases/tags/{tag} against GraphQL fetchDraftRelease (RepositoryReleaseByTag -> repository.release(tagName: $tagName) { databaseId isDraft } -> REST /releases/{databaseId}), so targeting a pre-drafted release by pending tag $tag resolves reliably with contents: write instead of failing with a REST tag 404.
    • --clobber ensures retries after a partial upload cleanly overwrite any previously uploaded asset rather than failing on duplicate asset names.
  • Atomic draft publish (gh release edit $tag --draft=false):
    • Verified against upstream cli/cli (pkg/cmd/release/edit/edit.go & http.go): resolves the draft via shared.FetchRelease, explicitly retains params[tag_name] = release.TagName, and sends PATCH /repos/{owner}/{repo}/releases/{databaseId} with {draft: false, tag_name: <tag>}.
    • Preserves the draft's authored title, release notes, prerelease setting, and newly attached assets; binds cleanly to the already-pushed git tag (refs/tags/v*, where target_commitish is unused once the tag exists); defaults make_latest to true on GitHub REST PATCH for non-prerelease releases.
  • Error gating ($LASTEXITCODE) & atomicity:
    • Every gh command (gh api, gh release upload, gh release edit, and fallback gh release create) is immediately followed by if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }.
    • A failing gh api exits before falling through to gh release create, and a failing gh release upload exits before gh release edit --draft=false, preventing publication of an empty or incomplete release.
  • PowerShell ConvertFrom-Json edge cases:
    • gh api emits compact single-line JSON. Empty array [] unrolls to $null (piping $null | Where-Object { ... } | Select-Object -First 1 yields $null cleanly under $ErrorActionPreference = 'stop' and falls through to gh release create); single-element array unwrapping to a scalar PSCustomObject still evaluates identically through Where-Object ... | Select-Object -First 1.
  • Hygiene & provenance: Valid YAML and pwsh syntax, zero local paths, 100% title-neutral. Confirmed c729ad76ba20e69cab653755051002dd46c1b2bf is PR #410's pushed HEAD.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7392422813 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7392422813). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T21:11:45Z. --- ### Gate 2 Deep Audit — PR #410 (`ci/atomic-draft-release`, commit `c729ad7`) **Verdict:** `VERIFIED CLEAN (0 P0, 0 P1)` Pure-reasoning read-only audit of `origin/main..HEAD` (`c729ad7`; `.github/workflows/release.yml`, `+12/-0` lines): - **Draft discovery (`gh api repos/$env:GITHUB_REPOSITORY/releases?per_page=30`):** - Top-level `permissions: contents: write` paired with `GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}` grants write access so GitHub REST `GET /repos/{owner}/{repo}/releases?per_page=30` returns both draft and published releases, with newly drafted releases at the top of page 1. - PowerShell string expansion `repos/$env:GITHUB_REPOSITORY/releases?per_page=30` terminates `$env:GITHUB_REPOSITORY` cleanly at `/`. - **Draft asset upload (`gh release upload $tag target/release/MiniVI.exe MiniVI.exe.sha256 --clobber`):** - Verified against upstream `cli/cli` (`pkg/cmd/release/upload/upload.go` -> `pkg/cmd/release/shared/fetch.go`): `shared.FetchRelease` races REST `/releases/tags/{tag}` against GraphQL `fetchDraftRelease` (`RepositoryReleaseByTag` -> `repository.release(tagName: $tagName) { databaseId isDraft }` -> REST `/releases/{databaseId}`), so targeting a pre-drafted release by pending tag `$tag` resolves reliably with `contents: write` instead of failing with a REST tag 404. - `--clobber` ensures retries after a partial upload cleanly overwrite any previously uploaded asset rather than failing on duplicate asset names. - **Atomic draft publish (`gh release edit $tag --draft=false`):** - Verified against upstream `cli/cli` (`pkg/cmd/release/edit/edit.go` & `http.go`): resolves the draft via `shared.FetchRelease`, explicitly retains `params[tag_name] = release.TagName`, and sends `PATCH /repos/{owner}/{repo}/releases/{databaseId}` with `{draft: false, tag_name: <tag>}`. - Preserves the draft's authored title, release notes, `prerelease` setting, and newly attached assets; binds cleanly to the already-pushed git tag (`refs/tags/v*`, where `target_commitish` is unused once the tag exists); defaults `make_latest` to `true` on GitHub REST `PATCH` for non-prerelease releases. - **Error gating (`$LASTEXITCODE`) & atomicity:** - Every `gh` command (`gh api`, `gh release upload`, `gh release edit`, and fallback `gh release create`) is immediately followed by `if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }`. - A failing `gh api` exits before falling through to `gh release create`, and a failing `gh release upload` exits before `gh release edit --draft=false`, preventing publication of an empty or incomplete release. - **PowerShell `ConvertFrom-Json` edge cases:** - `gh api` emits compact single-line JSON. Empty array `[]` unrolls to `$null` (piping `$null | Where-Object { ... } | Select-Object -First 1` yields `$null` cleanly under `$ErrorActionPreference = 'stop'` and falls through to `gh release create`); single-element array unwrapping to a scalar `PSCustomObject` still evaluates identically through `Where-Object ... | Select-Object -First 1`. - **Hygiene & provenance:** Valid YAML and `pwsh` syntax, zero local paths, 100% title-neutral. Confirmed `c729ad76ba20e69cab653755051002dd46c1b2bf` is PR #410's pushed `HEAD`.
Androtim commented 2026-12-03 23:53:08 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T23:53:08Z.


Gate 2 Audit (PR #411, \

<!-- greyfinch-sync:Androtim/MiniVI:comment:7396110531 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7396110531). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T23:53:08Z. --- Gate 2 Audit (PR #411, \
Androtim commented 2026-12-04 00:25:29 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T00:25:29Z.


Gate 2 Re-Audit — PR #412 (\ ix/amd-rdna-kill-continue-and-rebar, \5041795)

VERIFIED CLEAN (0 P0, 0 P1)

Pure static re-audit of \48379ce..5041795:

  1. Prior [P0]\ closed (\Lower::kill_end\ & \live_ok):
    • \Lower::kill_end()\ now requires \e.target == Target::Null && (!e.done || self.x.st.guards[to][i] == Some(Bool::FALSE))\ on every export in \ o, so live \exp null done\ exits in depth-only / Z-prepass / UAV-only pixel shaders (where \EXEC\ is not provably \Bool::FALSE) are never misclassified as kill blocks.
    • \live_ok\ now checks !l.counters.contains_key(&live) && !l.kill_end(b, live), preventing a second kill block (or loop header) from being treated as the live continuation.
    • Verified across depth-only early returns, inverted depth-only alpha-test (\ _cmpx_le_f32\ + \s_and_b32\ + \s_cbranch_scc0), and multi-predecessor kill blocks (shared pure-kill, mixed kill/live shared null exits, partially-killed phi filtering across all three \ ill_phis\ loops, and unreachable kill-block pruning in \itcode::write).
  2. **Zero new [P0]\ / [P1]\ regressions after fix & rebase onto \48379ce**:
    • \VICTORY_KILL_CONTINUE\ is keyed in \TRANSLATOR_ENV_KEYS\ (\crates/victory-gpu/src/shader_cache.rs).
    • Wave32-on-Wave64 lane indexing (\ _mbcnt_lo/\ _mbcnt_hi) and wide-ballot promotion (\s_bcnt1_i32_b32, \s_ff1_i32_b32, \s_cmp_eq_u32, \s_cmp_lg_u32, ballot-backed \ _mbcnt) remain sound.
    • New regression tests and \dump_dxil\ unique temp-file counter are statically sound.
  3. GPL-3.0 attribution & title-neutrality:
    • Upstream GPL-3.0 commit/PR attributions (\lobomfz/VIctory-xmem\ PR #195 & PR #344, \ReTerryDavis/ReVIctory) present in commit message and source comments; zero retail names or local paths.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7396763445 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7396763445). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T00:25:29Z. --- ### Gate 2 Re-Audit — PR #412 (\ ix/amd-rdna-kill-continue-and-rebar\, \5041795\) **VERIFIED CLEAN (0 P0, 0 P1)** Pure static re-audit of \48379ce..5041795\: 1. **Prior \[P0]\ closed (\Lower::kill_end\ & \live_ok\)**: - \Lower::kill_end()\ now requires \e.target == Target::Null && (!e.done || self.x.st.guards[to][i] == Some(Bool::FALSE))\ on every export in \ o\, so live \exp null done\ exits in depth-only / Z-prepass / UAV-only pixel shaders (where \EXEC\ is not provably \Bool::FALSE\) are never misclassified as kill blocks. - \live_ok\ now checks \!l.counters.contains_key(&live) && !l.kill_end(b, live)\, preventing a second kill block (or loop header) from being treated as the live continuation. - Verified across depth-only early returns, inverted depth-only alpha-test (\ _cmpx_le_f32\ + \s_and_b32\ + \s_cbranch_scc0\), and multi-predecessor kill blocks (shared pure-kill, mixed kill/live shared null exits, partially-killed phi filtering across all three \ ill_phis\ loops, and unreachable kill-block pruning in \itcode::write\). 2. **Zero new \[P0]\ / \[P1]\ regressions after fix & rebase onto \48379ce\**: - \VICTORY_KILL_CONTINUE\ is keyed in \TRANSLATOR_ENV_KEYS\ (\crates/victory-gpu/src/shader_cache.rs\). - Wave32-on-Wave64 lane indexing (\ _mbcnt_lo\/\ _mbcnt_hi\) and wide-ballot promotion (\s_bcnt1_i32_b32\, \s_ff1_i32_b32\, \s_cmp_eq_u32\, \s_cmp_lg_u32\, ballot-backed \ _mbcnt\) remain sound. - New regression tests and \dump_dxil\ unique temp-file counter are statically sound. 3. **GPL-3.0 attribution & title-neutrality**: - Upstream GPL-3.0 commit/PR attributions (\lobomfz/VIctory-xmem\ PR #195 & PR #344, \ReTerryDavis/ReVIctory\) present in commit message and source comments; zero retail names or local paths.
Androtim commented 2026-12-04 01:22:17 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T01:22:17Z.


Gate 2 Pure-Reasoning Re-Audit — PR #414 (\2b03060)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Re-audited \perf/ecoqos-tearing-hwrt-unmap-and-sl-dedup\ (\47cecb8..2b03060\ and full \origin/main..2b03060) via pure adversarial static reasoning:

  • Prior [P1]\ closed: \Presenter::buffers\ (\2..=4, default \3) is now propagated through \streamline::Planes { buffers: p.buffers, .. }\ into \uild_dlssg_options\ -> \bi::DlssgOptions.num_back_buffers, matching both \CreateSwapChainForHwnd\ and \ResizeBuffers. Verified all call sites (\Host::present_planes, \upscaler_check, and \streamline::resizing) and unit test coverage (\dlssg_options_uses_configured_swap_chain_buffer_count).
  • **Streamline log dedup polish verified (\
<!-- greyfinch-sync:Androtim/MiniVI:comment:7397749371 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7397749371). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T01:22:17Z. --- ### Gate 2 Pure-Reasoning Re-Audit — PR #414 (\2b03060\) **Verdict: VERIFIED CLEAN (0 P0, 0 P1)** Re-audited \perf/ecoqos-tearing-hwrt-unmap-and-sl-dedup\ (\47cecb8..2b03060\ and full \origin/main..2b03060\) via pure adversarial static reasoning: - **Prior \[P1]\ closed:** \Presenter::buffers\ (\2..=4\, default \3\) is now propagated through \streamline::Planes { buffers: p.buffers, .. }\ into \uild_dlssg_options\ -> \bi::DlssgOptions.num_back_buffers\, matching both \CreateSwapChainForHwnd\ and \ResizeBuffers\. Verified all call sites (\Host::present_planes\, \upscaler_check\, and \streamline::resizing\) and unit test coverage (\dlssg_options_uses_configured_swap_chain_buffer_count\). - **Streamline log dedup polish verified (\
Androtim commented 2026-12-04 01:23:50 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T01:23:50Z.


Gate 2 Re-Audit for PR #413 (\4fe9e16): VERIFIED CLEAN (0 P0, 0 P1)

  • Prior [P1]\ #1 (\device_made()\ TOCTOU race with \slShutdown()): CLOSED — \device_made()\ now serializes on Streamline's \calls()\ mutex and re-checks \SL_INITIALIZED && !SHUTTING_DOWN\ under the lock across \slSetD3DDevice, \slGetFeatureFunction, \slGetFeatureVersion, \slReflexSetOptions, and \proxied_queue; \shutdown_once()\ acquires \calls()\ before clearing ready flags and invoking \slShutdown().
  • Prior [P1]\ #2 (DLSS SR + FSR 3 Frame Generation teardown): CLOSED — \Host::drop_presenter_before_shutdown()\ now runs \ sr::resizing()\ after \settle_now(WHY_SYNC)\ and before dropping the swap chain and \HUD_TEXTURES, draining FSR 3 async presents (\DISPATCH_WAIT_FOR_PRESENTS_DX12) and retiring the frame-generation context while preserving \presenter -> CALLS / submitted / fsr::LIVE\ lock ordering.
  • Prior [P2]\ hygiene items (\docs/dlss.md\ wording, \SL.get()\ ordering after \SL_INITIALIZED.load(Acquire), and \ending::is_ending()\ re-checks around \ResizeBuffers): CLOSED.
  • Title-neutrality, exit code \75\ restart preservation, fatal/device-removed immediate-termination path, and no-SDK no-op path verified clean with zero new [P0]/[P1]\ regressions.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7397777746 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7397777746). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T01:23:50Z. --- Gate 2 Re-Audit for PR #413 (\4fe9e16\): **VERIFIED CLEAN (0 P0, 0 P1)** - Prior \[P1]\ #1 (\device_made()\ TOCTOU race with \slShutdown()\): **CLOSED** — \device_made()\ now serializes on Streamline's \calls()\ mutex and re-checks \SL_INITIALIZED && !SHUTTING_DOWN\ under the lock across \slSetD3DDevice\, \slGetFeatureFunction\, \slGetFeatureVersion\, \slReflexSetOptions\, and \proxied_queue\; \shutdown_once()\ acquires \calls()\ before clearing ready flags and invoking \slShutdown()\. - Prior \[P1]\ #2 (DLSS SR + FSR 3 Frame Generation teardown): **CLOSED** — \Host::drop_presenter_before_shutdown()\ now runs \ sr::resizing()\ after \settle_now(WHY_SYNC)\ and before dropping the swap chain and \HUD_TEXTURES\, draining FSR 3 async presents (\DISPATCH_WAIT_FOR_PRESENTS_DX12\) and retiring the frame-generation context while preserving \presenter -> CALLS / submitted / fsr::LIVE\ lock ordering. - Prior \[P2]\ hygiene items (\docs/dlss.md\ wording, \SL.get()\ ordering after \SL_INITIALIZED.load(Acquire)\, and \ending::is_ending()\ re-checks around \ResizeBuffers\): **CLOSED**. - Title-neutrality, exit code \75\ restart preservation, fatal/device-removed immediate-termination path, and no-SDK no-op path verified clean with zero new \[P0]\/\[P1]\ regressions.
Androtim commented 2026-12-04 01:25:13 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T01:25:13Z.


Gate 2 Re-Audit (Pure-Reasoning) — Wave 5B PR #415 (23050a6): VERIFIED CLEAN (0 P0, 0 P1)

  • Closed P0 #1 (UAV barrier tracking & transition folding in crates/victory-gpu/src/host/rec.rs): conflicts() treats per-resource UAV barriers as conflicting with transitions on the same resource across both <= 64 and > 64 paths in enqueue_barriers(), and blocks_transition_fold() blocks folding across held and intra-batch same-resource and null UAV barriers so a UAV barrier is never left on a non-UAV state.
  • Closed P0 #2 (Aliasing barrier boundaries in crates/victory-gpu/src/host/rec.rs): D3D12_RESOURCE_BARRIER_TYPE_ALIASING (specific, half-null, and global NULL) is treated as a hard ordering boundary in enqueue_barriers() and blocks folding in fold() and blocks_transition_fold().
  • Closed P1 #3 (Job::Value local-vs-ahead precedence in crates/victory-gpu/src/queue/behind.rs): classify_value_join() evaluates local joined-list will_meet before late_met_known, preserving wait_on_gpu = true on reused memory-wait slots and keeping JOIN_NEEDS_WAIT and host.rs waited_parts / split_part_waits semantics sound across direct and split-send Handoff paths.
  • Zero new P0/P1 regressions: Verified Rec auto-flush/explicit-flush coverage, borrowed ManuallyDrop resource lifetimes, NameGate concurrency/drop safety, GPL-3.0 attributions, and 100% title-neutrality.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7397804807 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7397804807). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T01:25:13Z. --- Gate 2 Re-Audit (Pure-Reasoning) — Wave 5B PR #415 (`23050a6`): **VERIFIED CLEAN (0 P0, 0 P1)** - **Closed P0 #1 (UAV barrier tracking & transition folding in `crates/victory-gpu/src/host/rec.rs`):** `conflicts()` treats per-resource UAV barriers as conflicting with transitions on the same resource across both `<= 64` and `> 64` paths in `enqueue_barriers()`, and `blocks_transition_fold()` blocks folding across held and intra-batch same-resource and null UAV barriers so a UAV barrier is never left on a non-UAV state. - **Closed P0 #2 (Aliasing barrier boundaries in `crates/victory-gpu/src/host/rec.rs`):** `D3D12_RESOURCE_BARRIER_TYPE_ALIASING` (specific, half-null, and global `NULL`) is treated as a hard ordering boundary in `enqueue_barriers()` and blocks folding in `fold()` and `blocks_transition_fold()`. - **Closed P1 #3 (`Job::Value` local-vs-ahead precedence in `crates/victory-gpu/src/queue/behind.rs`):** `classify_value_join()` evaluates local joined-list `will_meet` before `late_met_known`, preserving `wait_on_gpu = true` on reused memory-wait slots and keeping `JOIN_NEEDS_WAIT` and `host.rs` `waited_parts` / `split_part_waits` semantics sound across direct and split-send `Handoff` paths. - **Zero new P0/P1 regressions:** Verified `Rec` auto-flush/explicit-flush coverage, borrowed `ManuallyDrop` resource lifetimes, `NameGate` concurrency/drop safety, GPL-3.0 attributions, and 100% title-neutrality.
Androtim commented 2026-12-04 02:18:13 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T02:18:13Z.


Gate 2 Pure-Reasoning Audit — PR #416 (chore/split-emit-lower, 9cbceb753e6571482c56ad797755fa498b209b33)

VERIFIED CLEAN (0 P0, 0 P1)

Pure static line-by-line audit of f36f3544..9cbceb75 (origin/main...HEAD, 4 files under crates/victory-shader/src/emit/):

  1. 100% pure structural refactor (zero behavioral changes):
    • crates/victory-shader/src/emit/lower.rs (14,901 → 10,708 lines): exact diff is solely the 3 private module declarations (mod buffer;, mod image;, mod valu;) and extraction of two contiguous impl<'a> Lower<'a> method ranges (9636..12351 and 12681..14159). All remaining 10,705 lines are byte-for-byte identical; no #[allow] attributes on impl<'a> Lower<'a> or module-path-sensitive constructs (self::, file!, module_path!) exist in the extracted code.
    • crates/victory-shader/src/emit/lower/valu.rs (2,728 lines): exact 1:1 move of valu and its helper methods, with the sole path adjustment at line 1147 (super::shader_opt() & super::bitcode::opt::FIRST != 0 → super::super::shader_opt() & super::super::bitcode::opt::FIRST != 0) matching the one-level deeper module path.
    • crates/victory-shader/src/emit/lower/image.rs (954 lines): exact 1:1 move of image and cube_direction.
    • crates/victory-shader/src/emit/lower/buffer.rs (543 lines): exact 1:1 move of buffer.
  2. Minimal, sound visibility:
    • All 3 submodules are private; zero pub / pub(crate) widening.
    • pub(super) is added only to the 6 methods actually called across emit::lower submodules (valu, write_half, image, buffer from lower.rs; join64, split64 from image.rs). All other helpers remain private.
  3. Asset-policy file sizes & policy.rs integrity:
    • xtask/src/policy.rs is untouched.
    • All files are well under the 655,360-byte cap on Windows CRLF: lower.rs = 479,753 B CRLF (469,045 B LF), valu.rs = 129,450 B CRLF, image.rs = 44,374 B CRLF, buffer.rs = 24,291 B CRLF.
  4. Clean-room & title-neutrality:
    • Verified zero retail game/publisher names, title IDs, build versions, or local Windows paths in the commit message and all 4 files.

(Non-blocking [P2] hygiene note: crates/victory-shader/src/emit/lower/buffer.rs:1 contains a stray ASCII backspace control byte 0x08 in the //! doc comment — \x08uffer_* instead of buffer_*. Zero behavioral/CI/policy impact; easy cleanup anytime.)

<!-- greyfinch-sync:Androtim/MiniVI:comment:7398794709 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7398794709). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T02:18:13Z. --- ### Gate 2 Pure-Reasoning Audit — PR #416 (`chore/split-emit-lower`, `9cbceb753e6571482c56ad797755fa498b209b33`) **VERIFIED CLEAN (0 P0, 0 P1)** Pure static line-by-line audit of `f36f3544..9cbceb75` (`origin/main...HEAD`, 4 files under `crates/victory-shader/src/emit/`): 1. **100% pure structural refactor (zero behavioral changes):** - `crates/victory-shader/src/emit/lower.rs` (14,901 → 10,708 lines): exact diff is solely the 3 private module declarations (`mod buffer;`, `mod image;`, `mod valu;`) and extraction of two contiguous `impl<'a> Lower<'a>` method ranges (`9636..12351` and `12681..14159`). All remaining 10,705 lines are byte-for-byte identical; no `#[allow]` attributes on `impl<'a> Lower<'a>` or module-path-sensitive constructs (`self::`, `file!`, `module_path!`) exist in the extracted code. - `crates/victory-shader/src/emit/lower/valu.rs` (2,728 lines): exact 1:1 move of `valu` and its helper methods, with the sole path adjustment at line 1147 (`super::shader_opt() & super::bitcode::opt::FIRST != 0` → `super::super::shader_opt() & super::super::bitcode::opt::FIRST != 0`) matching the one-level deeper module path. - `crates/victory-shader/src/emit/lower/image.rs` (954 lines): exact 1:1 move of `image` and `cube_direction`. - `crates/victory-shader/src/emit/lower/buffer.rs` (543 lines): exact 1:1 move of `buffer`. 2. **Minimal, sound visibility:** - All 3 submodules are private; zero `pub` / `pub(crate)` widening. - `pub(super)` is added only to the 6 methods actually called across `emit::lower` submodules (`valu`, `write_half`, `image`, `buffer` from `lower.rs`; `join64`, `split64` from `image.rs`). All other helpers remain private. 3. **Asset-policy file sizes & `policy.rs` integrity:** - `xtask/src/policy.rs` is untouched. - All files are well under the 655,360-byte cap on Windows CRLF: `lower.rs` = 479,753 B CRLF (469,045 B LF), `valu.rs` = 129,450 B CRLF, `image.rs` = 44,374 B CRLF, `buffer.rs` = 24,291 B CRLF. 4. **Clean-room & title-neutrality:** - Verified zero retail game/publisher names, title IDs, build versions, or local Windows paths in the commit message and all 4 files. *(Non-blocking `[P2]` hygiene note: `crates/victory-shader/src/emit/lower/buffer.rs:1` contains a stray ASCII backspace control byte `0x08` in the `//!` doc comment — `\x08uffer_*` instead of `buffer_*`. Zero behavioral/CI/policy impact; easy cleanup anytime.)*
Androtim commented 2026-12-04 02:51:29 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T02:51:29Z.


Gate 2 Pure-Reasoning Re-Audit — PR #417 (\

<!-- greyfinch-sync:Androtim/MiniVI:comment:7399415953 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7399415953). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T02:51:29Z. --- ## Gate 2 Pure-Reasoning Re-Audit — PR #417 (\
Androtim commented 2026-12-04 03:02:49 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T03:02:49Z.


Gate 2 Pure-Reasoning Audit — PR #419 (fix/console-sample-mask-lod-fade) — VERIFIED CLEAN

  • PR / Commit: #419 @ 456ab3f8901b8bc44bfc2b9cfb82e2ad38480980 (port of ReTerryDavis/ReVIctory PR #31 / 4a783e4, GPL-3.0)
  • Result: 0 P0, 0 P1 — VERIFIED CLEAN

Audit Summary

  1. Shader lowering (victory-shader):
    • Lower::pixel_mask (emit/lower.rs) computes 2x2 quad parity (x & 1) | ((y & 1) << 1) from SV_Position.xy (FpToUi), tests bit place of USER_PIXEL_MASK (0x10a), and emits dx.op.discard (opcode 82, demote-to-helper) in entry without branching — preserving 2x2 quad helper lanes for derivatives and composing cleanly with PR #412's VICTORY_KILL_CONTINUE.
    • Explicitly clears flags::EARLY_DEPTH_STENCIL so masked-out pixels cannot write depth early.
    • Injects SV_Position at the preceding VS/MS OSG1 output row (position_row) when absent from console ISG1, uses centroid interpolation beside conservative depth outputs, and rejects row collisions cleanly.
    • with_pixel_mask restores thread-local PIXEL_MASK via RAII Drop guard (unwind-safe) and never touches compute / Wave32-on-Wave64 lowering.
    • All 10 modified files remain well below 640 KiB (largest: lower.rs at 463.44 KiB, draw.rs at 316.23 KiB).
  2. Shader cache & pipeline keys (shader_cache.rs, pipeline.rs, pipeline/host.rs, pipeline/make.rs):
    • Zero cache/PSO collision risk:
      • Disk shader cache (shader_cache.rs): mask_key(build(), Some(mask)) hashes build() + domain separator + position_row while leaving plain keys unchanged.
      • PSO library (pipeline/host.rs): library::name hashes root_blob + translated stage DXIL bytes + state, naturally isolating masked PSOs.
      • Pending::key (pipeline/make.rs): appends b"masked" + position_row for masked stages while keeping plain keys unchanged.
      • In-memory Shader: masked twins live in masked_twins with separate OnceLock<Option<Translated>>; Shader::dxil() reloads trimmed masked bytecode via host_shader_masked, and Translated::position_row avoids submission-thread reloads.
    • GraphicsState::clone safely re-seats SemanticName pointers onto cloned CString storage.
    • Verified PR #409's CS_RaytracingResolve throttle (make.rs) and PR #415's name_gate (pipeline/library.rs) / host::rec (host.rs) remain completely intact.
  3. Command lists & draw dispatch (draw.rs, list.rs, list/thin.rs):
    • Newer command-list slot 142 (0x470) OMSetSampleMaskX is wired on both direct (NEWER_METHODS) and thin (thin::table(true) + plain! SAMPLE_MASK) command lists; older lists remain untouched.
    • VICTORY_SAMPLE_MASK=0 short-circuits immediately before touching draw state.
    • State::reset clears pixel_mask to None across Reset/ResetX; State::replay preserves pixel_mask and invalidates cached host bindings across command-list cuts; sample_mask_x uses with_state (bumping title_calls and flushing held indirect runs so indirect merging cannot coalesce draws across mask changes).
    • Default/full-coverage masks (u64::MAX / 0x0001_0001_0001_0001) map to pixel_mask = None, taking the fast plain path in graphics_pipeline() with zero extra work or compile stalls; partial masks lazily enqueue guarded twins via make::ready and fall back to plain while compiling.
  4. License & title-neutrality:
    • Explicit ReTerryDavis/ReVIctory PR #31 (4a783e4, GPL-3.0) attribution across code and tests; 100% title-neutral with zero retail names or local paths.

Non-blocking Notes (P2/P3)

  • (P2) In lower.rs, self.inputs()? runs before self.pixel_mask(mask); if a pixel shader lacks SV_Position and has an unpacked SV_IsFrontFace (row: None) while the preceding stage places SV_Position at free, FrontFace would claim that row first and pixel_mask would safely fall back via Err to the unmasked pipeline.
  • (P3) trim_shader_bytecode (pipeline.rs) only walks SHADERS (plain shaders), not masked_twins; impact is negligible given the small count of LOD-fade pixel shaders.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7399630567 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7399630567). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T03:02:49Z. --- ### Gate 2 Pure-Reasoning Audit — PR #419 (`fix/console-sample-mask-lod-fade`) — **VERIFIED CLEAN** - **PR / Commit:** #419 @ `456ab3f8901b8bc44bfc2b9cfb82e2ad38480980` (port of `ReTerryDavis/ReVIctory` PR `#31` / `4a783e4`, GPL-3.0) - **Result:** **0 P0, 0 P1** — **VERIFIED CLEAN** #### Audit Summary 1. **Shader lowering (`victory-shader`):** - `Lower::pixel_mask` (`emit/lower.rs`) computes 2x2 quad parity `(x & 1) | ((y & 1) << 1)` from `SV_Position.xy` (`FpToUi`), tests bit `place` of `USER_PIXEL_MASK` (`0x10a`), and emits `dx.op.discard` (opcode 82, demote-to-helper) in `entry` without branching — preserving 2x2 quad helper lanes for derivatives and composing cleanly with PR #412's `VICTORY_KILL_CONTINUE`. - Explicitly clears `flags::EARLY_DEPTH_STENCIL` so masked-out pixels cannot write depth early. - Injects `SV_Position` at the preceding VS/MS `OSG1` output row (`position_row`) when absent from console `ISG1`, uses centroid interpolation beside conservative depth outputs, and rejects row collisions cleanly. - `with_pixel_mask` restores thread-local `PIXEL_MASK` via RAII `Drop` guard (unwind-safe) and never touches compute / Wave32-on-Wave64 lowering. - All 10 modified files remain well below 640 KiB (largest: `lower.rs` at 463.44 KiB, `draw.rs` at 316.23 KiB). 2. **Shader cache & pipeline keys (`shader_cache.rs`, `pipeline.rs`, `pipeline/host.rs`, `pipeline/make.rs`):** - **Zero cache/PSO collision risk:** - Disk shader cache (`shader_cache.rs`): `mask_key(build(), Some(mask))` hashes `build()` + domain separator + `position_row` while leaving plain keys unchanged. - PSO library (`pipeline/host.rs`): `library::name` hashes `root_blob` + translated stage DXIL bytes + state, naturally isolating masked PSOs. - `Pending::key` (`pipeline/make.rs`): appends `b"masked"` + `position_row` for masked stages while keeping plain keys unchanged. - In-memory `Shader`: masked twins live in `masked_twins` with separate `OnceLock<Option<Translated>>`; `Shader::dxil()` reloads trimmed masked bytecode via `host_shader_masked`, and `Translated::position_row` avoids submission-thread reloads. - `GraphicsState::clone` safely re-seats `SemanticName` pointers onto cloned `CString` storage. - Verified PR #409's `CS_RaytracingResolve` throttle (`make.rs`) and PR #415's `name_gate` (`pipeline/library.rs`) / `host::rec` (`host.rs`) remain completely intact. 3. **Command lists & draw dispatch (`draw.rs`, `list.rs`, `list/thin.rs`):** - Newer command-list slot 142 (`0x470`) `OMSetSampleMaskX` is wired on both direct (`NEWER_METHODS`) and thin (`thin::table(true)` + `plain! SAMPLE_MASK`) command lists; older lists remain untouched. - `VICTORY_SAMPLE_MASK=0` short-circuits immediately before touching draw state. - `State::reset` clears `pixel_mask` to `None` across `Reset`/`ResetX`; `State::replay` preserves `pixel_mask` and invalidates cached host bindings across command-list cuts; `sample_mask_x` uses `with_state` (bumping `title_calls` and flushing held indirect runs so indirect merging cannot coalesce draws across mask changes). - Default/full-coverage masks (`u64::MAX` / `0x0001_0001_0001_0001`) map to `pixel_mask = None`, taking the fast `plain` path in `graphics_pipeline()` with zero extra work or compile stalls; partial masks lazily enqueue guarded twins via `make::ready` and fall back to `plain` while compiling. 4. **License & title-neutrality:** - Explicit `ReTerryDavis/ReVIctory` PR `#31` (`4a783e4`, GPL-3.0) attribution across code and tests; 100% title-neutral with zero retail names or local paths. #### Non-blocking Notes (P2/P3) - *(P2)* In `lower.rs`, `self.inputs()?` runs before `self.pixel_mask(mask)`; if a pixel shader lacks `SV_Position` and has an unpacked `SV_IsFrontFace` (`row: None`) while the preceding stage places `SV_Position` at `free`, `FrontFace` would claim that row first and `pixel_mask` would safely fall back via `Err` to the unmasked pipeline. - *(P3)* `trim_shader_bytecode` (`pipeline.rs`) only walks `SHADERS` (plain shaders), not `masked_twins`; impact is negligible given the small count of LOD-fade pixel shaders.
Androtim commented 2026-12-04 03:18:27 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T03:18:27Z.


Gate 2 Pure-Reasoning Re-Audit — PR #418 (b689a095b4439a080b22b2202370892c2123073b)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Verification Summary

  1. Overlap-clearing Physical::holes (BTreeMap<usize, usize>) + clear_holes:
    • consume_hole suffix fabrication is completely removed.
    • clear_holes(physical, base, len) guards len == 0, computes end = base.saturating_add(len) (ensuring base.saturating_add(1) <= end with zero range-panic risk even at usize::MAX), removes the unique possible overlapping predecessor via range(..=base).next_back().filter(|&(&at, &size)| at.saturating_add(size) > base), and removes all interior-starting overlaps via range(base.saturating_add(1)..end) while preserving adjacent non-overlapping entries (at + size == base and at == end).
  2. All placeholder-mutating sites preserve strict disjointness and freshness:
    • map_as, map_lazy_as, change, unmap, one_placeholder, all 3 branches of coalesce_placeholders (exact single region, split single region, multi-region coalesce with boundary splits), and title_virtual_free (both span release/decommit and MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS, guarded by !HOLDING.get() after releasing LIVE).
    • Regression test partial_hole_mapping_never_fabricates_stale_holes_for_eager_lazy_or_alias covers eager, lazy (materialize_for), run-coalesced alias_as(..., true, false), and title_virtual_free placeholder split paths.
  3. Prior items, attribution, and neutrality:
    • XMemAllocatePhysicalPages page-number budget guard, Wine/disabled-split test guard, ReTerryDavis/ReVIctory PR #3 (7f2fcea, GPL-3.0) attribution, and 100% title-neutrality all remain clean.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7399925207 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7399925207). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T03:18:27Z. --- ## Gate 2 Pure-Reasoning Re-Audit — PR #418 (`b689a095b4439a080b22b2202370892c2123073b`) **Verdict: `VERIFIED CLEAN` (`0 P0`, `0 P1`)** ### Verification Summary 1. **Overlap-clearing `Physical::holes` (`BTreeMap<usize, usize>`) + `clear_holes`:** - `consume_hole` suffix fabrication is completely removed. - `clear_holes(physical, base, len)` guards `len == 0`, computes `end = base.saturating_add(len)` (ensuring `base.saturating_add(1) <= end` with zero range-panic risk even at `usize::MAX`), removes the unique possible overlapping predecessor via `range(..=base).next_back().filter(|&(&at, &size)| at.saturating_add(size) > base)`, and removes all interior-starting overlaps via `range(base.saturating_add(1)..end)` while preserving adjacent non-overlapping entries (`at + size == base` and `at == end`). 2. **All placeholder-mutating sites preserve strict disjointness and freshness:** - `map_as`, `map_lazy_as`, `change`, `unmap`, `one_placeholder`, all 3 branches of `coalesce_placeholders` (exact single region, split single region, multi-region coalesce with boundary splits), and `title_virtual_free` (both `span` release/decommit and `MEM_PRESERVE_PLACEHOLDER | MEM_COALESCE_PLACEHOLDERS`, guarded by `!HOLDING.get()` after releasing `LIVE`). - Regression test `partial_hole_mapping_never_fabricates_stale_holes_for_eager_lazy_or_alias` covers eager, lazy (`materialize_for`), run-coalesced `alias_as(..., true, false)`, and `title_virtual_free` placeholder split paths. 3. **Prior items, attribution, and neutrality:** - `XMemAllocatePhysicalPages` page-number budget guard, Wine/disabled-split test guard, `ReTerryDavis/ReVIctory` PR `#3` (`7f2fcea`, GPL-3.0) attribution, and 100% title-neutrality all remain clean.
Androtim commented 2026-12-04 03:22:59 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T03:22:59Z.


Gate 2 Pure-Reasoning Audit — PR #420 (fix/smoke-standin-alpha) — VERIFIED CLEAN

  • PR / Commit: #420 @ 25267c40b9f735ad9fe4ff2f8be9f2dc6e2a91b9
  • Scope: crates/victory-gpu/src/descriptor/host.rs (+146 / -24)
  • Result: 0 P0, 0 P1 — VERIFIED CLEAN

Audit Summary

  1. Backing Resource & Format Decoding (Zero Block-Encoding / NaN / Validation Risks):
    • make_neutral() always allocates a 1×1 (1×1×6 for Cube) uncompressed DXGI_FORMAT_R8G8B8A8_UNORM DEFAULT texture (256-byte RowPitch upload synced on COPY fence) and neutral_for() binds a matching DXGI_FORMAT_R8G8B8A8_UNORM SRV (MipLevels = 1, matching ArraySize/NumCubes). There are no compressed BCn block encodings to corrupt, zero D3D12 format-mismatch validation errors, and zero NaN risk (strict UNORM [0.0, 1.0]).
    • standin_texel(false) writes [0x80, 0x80, 0x80, 0x00] → (0.50196, 0.50196, 0.50196, 0.0); VICTORY_STANDIN_OPAQUE=1 (standin_texel(true)) preserves [0x80, 0x80, 0x80, 0xff] → A = 1.0. NEUTRALS indexing (stand as usize + 4 * usize::from(opaque)) stays strictly in 0..8.
  2. Shader4ComponentMapping & Per-Format Coverage:
    • standin_component_mapping() for format_without_alpha() (BC5_TYPELESS/UNORM, R8G8_TYPELESS/UNORM, B8G8R8X8_TYPELESS/UNORM/UNORM_SRGB, B5G6R5_UNORM) encodes FROM_MEMORY_COMPONENT_0 | (1<<3) | (2<<6) | (FORCE_VALUE_1<<9) | (1<<12) = 6792 (0x1a88), matching D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, 5). BC5/R8G8 normal maps and NV12 UV chroma still read (0.502, 0.502) with A = 1.0.
    • Alpha-capable formats (BC1, BC2, BC3, BC7, R8G8B8A8, B8G8R8A8, R10G10B10A2_UNORM, R16G16B16A16_UNORM, B5G5R5A1, B4G4R4A4) keep D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING (5768 / 0x1688), sampling RGB = 0.502, A = 0.0 (so opaque BC1/albedo ignores .a, 1-bit BC1/cutout foliage discards cleanly instead of solid gray cards, and alpha-blended smoke/particles/decals stay invisible until resident).
    • gray_fits() preserves every PR #409 exclusion (R8_UNORM, BC4_*, BC6H_*, R11G11B10_FLOAT, R16G16B16A16_FLOAT, R32*_FLOAT, depth/stencil, *_SNORM) and additionally excludes A8_UNORM, R8_TYPELESS, and R9G9B9E5_SHAREDEXP so alpha-only masks and shared-exponent HDR textures stay null (0,0,0,0).
  3. Visual Regression Risk:
    • Low and strictly positive for transient unstreamed/evicted slots: opaque surfaces ignore .a; water normal maps (BC5/R8G8) keep flat (0.502, 0.502, *, 1.0); reflection/HDR probes stay null (0,0,0,0); host G-buffer/render/UAV targets are excluded by waits_gray() (!title_fills) and never bind neutral_for().
  4. Title-Neutrality:
    • 100% title-neutral across code, comments, tests, commit message, and PR description (zero retail names or local Windows paths).

Non-Blocking Notes (P3)

  • (P3) If any transient unstreamed particle/UI sprite uses pre-multiplied-in-texture blending (ONE, INV_SRC_ALPHA) without multiplying .rgb by .a in the shader, (0.502, 0.502, 0.502, 0.0) behaves additively (dst + 0.502) rather than blending (0.502 + 0.498 * dst) while unresident; straight-alpha smoke/exhaust billboards benefit cleanly.
  • (P3) Two-channel formats (BC5, R8G8) keep B = FROM_MEMORY_COMPONENT_2 (0.502, unchanged from pre-PR #420) rather than hardware's FORCE_VALUE_0; normal maps and UV chroma only read .rg.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7400014810 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7400014810). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T03:22:59Z. --- ### Gate 2 Pure-Reasoning Audit — PR #420 (`fix/smoke-standin-alpha`) — **VERIFIED CLEAN** - **PR / Commit:** #420 @ `25267c40b9f735ad9fe4ff2f8be9f2dc6e2a91b9` - **Scope:** `crates/victory-gpu/src/descriptor/host.rs` (+146 / -24) - **Result:** **0 P0, 0 P1** — **VERIFIED CLEAN** #### Audit Summary 1. **Backing Resource & Format Decoding (Zero Block-Encoding / NaN / Validation Risks):** - `make_neutral()` always allocates a 1×1 (1×1×6 for Cube) uncompressed `DXGI_FORMAT_R8G8B8A8_UNORM` `DEFAULT` texture (256-byte `RowPitch` upload synced on COPY fence) and `neutral_for()` binds a matching `DXGI_FORMAT_R8G8B8A8_UNORM` SRV (`MipLevels = 1`, matching `ArraySize`/`NumCubes`). There are no compressed BCn block encodings to corrupt, zero D3D12 format-mismatch validation errors, and zero NaN risk (strict UNORM `[0.0, 1.0]`). - `standin_texel(false)` writes `[0x80, 0x80, 0x80, 0x00]` → `(0.50196, 0.50196, 0.50196, 0.0)`; `VICTORY_STANDIN_OPAQUE=1` (`standin_texel(true)`) preserves `[0x80, 0x80, 0x80, 0xff]` → `A = 1.0`. `NEUTRALS` indexing (`stand as usize + 4 * usize::from(opaque)`) stays strictly in `0..8`. 2. **`Shader4ComponentMapping` & Per-Format Coverage:** - `standin_component_mapping()` for `format_without_alpha()` (`BC5_TYPELESS/UNORM`, `R8G8_TYPELESS/UNORM`, `B8G8R8X8_TYPELESS/UNORM/UNORM_SRGB`, `B5G6R5_UNORM`) encodes `FROM_MEMORY_COMPONENT_0 | (1<<3) | (2<<6) | (FORCE_VALUE_1<<9) | (1<<12)` = `6792` (`0x1a88`), matching `D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(0, 1, 2, 5)`. `BC5`/`R8G8` normal maps and NV12 UV chroma still read `(0.502, 0.502)` with `A = 1.0`. - Alpha-capable formats (`BC1`, `BC2`, `BC3`, `BC7`, `R8G8B8A8`, `B8G8R8A8`, `R10G10B10A2_UNORM`, `R16G16B16A16_UNORM`, `B5G5R5A1`, `B4G4R4A4`) keep `D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING` (`5768` / `0x1688`), sampling `RGB = 0.502, A = 0.0` (so opaque `BC1`/albedo ignores `.a`, 1-bit `BC1`/cutout foliage discards cleanly instead of solid gray cards, and alpha-blended smoke/particles/decals stay invisible until resident). - `gray_fits()` preserves every PR #409 exclusion (`R8_UNORM`, `BC4_*`, `BC6H_*`, `R11G11B10_FLOAT`, `R16G16B16A16_FLOAT`, `R32*_FLOAT`, depth/stencil, `*_SNORM`) and additionally excludes `A8_UNORM`, `R8_TYPELESS`, and `R9G9B9E5_SHAREDEXP` so alpha-only masks and shared-exponent HDR textures stay null `(0,0,0,0)`. 3. **Visual Regression Risk:** - Low and strictly positive for transient unstreamed/evicted slots: opaque surfaces ignore `.a`; water normal maps (`BC5`/`R8G8`) keep flat `(0.502, 0.502, *, 1.0)`; reflection/HDR probes stay null `(0,0,0,0)`; host G-buffer/render/UAV targets are excluded by `waits_gray()` (`!title_fills`) and never bind `neutral_for()`. 4. **Title-Neutrality:** - 100% title-neutral across code, comments, tests, commit message, and PR description (zero retail names or local Windows paths). #### Non-Blocking Notes (P3) - *(P3)* If any transient unstreamed particle/UI sprite uses pre-multiplied-in-texture blending (`ONE, INV_SRC_ALPHA`) without multiplying `.rgb` by `.a` in the shader, `(0.502, 0.502, 0.502, 0.0)` behaves additively (`dst + 0.502`) rather than blending (`0.502 + 0.498 * dst`) while unresident; straight-alpha smoke/exhaust billboards benefit cleanly. - *(P3)* Two-channel formats (`BC5`, `R8G8`) keep `B = FROM_MEMORY_COMPONENT_2` (`0.502`, unchanged from pre-PR #420) rather than hardware's `FORCE_VALUE_0`; normal maps and UV chroma only read `.rg`.
Androtim commented 2026-12-04 03:54:23 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T03:54:23Z.


Gate 2 Pure-Reasoning Audit — PR #381 (fix/missing-character-head) — VERIFIED CLEAN

  • PR / Commit: #381 @ 63ac4217901fd28628bf24526037ec0bdd242ee7 (CI check PASS)
  • Scope: pipeline/make.rs, shader_cache.rs, emit/lower.rs, emit/lower_tests.rs, emit/mod.rs (+214 / -7)
  • Result: 0 P0, 0 P1 — VERIFIED CLEAN

Audit Summary

  1. crates/victory-gpu/src/pipeline/make.rs (scene_input()):
    • Adds single compute program HEAD_BLEND_SHAPE_MAP (61e54e90adccaf6a) to scene_input(). At pipeline creation, make::early() enqueues it at REQUESTED priority into Queue::screen (non-blocking — never calls wait() during creation), preserving left_out guards and strict lock ordering (QUEUE → DONE / SPENT never nested), so deadlock is impossible.
    • Does not set rt_resolve, touch requested_slow/slow_now, or compete with PR #409's CS_RaytracingResolve throttling.
    • Compute-only (stage == "compute", no "pixel" stage), so PR #419's lazy host_pipeline_masked() sample-mask twin path is unaffected; unit test the_head_blend_shape_map_is_made_at_creation matches Shader's #[cfg(windows)] layout including mask and masked_twins.
  2. crates/victory-shader/src/emit/{mod.rs,lower.rs,lower_tests.rs} (LDS bounds exemption):
    • parse_lds_bounds_exempt() defaults (None) strictly to the 25 exact 16-hex hashes in FACE_PROGRAMS, rejects prefixes/malformed tokens into ignored, honors VICTORY_LDS_BOUNDS_EXEMPT=0 (and "") opt-out cleanly, and matches via exact case-insensitive equality (eq_ignore_ascii_case, never prefix match) scoped by emit::translate()'s unwind-safe with_program() RAII guard. Unrelated shaders (including PROGRAM == "") cannot be accidentally exempted.
    • lower::lds_bounds() gates only limit = self.s.title_lds_dwords vs 0 (self.s.lds_dwords == 0 refusal remains enforced). Exempted programs emit direct on-chip TGSM addrspace(3) GEP (matching pre-VICTORY_LDS_BOUNDS behavior): TGSM accesses cannot trigger virtual-memory page faults, halves/ticket (wave_base) run exclusively in the entry block before title code, and pairs (meet()) polling is strictly bounded by MEETING_POLLS — zero D3D12 TDR risk on valid inputs.
    • lower.rs size is 474,655 bytes (~463.5 KiB), well below the 640 KiB cap.
  3. crates/victory-gpu/src/shader_cache.rs:
    • Adds VICTORY_LDS_BOUNDS_EXEMPT to TRANSLATOR_ENV_KEYS (feeding both shader cache keys and pipeline/known.rs via shader_cache::translation()) and bumps SHADER_CACHE_VERSION 4 -> 5, invalidating all stale v1–v4 DXIL cache entries via victory-pipeline's Converter::version().
  4. Title-Neutrality:
    • 100% title-neutral across all 5 files, tests, comments, and commit message (zero retail game/character names or local Windows paths).

Non-Blocking Note (P3)

  • (P3) append_translator_env encodes unset (None) and empty (Some("")) identically (VICTORY_LDS_BOUNDS_EXEMPT=\0), whereas parse_lds_bounds_exempt(Some("")) disables exemptions while None enables FACE_PROGRAMS. On Windows (cmd/PowerShell) empty values unset the variable, and the documented opt-out VICTORY_LDS_BOUNDS_EXEMPT=0 produces a distinct cache key (VICTORY_LDS_BOUNDS_EXEMPT=0\0).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7400598005 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7400598005). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T03:54:23Z. --- ### Gate 2 Pure-Reasoning Audit — PR #381 (`fix/missing-character-head`) — **VERIFIED CLEAN** - **PR / Commit:** #381 @ `63ac4217901fd28628bf24526037ec0bdd242ee7` (CI `check` PASS) - **Scope:** `pipeline/make.rs`, `shader_cache.rs`, `emit/lower.rs`, `emit/lower_tests.rs`, `emit/mod.rs` (+214 / -7) - **Result:** **0 P0, 0 P1** — **VERIFIED CLEAN** #### Audit Summary 1. **`crates/victory-gpu/src/pipeline/make.rs` (`scene_input()`):** - Adds single compute program `HEAD_BLEND_SHAPE_MAP` (`61e54e90adccaf6a`) to `scene_input()`. At pipeline creation, `make::early()` enqueues it at `REQUESTED` priority into `Queue::screen` (non-blocking — never calls `wait()` during creation), preserving `left_out` guards and strict lock ordering (`QUEUE` → `DONE` / `SPENT` never nested), so deadlock is impossible. - Does not set `rt_resolve`, touch `requested_slow`/`slow_now`, or compete with PR `#409`'s `CS_RaytracingResolve` throttling. - Compute-only (`stage == "compute"`, no `"pixel"` stage), so PR `#419`'s lazy `host_pipeline_masked()` sample-mask twin path is unaffected; unit test `the_head_blend_shape_map_is_made_at_creation` matches `Shader`'s `#[cfg(windows)]` layout including `mask` and `masked_twins`. 2. **`crates/victory-shader/src/emit/{mod.rs,lower.rs,lower_tests.rs}` (LDS bounds exemption):** - `parse_lds_bounds_exempt()` defaults (`None`) strictly to the 25 exact 16-hex hashes in `FACE_PROGRAMS`, rejects prefixes/malformed tokens into `ignored`, honors `VICTORY_LDS_BOUNDS_EXEMPT=0` (and `""`) opt-out cleanly, and matches via exact case-insensitive equality (`eq_ignore_ascii_case`, never prefix match) scoped by `emit::translate()`'s unwind-safe `with_program()` RAII guard. Unrelated shaders (including `PROGRAM == ""`) cannot be accidentally exempted. - `lower::lds_bounds()` gates only `limit = self.s.title_lds_dwords` vs `0` (`self.s.lds_dwords == 0` refusal remains enforced). Exempted programs emit direct on-chip TGSM `addrspace(3)` GEP (matching pre-`VICTORY_LDS_BOUNDS` behavior): TGSM accesses cannot trigger virtual-memory page faults, `halves`/`ticket` (`wave_base`) run exclusively in the entry block before title code, and `pairs` (`meet()`) polling is strictly bounded by `MEETING_POLLS` — zero D3D12 TDR risk on valid inputs. - `lower.rs` size is `474,655` bytes (~463.5 KiB), well below the 640 KiB cap. 3. **`crates/victory-gpu/src/shader_cache.rs`:** - Adds `VICTORY_LDS_BOUNDS_EXEMPT` to `TRANSLATOR_ENV_KEYS` (feeding both shader cache keys and `pipeline/known.rs` via `shader_cache::translation()`) and bumps `SHADER_CACHE_VERSION` `4 -> 5`, invalidating all stale v1–v4 DXIL cache entries via `victory-pipeline`'s `Converter::version()`. 4. **Title-Neutrality:** - 100% title-neutral across all 5 files, tests, comments, and commit message (zero retail game/character names or local Windows paths). #### Non-Blocking Note (P3) - *(P3)* `append_translator_env` encodes unset (`None`) and empty (`Some("")`) identically (`VICTORY_LDS_BOUNDS_EXEMPT=\0`), whereas `parse_lds_bounds_exempt(Some(""))` disables exemptions while `None` enables `FACE_PROGRAMS`. On Windows (`cmd`/PowerShell) empty values unset the variable, and the documented opt-out `VICTORY_LDS_BOUNDS_EXEMPT=0` produces a distinct cache key (`VICTORY_LDS_BOUNDS_EXEMPT=0\0`).
Androtim commented 2026-12-04 04:28:51 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T04:28:51Z.


Gate 2 Pure-Reasoning Re-Audit — PR #391 (feat/hwrt-rayquery-lift-remaining) — VERIFIED CLEAN

  • PR / Commit: #391 @ aabb9c456d6644f38948ca3067a9afb98ee7ae81
  • Scope: crates/victory-shader/src/emit/lower/rayquery.rs, crates/victory-shader/src/emit/lower/rayquery/analyze.rs, crates/victory-shader/src/emit/rayquery_tests.rs (3 files, +5849 / -653 vs origin/main)
  • Result: 0 P0, 0 P1 — VERIFIED CLEAN

Audit Summary

  1. Prior [P1] (in-callback EXEC widening producing st.guards[b][i] == None and clobbering opaque-hit tmax / accept_first_hit state): 100% CLOSED
    • Global EXEC-subset invariant (analyze.rs:3979-4020, cb_mask_within_ce at L7167-7376): find_triangle_hit_info now requires a resolved ce = ni_exec_bool and proves every EXEC write inside cb_inst_sites (both halves in wave64; partial writes fail closed) stays within ce. cb_mask_within_ce combines st.mask_bits (!meet(&[(mb, true), (ce, false)])) with sound unmemoized stack co-induction over callback-internal PHIs (all reachable preds) and subset-preserving callback-internal mask ops (v_cmpx*, s_{and,andn1,andn2,or,xor}_saveexec, s_{andn1,andn2}_wrexec, s_{mov,and,andn2,xor,or,cselect}), matching RDNA2 ISA and structure.rs semantics while rejecting s_wqm, widening saves (s_or/xor_saveexec with outer masks), and outer-mask s_andn2_wrexec / s_mov restores.
    • Per-site cb_exec_within_entry gating (analyze.rs:4021-4027): Defense-in-depth cb_exec_within_entry gating is now enforced at every in_cb guard/preservation site (is_cb_entry_guard, guarded_cb_mov_chain_preserves_opaque, pattern_b_guard_ok, blocks_site_decision, inline_site_decision, preserves_old_state_ok, and preserves_old_dst_ok).
    • Strict Case 2 inline saveexec stack (analyze.rs:6910-6959, 7050-7159): Replaced integer exec_depth with Vec<(u8, Value, Option<Value>)> matching exact saved (reg, lo, hi) pairs (both halves in wave64), validating s_xor/s_andn2 else-flips strictly against exec_stack.last(), and rejecting aliased outer EXEC restores (e.g., s21 = s18).
    • Zero regressions on real shaders: Inner wave32/wave64 waterfall loops (s_andn2_wrexec / s_andn2 + callback-internal PHIs + cb_head entry EXEC restore), Case 1b (without_execz_skips), and Case 2 inline if/else (s_and/andn1_saveexec + s_xor/s_andn2 + matching restore) remain cleanly accepted.
    • Regression coverage (rayquery_tests.rs:5908-6074): in_callback_exec_widening_clobbering_opaque_hit_bails exercises all 6 CallbackKind::Blocks (s_mov, s_or_saveexec, s_andn2_wrexec) and CallbackKind::Inline (aliased s21 = s18 saveexec restore) tmax and accept_first_hit state clobber counterexamples.
  2. Title-Neutrality (origin/main...HEAD):
    • 100% CLEAN across all 3 changed files and all 13 commits (zero retail game/studio/console names and zero local Windows paths).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7401272161 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7401272161). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T04:28:51Z. --- ### Gate 2 Pure-Reasoning Re-Audit — PR #391 (`feat/hwrt-rayquery-lift-remaining`) — **VERIFIED CLEAN** - **PR / Commit:** #391 @ `aabb9c456d6644f38948ca3067a9afb98ee7ae81` - **Scope:** `crates/victory-shader/src/emit/lower/rayquery.rs`, `crates/victory-shader/src/emit/lower/rayquery/analyze.rs`, `crates/victory-shader/src/emit/rayquery_tests.rs` (3 files, +5849 / -653 vs `origin/main`) - **Result:** **0 P0, 0 P1** — **VERIFIED CLEAN** #### Audit Summary 1. **Prior `[P1]` (in-callback `EXEC` widening producing `st.guards[b][i] == None` and clobbering opaque-hit `tmax` / `accept_first_hit` state): 100% CLOSED** - **Global `EXEC`-subset invariant (`analyze.rs:3979-4020`, `cb_mask_within_ce` at `L7167-7376`):** `find_triangle_hit_info` now requires a resolved `ce = ni_exec_bool` and proves every `EXEC` write inside `cb_inst_sites` (both halves in wave64; partial writes fail closed) stays within `ce`. `cb_mask_within_ce` combines `st.mask_bits` (`!meet(&[(mb, true), (ce, false)])`) with sound unmemoized stack co-induction over callback-internal PHIs (all reachable preds) and subset-preserving callback-internal mask ops (`v_cmpx*`, `s_{and,andn1,andn2,or,xor}_saveexec`, `s_{andn1,andn2}_wrexec`, `s_{mov,and,andn2,xor,or,cselect}`), matching RDNA2 ISA and `structure.rs` semantics while rejecting `s_wqm`, widening saves (`s_or/xor_saveexec` with outer masks), and outer-mask `s_andn2_wrexec` / `s_mov` restores. - **Per-site `cb_exec_within_entry` gating (`analyze.rs:4021-4027`):** Defense-in-depth `cb_exec_within_entry` gating is now enforced at every `in_cb` guard/preservation site (`is_cb_entry_guard`, `guarded_cb_mov_chain_preserves_opaque`, `pattern_b_guard_ok`, `blocks_site_decision`, `inline_site_decision`, `preserves_old_state_ok`, and `preserves_old_dst_ok`). - **Strict Case 2 inline `saveexec` stack (`analyze.rs:6910-6959`, `7050-7159`):** Replaced integer `exec_depth` with `Vec<(u8, Value, Option<Value>)>` matching exact saved `(reg, lo, hi)` pairs (both halves in wave64), validating `s_xor`/`s_andn2` else-flips strictly against `exec_stack.last()`, and rejecting aliased outer `EXEC` restores (e.g., `s21 = s18`). - **Zero regressions on real shaders:** Inner wave32/wave64 waterfall loops (`s_andn2_wrexec` / `s_andn2` + callback-internal PHIs + `cb_head` entry `EXEC` restore), Case 1b (`without_execz_skips`), and Case 2 inline `if/else` (`s_and/andn1_saveexec` + `s_xor`/`s_andn2` + matching restore) remain cleanly accepted. - **Regression coverage (`rayquery_tests.rs:5908-6074`):** `in_callback_exec_widening_clobbering_opaque_hit_bails` exercises all 6 `CallbackKind::Blocks` (`s_mov`, `s_or_saveexec`, `s_andn2_wrexec`) and `CallbackKind::Inline` (aliased `s21 = s18` saveexec restore) `tmax` and `accept_first_hit` state clobber counterexamples. 2. **Title-Neutrality (`origin/main...HEAD`):** - **100% CLEAN** across all 3 changed files and all 13 commits (zero retail game/studio/console names and zero local Windows paths).
Androtim commented 2026-12-04 04:32:08 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T04:32:08Z.


Gate 2 Pure-Reasoning Audit — PR #422 (perf/bounded-placed-view-table) — VERIFIED CLEAN

  • PR / Commit: #422 @ 3ed6a9e03fcd938488d4824723e2b733c6b06af8
  • Scope: crates/victory-gpu/src/descriptor.rs, crates/victory-gpu/src/descriptor/host.rs (2 files, +436 / -74 vs origin/main)
  • Result: 0 P0, 0 P1 — VERIFIED CLEAN

Audit Summary

  1. Concurrency & Lifetime Safety (ViewEntry, ReadMostly<Views>, MIRROR_CACHE, views_alive):
    • ViewEntry { view, generation, last_used: AtomicU64, live } is Send + Sync; touch() writes last_used atomically with Ordering::Relaxed under shard read guards. ReadMostly::read drop (RwLockReadGuard Release) into ReadMostly::write (RwLockWriteGuard Acquire across all SHARDS + 1 locks) establishes strict happens-before from every reader touch() to evict_idle_slice's Relaxed load.
    • Every active read/validation path refreshes last_used on live generation match: Views::lookup_entry, Views::entry_of, Views::entry_made, views_alive (draw heap buffer-slot cache validation), and descriptor::host::views_entry_alive (MIRROR_CACHE hits).
    • Retired slots clear index, set live = false, advance generation = ((old_gen + 1) & GENERATIONS).max(1) (always in 1..=0x3fff_ffff, never 0, never colliding with KIND_SHIFT bits 30..31, and never overflowing u32), and push to free. Stale descriptor handles and MIRROR_CACHE entries cleanly resolve to None / invalidate both while free and after slot reuse.
    • Frame-age checks use now.saturating_sub(last_used) and now.saturating_sub(prev), safe at frame 0, last_used == 0, and across concurrent frame-boundary increments.
  2. ownerless FIFO Queue & Resource/Sampler Retention:
    • Strict live + generation + index guards across evict_idle_slice, free_ownerless, and forget guarantee zero double-free and zero duplicate slot indices in free. evict_idle_slice prunes already-retired front entries from ownerless while preserving ownerless_cap() (1 << 20).
    • View::is_evictable() matches only View::Placed(..) | View::Constant(..); View::Shader, View::Unordered, View::Sampler, and View::ConsoleSampler are never idle-evicted.
  3. PLACED_SHAPE_CAP, VICTORY_VIEW_EVICT=0, Lock Ordering & Cursor Bounds:
    • Once ViewShapes::shapes.len() >= shape_cap (PLACED_SHAPE_CAP = 262_144), shape_number() returns None under shapes_read() without taking shapes_write(), overflowing into Views while keeping LOCAL_SHAPES bounded and consistent. VICTORY_VIEW_EVICT=0 restores shape_cap = SHAPES and disables both periodic and on-demand eviction.
    • maybe_sweep_idle_views() runs at the entry of sync_heaps() before if !sync_on() { return; } and before SHADER_HEAPS.read(), so idle sweeps run even under VICTORY_HEAP_SYNC=0 (via begin_sync_heaps()'s !sync_aside() path). views_read() is dropped before views_write(), and on-demand eviction in entry_made() acquires no nested locks — zero lock-order inversion or deadlock.
    • evict_idle_slice() guards len == 0 || slice == 0, clamps sweep_cursor >= len to 0, bounds iterations to slice.min(len), and wraps sweep_cursor modulo len — zero out-of-bounds panic possible.
  4. Attribution, File Sizes & Title-Neutrality:
    • GPL-3.0 attribution present in commit message and descriptor.rs (ViewEntry & PLACED_SHAPE_CAP) citing ReTerryDavis/ReVIctory PR #26 (fc8f19f) and monte-alt/vesper PR #25 (VSP-19).
    • File sizes under 640 KiB cap: descriptor.rs = 146,885 B (143.44 KiB), descriptor/host.rs = 561,772 B (548.61 KiB).
    • 100% title-neutral (zero retail names or local Windows paths).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7401340624 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7401340624). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T04:32:08Z. --- ### Gate 2 Pure-Reasoning Audit — PR #422 (`perf/bounded-placed-view-table`) — **VERIFIED CLEAN** - **PR / Commit:** #422 @ `3ed6a9e03fcd938488d4824723e2b733c6b06af8` - **Scope:** `crates/victory-gpu/src/descriptor.rs`, `crates/victory-gpu/src/descriptor/host.rs` (2 files, +436 / -74 vs `origin/main`) - **Result:** **0 P0, 0 P1** — **VERIFIED CLEAN** #### Audit Summary 1. **Concurrency & Lifetime Safety (`ViewEntry`, `ReadMostly<Views>`, `MIRROR_CACHE`, `views_alive`):** - `ViewEntry { view, generation, last_used: AtomicU64, live }` is `Send + Sync`; `touch()` writes `last_used` atomically with `Ordering::Relaxed` under shard read guards. `ReadMostly::read` drop (`RwLockReadGuard` Release) into `ReadMostly::write` (`RwLockWriteGuard` Acquire across all `SHARDS + 1` locks) establishes strict happens-before from every reader `touch()` to `evict_idle_slice`'s `Relaxed` load. - Every active read/validation path refreshes `last_used` on live generation match: `Views::lookup_entry`, `Views::entry_of`, `Views::entry_made`, `views_alive` (draw heap buffer-slot cache validation), and `descriptor::host::views_entry_alive` (`MIRROR_CACHE` hits). - Retired slots clear `index`, set `live = false`, advance `generation = ((old_gen + 1) & GENERATIONS).max(1)` (always in `1..=0x3fff_ffff`, never `0`, never colliding with `KIND_SHIFT` bits `30..31`, and never overflowing `u32`), and push to `free`. Stale descriptor handles and `MIRROR_CACHE` entries cleanly resolve to `None` / invalidate both while free and after slot reuse. - Frame-age checks use `now.saturating_sub(last_used)` and `now.saturating_sub(prev)`, safe at frame `0`, `last_used == 0`, and across concurrent frame-boundary increments. 2. **`ownerless` FIFO Queue & Resource/Sampler Retention:** - Strict `live` + `generation` + `index` guards across `evict_idle_slice`, `free_ownerless`, and `forget` guarantee zero double-free and zero duplicate slot indices in `free`. `evict_idle_slice` prunes already-retired front entries from `ownerless` while preserving `ownerless_cap()` (`1 << 20`). - `View::is_evictable()` matches only `View::Placed(..) | View::Constant(..)`; `View::Shader`, `View::Unordered`, `View::Sampler`, and `View::ConsoleSampler` are never idle-evicted. 3. **`PLACED_SHAPE_CAP`, `VICTORY_VIEW_EVICT=0`, Lock Ordering & Cursor Bounds:** - Once `ViewShapes::shapes.len() >= shape_cap` (`PLACED_SHAPE_CAP = 262_144`), `shape_number()` returns `None` under `shapes_read()` without taking `shapes_write()`, overflowing into `Views` while keeping `LOCAL_SHAPES` bounded and consistent. `VICTORY_VIEW_EVICT=0` restores `shape_cap = SHAPES` and disables both periodic and on-demand eviction. - `maybe_sweep_idle_views()` runs at the entry of `sync_heaps()` before `if !sync_on() { return; }` and before `SHADER_HEAPS.read()`, so idle sweeps run even under `VICTORY_HEAP_SYNC=0` (via `begin_sync_heaps()`'s `!sync_aside()` path). `views_read()` is dropped before `views_write()`, and on-demand eviction in `entry_made()` acquires no nested locks — zero lock-order inversion or deadlock. - `evict_idle_slice()` guards `len == 0 || slice == 0`, clamps `sweep_cursor >= len` to `0`, bounds iterations to `slice.min(len)`, and wraps `sweep_cursor` modulo `len` — zero out-of-bounds panic possible. 4. **Attribution, File Sizes & Title-Neutrality:** - `GPL-3.0` attribution present in commit message and `descriptor.rs` (`ViewEntry` & `PLACED_SHAPE_CAP`) citing `ReTerryDavis/ReVIctory` PR `#26` (`fc8f19f`) and `monte-alt/vesper` PR `#25` (VSP-19). - File sizes under 640 KiB cap: `descriptor.rs` = `146,885` B (`143.44 KiB`), `descriptor/host.rs` = `561,772` B (`548.61 KiB`). - 100% title-neutral (zero retail names or local Windows paths).
Androtim commented 2026-12-04 04:33:11 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T04:33:11Z.


Gate 2 Pure-Reasoning Re-Audit — PR #421 (feat/ambient-alpha-library-version-agility) — VERIFIED CLEAN

  • PR / Commit: #421 @ 105c4bd6a7180b188a23c6d6ee19652789ff2ada (base origin/main d34843d1c5f4f6cf0add44751135b9969e8ba079)
  • Scope: crates/victory-gpu/src/pipeline/library.rs, crates/victory-gpu/src/shader_cache.rs (2 files, +100 / -2 vs origin/main)
  • Result: 0 P0, 0 P1 — VERIFIED CLEAN

Audit Summary

  1. Prior [P0-1] & [P0-2] (Agility SDK D3D12SDKVersion = 0 edits from 34ea9b59): 100% CLOSED
    • git diff origin/main..HEAD confirms apps/victory/src/main.rs and apps/victory/build.rs are 100% untouched vs origin/main (d34843d).
    • Only crates/victory-gpu/src/pipeline/library.rs and crates/victory-gpu/src/shader_cache.rs are modified.
  2. Shader Cache & Translator Fingerprint (crates/victory-gpu/src/shader_cache.rs):
    • Preserves PR #381's SHADER_CACHE_VERSION = 5 cleanly (line 259 untouched).
    • Exposes pub(crate) fn translator_id() -> &'static str returning env!(VICTORY_TRANSLATOR) (64-hex BLAKE3 built in crates/victory-gpu/build.rs, which hashes shader_cache.rs, victory-shader/src/**, victory-shader/Cargo.toml, Cargo.lock, and rust-toolchain.toml, so translator or cache-version changes automatically rotate translator_id()).
  3. Pipeline Library Translator-Version Guard (crates/victory-gpu/src/pipeline/library.rs, TrustNo1/Darner 34b0ba7):
    • made_by_another_build / made_by_another_build_with skips cleanly when neither host-pipelines.bin nor host-pipelines.next exists, falls back safely to Blob::None on missing/truncated/corrupt/mismatched host-pipelines.translator (never mapping a stale library), and honors VICTORY_LIBRARY_KEEP_OLD=1 opt-in.
    • replace_library runs under host-pipelines.lock only when bytes > 0, supersedes any existing pending host-pipelines.next so a stale pending file cannot shadow a newly saved library on next startup, and atomically writes host-pipelines.translator via write_atomically.
    • Unit tests cover fresh dir, pre-marker library, VICTORY_LIBRARY_KEEP_OLD=1, mismatched translator, in-place replacement, and pending NEXT_FILE detection & superseding.
  4. Attribution, File Sizes & Title-Neutrality:
    • Proper GPL-3.0 upstream attribution (TrustNo1/Darner commit 34b0ba7, #188) in comments and commit message.
    • File sizes well under 640 KiB cap: library.rs = 54,944 B (53.66 KiB), shader_cache.rs = 28,141 B (27.48 KiB).
    • 100% title-neutral (zero retail title names or local Windows paths).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7401363639 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7401363639). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T04:33:11Z. --- ### Gate 2 Pure-Reasoning Re-Audit — PR #421 (`feat/ambient-alpha-library-version-agility`) — **VERIFIED CLEAN** - **PR / Commit:** #421 @ `105c4bd6a7180b188a23c6d6ee19652789ff2ada` (base `origin/main` `d34843d1c5f4f6cf0add44751135b9969e8ba079`) - **Scope:** `crates/victory-gpu/src/pipeline/library.rs`, `crates/victory-gpu/src/shader_cache.rs` (2 files, +100 / -2 vs `origin/main`) - **Result:** **0 P0, 0 P1** — **VERIFIED CLEAN** #### Audit Summary 1. **Prior `[P0-1]` & `[P0-2]` (Agility SDK `D3D12SDKVersion = 0` edits from `34ea9b59`): 100% CLOSED** - `git diff origin/main..HEAD` confirms `apps/victory/src/main.rs` and `apps/victory/build.rs` are **100% untouched** vs `origin/main` (`d34843d`). - Only `crates/victory-gpu/src/pipeline/library.rs` and `crates/victory-gpu/src/shader_cache.rs` are modified. 2. **Shader Cache & Translator Fingerprint (`crates/victory-gpu/src/shader_cache.rs`):** - Preserves PR `#381`'s `SHADER_CACHE_VERSION = 5` cleanly (line 259 untouched). - Exposes `pub(crate) fn translator_id() -> &'static str` returning `env!(VICTORY_TRANSLATOR)` (64-hex BLAKE3 built in `crates/victory-gpu/build.rs`, which hashes `shader_cache.rs`, `victory-shader/src/**`, `victory-shader/Cargo.toml`, `Cargo.lock`, and `rust-toolchain.toml`, so translator or cache-version changes automatically rotate `translator_id()`). 3. **Pipeline Library Translator-Version Guard (`crates/victory-gpu/src/pipeline/library.rs`, `TrustNo1/Darner 34b0ba7`):** - `made_by_another_build` / `made_by_another_build_with` skips cleanly when neither `host-pipelines.bin` nor `host-pipelines.next` exists, falls back safely to `Blob::None` on missing/truncated/corrupt/mismatched `host-pipelines.translator` (never mapping a stale library), and honors `VICTORY_LIBRARY_KEEP_OLD=1` opt-in. - `replace_library` runs under `host-pipelines.lock` only when `bytes > 0`, supersedes any existing pending `host-pipelines.next` so a stale pending file cannot shadow a newly saved library on next startup, and atomically writes `host-pipelines.translator` via `write_atomically`. - Unit tests cover fresh dir, pre-marker library, `VICTORY_LIBRARY_KEEP_OLD=1`, mismatched translator, in-place replacement, and pending `NEXT_FILE` detection & superseding. 4. **Attribution, File Sizes & Title-Neutrality:** - Proper `GPL-3.0` upstream attribution (`TrustNo1/Darner` commit `34b0ba7`, `#188`) in comments and commit message. - File sizes well under 640 KiB cap: `library.rs` = `54,944` B (`53.66 KiB`), `shader_cache.rs` = `28,141` B (`27.48 KiB`). - 100% title-neutral (zero retail title names or local Windows paths).
Androtim commented 2026-12-04 05:40:07 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T05:40:07Z.


Gate 2 Pure-Reasoning Re-Audit — PR #423 (fix/watch-page-mirror-alias-hdr-audio) — VERIFIED CLEAN

  • PR / Commit: #423 @ ca3e4c109e87d4460121d276bfac993beb11000b (base origin/main 82b11a13f5cff2df35ae533eb61df78997b3a80b)
  • Scope: crates/victory-gpu/src/descriptor.rs, crates/victory-gpu/src/watch.rs (2 files, +240 / -13 vs origin/main)
  • Result: 0 P0, 0 P1 — VERIFIED CLEAN

Audit Summary

  1. Prior [P1] (watch.rs single-view ALIASES[1] self/in-range overcount): 100% CLOSED
    • open_resolved_with() (crates/victory-gpu/src/watch.rs:3578-3581) now guards the diagnostics-gated single-view counter with if !(first..last).contains(&other) && set.get(other).clean.contains(other), matching the multi-view branch (L3587) so block itself (included by snapshot_open_aliases() -> inplace::pages_of()) and any clean alias inside first..last are excluded while duplicate external entries are counted at most once (since clean.remove(other) immediately clears the bit).
    • Zero regressions in diagnostics or non-diagnostics builds: set.get_mut(other).clean.remove(other) and PUBLISHED.clear(other) remain unchanged, and all added code/tests stay strictly behind #[cfg(feature = diagnostics)].
    • open_resolved_with_counts_cleared_clean_aliases (L7107-7163) acquires lock_shards(u64::MAX) in ascending shard order to prevent concurrent ALIASES[1] noise and verifies exact deltas (2 with clean in-range b0/b0_in_range + external clean b1/b2 + unclean b3; 0 when only b0 is clean and external b3 is unclean).
  2. crates/victory-gpu/src/descriptor.rs (sync_record_parts & sync_heaps): 100% CLEAN
    • Production code (sync_record_parts and sync_heaps, previously verified clean at 07427d8075da478187066f781580bdda91060907) is completely untouched in 07427d8..ca3e4c1.
    • Only mod tests adds a #[cfg(windows)] SYNC_HEAPS_TEST_LOCK mutex (with poison recovery) serializing the two sync_heaps() unit tests so parallel test runs cannot consume each other's MEM_WRITE_WATCH bits.
  3. Attribution, File Sizes & Title-Neutrality:
    • Proper GPL-3.0 upstream attribution in code comments and commits (TrustNo1/Darner PR #163 / bc1e3fd, originally readmet3xt-lab/foxhound PR #504; lobomfz/VIctory-xmem PR #424 / ca1f0e4).
    • File sizes well under 640 KiB cap: descriptor.rs = 153,348 B (149.75 KiB), watch.rs = 314,349 B (306.98 KiB).
    • 100% title-neutral (zero retail title names or local Windows paths).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7402615183 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7402615183). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T05:40:07Z. --- ### Gate 2 Pure-Reasoning Re-Audit — PR #423 (`fix/watch-page-mirror-alias-hdr-audio`) — **VERIFIED CLEAN** - **PR / Commit:** #423 @ `ca3e4c109e87d4460121d276bfac993beb11000b` (base `origin/main` `82b11a13f5cff2df35ae533eb61df78997b3a80b`) - **Scope:** `crates/victory-gpu/src/descriptor.rs`, `crates/victory-gpu/src/watch.rs` (2 files, +240 / -13 vs `origin/main`) - **Result:** **0 P0, 0 P1** — **VERIFIED CLEAN** #### Audit Summary 1. **Prior `[P1]` (`watch.rs` single-view `ALIASES[1]` self/in-range overcount): 100% CLOSED** - `open_resolved_with()` (`crates/victory-gpu/src/watch.rs:3578-3581`) now guards the diagnostics-gated single-view counter with `if !(first..last).contains(&other) && set.get(other).clean.contains(other)`, matching the multi-view branch (`L3587`) so `block` itself (included by `snapshot_open_aliases()` -> `inplace::pages_of()`) and any clean alias inside `first..last` are excluded while duplicate external entries are counted at most once (since `clean.remove(other)` immediately clears the bit). - Zero regressions in diagnostics or non-diagnostics builds: `set.get_mut(other).clean.remove(other)` and `PUBLISHED.clear(other)` remain unchanged, and all added code/tests stay strictly behind `#[cfg(feature = diagnostics)]`. - `open_resolved_with_counts_cleared_clean_aliases` (`L7107-7163`) acquires `lock_shards(u64::MAX)` in ascending shard order to prevent concurrent `ALIASES[1]` noise and verifies exact deltas (`2` with clean in-range `b0`/`b0_in_range` + external clean `b1`/`b2` + unclean `b3`; `0` when only `b0` is clean and external `b3` is unclean). 2. **`crates/victory-gpu/src/descriptor.rs` (`sync_record_parts` & `sync_heaps`): 100% CLEAN** - Production code (`sync_record_parts` and `sync_heaps`, previously verified clean at `07427d8075da478187066f781580bdda91060907`) is completely untouched in `07427d8..ca3e4c1`. - Only `mod tests` adds a `#[cfg(windows)]` `SYNC_HEAPS_TEST_LOCK` mutex (with poison recovery) serializing the two `sync_heaps()` unit tests so parallel test runs cannot consume each other's `MEM_WRITE_WATCH` bits. 3. **Attribution, File Sizes & Title-Neutrality:** - Proper `GPL-3.0` upstream attribution in code comments and commits (`TrustNo1/Darner` PR `#163` / `bc1e3fd`, originally `readmet3xt-lab/foxhound` PR `#504`; `lobomfz/VIctory-xmem` PR `#424` / `ca1f0e4`). - File sizes well under 640 KiB cap: `descriptor.rs` = `153,348` B (`149.75 KiB`), `watch.rs` = `314,349` B (`306.98 KiB`). - 100% title-neutral (zero retail title names or local Windows paths).
Androtim commented 2026-12-04 05:50:44 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T05:50:44Z.


Gate 2 Pure-Reasoning Re-Audit — PR #424 (perf/audio-offload-apu-dsp) — VERIFIED CLEAN

  • PR / Commit: #424 @ 1e14358884c160f8020e088a392a108dea7bf91d (base origin/main 82b11a13f5cff2df35ae533eb61df78997b3a80b)
  • Scope: crates/victory-hle/src/modules/apu.rs, crates/victory-hle/src/modules/dsp.rs (2 files, +1460 / -92 vs origin/main)
  • Result: 0 P0, 0 P1 — VERIFIED CLEAN

Audit Summary

  1. Prior [P1] #1 (apu.rs premature SetEvent / lost wakeup on cross-stream out-of-order completion): 100% CLOSED
    • Shared::pending_signals: Mutex<VecDeque<(Arc<Slot>, bool)>> mirrors state.results FIFO order under connection.state whenever shared.event != 0, populated before worker submission.
    • run_job publishes slot.done.store(true, Ordering::Release), drains only the contiguous completed FIFO prefix under pending_signals, ORs popped signal bits into should_signal, drops the lock, and calls SetEvent iff should_signal before in_flight.fetch_sub(1, Ordering::AcqRel).
    • All concurrent completion linearizations preserve exact FIFO wakeup without premature signals or lost wakeups; strict lock order connection.state -> { pending_signals, senders[i], streams[stream], slot.result } with zero worker acquisition of connection.state guarantees deadlock freedom. Covered by result_event_waits_for_fifo_prefix_on_out_of_order_completion.
  2. Prior [P1] #2 (dsp.rs non-atomic Status data race & invalid fence(Release) pairing): 100% CLOSED
    • dsp::Status fields are now AtomicU32 (submitted, completed) and AtomicI32 (result) under #[repr(C)], preserving the exact 16-byte / 4-byte-aligned ABI (verified by status_abi_layout_is_16_bytes_atomic) with UnsafeCell and all read_volatile/write_volatile/unpaired fences removed.
    • run_job stores result (Relaxed) then completed (Release); readers poll completed (Acquire) before reading result (Relaxed) and output samples; XDspSubmitCommand publishes submitted (Release).
  3. Prior [P1] #3 (apu.rs cross-thread XApuEnqueueCommand submission reordering race): 100% CLOSED
    • XApuEnqueueCommand keeps connection.state locked across workers().submit(stream, job) (and inline run_job fallback/sync execution), ensuring worker shard queue order strictly matches state.results and pending_signals FIFO order across concurrent callers.
    • Workers never touch connection.state (and submit() drops senders[shard] before blocking tx.send()), so bounded-channel backpressure cannot deadlock. Covered by concurrent_enqueue_preserves_fifo_order_on_same_stream.
  4. Prior [P1] #4 (dsp.rs late in-place overrun buffer aliasing UB while in_flight > 0): 100% CLOSED
    • Stream::active_outputs: Mutex<Vec<(u32, usize, usize)>> registers (ticket, out_start, out_end) for async jobs with non-null output before in_flight.fetch_add(1, Ordering::AcqRel) and removes the ticket in run_job after all output writes (including panic zero-fill) and before in_flight.fetch_sub(1, Ordering::AcqRel).
    • XDspSubmitCommand bypasses locking on the in_flight.load(Ordering::Acquire) == 0 fast path; on overruns (in_flight != 0), it waits (releasing the lock before yield/sleep) only when [command.input, command.input + byte_len) overlaps an active worker output range via ranges_overlap, keeping disjoint double-buffered pipelining non-blocking while establishing happens-before before copying command.input. Covered by late_in_place_overrun_waits_for_overlap_and_allows_disjoint_pipelining.
  5. Prior [P2] #5, Shutdown/Opt-Out & Compliance: 100% CLEAN
    • worker_pool_clean_shutdown_drains_and_rejects_after_close mutates (*stream).asynchronous = true prior to creating &Stream, eliminating test aliasing UB; zero newly introduced [P0]/[P1] issues across both modules.
    • OnceLock global pools avoid ExitProcess loader-lock deadlocks; VICTORY_AUDIO_OFFLOAD=0 (VICTORY_APU_ASYNC=0 / VICTORY_DSP_ASYNC=0) cleanly disables offloading with zero threads spawned and preserves MiniVI's APU Converter and mono DSP convolution (VICTORY_DSP_CONVOLVE, VICTORY_DSP_GAIN).
    • Proper GPL-3.0 upstream attribution (ReTerryDavis/ReVIctory PR #37, 073fc17) in both files and commit history; file sizes well under 640 KiB (apu.rs = 66,403 B / 64.85 KiB, dsp.rs = 39,669 B / 38.74 KiB); 100% title-neutral with zero retail names or local Windows paths.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7402798938 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7402798938). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T05:50:44Z. --- ### Gate 2 Pure-Reasoning Re-Audit — PR #424 (`perf/audio-offload-apu-dsp`) — **VERIFIED CLEAN** - **PR / Commit:** #424 @ `1e14358884c160f8020e088a392a108dea7bf91d` (base `origin/main` `82b11a13f5cff2df35ae533eb61df78997b3a80b`) - **Scope:** `crates/victory-hle/src/modules/apu.rs`, `crates/victory-hle/src/modules/dsp.rs` (2 files, +1460 / -92 vs `origin/main`) - **Result:** **0 P0, 0 P1** — **VERIFIED CLEAN** #### Audit Summary 1. **Prior `[P1] #1` (`apu.rs` premature `SetEvent` / lost wakeup on cross-stream out-of-order completion): 100% CLOSED** - `Shared::pending_signals: Mutex<VecDeque<(Arc<Slot>, bool)>>` mirrors `state.results` FIFO order under `connection.state` whenever `shared.event != 0`, populated before worker submission. - `run_job` publishes `slot.done.store(true, Ordering::Release)`, drains only the contiguous completed FIFO prefix under `pending_signals`, ORs popped `signal` bits into `should_signal`, drops the lock, and calls `SetEvent` iff `should_signal` before `in_flight.fetch_sub(1, Ordering::AcqRel)`. - All concurrent completion linearizations preserve exact FIFO wakeup without premature signals or lost wakeups; strict lock order `connection.state -> { pending_signals, senders[i], streams[stream], slot.result }` with zero worker acquisition of `connection.state` guarantees deadlock freedom. Covered by `result_event_waits_for_fifo_prefix_on_out_of_order_completion`. 2. **Prior `[P1] #2` (`dsp.rs` non-atomic `Status` data race & invalid `fence(Release)` pairing): 100% CLOSED** - `dsp::Status` fields are now `AtomicU32` (`submitted`, `completed`) and `AtomicI32` (`result`) under `#[repr(C)]`, preserving the exact 16-byte / 4-byte-aligned ABI (verified by `status_abi_layout_is_16_bytes_atomic`) with `UnsafeCell` and all `read_volatile`/`write_volatile`/unpaired fences removed. - `run_job` stores `result` (`Relaxed`) then `completed` (`Release`); readers poll `completed` (`Acquire`) before reading `result` (`Relaxed`) and output samples; `XDspSubmitCommand` publishes `submitted` (`Release`). 3. **Prior `[P1] #3` (`apu.rs` cross-thread `XApuEnqueueCommand` submission reordering race): 100% CLOSED** - `XApuEnqueueCommand` keeps `connection.state` locked across `workers().submit(stream, job)` (and inline `run_job` fallback/sync execution), ensuring worker shard queue order strictly matches `state.results` and `pending_signals` FIFO order across concurrent callers. - Workers never touch `connection.state` (and `submit()` drops `senders[shard]` before blocking `tx.send()`), so bounded-channel backpressure cannot deadlock. Covered by `concurrent_enqueue_preserves_fifo_order_on_same_stream`. 4. **Prior `[P1] #4` (`dsp.rs` late in-place overrun buffer aliasing UB while `in_flight > 0`): 100% CLOSED** - `Stream::active_outputs: Mutex<Vec<(u32, usize, usize)>>` registers `(ticket, out_start, out_end)` for async jobs with non-null `output` before `in_flight.fetch_add(1, Ordering::AcqRel)` and removes the ticket in `run_job` after all output writes (including panic zero-fill) and before `in_flight.fetch_sub(1, Ordering::AcqRel)`. - `XDspSubmitCommand` bypasses locking on the `in_flight.load(Ordering::Acquire) == 0` fast path; on overruns (`in_flight != 0`), it waits (releasing the lock before yield/sleep) only when `[command.input, command.input + byte_len)` overlaps an active worker output range via `ranges_overlap`, keeping disjoint double-buffered pipelining non-blocking while establishing happens-before before copying `command.input`. Covered by `late_in_place_overrun_waits_for_overlap_and_allows_disjoint_pipelining`. 5. **Prior `[P2] #5`, Shutdown/Opt-Out & Compliance: 100% CLEAN** - `worker_pool_clean_shutdown_drains_and_rejects_after_close` mutates `(*stream).asynchronous = true` prior to creating `&Stream`, eliminating test aliasing UB; zero newly introduced `[P0]`/`[P1]` issues across both modules. - `OnceLock` global pools avoid `ExitProcess` loader-lock deadlocks; `VICTORY_AUDIO_OFFLOAD=0` (`VICTORY_APU_ASYNC=0` / `VICTORY_DSP_ASYNC=0`) cleanly disables offloading with zero threads spawned and preserves MiniVI's APU `Converter` and mono DSP convolution (`VICTORY_DSP_CONVOLVE`, `VICTORY_DSP_GAIN`). - Proper `GPL-3.0` upstream attribution (`ReTerryDavis/ReVIctory` PR `#37`, `073fc17`) in both files and commit history; file sizes well under 640 KiB (`apu.rs` = `66,403` B / `64.85 KiB`, `dsp.rs` = `39,669` B / `38.74 KiB`); 100% title-neutral with zero retail names or local Windows paths.
Androtim commented 2026-12-04 08:03:49 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T08:03:49Z.


Gate 2 Adversarial Pure-Reasoning Audit — PR #425 (perf/w9b-cpu-vram-fps) — CHANGES REQUESTED (0 P0, 2 P1)

  • PR / Commit: #425 @ 7c1ed141dab63e93dd378a91eb81f6383ae2054f (base main ab8e3372b8cef19d68c2661f42a737faa9450052)
  • Scope: crates/victory-gpu/src/cores.rs, crates/victory-gpu/src/descriptor/host.rs, crates/victory-gpu/src/host.rs, crates/victory-gpu/src/host/place.rs, crates/victory-gpu/src/list/thin.rs, crates/victory-gpu/src/watch.rs (6 files, +351 / -26 vs main)
  • Result: 0 P0, 2 P1 — fixes required before merge.

Findings

  1. [P1] crates/victory-gpu/src/cores.rs:52-71 (l3_of_sets) — Union size vs. RelationCache record size deterministically skips the final cache record on x86_64 Windows

    • Root cause: In windows-sys 0.61.2 on x86_64 Windows, size_of::<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>() is 80 bytes (8-byte header + 72-byte union dominated by GROUP_RELATIONSHIP), whereas every single-group RelationCache record returned by GetLogicalProcessorInformationEx(RelationCache, ...) has info.Size == 56 bytes (8-byte header + 48-byte CACHE_RELATIONSHIP).
    • Because line 52 loops while at + size_of::<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>() <= bytes as usize (at + 80 <= bytes), when at reaches the final 56-byte record (bytes - at == 56 < 80), the loop always terminates early and silently drops the last RelationCache record.
    • On systems where an L3 cache record is emitted at the end of the buffer (e.g. CCD1's L3 on a uniform dual-CCD non-X3D CPU such as 7950X/9950X, or the 3D V-Cache CCD's L3 if enumerated last), those logical processors retain only their L2 size in by_processor, causing fast_by_cache() to either falsely classify a uniform dual-CCD CPU as asymmetric X3D or invert fast/slow CCD placement on an X3D CPU.
    • Required fix: Parse RelationCache records via raw pointers without forming &SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX (note: merely lowering the loop guard to at + 56 <= bytes while still creating &SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX would form an 80-byte reference extending 24 bytes past the end of buffer, causing immediate Rust UB):
      1. Loop while ok != 0 && (bytes as usize).saturating_sub(at) >= header_size (where header_size = std::mem::offset_of!(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, Anonymous), i.e. 8 bytes).
      2. Read relationship and record_size from the 8-byte header via raw pointers (addr_of!), breaking if record_size < header_size || record_size > (bytes as usize) - at.
      3. When relationship == RelationCache && record_size >= header_size + size_of::<CACHE_RELATIONSHIP>(), read CACHE_RELATIONSHIP via raw pointer (ptr.add(header_size).cast::<CACHE_RELATIONSHIP>()), and iterate its group masks (0..cache.GroupCount.max(1) within record_size) to update by_processor for mask.Group == 0.
      4. Add a unit test parsing a synthetic buffer of 56-byte RelationCache records (including an L3 record as the final entry) proving the last record is not dropped.
  2. [P1] crates/victory-gpu/src/host/place.rs:678-706 (copy_barrier_desc) — Missing D3D12_BARRIER_SYNC_BUILD_RAYTRACING_ACCELERATION_STRUCTURE breaks GPU sync between place_copy and MiniVI hwrt.rs BLAS builds

    • Root cause: copy_barrier_desc replaces wait_for_all (D3D12_BARRIER_SYNC_ALL / D3D12_BARRIER_ACCESS_COMMON) in HostList::place_copy and HostList::place_source with shader_sync = D3D12_BARRIER_SYNC_ALL_SHADING | D3D12_BARRIER_SYNC_COPY | D3D12_BARRIER_SYNC_EXECUTE_INDIRECT | D3D12_BARRIER_SYNC_INDEX_INPUT.
    • In D3D12 Enhanced Barriers, D3D12_BARRIER_SYNC_ALL_SHADING (0x1000) does not cover D3D12_BARRIER_SYNC_BUILD_RAYTRACING_ACCELERATION_STRUCTURE (0x800000).
    • Unlike upstream ReVIctory, MiniVI's hwrt.rs records list4.BuildRaytracingAccelerationStructure (hwrt.rs:1404) on the same HostList reading vertex (hwrt.rs:2129-2132), index (hwrt.rs:2194-2197), and transform3x4 (hwrt.rs:2345) inputs directly from Shadow::buffer, preceded only by a legacy D3D12_RESOURCE_BARRIER_TYPE_UAV (hwrt.rs:1535), which does not synchronize COPY with BUILD_RAYTRACING_ACCELERATION_STRUCTURE.
    • On DXR + Enhanced Barriers hosts, place_copy -> copy_barrier(..., false) -> BuildRaytracingAccelerationStructure has a RAW hazard, and BuildRaytracingAccelerationStructure -> copy_barrier(..., true) -> place_copy has a WAR hazard on shared Shadow::buffer memory.
    • Required fix: Pass raytracing: bool (from crate::hwrt::active()) into copy_barrier_desc(before, raytracing) and include D3D12_BARRIER_SYNC_BUILD_RAYTRACING_ACCELERATION_STRUCTURE in shader_sync when raytracing is true (keeping RENDER_TARGET and DEPTH_STENCIL excluded; D3D12_BARRIER_ACCESS_SHADER_RESOURCE for geometry/transform inputs is already in buffer_access, and gating on hwrt::active() avoids validation issues on non-DXR adapters). Extend copy_barrier_desc_excludes_render_and_depth_targets to assert both raytracing = false and raytracing = true.

Verified Clean Areas

  • descriptor/host.rs (stride_shadow / address_shadow): Zero-initialized matching std::ptr::write_bytes(..., 0, ...); all static-slot callers hold self.made.lock(index) and dynamic slots have exclusive DynamicPool (Mutex) ownership establishing happens-before across reuse; out-of-range indices fall through safely to write_volatile. PR #422 & #423 invariants preserved intact.
  • watch.rs (Bits::has / static RESTING): GuardShard stripes align 1:1 with 64-block u64 words (block >> 6), serializing opened_at and rests per block under the same Mutex<Guards>; !rest.is_zero() prevents premature clearing when VICTORY_GUARD_REST is toggled off; open_resolved_with (PR #423) untouched.
  • host/place.rs PR #415 integration: Rec::barriers() + rec.cast::<ID3D12GraphicsCommandList7>() (and fallback &ID3D12GraphicsCommandList coercion) flush buffered barriers via Rec::deref() before list7.Barrier(...); HostList is always D3D12_COMMAND_LIST_TYPE_DIRECT.
  • cores.rs hybrid/non-Windows/PR #417: Hybrid CPUs (e.g. i7-13700F) take fast_of(&sets) directly; cores.rs and list/thin.rs are #[cfg(windows)]-gated; PR #417 VICTORY_LANE_PRIORITY (Part::Lane/Helper/Beside, ASKED, settle()) preserved intact.
  • host.rs (late_most 512) & pipeline/library.rs: late_most() = 512 is bounded by segments::tight settling (host.rs:7461-7470) and PORTABLE_DYNAMIC_DEFAULT = 393,216; vram_keep_below and draw.rs are untouched; pipeline/library.rs has no legacy-root fallback and is already guarded by PR #421 made_by_another_build().
  • Policy & Clean-Room: Title-neutral, proper GPL-3.0 attributions (ReTerryDavis/ReVIctory 1ee967b, aefb79b), all touched files under the 640 KiB cap (host.rs shrank to 644,171 B LF; .gitattributes enforces LF). (Minor non-blocking note: PR #425's GitHub description body has PowerShell escape typos like ^Gb8e337 / \fast_by_cache.)
<!-- greyfinch-sync:Androtim/MiniVI:comment:7405452619 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7405452619). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T08:03:49Z. --- ### Gate 2 Adversarial Pure-Reasoning Audit — PR #425 (`perf/w9b-cpu-vram-fps`) — **CHANGES REQUESTED (0 P0, 2 P1)** - **PR / Commit:** #425 @ `7c1ed141dab63e93dd378a91eb81f6383ae2054f` (base `main` `ab8e3372b8cef19d68c2661f42a737faa9450052`) - **Scope:** `crates/victory-gpu/src/cores.rs`, `crates/victory-gpu/src/descriptor/host.rs`, `crates/victory-gpu/src/host.rs`, `crates/victory-gpu/src/host/place.rs`, `crates/victory-gpu/src/list/thin.rs`, `crates/victory-gpu/src/watch.rs` (6 files, +351 / -26 vs `main`) - **Result:** **0 P0, 2 P1** — fixes required before merge. --- #### Findings 1. **`[P1]` `crates/victory-gpu/src/cores.rs:52-71` (`l3_of_sets`) — Union size vs. `RelationCache` record size deterministically skips the final cache record on x86_64 Windows** - **Root cause:** In `windows-sys 0.61.2` on x86_64 Windows, `size_of::<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>()` is **80 bytes** (8-byte header + 72-byte union dominated by `GROUP_RELATIONSHIP`), whereas every single-group `RelationCache` record returned by `GetLogicalProcessorInformationEx(RelationCache, ...)` has `info.Size == 56` bytes (8-byte header + 48-byte `CACHE_RELATIONSHIP`). - Because line 52 loops while `at + size_of::<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>() <= bytes as usize` (`at + 80 <= bytes`), when `at` reaches the final 56-byte record (`bytes - at == 56 < 80`), the loop **always terminates early and silently drops the last `RelationCache` record**. - On systems where an L3 cache record is emitted at the end of the buffer (e.g. CCD1's L3 on a uniform dual-CCD non-X3D CPU such as 7950X/9950X, or the 3D V-Cache CCD's L3 if enumerated last), those logical processors retain only their L2 size in `by_processor`, causing `fast_by_cache()` to either falsely classify a uniform dual-CCD CPU as asymmetric X3D or invert fast/slow CCD placement on an X3D CPU. - **Required fix:** Parse `RelationCache` records via raw pointers without forming `&SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX` (note: merely lowering the loop guard to `at + 56 <= bytes` while still creating `&SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX` would form an 80-byte reference extending 24 bytes past the end of `buffer`, causing immediate Rust UB): 1. Loop while `ok != 0 && (bytes as usize).saturating_sub(at) >= header_size` (where `header_size = std::mem::offset_of!(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, Anonymous)`, i.e. 8 bytes). 2. Read `relationship` and `record_size` from the 8-byte header via raw pointers (`addr_of!`), breaking if `record_size < header_size || record_size > (bytes as usize) - at`. 3. When `relationship == RelationCache && record_size >= header_size + size_of::<CACHE_RELATIONSHIP>()`, read `CACHE_RELATIONSHIP` via raw pointer (`ptr.add(header_size).cast::<CACHE_RELATIONSHIP>()`), and iterate its group masks (`0..cache.GroupCount.max(1)` within `record_size`) to update `by_processor` for `mask.Group == 0`. 4. Add a unit test parsing a synthetic buffer of 56-byte `RelationCache` records (including an L3 record as the final entry) proving the last record is not dropped. 2. **`[P1]` `crates/victory-gpu/src/host/place.rs:678-706` (`copy_barrier_desc`) — Missing `D3D12_BARRIER_SYNC_BUILD_RAYTRACING_ACCELERATION_STRUCTURE` breaks GPU sync between `place_copy` and MiniVI `hwrt.rs` BLAS builds** - **Root cause:** `copy_barrier_desc` replaces `wait_for_all` (`D3D12_BARRIER_SYNC_ALL` / `D3D12_BARRIER_ACCESS_COMMON`) in `HostList::place_copy` and `HostList::place_source` with `shader_sync = D3D12_BARRIER_SYNC_ALL_SHADING | D3D12_BARRIER_SYNC_COPY | D3D12_BARRIER_SYNC_EXECUTE_INDIRECT | D3D12_BARRIER_SYNC_INDEX_INPUT`. - In D3D12 Enhanced Barriers, `D3D12_BARRIER_SYNC_ALL_SHADING` (`0x1000`) does **not** cover `D3D12_BARRIER_SYNC_BUILD_RAYTRACING_ACCELERATION_STRUCTURE` (`0x800000`). - Unlike upstream `ReVIctory`, MiniVI's `hwrt.rs` records `list4.BuildRaytracingAccelerationStructure` (`hwrt.rs:1404`) on the **same `HostList`** reading vertex (`hwrt.rs:2129-2132`), index (`hwrt.rs:2194-2197`), and transform3x4 (`hwrt.rs:2345`) inputs directly from `Shadow::buffer`, preceded only by a legacy `D3D12_RESOURCE_BARRIER_TYPE_UAV` (`hwrt.rs:1535`), which does not synchronize `COPY` with `BUILD_RAYTRACING_ACCELERATION_STRUCTURE`. - On DXR + Enhanced Barriers hosts, `place_copy` -> `copy_barrier(..., false)` -> `BuildRaytracingAccelerationStructure` has a **RAW hazard**, and `BuildRaytracingAccelerationStructure` -> `copy_barrier(..., true)` -> `place_copy` has a **WAR hazard** on shared `Shadow::buffer` memory. - **Required fix:** Pass `raytracing: bool` (from `crate::hwrt::active()`) into `copy_barrier_desc(before, raytracing)` and include `D3D12_BARRIER_SYNC_BUILD_RAYTRACING_ACCELERATION_STRUCTURE` in `shader_sync` when `raytracing` is `true` (keeping `RENDER_TARGET` and `DEPTH_STENCIL` excluded; `D3D12_BARRIER_ACCESS_SHADER_RESOURCE` for geometry/transform inputs is already in `buffer_access`, and gating on `hwrt::active()` avoids validation issues on non-DXR adapters). Extend `copy_barrier_desc_excludes_render_and_depth_targets` to assert both `raytracing = false` and `raytracing = true`. --- #### Verified Clean Areas - **`descriptor/host.rs` (`stride_shadow` / `address_shadow`):** Zero-initialized matching `std::ptr::write_bytes(..., 0, ...)`; all static-slot callers hold `self.made.lock(index)` and dynamic slots have exclusive `DynamicPool` (`Mutex`) ownership establishing happens-before across reuse; out-of-range indices fall through safely to `write_volatile`. PR #422 & #423 invariants preserved intact. - **`watch.rs` (`Bits::has` / `static RESTING`):** `GuardShard` stripes align 1:1 with 64-block `u64` words (`block >> 6`), serializing `opened_at` and `rests` per block under the same `Mutex<Guards>`; `!rest.is_zero()` prevents premature clearing when `VICTORY_GUARD_REST` is toggled off; `open_resolved_with` (PR #423) untouched. - **`host/place.rs` PR #415 integration:** `Rec::barriers()` + `rec.cast::<ID3D12GraphicsCommandList7>()` (and fallback `&ID3D12GraphicsCommandList` coercion) flush buffered barriers via `Rec::deref()` before `list7.Barrier(...)`; `HostList` is always `D3D12_COMMAND_LIST_TYPE_DIRECT`. - **`cores.rs` hybrid/non-Windows/PR #417:** Hybrid CPUs (e.g. i7-13700F) take `fast_of(&sets)` directly; `cores.rs` and `list/thin.rs` are `#[cfg(windows)]`-gated; PR #417 `VICTORY_LANE_PRIORITY` (`Part::Lane/Helper/Beside`, `ASKED`, `settle()`) preserved intact. - **`host.rs` (`late_most` 512) & `pipeline/library.rs`:** `late_most() = 512` is bounded by `segments::tight` settling (`host.rs:7461-7470`) and `PORTABLE_DYNAMIC_DEFAULT = 393,216`; `vram_keep_below` and `draw.rs` are untouched; `pipeline/library.rs` has no legacy-root fallback and is already guarded by PR #421 `made_by_another_build()`. - **Policy & Clean-Room:** Title-neutral, proper `GPL-3.0` attributions (`ReTerryDavis/ReVIctory` `1ee967b`, `aefb79b`), all touched files under the 640 KiB cap (`host.rs` shrank to 644,171 B LF; `.gitattributes` enforces LF). *(Minor non-blocking note: PR #425's GitHub description body has PowerShell escape typos like `^Gb8e337` / `\fast_by_cache`.)*
Androtim commented 2026-12-04 08:13:07 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T08:13:07Z.


Gate 2 Adversarial Pure-Reasoning Audit — PR #426 (fix/w9a-indoor-visuals) — BLOCKED (3 P0, 1 P1)

  • PR / Commit: #426 @ 8b5d82ee48dd8faf404fa906c35f20b64925d4d8 (branched from ab8e337; 8 files, +451 / -21)
  • Result: 3 P0, 1 P1 — fixes required before merge.

Blocking Findings

  1. [P0] Use-After-Free on unpinned This returned by resource::target_copy_at

    • Location: crates/victory-gpu/src/resource.rs:4587-4604, crates/victory-gpu/src/list.rs:2105-2106, crates/victory-gpu/src/host.rs:9246-9269
    • Issue: target_copy_at looks up this: This under TARGETS_AT.lock(), drops the lock, and returns a raw unpinned This without calling crate::object::add_ref_alive(this) to wrap it in Held (unlike alias_of at resource.rs:1744-1745). A concurrent Release (which may already have refcount 0 and be waiting on TARGETS_AT.lock() inside Resource::drop at resource.rs:4291) frees Resource as soon as TARGETS_AT unlocks, while HostList::texture_copy_to_memory dereferences tex in self.twin_use(tex, false, false) and crate::texture::upload(self, tex, &copy.texture).
    • Required fix: Under TARGETS_AT.lock() in target_copy_at, require crate::object::add_ref_alive(this) and return Held(this) instead of raw This; pass tex.get() into list.texture_copy_to_memory(...) while keeping Held alive across the call.
  2. [P0] D3D12 validation error / device removal on MSAA, 3D, or stand-in targets via target_copy_at -> texback::record

    • Location: crates/victory-gpu/src/resource.rs:4587-4604, crates/victory-gpu/src/texback.rs:278-281
    • Issue: TARGETS_AT registers all non-fills targets, including MSAA render/depth targets (sample_count > 1), 3D UAV/RT volumes (dimension == TEXTURE_3D), and format-substituted stand-ins (stands_in). Previously texback::record was only reached through texture_kind (dimension == TEXTURE_2D && sample_count <= 1). target_copy_at omits these guards:
      • MSAA (sample_count > 1): texback::record calls GetCopyableFootprints and CopyTextureRegion on an MSAA texture (illegal in D3D12 -> validation error / device removal).
      • 3D textures (dimension == TEXTURE_3D): texback.rs:280 computes subresources = mips * u32::from(desc.DepthOrArraySize.max(1)), which is wrong for TEXTURE3D (DepthOrArraySize is Z-depth; subresource count is mips), passing out-of-bounds subresource counts/indices to GetCopyableFootprints and CopyTextureRegion -> validation error / device removal.
      • Format stand-ins (target_format(own) != own): host texture layout does not match r.desc's format layout.
    • Required fix: In target_copy_at, reject r.desc.dimension != TEXTURE_2D, r.desc.sample_count > 1, and format stand-ins (let own = pc_format(r.desc.format); if target_format(own) != own && unsafe { copy.texture.GetDesc() }.Format.0 as u32 == target_format(own) { return None; }). In texback::record, also guard if desc.SampleDesc.Count > 1 { return None; } and compute subresources = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { mips } else { mips * u32::from(desc.DepthOrArraySize.max(1)) }.
  3. [P0] Host::submit sync override leaves publish = true under VICTORY_SUBMIT_SPLIT=1 and drops waited_parts barriers

    • Location: crates/victory-gpu/src/host.rs:7854-7860 (interacting with host.rs:7413-7470, 7871, 8189, 8202-8258, 8292-8296, 8347-8356)
    • Issue: Overriding late = false inside Host::submit without clearing publish breaks two invariants:
      1. Under VICTORY_SUBMIT_SPLIT=1 (send_late passes late = true, publish = true), late becomes false while publish stays true: wait_sent() (7871) is skipped despite settle (7933), flown (8189) becomes false, and if publish (8202, 8222) still returns an async Handoff to sender — completely bypassing the synchronous execute/wait/readback path (8349-8490) and passing h.flown = false into send_published -> card_record.
      2. Even with VICTORY_SUBMIT_SPLIT=0, joined submissions from execute_parts with non-empty waited_parts fall through to host.rs:8347-8356 (single ExecuteCommandLists), silently skipping prepare_part_barriers / execute_part_lists (8292-8296) and dropping inter-part GPU barriers.
    • Required fix: Remove the late override from Host::submit (host.rs:7854-7860), and instead settle synchronously in Host::send_late (host.rs:7468): compute let packed_linear = order.iter().any(|&i| lists[i].host().deferred().texture_backs.iter().any(crate::texback::Back::is_packed_linear)); and settle via if (told && !late_writes()) || packed_linear { self.settle(&mut submitted, WHY_SYNC); } (preserving waited_parts, publish => late, and waiting through relay_wait / fence + texback::land_batch before returning).
  4. [P1] crates/victory-gpu/src/host.rs exceeds the Windows CRLF 655,360 B cap (660,322 B, 100.8%)

    • Location: crates/victory-gpu/src/host.rs
    • Issue: PR #426 grows host.rs by +1,553 B (644,358 B -> 645,911 B LF, 98.6% of 655,360 B, only 9,449 B LF headroom), pushing its Windows CRLF size to 660,322 B (+4,962 B over the 655,360 B cap; pre-existing 658,732 B on origin/main). While .gitattributes sets eol=lf, any CRLF checkout/edit exceeds MAX_FILE_SIZE.
    • Required fix: Avoid growing host.rs further (move texture_copy_to_memory / sync-settle helper logic into texback.rs, and/or split host.rs so it sits well below 655,360 B in CRLF).

Verified Clean Areas

  • texture/ahead.rs (ReVIctory 2b910e0): Requiring job.upload.cpu().is_populated(), skipping empty copy-list submissions, and calling descriptor::host::read_short(job.staging.memory as u64) on skipped/failed jobs are race-free, deadlock-free, reset last.hash via reset_for_new_cpu on direct retry, preserve 8 GB VRAM/staging caps, and do not conflict with PR #420 stand-in alpha or PR #422/#423.
  • victory-shader/src/emit/lower.rs (same_as_done): Sound with VICTORY_KILL_CONTINUE (PR #412) and OMSetSampleMaskX (PR #419); crates/victory-gpu/build.rs automatically hashes victory-shader/src into VICTORY_TRANSLATOR to invalidate shader/pipeline caches (PR #421).
  • texback.rs pitch/packing & lock ordering: packed_linear_size, pack_linear_rows, partial-copy clamping, and watch::writing + host::write_mapped lock order (MAPPING -> TICKETS -> PHYSICAL, consistent with xmem's MAPPING.write() -> PHYSICAL) are sound.
  • ambient.rs / resolution.rs / Policy & Clean-Room: ambient.rs (VICTORY_AMBIENT_ALPHA + bound_alpha) and resolution.rs (absent) are untouched; diff is 100% title-neutral with zero local paths and proper GPL-3.0 attribution; all other 7 modified Rust files are well under the CRLF 655,360 B cap (4.7%–74.2%).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7405652022 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7405652022). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T08:13:07Z. --- ### Gate 2 Adversarial Pure-Reasoning Audit — PR #426 (`fix/w9a-indoor-visuals`) — **BLOCKED (3 P0, 1 P1)** - **PR / Commit:** #426 @ `8b5d82ee48dd8faf404fa906c35f20b64925d4d8` (branched from `ab8e337`; 8 files, `+451 / -21`) - **Result:** **3 P0, 1 P1** — fixes required before merge. #### Blocking Findings 1. **`[P0]` Use-After-Free on unpinned `This` returned by `resource::target_copy_at`** - **Location:** `crates/victory-gpu/src/resource.rs:4587-4604`, `crates/victory-gpu/src/list.rs:2105-2106`, `crates/victory-gpu/src/host.rs:9246-9269` - **Issue:** `target_copy_at` looks up `this: This` under `TARGETS_AT.lock()`, drops the lock, and returns a raw unpinned `This` without calling `crate::object::add_ref_alive(this)` to wrap it in `Held` (unlike `alias_of` at `resource.rs:1744-1745`). A concurrent `Release` (which may already have refcount `0` and be waiting on `TARGETS_AT.lock()` inside `Resource::drop` at `resource.rs:4291`) frees `Resource` as soon as `TARGETS_AT` unlocks, while `HostList::texture_copy_to_memory` dereferences `tex` in `self.twin_use(tex, false, false)` and `crate::texture::upload(self, tex, &copy.texture)`. - **Required fix:** Under `TARGETS_AT.lock()` in `target_copy_at`, require `crate::object::add_ref_alive(this)` and return `Held(this)` instead of raw `This`; pass `tex.get()` into `list.texture_copy_to_memory(...)` while keeping `Held` alive across the call. 2. **`[P0]` D3D12 validation error / device removal on MSAA, 3D, or stand-in targets via `target_copy_at` -> `texback::record`** - **Location:** `crates/victory-gpu/src/resource.rs:4587-4604`, `crates/victory-gpu/src/texback.rs:278-281` - **Issue:** `TARGETS_AT` registers all non-`fills` targets, including MSAA render/depth targets (`sample_count > 1`), 3D UAV/RT volumes (`dimension == TEXTURE_3D`), and format-substituted stand-ins (`stands_in`). Previously `texback::record` was only reached through `texture_kind` (`dimension == TEXTURE_2D && sample_count <= 1`). `target_copy_at` omits these guards: - **MSAA (`sample_count > 1`):** `texback::record` calls `GetCopyableFootprints` and `CopyTextureRegion` on an MSAA texture (illegal in D3D12 -> validation error / device removal). - **3D textures (`dimension == TEXTURE_3D`):** `texback.rs:280` computes `subresources = mips * u32::from(desc.DepthOrArraySize.max(1))`, which is wrong for `TEXTURE3D` (`DepthOrArraySize` is Z-depth; subresource count is `mips`), passing out-of-bounds subresource counts/indices to `GetCopyableFootprints` and `CopyTextureRegion` -> validation error / device removal. - **Format stand-ins (`target_format(own) != own`):** host texture layout does not match `r.desc`'s format layout. - **Required fix:** In `target_copy_at`, reject `r.desc.dimension != TEXTURE_2D`, `r.desc.sample_count > 1`, and format stand-ins (`let own = pc_format(r.desc.format); if target_format(own) != own && unsafe { copy.texture.GetDesc() }.Format.0 as u32 == target_format(own) { return None; }`). In `texback::record`, also guard `if desc.SampleDesc.Count > 1 { return None; }` and compute `subresources = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { mips } else { mips * u32::from(desc.DepthOrArraySize.max(1)) }`. 3. **`[P0]` `Host::submit` sync override leaves `publish = true` under `VICTORY_SUBMIT_SPLIT=1` and drops `waited_parts` barriers** - **Location:** `crates/victory-gpu/src/host.rs:7854-7860` (interacting with `host.rs:7413-7470`, `7871`, `8189`, `8202-8258`, `8292-8296`, `8347-8356`) - **Issue:** Overriding `late = false` inside `Host::submit` without clearing `publish` breaks two invariants: 1. Under `VICTORY_SUBMIT_SPLIT=1` (`send_late` passes `late = true, publish = true`), `late` becomes `false` while `publish` stays `true`: `wait_sent()` (`7871`) is skipped despite `settle` (`7933`), `flown` (`8189`) becomes `false`, and `if publish` (`8202, 8222`) still returns an async `Handoff` to `sender` — completely bypassing the synchronous execute/wait/readback path (`8349-8490`) and passing `h.flown = false` into `send_published` -> `card_record`. 2. Even with `VICTORY_SUBMIT_SPLIT=0`, joined submissions from `execute_parts` with non-empty `waited_parts` fall through to `host.rs:8347-8356` (single `ExecuteCommandLists`), silently skipping `prepare_part_barriers` / `execute_part_lists` (`8292-8296`) and dropping inter-part GPU barriers. - **Required fix:** Remove the `late` override from `Host::submit` (`host.rs:7854-7860`), and instead settle synchronously in `Host::send_late` (`host.rs:7468`): compute `let packed_linear = order.iter().any(|&i| lists[i].host().deferred().texture_backs.iter().any(crate::texback::Back::is_packed_linear));` and settle via `if (told && !late_writes()) || packed_linear { self.settle(&mut submitted, WHY_SYNC); }` (preserving `waited_parts`, `publish => late`, and waiting through `relay_wait` / fence + `texback::land_batch` before returning). 4. **`[P1]` `crates/victory-gpu/src/host.rs` exceeds the Windows CRLF `655,360 B` cap (`660,322 B`, 100.8%)** - **Location:** `crates/victory-gpu/src/host.rs` - **Issue:** PR #426 grows `host.rs` by `+1,553 B` (`644,358 B` -> `645,911 B` LF, `98.6%` of `655,360 B`, only `9,449 B` LF headroom), pushing its Windows CRLF size to **`660,322 B`** (`+4,962 B` over the `655,360 B` cap; pre-existing `658,732 B` on `origin/main`). While `.gitattributes` sets `eol=lf`, any CRLF checkout/edit exceeds `MAX_FILE_SIZE`. - **Required fix:** Avoid growing `host.rs` further (move `texture_copy_to_memory` / sync-settle helper logic into `texback.rs`, and/or split `host.rs` so it sits well below `655,360 B` in CRLF). #### Verified Clean Areas - **`texture/ahead.rs` (`ReVIctory 2b910e0`):** Requiring `job.upload.cpu().is_populated()`, skipping empty copy-list submissions, and calling `descriptor::host::read_short(job.staging.memory as u64)` on skipped/failed jobs are race-free, deadlock-free, reset `last.hash` via `reset_for_new_cpu` on direct retry, preserve 8 GB VRAM/staging caps, and do not conflict with PR #420 stand-in alpha or PR #422/#423. - **`victory-shader/src/emit/lower.rs` (`same_as_done`):** Sound with `VICTORY_KILL_CONTINUE` (PR #412) and `OMSetSampleMaskX` (PR #419); `crates/victory-gpu/build.rs` automatically hashes `victory-shader/src` into `VICTORY_TRANSLATOR` to invalidate shader/pipeline caches (PR #421). - **`texback.rs` pitch/packing & lock ordering:** `packed_linear_size`, `pack_linear_rows`, partial-copy clamping, and `watch::writing` + `host::write_mapped` lock order (`MAPPING` -> `TICKETS` -> `PHYSICAL`, consistent with `xmem`'s `MAPPING.write()` -> `PHYSICAL`) are sound. - **`ambient.rs` / `resolution.rs` / Policy & Clean-Room:** `ambient.rs` (`VICTORY_AMBIENT_ALPHA` + `bound_alpha`) and `resolution.rs` (absent) are untouched; diff is 100% title-neutral with zero local paths and proper `GPL-3.0` attribution; all other 7 modified Rust files are well under the CRLF `655,360 B` cap (`4.7%`–`74.2%`).
Androtim commented 2026-12-04 08:15:34 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T08:15:34Z.


Gate 2 Pure-Reasoning Re-Audit — PR #425 (\perf/w9b-cpu-vram-fps) — VERIFIED CLEAN (0 P0, 0 P1)

  • PR / Commit: #425 @ \f86f8425d0bcba395ac38578f4797bf904a3f4a\ (delta \7c1ed14..af86f84, merge-base \b8e3372, cleanly \MERGEABLE\ on \origin/main\ \1193611)
  • Result: VERIFIED CLEAN (0 P0, 0 P1) — both prior [P1]\ findings from comment \7405452619\ are fully resolved with zero regressions.

Prior [P1]\ Verification

  1. \crates/victory-gpu/src/cores.rs\ (\parse_l3_cache_records\ / \l3_of_sets) — FIXED:
    • Parses \RelationCache\ buffers via \offset_of!\ (\HEADER_SIZE = 8, \REL_OFFSET = 0, \SIZE_OFFSET = 4, \MASKS_OFFSET = 32) and raw-pointer
      ead_unaligned, eliminating the 80-byte &SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX\ over-read UB and ensuring final 56-byte \RelationCache\ records are never dropped.
    • Enforces strict bounds checks (\uf.len() - at >= HEADER_SIZE,
      ecord_size < HEADER_SIZE || record_size > bytes_left,
      ecord_size >= HEADER_SIZE + size_of::<CACHE_RELATIONSHIP>(), checked \GROUP_AFFINITY\ offset arithmetic for \
<!-- greyfinch-sync:Androtim/MiniVI:comment:7405708302 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7405708302). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T08:15:34Z. --- ### Gate 2 Pure-Reasoning Re-Audit — PR #425 (\perf/w9b-cpu-vram-fps\) — **VERIFIED CLEAN (0 P0, 0 P1)** - **PR / Commit:** #425 @ \f86f8425d0bcba395ac38578f4797bf904a3f4a\ (delta \7c1ed14..af86f84\, merge-base \b8e3372\, cleanly \MERGEABLE\ on \origin/main\ \1193611\) - **Result:** **VERIFIED CLEAN (0 P0, 0 P1)** — both prior \[P1]\ findings from comment \7405452619\ are fully resolved with zero regressions. #### Prior \[P1]\ Verification 1. **\crates/victory-gpu/src/cores.rs\ (\parse_l3_cache_records\ / \l3_of_sets\) — FIXED:** - Parses \RelationCache\ buffers via \offset_of!\ (\HEADER_SIZE = 8\, \REL_OFFSET = 0\, \SIZE_OFFSET = 4\, \MASKS_OFFSET = 32\) and raw-pointer \ ead_unaligned\, eliminating the 80-byte \&SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX\ over-read UB and ensuring final 56-byte \RelationCache\ records are never dropped. - Enforces strict bounds checks (\uf.len() - at >= HEADER_SIZE\, \ ecord_size < HEADER_SIZE || record_size > bytes_left\, \ ecord_size >= HEADER_SIZE + size_of::<CACHE_RELATIONSHIP>()\, checked \GROUP_AFFINITY\ offset arithmetic for \
Androtim commented 2026-12-04 08:27:47 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T08:27:47Z.


Gate 2 Adversarial Pure-Reasoning Audit — PR #427 (perf/w10a-hwrt-cpu-prep, 4823582)

Verdict: CHANGES REQUIRED — 2 [P0], 2 [P1]

[P0] Findings (Merge Blockers)

  1. [P0] Persistent GpuBlasTable Desync & GPU UAF if alloc_or_reuse_as fails after list.plane_upload

    • Location: crates/victory-gpu/src/hwrt.rs:3073-3144 (and write_patch at hwrt.rs:724-771)
    • Root Cause: execute_build registers list.plane_upload(patch_bytes, ..., mgr.fill_blas_table_patch(...)) onto list.deferred().steps_raw at lines 3073-3098, and only afterwards calls self.alloc_or_reuse_as(...) at line 3122. If alloc_or_reuse_as returns None, execute_build returns early at line 3143 without recording Dispatch(patch_groups, 1, 1) (hwrt.rs:3215). When list is later submitted, run_deferred() still executes the queued Step::Plane → fill_blas_table_patch → cached.write_patch, which clears cached.gpu_dirty and sets cached.gpu_needs_full = false even though the GPU table was never patched. Subsequent TLAS builds emit mode = 0 no-ops while gpu_table.buffer retains dangling/freed BLAS GPU VAs (or uninitialized memory on first upload) → GPU use-after-free / DXGI_ERROR_DEVICE_REMOVED.
    • Required Fix: Move alloc_or_reuse_as before list.plane_upload so there is no fallible return after registering the Step::Plane callback (or gate the callback on an Arc<AtomicBool> armed only after patch_table Dispatch is recorded, emitting a mode = 0 16-byte header without touching CachedBlasTable when disarmed).
  2. [P0] Unchecked OOB GPU Index Reads via should_skip_clamp_ib & validated_ibs Cache

    • Location: crates/victory-gpu/src/hwrt.rs:789-812, hwrt.rs:2702-2849, hwrt.rs:4028 (interacting with list.rs:1318, host.rs:7909,8164,8190,9980, watch.rs:1321-1324, shadow.rs:4807,4922)
    • Root Cause: Previously validated_ibs was only an eff_vc hint and clamp_ib still ran on GPU after all submit-time copies/refreshes. PR #427 now uses record-time scanned_max / validated_ibs to omit clamp_ib (should_skip_clamp_ib), opening three OOB GPU crash paths:
      1. Record-time scan vs. submit-time CopyBufferRegion (Step::Copy) / CPU-write / picked UAV-write TOCTOU: prepare_triangles runs at record time (list::external), while CopyBufferRegion (list.defer_copy → Step::Copy, which does not set sh_ib.written() or writes_pending_in), sh_ib.refresh (Step::Refresh), and bindless UAV write discovery (picked::declare) run later at submit time. A title recording CopyBufferRegion(ib, upload) then BuildRaytracingAccelerationStructure(ib) (or writing ib on CPU between record and submit) scans pre-copy bytes (e.g. zeros → scanned_max = Some(0) < eff_vc), skips clamp_ib, and then executes the BLAS build on newly copied unchecked indices → OOB vertex read / TDR. (Shadow::gpu_writes can also skip written.store(true) via self.quiet.should_skip at shadow.rs:4922.)
      2. Stale JOURNAL.ahead during concurrent victory-submit (ask_once): While victory-submit holds global JOURNAL.ahead (host.rs:7909..8164), a worker/title thread calling watch::writes_since(ib_start, ib_end, true, since) (hwrt.rs:2728) hits ahead(&journal()) (watch.rs:1322) without calling GetWriteWatch, returning a stale dirty = false even if CPU wrote new indices after Frame N's ask_once → stale validated_ibs hit skips clamp_ib.
      3. Unwatched watch_epoch == 0 hit on was_update_req == true even on refit fallback: validated_ib_hit (hwrt.rs:804) trusts watch_epoch == 0 (including Shadow::placed in-place memory, which forces NOT_WATCHED) whenever was_update_req is true, before flush_blas_waves (hwrt.rs:2082-2182) determines whether the refit matches or falls back to a full build.
      4. (Secondary) title_memory_freed_many (hwrt.rs:4028) only checks !gone(ib_va) rather than overlapping [ib_va, ib_va + ibytes).
    • Required Fix: Do not skip clamp_ib using record-time CPU scans or validated_ibs on Shadow-backed IBs (keep validated_ibs strictly as a CPU scan skip for eff_vc expansion while keeping GPU clamp_ib), or only skip clamp_ib if the validated IB bytes are copied into an immutable staging upload at scan time (or re-validated at submit time after Step::Copy + ask_once_end, strictly requiring watch_epoch != 0, no pending/historical/quiet-skipped GPU writes, and range-overlap eviction in title_memory_freed_many).

[P1] Findings

  1. [P1] Even-Interval LRU Feedback Throttling (8 / 16) Can Phase-Lock and Starve Alternating-Frame TLASes

    • Location: crates/victory-gpu/src/hwrt/budget.rs:29-36, 458-473
    • Root Cause: FEEDBACK_ACTIVE_INTERVAL = 8 and FEEDBACK_IDLE_INTERVAL = 16 are powers of 2; frame.is_multiple_of(interval) never fires on odd frames (frame % 2 == 1) or out-of-phase 2/4-frame cadences. BLASes referenced exclusively by an alternating/half-rate TLAS never receive LRU touches, get evicted after BLAS_KEEP_FRAMES = 120, and are never re-requested by feedback.
    • Required Fix: Use odd/prime intervals coprime to 2/3/4/6 (e.g., 7 / 13 or 17) or track last_feedback_frame: AtomicU64 and sample when frame.saturating_sub(last) >= interval.
  2. [P1] CachedBlasTableGeneric::apply_dirty Silently Drops Failed upserts Without Recovery

    • Location: crates/victory-gpu/src/hwrt.rs:702-718, 1614-1652
    • Root Cause: If self.table.upsert(key, ...) returns None during incremental sync (e.g., a burst of BLASes pushes count to the 75% load limit between TLAS record-time approx_blas sizing and submit-time fill_blas_table_patch, or a 64-step probe chain saturates), apply_dirty drops the key while dirty_blas has already been drained and cached.version = ver is stored. Those BLASes remain permanently missing (Missing) from the table until an unrelated resize or mark_dirty_full().
    • Required Fix: Have apply_dirty return whether any upsert failed (overflowed: bool); if true, call self.mark_dirty_full() (or trigger rebuild_blas_table_locked) so the next TLAS sync recovers all entries once resized/freed.

Verified Clean Areas

  • BlasHashTable & PATCH_TABLE_HLSL / REMAP_HLSL: Linear probing (0..64), Murmur3 finalizer, circular backshift delete, wrap-around, empty-slot sentinel (0), slot-deduped scatter-patch layout (16 + i*20), and barrier state machine (SRV -> UAV -> SRV) are consistent.
  • CoW ChunkedRefs (BlasRefs) & Lock Hierarchy: Arc::make_mut isolates in-flight TLAS snapshots; HostAs::drop retires resources past GPU fences; lock hierarchy (blas_table -> queue -> lru -> as_map/shown -> recording_tlas -> dirty_blas) is acyclic; all shown/waiting/evicted mutations mark dirty keys after mutating state.
  • flush_blas_waves list.scratch_held: 256B base alignment + 16B align_stage offsets satisfy VB/IB/Transform3x4; oversized waves (> 4 MiB SCRATCH_CHUNK) fall back cleanly to take_list_upload (host.rs:9513-9519); buffer lifetimes hold until post-fence HostList::reset().
  • Arc<OwnedBuild> + normalize_recipe, cached_meshlet_ib on rehydrate, decoders.rs TLS scratch, Feedback readback cleanup & pool.stats gating: Sound, zero leaks, zero OOB in decode_quant24_loop / decode_title_meshlet_ib.
  • Policy & Clean-Room: 100% title-neutral, zero local paths, CRLF sizes well under 655,360 B (hwrt.rs: 194,078 B, budget.rs: 59,796 B, decoders.rs: 26,337 B).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7405972309 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7405972309). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T08:27:47Z. --- ## Gate 2 Adversarial Pure-Reasoning Audit — PR #427 (`perf/w10a-hwrt-cpu-prep`, `4823582`) **Verdict: CHANGES REQUIRED — 2 `[P0]`, 2 `[P1]`** ### `[P0]` Findings (Merge Blockers) 1. **`[P0]` Persistent `GpuBlasTable` Desync & GPU UAF if `alloc_or_reuse_as` fails after `list.plane_upload`** - **Location:** `crates/victory-gpu/src/hwrt.rs:3073-3144` (and `write_patch` at `hwrt.rs:724-771`) - **Root Cause:** `execute_build` registers `list.plane_upload(patch_bytes, ..., mgr.fill_blas_table_patch(...))` onto `list.deferred().steps_raw` at lines 3073-3098, and only afterwards calls `self.alloc_or_reuse_as(...)` at line 3122. If `alloc_or_reuse_as` returns `None`, `execute_build` returns early at line 3143 **without** recording `Dispatch(patch_groups, 1, 1)` (`hwrt.rs:3215`). When `list` is later submitted, `run_deferred()` still executes the queued `Step::Plane` → `fill_blas_table_patch` → `cached.write_patch`, which **clears `cached.gpu_dirty` and sets `cached.gpu_needs_full = false`** even though the GPU table was never patched. Subsequent TLAS builds emit `mode = 0` no-ops while `gpu_table.buffer` retains dangling/freed BLAS GPU VAs (or uninitialized memory on first upload) → **GPU use-after-free / `DXGI_ERROR_DEVICE_REMOVED`**. - **Required Fix:** Move `alloc_or_reuse_as` **before** `list.plane_upload` so there is no fallible return after registering the `Step::Plane` callback (or gate the callback on an `Arc<AtomicBool>` armed only after `patch_table` `Dispatch` is recorded, emitting a `mode = 0` 16-byte header without touching `CachedBlasTable` when disarmed). 2. **`[P0]` Unchecked OOB GPU Index Reads via `should_skip_clamp_ib` & `validated_ibs` Cache** - **Location:** `crates/victory-gpu/src/hwrt.rs:789-812`, `hwrt.rs:2702-2849`, `hwrt.rs:4028` (interacting with `list.rs:1318`, `host.rs:7909,8164,8190,9980`, `watch.rs:1321-1324`, `shadow.rs:4807,4922`) - **Root Cause:** Previously `validated_ibs` was only an `eff_vc` hint and `clamp_ib` still ran on GPU after all submit-time copies/refreshes. PR #427 now uses record-time `scanned_max` / `validated_ibs` to omit `clamp_ib` (`should_skip_clamp_ib`), opening three OOB GPU crash paths: 1. **Record-time scan vs. submit-time `CopyBufferRegion` (`Step::Copy`) / CPU-write / `picked` UAV-write TOCTOU:** `prepare_triangles` runs at record time (`list::external`), while `CopyBufferRegion` (`list.defer_copy` → `Step::Copy`, which does **not** set `sh_ib.written()` or `writes_pending_in`), `sh_ib.refresh` (`Step::Refresh`), and bindless UAV write discovery (`picked::declare`) run later at submit time. A title recording `CopyBufferRegion(ib, upload)` then `BuildRaytracingAccelerationStructure(ib)` (or writing `ib` on CPU between record and submit) scans pre-copy bytes (e.g. zeros → `scanned_max = Some(0) < eff_vc`), skips `clamp_ib`, and then executes the BLAS build on newly copied unchecked indices → OOB vertex read / TDR. (`Shadow::gpu_writes` can also skip `written.store(true)` via `self.quiet.should_skip` at `shadow.rs:4922`.) 2. **Stale `JOURNAL.ahead` during concurrent `victory-submit` (`ask_once`):** While `victory-submit` holds global `JOURNAL.ahead` (`host.rs:7909..8164`), a worker/title thread calling `watch::writes_since(ib_start, ib_end, true, since)` (`hwrt.rs:2728`) hits `ahead(&journal())` (`watch.rs:1322`) without calling `GetWriteWatch`, returning a stale `dirty = false` even if CPU wrote new indices after Frame N's `ask_once` → stale `validated_ibs` hit skips `clamp_ib`. 3. **Unwatched `watch_epoch == 0` hit on `was_update_req == true` even on refit fallback:** `validated_ib_hit` (`hwrt.rs:804`) trusts `watch_epoch == 0` (including `Shadow::placed` in-place memory, which forces `NOT_WATCHED`) whenever `was_update_req` is true, before `flush_blas_waves` (`hwrt.rs:2082-2182`) determines whether the refit matches or falls back to a full build. 4. *(Secondary)* `title_memory_freed_many` (`hwrt.rs:4028`) only checks `!gone(ib_va)` rather than overlapping `[ib_va, ib_va + ibytes)`. - **Required Fix:** Do **not** skip `clamp_ib` using record-time CPU scans or `validated_ibs` on `Shadow`-backed IBs (keep `validated_ibs` strictly as a CPU scan skip for `eff_vc` expansion while keeping GPU `clamp_ib`), **or** only skip `clamp_ib` if the validated IB bytes are copied into an immutable staging upload at scan time (or re-validated at submit time after `Step::Copy` + `ask_once_end`, strictly requiring `watch_epoch != 0`, no pending/historical/quiet-skipped GPU writes, and range-overlap eviction in `title_memory_freed_many`). --- ### `[P1]` Findings 3. **`[P1]` Even-Interval LRU Feedback Throttling (`8` / `16`) Can Phase-Lock and Starve Alternating-Frame TLASes** - **Location:** `crates/victory-gpu/src/hwrt/budget.rs:29-36, 458-473` - **Root Cause:** `FEEDBACK_ACTIVE_INTERVAL = 8` and `FEEDBACK_IDLE_INTERVAL = 16` are powers of 2; `frame.is_multiple_of(interval)` never fires on odd frames (`frame % 2 == 1`) or out-of-phase 2/4-frame cadences. BLASes referenced exclusively by an alternating/half-rate TLAS never receive LRU touches, get evicted after `BLAS_KEEP_FRAMES = 120`, and are never re-requested by feedback. - **Required Fix:** Use odd/prime intervals coprime to 2/3/4/6 (e.g., `7` / `13` or `17`) or track `last_feedback_frame: AtomicU64` and sample when `frame.saturating_sub(last) >= interval`. 4. **`[P1]` `CachedBlasTableGeneric::apply_dirty` Silently Drops Failed `upsert`s Without Recovery** - **Location:** `crates/victory-gpu/src/hwrt.rs:702-718, 1614-1652` - **Root Cause:** If `self.table.upsert(key, ...)` returns `None` during incremental sync (e.g., a burst of BLASes pushes count to the 75% load limit between TLAS record-time `approx_blas` sizing and submit-time `fill_blas_table_patch`, or a 64-step probe chain saturates), `apply_dirty` drops the key while `dirty_blas` has already been drained and `cached.version = ver` is stored. Those BLASes remain permanently missing (`Missing`) from the table until an unrelated resize or `mark_dirty_full()`. - **Required Fix:** Have `apply_dirty` return whether any `upsert` failed (`overflowed: bool`); if `true`, call `self.mark_dirty_full()` (or trigger `rebuild_blas_table_locked`) so the next TLAS sync recovers all entries once resized/freed. --- ### Verified Clean Areas - **`BlasHashTable` & `PATCH_TABLE_HLSL` / `REMAP_HLSL`:** Linear probing (`0..64`), Murmur3 finalizer, circular backshift delete, wrap-around, empty-slot sentinel (`0`), slot-deduped scatter-patch layout (`16 + i*20`), and barrier state machine (`SRV -> UAV -> SRV`) are consistent. - **CoW `ChunkedRefs` (`BlasRefs`) & Lock Hierarchy:** `Arc::make_mut` isolates in-flight TLAS snapshots; `HostAs::drop` retires resources past GPU fences; lock hierarchy (`blas_table -> queue -> lru -> as_map/shown -> recording_tlas -> dirty_blas`) is acyclic; all `shown`/`waiting`/`evicted` mutations mark dirty keys after mutating state. - **`flush_blas_waves` `list.scratch_held`:** 256B base alignment + 16B `align_stage` offsets satisfy VB/IB/`Transform3x4`; oversized waves (`> 4 MiB` `SCRATCH_CHUNK`) fall back cleanly to `take_list_upload` (`host.rs:9513-9519`); buffer lifetimes hold until post-fence `HostList::reset()`. - **`Arc<OwnedBuild>` + `normalize_recipe`, `cached_meshlet_ib` on rehydrate, `decoders.rs` TLS scratch, `Feedback` readback cleanup & `pool.stats` gating:** Sound, zero leaks, zero OOB in `decode_quant24_loop` / `decode_title_meshlet_ib`. - **Policy & Clean-Room:** 100% title-neutral, zero local paths, CRLF sizes well under `655,360 B` (`hwrt.rs`: `194,078 B`, `budget.rs`: `59,796 B`, `decoders.rs`: `26,337 B`).
Androtim commented 2026-12-04 08:36:47 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T08:36:47Z.


Gate 2 Pure-Reasoning Re-Audit — PR #426 (\ ix/w9a-indoor-visuals) — VERIFIED CLEAN (0 P0, 0 P1)

  • PR / Commit: #426 @ \d6e031f\ (delta \8b5d82e..d6e031f: 5 files, +289 / -265; full PR \origin/main...d6e031f: 9 files, +697 / -243, merge-base \b8e337)
  • Result: VERIFIED CLEAN (0 P0, 0 P1) — all 4 findings from comment \7405652022\ are resolved with zero new P0/P1 regressions.

Verification of All 4 Prior Findings

  1. [P0]\
    esource::target_copy_at\ UAF — RESOLVED

    • \crates/victory-gpu/src/resource.rs:4588-4617: \ arget_copy_at\ now acquires an owned reference under \TARGETS_AT.lock()\ via \crate::object::add_ref_alive(this).then(|| Held(this))?, unlocks \TARGETS_AT\ immediately (preventing re-entrant drop deadlock if \Held\ later releases the final refcount), and returns \Option<(Held, Arc, Layout, bool)>.
    • \crates/victory-gpu/src/list.rs:2105-2110: \ ex: Held\ remains bound for the entire \if let ... && crate::texback::copy_to_memory(list, tex.get(), ...)\ expression, keeping \Resource\ alive across \list.twin_use\ and \crate::texture::upload; neither retains raw \This\ after returning.
  2. [P0]\ MSAA / 3D / stand-in D3D12 validation errors — RESOLVED

    • \crates/victory-gpu/src/resource.rs:4600-4613: \ arget_copy_at\ rejects
      .desc.dimension != TEXTURE_2D,
      .desc.sample_count > 1, format stand-ins (\ arget_format(own) != own && copy.texture.GetDesc().Format.0 as u32 == target_format(own)), and multi-plane textures (\let [plane] = &t.planes[..], including console depth+stencil \118..=120).
    • \crates/victory-gpu/src/texback.rs:309-317: \ exback::record\ independently guards \desc.SampleDesc.Count > 1\ and computes \subresources = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { mips } else { mips * u32::from(desc.DepthOrArraySize.max(1)) }.
  3. [P0]\ \Host::submit\ \late\ override — RESOLVED

    • \crates/victory-gpu/src/host.rs:7638-7647: The \late\ override was removed from \Host::submit, preserving \publish => late\ under \VICTORY_SUBMIT_SPLIT=1\ (\ lown = late && relay()) and preserving \waited_parts\ inter-part barrier execution via \prepare_part_barriers\ / \execute_part_lists\ (or \Handoff.parts).
    • \crates/victory-gpu/src/host.rs:7209-7216, 7259-7260: \Host::send_late\ computes \packed_linear\ from \lists[i].host().deferred().texture_backs\ before moving \lists\ into \Flight, publishes \handoff\ and wakes
      elay, then settles synchronously via \if (told && !late_writes()) || packed_linear { self.settle(&mut submitted, if packed_linear { WHY_SYNC } else { WHY_WRITES }); }\ — waiting through
      elay_wait\ + \ exback::land_batch\ (when
      elay()) or fence wait +
      ead_backs\ (when !relay()) with no lock inversion on \self.submitted.
  4. [P1]\ \crates/victory-gpu/src/host.rs\ size cap — RESOLVED

    • \host.rs\ shrank from \644,358 B\ LF / \658,732 B\ CRLF (\origin/main) and \645,911 B\ LF / \660,322 B\ CRLF (\8b5d82e) down to \635,420 B\ LF / \649,589 B\ CRLF (**\99.12%**, -5,771 B\ below the \655,360 B\ cap and -9,143 B\ CRLF smaller than \origin/main) by moving
      eadback_pool_tests\ into \crates/victory-gpu/src/host/readback_pool_tests.rs\ (\8,762 B\ CRLF) and moving \ exture_copy_to_memory\ into \crates/victory-gpu/src/texback.rs\ (\36,339 B\ CRLF).
    • All 9 changed files in \origin/main...d6e031f\ are below the \655,360 B\ CRLF cap (\1.3%\–\99.1%).

Regression & Sanity Check (\d6e031f)

  • Module layout, #[cfg(windows)]\ / #[cfg(test)]\ gating, visibility (\HostList::settle, \HostList::push_texture_back, \HostList::twin_use, \ exback::copy_to_memory), imports (\D3D12_RESOURCE_DIMENSION_TEXTURE3D, \This, \Arc), and \copy_to_memory\ failure fallback behavior are all sound.
  • Clean-room / title-neutrality / GPL-3.0 attribution intact; zero new P0 or P1 issues found.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7406170407 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7406170407). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T08:36:47Z. --- ### Gate 2 Pure-Reasoning Re-Audit — PR #426 (\ ix/w9a-indoor-visuals\) — **VERIFIED CLEAN (0 P0, 0 P1)** - **PR / Commit:** #426 @ \d6e031f\ (delta \8b5d82e..d6e031f\: 5 files, \+289 / -265\; full PR \origin/main...d6e031f\: 9 files, \+697 / -243\, merge-base \b8e337\) - **Result:** **VERIFIED CLEAN (0 P0, 0 P1)** — all 4 findings from comment \7405652022\ are resolved with zero new P0/P1 regressions. #### Verification of All 4 Prior Findings 1. **\[P0]\ \ esource::target_copy_at\ UAF — RESOLVED** - \crates/victory-gpu/src/resource.rs:4588-4617\: \ arget_copy_at\ now acquires an owned reference under \TARGETS_AT.lock()\ via \crate::object::add_ref_alive(this).then(|| Held(this))?\, unlocks \TARGETS_AT\ immediately (preventing re-entrant drop deadlock if \Held\ later releases the final refcount), and returns \Option<(Held, Arc<HostTexture>, Layout, bool)>\. - \crates/victory-gpu/src/list.rs:2105-2110\: \ ex: Held\ remains bound for the entire \if let ... && crate::texback::copy_to_memory(list, tex.get(), ...)\ expression, keeping \Resource\ alive across \list.twin_use\ and \crate::texture::upload\; neither retains raw \This\ after returning. 2. **\[P0]\ MSAA / 3D / stand-in D3D12 validation errors — RESOLVED** - \crates/victory-gpu/src/resource.rs:4600-4613\: \ arget_copy_at\ rejects \ .desc.dimension != TEXTURE_2D\, \ .desc.sample_count > 1\, format stand-ins (\ arget_format(own) != own && copy.texture.GetDesc().Format.0 as u32 == target_format(own)\), and multi-plane textures (\let [plane] = &t.planes[..]\, including console depth+stencil \118..=120\). - \crates/victory-gpu/src/texback.rs:309-317\: \ exback::record\ independently guards \desc.SampleDesc.Count > 1\ and computes \subresources = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { mips } else { mips * u32::from(desc.DepthOrArraySize.max(1)) }\. 3. **\[P0]\ \Host::submit\ \late\ override — RESOLVED** - \crates/victory-gpu/src/host.rs:7638-7647\: The \late\ override was removed from \Host::submit\, preserving \publish => late\ under \VICTORY_SUBMIT_SPLIT=1\ (\ lown = late && relay()\) and preserving \waited_parts\ inter-part barrier execution via \prepare_part_barriers\ / \execute_part_lists\ (or \Handoff.parts\). - \crates/victory-gpu/src/host.rs:7209-7216, 7259-7260\: \Host::send_late\ computes \packed_linear\ from \lists[i].host().deferred().texture_backs\ before moving \lists\ into \Flight\, publishes \handoff\ and wakes \ elay\, then settles synchronously via \if (told && !late_writes()) || packed_linear { self.settle(&mut submitted, if packed_linear { WHY_SYNC } else { WHY_WRITES }); }\ — waiting through \ elay_wait\ + \ exback::land_batch\ (when \ elay()\) or fence wait + \ ead_backs\ (when \!relay()\) with no lock inversion on \self.submitted\. 4. **\[P1]\ \crates/victory-gpu/src/host.rs\ size cap — RESOLVED** - \host.rs\ shrank from \644,358 B\ LF / \658,732 B\ CRLF (\origin/main\) and \645,911 B\ LF / \660,322 B\ CRLF (\8b5d82e\) down to **\635,420 B\ LF / \649,589 B\ CRLF** (**\99.12%\**, \-5,771 B\ below the \655,360 B\ cap and \-9,143 B\ CRLF smaller than \origin/main\) by moving \ eadback_pool_tests\ into \crates/victory-gpu/src/host/readback_pool_tests.rs\ (\8,762 B\ CRLF) and moving \ exture_copy_to_memory\ into \crates/victory-gpu/src/texback.rs\ (\36,339 B\ CRLF). - All 9 changed files in \origin/main...d6e031f\ are below the \655,360 B\ CRLF cap (\1.3%\–\99.1%\). #### Regression & Sanity Check (\d6e031f\) - Module layout, \#[cfg(windows)]\ / \#[cfg(test)]\ gating, visibility (\HostList::settle\, \HostList::push_texture_back\, \HostList::twin_use\, \ exback::copy_to_memory\), imports (\D3D12_RESOURCE_DIMENSION_TEXTURE3D\, \This\, \Arc\), and \copy_to_memory\ failure fallback behavior are all sound. - Clean-room / title-neutrality / GPL-3.0 attribution intact; zero new P0 or P1 issues found.
Androtim commented 2026-12-04 08:37:18 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T08:37:18Z.


Gate 2 Adversarial Pure-Reasoning Audit — PR #428 (905e8e7, perf/w10b-shader-opt-m1)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Pure-reasoning audit of origin/main..905e8e7 (opt.rs, lower.rs, mod.rs, cost_checks.rs) plus surrounding context (bitcode.rs, shader.rs, shader_cache.rs, build.rs, descriptor/host.rs, draw.rs, pipeline/host.rs):

  1. pred::ONE (6) never emitted: Verified across negate_bool (opt.rs:665), Xor(Cmp, 1) (opt.rs:1152), and swap_pred/canonical_cmp (opt.rs:178-208); pred::UEQ falls back to Xor(_, true) and Key::Cmp/facts.compares never emit new Op::Cmp instructions.
  2. Float arithmetic never folded: Op::Bin folding returns early unless int_bits(ty).is_some(), Key::Bin commutes integer ops only, facts.values records integer EQ/NE only (preserving -0.0), and map_i32_to_f32_arm preserves exact 32-bit bit patterns (-0.0, NaN payloads, subnormals).
  3. NaN bitmask & fract select preserved: (bitcast(f) & 0x7FFF_FFFF) > 0x7F80_0000 yields a_min=0, a_max=0x7FFF_FFFF in known-bits (never folded to fcmp uno), and float Select is never rewritten to FMin/FMax.
  4. promote_float_webs (Select + PHI) & bitcast(select) peephole: Strictly i32 <-> f32, never touches "dx.types.Handle" (also guarded by is_handle_ty in Op::Select), greatest fixpoint + undirected witnessed closure guarantee zero mixed-type edges, and immediate merge() removes every resulting bitcast f32 -> f32.
  5. Shift/mask/known-bits & fixpoint termination: Shl/LShr reassociation checks s1 < bits && s2 < bits and folds sum >= bits to 0 (clamping AShr to bits - 1); known_bits (depth 4) is exact across 1..=64 bits for And/Or/Xor/Add/Sub/Mul/Shl/LShr/AShr/URem/ZExt/SExt/Trunc/Select/Countbits/UMin; simplify_call matches DXIL MSB-indexed FirstbitHi/FirstbitSHi and IMax/IMin/UMax/UMin semantics; all in-place rewrites strictly decrease SSA DAG depth (no oscillation).
  6. Loop header FACTS: single_forward skips only b-dominated back-edges, proving p strictly dominates b (so c and all learn operands are loop-invariant outside b), skips irreducible multi-entry loops, and applies known_val only to body/term (never phis).
  7. slot_word mark_pure & dce_insts: SLOT_STRIDES/SLOT_TABLE_STRIDES bind the host's CPU upload buffer (heap.strides) as a root SRV (immutable across the entire GPU dispatch); dce_insts preserves all Store/AtomicRmw/CmpXchg, non-pure Effect::Writes calls, and branch conditions.
  8. Cache invalidation & policy: VICTORY_SHADER_OPT default 255 -> 1279 and build-time VICTORY_TRANSLATOR hash both invalidate old cached DXIL cleanly; 100% title-neutral, 0 local paths, opt.rs is 212,254 B LF / 217,475 B CRLF (well under 655,360 B cap).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7406180960 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7406180960). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T08:37:18Z. --- ### Gate 2 Adversarial Pure-Reasoning Audit — PR #428 (`905e8e7`, `perf/w10b-shader-opt-m1`) **Verdict: `VERIFIED CLEAN (0 P0, 0 P1)`** Pure-reasoning audit of `origin/main..905e8e7` (`opt.rs`, `lower.rs`, `mod.rs`, `cost_checks.rs`) plus surrounding context (`bitcode.rs`, `shader.rs`, `shader_cache.rs`, `build.rs`, `descriptor/host.rs`, `draw.rs`, `pipeline/host.rs`): 1. **`pred::ONE (6)` never emitted:** Verified across `negate_bool` (`opt.rs:665`), `Xor(Cmp, 1)` (`opt.rs:1152`), and `swap_pred`/`canonical_cmp` (`opt.rs:178-208`); `pred::UEQ` falls back to `Xor(_, true)` and `Key::Cmp`/`facts.compares` never emit new `Op::Cmp` instructions. 2. **Float arithmetic never folded:** `Op::Bin` folding returns early unless `int_bits(ty).is_some()`, `Key::Bin` commutes integer ops only, `facts.values` records integer `EQ`/`NE` only (preserving `-0.0`), and `map_i32_to_f32_arm` preserves exact 32-bit bit patterns (`-0.0`, NaN payloads, subnormals). 3. **NaN bitmask & `fract` select preserved:** `(bitcast(f) & 0x7FFF_FFFF) > 0x7F80_0000` yields `a_min=0, a_max=0x7FFF_FFFF` in known-bits (never folded to `fcmp uno`), and float `Select` is never rewritten to `FMin`/`FMax`. 4. **`promote_float_webs` (`Select` + `PHI`) & `bitcast(select)` peephole:** Strictly `i32 <-> f32`, never touches `"dx.types.Handle"` (also guarded by `is_handle_ty` in `Op::Select`), greatest fixpoint + undirected `witnessed` closure guarantee zero mixed-type edges, and immediate `merge()` removes every resulting `bitcast f32 -> f32`. 5. **Shift/mask/known-bits & fixpoint termination:** `Shl`/`LShr` reassociation checks `s1 < bits && s2 < bits` and folds `sum >= bits` to `0` (clamping `AShr` to `bits - 1`); `known_bits` (depth 4) is exact across `1..=64` bits for `And`/`Or`/`Xor`/`Add`/`Sub`/`Mul`/`Shl`/`LShr`/`AShr`/`URem`/`ZExt`/`SExt`/`Trunc`/`Select`/`Countbits`/`UMin`; `simplify_call` matches DXIL MSB-indexed `FirstbitHi`/`FirstbitSHi` and `IMax`/`IMin`/`UMax`/`UMin` semantics; all in-place rewrites strictly decrease SSA DAG depth (no oscillation). 6. **Loop header `FACTS`:** `single_forward` skips only `b`-dominated back-edges, proving `p` strictly dominates `b` (so `c` and all `learn` operands are loop-invariant outside `b`), skips irreducible multi-entry loops, and applies `known_val` only to `body`/`term` (never `phis`). 7. **`slot_word` `mark_pure` & `dce_insts`:** `SLOT_STRIDES`/`SLOT_TABLE_STRIDES` bind the host's CPU upload buffer (`heap.strides`) as a root SRV (immutable across the entire GPU dispatch); `dce_insts` preserves all `Store`/`AtomicRmw`/`CmpXchg`, non-pure `Effect::Writes` calls, and branch conditions. 8. **Cache invalidation & policy:** `VICTORY_SHADER_OPT` default `255 -> 1279` and build-time `VICTORY_TRANSLATOR` hash both invalidate old cached DXIL cleanly; 100% title-neutral, 0 local paths, `opt.rs` is 212,254 B LF / 217,475 B CRLF (well under 655,360 B cap).
Androtim commented 2026-12-04 08:51:46 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T08:51:46Z.


Gate 2 Pure-Reasoning Re-Audit — PR #427 (perf/w10a-hwrt-cpu-prep, 4489200)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Audited delta 4823582..4489200 and full PR diff (1193611..4489200, touching crates/victory-gpu/src/hwrt.rs, crates/victory-gpu/src/hwrt/budget.rs, and crates/victory-gpu/src/hwrt/decoders.rs) against all 4 findings from comment 7405972309:

  1. [P0] GpuBlasTable desync & GPU UAF — RESOLVED

    • alloc_or_reuse_as (hwrt.rs:3141-3158) now executes before list.plane_upload (hwrt.rs:3175-3214), returning fb.readback on failure without queueing any Step::Plane.
    • Zero fallible early returns exist between list.plane_upload (hwrt.rs:3175) and list4.Dispatch(patch_groups, 1, 1) + dispatch_armed.store(true, Ordering::Release) (hwrt.rs:3277-3278).
    • dispatch_armed: Arc<AtomicBool> is checked with Ordering::Acquire at the start of the plane_upload callback (hwrt.rs:3176-3182), emitting a 16-byte mode = 0 no-op (write_noop_patch) without locking or mutating CachedBlasTable if unarmed. Also target_fill now holds Arc::clone(&dest_as) directly (safe across repeated list execution), and plane_upload failure cleanly rolls back as_map via Arc::ptr_eq.
  2. [P0] clamp_ib TOCTOU OOB reads — RESOLVED

    • should_skip_clamp_ib is completely removed; GPU clamp_ib (hwrt.rs:2877-2898) runs unconditionally on all mutable Shadow-backed standard index buffers, keeping validated_ibs strictly as a CPU scan skip for eff_vc expansion (whose expanded bounds remain verified against crate::shadow::find(vertex_buffer, exp_bytes)).
    • ValidatedIb now stores ibytes, and title_memory_freed_many (hwrt.rs:4047-4064, 4110-4111) evicts validated_ibs via exact half-open range overlap [ib_va, ib_va.saturating_add(entry.ibytes)) against joined_spans.
  3. [P1] LRU feedback phase-lock — RESOLVED

    • FEEDBACK_ACTIVE_INTERVAL = 7 and FEEDBACK_IDLE_INTERVAL = 13 (budget.rs:28-36) are odd primes coprime to 2/3/4/6.
    • should_sample_feedback (budget.rs:462-481) gates on frame.saturating_sub(last_feedback_frame) >= interval while allowing last_feedback_frame == NO_FEEDBACK_FRAME || frame == last_feedback_frame so all TLASes built on the same sampled frame report without starving alternating or offset-period TLASes.
    • record_feedback_frame (budget.rs:484-500) updates last_feedback_frame monotonically via CAS only after alloc_or_reuse_as and plane_upload succeed (hwrt.rs:3228).
  4. [P1] apply_dirty failed upsert recovery — RESOLVED

    • CachedBlasTableGeneric::apply_dirty (hwrt.rs:697-746) and rebuild (hwrt.rs:655-692) both return overflowed: bool whenever refs is uninitialized or any upsert fails.
    • fill_blas_table_patch (hwrt.rs:1640-1707) immediately falls back to rebuild_blas_table_locked when apply_dirty overflows, and if rebuilding still overflows cap, invokes self.mark_dirty_full() after updating cached.version = ver (preserving the acyclic blas_table -> dirty_blas lock order) so the next TLAS sync performs a full rebuild (with a grown cap when needed) with zero permanently lost entries.

Additional Checks

  • No new [P0]/[P1] regressions in 4489200.
  • Policy / Size / Clean-Room: Title-neutral, zero local paths, zero origin/main conflicts on touched hwrt files, and all modified files well under the 655,360 B limit (hwrt.rs: 198,132 B, budget.rs: 62,482 B, decoders.rs: 25,649 B).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7406514018 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7406514018). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T08:51:46Z. --- ## Gate 2 Pure-Reasoning Re-Audit — PR #427 (`perf/w10a-hwrt-cpu-prep`, `4489200`) **Verdict: VERIFIED CLEAN (0 P0, 0 P1)** Audited delta `4823582..4489200` and full PR diff (`1193611..4489200`, touching `crates/victory-gpu/src/hwrt.rs`, `crates/victory-gpu/src/hwrt/budget.rs`, and `crates/victory-gpu/src/hwrt/decoders.rs`) against all 4 findings from comment `7405972309`: 1. **`[P0]` `GpuBlasTable` desync & GPU UAF — RESOLVED** - `alloc_or_reuse_as` (`hwrt.rs:3141-3158`) now executes before `list.plane_upload` (`hwrt.rs:3175-3214`), returning `fb.readback` on failure without queueing any `Step::Plane`. - Zero fallible early returns exist between `list.plane_upload` (`hwrt.rs:3175`) and `list4.Dispatch(patch_groups, 1, 1)` + `dispatch_armed.store(true, Ordering::Release)` (`hwrt.rs:3277-3278`). - `dispatch_armed: Arc<AtomicBool>` is checked with `Ordering::Acquire` at the start of the `plane_upload` callback (`hwrt.rs:3176-3182`), emitting a 16-byte `mode = 0` no-op (`write_noop_patch`) without locking or mutating `CachedBlasTable` if unarmed. Also `target_fill` now holds `Arc::clone(&dest_as)` directly (safe across repeated list execution), and `plane_upload` failure cleanly rolls back `as_map` via `Arc::ptr_eq`. 2. **`[P0]` `clamp_ib` TOCTOU OOB reads — RESOLVED** - `should_skip_clamp_ib` is completely removed; GPU `clamp_ib` (`hwrt.rs:2877-2898`) runs unconditionally on all mutable `Shadow`-backed standard index buffers, keeping `validated_ibs` strictly as a CPU scan skip for `eff_vc` expansion (whose expanded bounds remain verified against `crate::shadow::find(vertex_buffer, exp_bytes)`). - `ValidatedIb` now stores `ibytes`, and `title_memory_freed_many` (`hwrt.rs:4047-4064, 4110-4111`) evicts `validated_ibs` via exact half-open range overlap `[ib_va, ib_va.saturating_add(entry.ibytes))` against `joined_spans`. 3. **`[P1]` LRU feedback phase-lock — RESOLVED** - `FEEDBACK_ACTIVE_INTERVAL = 7` and `FEEDBACK_IDLE_INTERVAL = 13` (`budget.rs:28-36`) are odd primes coprime to 2/3/4/6. - `should_sample_feedback` (`budget.rs:462-481`) gates on `frame.saturating_sub(last_feedback_frame) >= interval` while allowing `last_feedback_frame == NO_FEEDBACK_FRAME || frame == last_feedback_frame` so all TLASes built on the same sampled frame report without starving alternating or offset-period TLASes. - `record_feedback_frame` (`budget.rs:484-500`) updates `last_feedback_frame` monotonically via CAS only after `alloc_or_reuse_as` and `plane_upload` succeed (`hwrt.rs:3228`). 4. **`[P1]` `apply_dirty` failed `upsert` recovery — RESOLVED** - `CachedBlasTableGeneric::apply_dirty` (`hwrt.rs:697-746`) and `rebuild` (`hwrt.rs:655-692`) both return `overflowed: bool` whenever `refs` is uninitialized or any `upsert` fails. - `fill_blas_table_patch` (`hwrt.rs:1640-1707`) immediately falls back to `rebuild_blas_table_locked` when `apply_dirty` overflows, and if rebuilding still overflows `cap`, invokes `self.mark_dirty_full()` after updating `cached.version = ver` (preserving the acyclic `blas_table -> dirty_blas` lock order) so the next TLAS sync performs a full rebuild (with a grown `cap` when needed) with zero permanently lost entries. ### Additional Checks - **No new `[P0]`/`[P1]` regressions** in `4489200`. - **Policy / Size / Clean-Room:** Title-neutral, zero local paths, zero `origin/main` conflicts on touched `hwrt` files, and all modified files well under the `655,360 B` limit (`hwrt.rs`: `198,132 B`, `budget.rs`: `62,482 B`, `decoders.rs`: `25,649 B`).
Androtim commented 2026-12-04 09:57:36 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T09:57:36Z.


Gate 2 Adversarial Pure-Reasoning Audit — PR #429 (perf/w11a-shader-opt-m2, 2e44fc9)

Verdict: CHANGES REQUESTED — 1 [P0], 1 [P1]

Audited full PR diff origin/main...HEAD (2e44fc9, 5 touched files) and full context of bitcode.rs, opt.rs, opt/cfg.rs, opt/licm.rs, emit/mod.rs, shader.rs, hdr.rs, victory-gpu/build.rs, and shader_cache.rs via pure reasoning (zero builds/edits/runs).


Findings

  1. [P0] Cross-lane (wave*/quad*) & derivative (deriv*, unary.f32 83..=86, implicit-derivative sample*/calculateLOD*) miscompilation in coalesce_guard_diamonds

    • Location: crates/victory-shader/src/emit/bitcode/opt/cfg.rs:700-738 and 844-854
    • Root cause: coalesce_guard_diamonds only rejects dx.op.barrier and dx.op.discard* (lines 700-711). For same-guard coalescing (is_same_guard == true), there is no effect check at all on T1/T2; for complementary-guard coalescing (!is_same_guard), lines 716-738 ignore Effect::Lanes (_ => {}), ignore Attr::ReadNone derivatives (dx.op.unary.f32 opcodes 83..=86), and allow Effect::Reads implicit-derivative texture ops (sample, sampleBias, sampleCmp, calculateLOD) whenever the other branch has no Writes.
    • Concrete miscompilation:
      • Same-guard: P: CondBr(g, T1, J1) where T1 computes %v1, J1: %r1 = phi [(%v1, T1), (%x, P)] -> CondBr(g, T2, J2), and T2 runs quadReadLaneAt(%r1, 0) (or quadOp, waveReadLaneAt, unary.f32 83..=86, or sample.f32(..., %r1) with implicit 2x2 quad derivatives). Before coalescing, inactive lane 0 holds %r1 = %x at J1, and active lane 1 reads lane 0's %x. After coalescing, line 850 rewrites %r1 -> %v1 inside T2.body; lane 0 never executed T1, so lane 1 reads uninitialized/stale garbage from lane 0's %v1 instead of %x.
      • Complementary-guard: Same diamond with J1: CondBr(!g, T2, J2) where T1 is Effect::Pure and T2 calls quadReadLaneAt(%r1, 1) or sample.f32(..., %r1) (Effect::Reads). Before coalescing, lane 1 computed %v1 before J1 and lane 0 read lane 1's %v1; after coalescing, line 850 rewrites %r1 -> %x (and SIMT hardware may execute T2 before T1), so lane 0 reads lane 1's %x instead of %v1.
    • Required fix: Reject guard coalescing in cfg.rs:700-711 whenever any instruction in T1.body or T2.body is:
      • dx.op.barrier or dx.op.discard*
      • Effect::Lanes (self.class(&effects, i) == Effect::Lanes)
      • An Op::Call whose stripped dx.op. name starts with wave, quad, deriv, isHelperLane, calculateLOD, or is an implicit-derivative sample op (short.starts_with(sample) && !short.starts_with(sampleLevel) && !short.starts_with(sampleGrad) && !short.starts_with(sampleCmpLevelZero)), or short == unary.f32 with opcode 83..=86.
      • Add unit tests confirming same-guard and complementary-guard diamonds with quadReadLaneAt/waveReadLaneAt/sample.f32 in T2 are NOT coalesced.
  2. [P1] Speculative out-of-bounds constant-global Op::Load in LICM::hoist_safety

    • Location: crates/victory-shader/src/emit/bitcode/opt/licm.rs:155-175
    • Root cause: Op::Load(p) from a constant global (space == 0 && init.is_some()) is classified HoistSafety::Speculative without proving the GEP index is in-bounds. In general IR, a loop-invariant load if (idx < N) { load @lut[idx] } inside a conditional loop branch will be speculatively hoisted into the preheader and executed unconditionally even when idx >= N (LLVM UB). (Currently mitigated in translated shaders only because hdr.rs:182-184 clamps its code index with Select, making this [P1] rather than [P0].)
    • Required fix: Classify constant-global Op::Load as HoistSafety::MustExecOnly (or HoistSafety::Speculative only when every intermediate Op::Gep into TypeDef::Array(len, _) uses a constant deref 0 and constant element index < len).

Verified Clean Invariants

  • SimplifyCFG (opt/cfg.rs):
    • Transform 1 (CondBr(c, T, T) -> Br(T)): verifies PHI agreement on b before deduplicating.
    • Transform 2 (CondBr(xor(c, true), t, f)): preserves dominance, never emits pred::ONE (6).
    • Transform 3 (A -> B merge): strip_unreachable_phi_edges() runs first; checks b != a && b != 0 && preds[b] == [a] and single-value PHIs; chain resolution is acyclic and dominance-safe.
    • Transform 4 (empty guard diamond -> Select): strictly rejects dx.types.Handle and non-scalar differing PHIs; preserves SSA dominance.
    • Transform 5 (empty forwarding block bypass): forbids duplicate (v, P) PHI collision in T and forbids critical edges into loop headers, back-edges, and loop exits, preserving bitcode.rs:842-871 AMD empty-latch folding; pred_count accounting and PHI dominance are exact.
    • Transform 6 (guard coalescing, aside from [P0] #1): sign/polarity table across all 8 (same_cond/opp_cond, p1_t1, p2_t2) cases, dx.types.Handle PHI exclusion, complementary Writes vs Reads/Writes ordering, J1 PHI migration to J2 (only when preds[j2] == {j1, t2}), and j1_g2_inst hoisting to P are sound.
  • LICM (opt/licm.rs):
    • Natural loop detection, reducibility, innermost-first ordering, preheader reuse/synthesis, header PHI splitting (outside -> ph, inside + (ph_val, ph) -> h), and outer-loop block/membership updates are sound.
    • Hard deadlock invariant: Non-pure rawBufferLoad SRVs, textureLoad, sample*, and LDS/TGSM Op::Load (space == 3) are HoistSafety::Never.
    • Hard wave-uniformity invariant: createHandleFromHeap, non-binding annotateHandle, cbufferLoadLegacy, getDimensions, and pure_loads are MustExecOnly; must_exec_limit covers only the unconditional linear header prefix before any dx.op.discard or CondBr.
    • Hard trap/UB invariant (aside from [P1] #2): Shifts require const RHS < bits (MustExecOnly), UDiv/URem require const != 0 (MustExecOnly), SDiv requires const != 0 && != -1 (MustExecOnly); Effect::Lanes, wave*/quad*/deriv*/isHelperLane/unary.f32 83..=86, Op::Phi, and Effect::Writes are Never.
  • Cache key & policy: SIMPLIFY_CFG (256) and LICM (512) wired into MODULE/ALL/DEFAULT = 2047, hashed via shader_opt() + VICTORY_TRANSLATOR; 100% title-neutral, zero local paths, all 5 touched files well under the 655,360 B CRLF cap (max emit/mod.rs = 234,788 B).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7408048958 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7408048958). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T09:57:36Z. --- ### Gate 2 Adversarial Pure-Reasoning Audit — PR #429 (`perf/w11a-shader-opt-m2`, `2e44fc9`) **Verdict: CHANGES REQUESTED — 1 `[P0]`, 1 `[P1]`** Audited full PR diff `origin/main...HEAD` (`2e44fc9`, 5 touched files) and full context of `bitcode.rs`, `opt.rs`, `opt/cfg.rs`, `opt/licm.rs`, `emit/mod.rs`, `shader.rs`, `hdr.rs`, `victory-gpu/build.rs`, and `shader_cache.rs` via pure reasoning (zero builds/edits/runs). --- #### Findings 1. **`[P0]` Cross-lane (`wave*`/`quad*`) & derivative (`deriv*`, `unary.f32` 83..=86, implicit-derivative `sample*`/`calculateLOD*`) miscompilation in `coalesce_guard_diamonds`** - **Location:** `crates/victory-shader/src/emit/bitcode/opt/cfg.rs:700-738` and `844-854` - **Root cause:** `coalesce_guard_diamonds` only rejects `dx.op.barrier` and `dx.op.discard*` (lines 700-711). For same-guard coalescing (`is_same_guard == true`), there is no effect check at all on `T1`/`T2`; for complementary-guard coalescing (`!is_same_guard`), lines 716-738 ignore `Effect::Lanes` (`_ => {}`), ignore `Attr::ReadNone` derivatives (`dx.op.unary.f32` opcodes `83..=86`), and allow `Effect::Reads` implicit-derivative texture ops (`sample`, `sampleBias`, `sampleCmp`, `calculateLOD`) whenever the other branch has no `Writes`. - **Concrete miscompilation:** - *Same-guard:* `P: CondBr(g, T1, J1)` where `T1` computes `%v1`, `J1: %r1 = phi [(%v1, T1), (%x, P)]` -> `CondBr(g, T2, J2)`, and `T2` runs `quadReadLaneAt(%r1, 0)` (or `quadOp`, `waveReadLaneAt`, `unary.f32` 83..=86, or `sample.f32(..., %r1)` with implicit 2x2 quad derivatives). Before coalescing, inactive lane 0 holds `%r1 = %x` at `J1`, and active lane 1 reads lane 0's `%x`. After coalescing, line 850 rewrites `%r1 -> %v1` inside `T2.body`; lane 0 never executed `T1`, so lane 1 reads **uninitialized/stale garbage** from lane 0's `%v1` instead of `%x`. - *Complementary-guard:* Same diamond with `J1: CondBr(!g, T2, J2)` where `T1` is `Effect::Pure` and `T2` calls `quadReadLaneAt(%r1, 1)` or `sample.f32(..., %r1)` (`Effect::Reads`). Before coalescing, lane 1 computed `%v1` before `J1` and lane 0 read lane 1's `%v1`; after coalescing, line 850 rewrites `%r1 -> %x` (and SIMT hardware may execute `T2` before `T1`), so lane 0 reads lane 1's `%x` instead of `%v1`. - **Required fix:** Reject guard coalescing in `cfg.rs:700-711` whenever any instruction in `T1.body` or `T2.body` is: - `dx.op.barrier` or `dx.op.discard*` - `Effect::Lanes` (`self.class(&effects, i) == Effect::Lanes`) - An `Op::Call` whose stripped `dx.op.` name starts with `wave`, `quad`, `deriv`, `isHelperLane`, `calculateLOD`, or is an implicit-derivative sample op (`short.starts_with(sample) && !short.starts_with(sampleLevel) && !short.starts_with(sampleGrad) && !short.starts_with(sampleCmpLevelZero)`), or `short == unary.f32` with opcode `83..=86`. - Add unit tests confirming same-guard and complementary-guard diamonds with `quadReadLaneAt`/`waveReadLaneAt`/`sample.f32` in `T2` are NOT coalesced. 2. **`[P1]` Speculative out-of-bounds constant-global `Op::Load` in `LICM::hoist_safety`** - **Location:** `crates/victory-shader/src/emit/bitcode/opt/licm.rs:155-175` - **Root cause:** `Op::Load(p)` from a constant global (`space == 0 && init.is_some()`) is classified `HoistSafety::Speculative` without proving the GEP index is in-bounds. In general IR, a loop-invariant load `if (idx < N) { load @lut[idx] }` inside a conditional loop branch will be speculatively hoisted into the preheader and executed unconditionally even when `idx >= N` (LLVM UB). (Currently mitigated in translated shaders only because `hdr.rs:182-184` clamps its `code` index with `Select`, making this `[P1]` rather than `[P0]`.) - **Required fix:** Classify constant-global `Op::Load` as `HoistSafety::MustExecOnly` (or `HoistSafety::Speculative` only when every intermediate `Op::Gep` into `TypeDef::Array(len, _)` uses a constant deref `0` and constant element index `< len`). --- #### Verified Clean Invariants - **`SimplifyCFG` (`opt/cfg.rs`):** - Transform 1 (`CondBr(c, T, T) -> Br(T)`): verifies PHI agreement on `b` before deduplicating. - Transform 2 (`CondBr(xor(c, true), t, f)`): preserves dominance, never emits `pred::ONE (6)`. - Transform 3 (`A -> B` merge): `strip_unreachable_phi_edges()` runs first; checks `b != a && b != 0 && preds[b] == [a]` and single-value PHIs; chain resolution is acyclic and dominance-safe. - Transform 4 (empty guard diamond -> `Select`): strictly rejects `dx.types.Handle` and non-scalar differing PHIs; preserves SSA dominance. - Transform 5 (empty forwarding block bypass): forbids duplicate `(v, P)` PHI collision in `T` and forbids critical edges into loop headers, back-edges, and loop exits, preserving `bitcode.rs:842-871` AMD empty-latch folding; `pred_count` accounting and PHI dominance are exact. - Transform 6 (guard coalescing, aside from `[P0]` #1): sign/polarity table across all 8 `(same_cond/opp_cond, p1_t1, p2_t2)` cases, `dx.types.Handle` PHI exclusion, complementary `Writes` vs `Reads`/`Writes` ordering, `J1` PHI migration to `J2` (only when `preds[j2] == {j1, t2}`), and `j1_g2_inst` hoisting to `P` are sound. - **`LICM` (`opt/licm.rs`):** - Natural loop detection, reducibility, innermost-first ordering, preheader reuse/synthesis, header PHI splitting (outside -> `ph`, inside + `(ph_val, ph)` -> `h`), and outer-loop block/membership updates are sound. - **Hard deadlock invariant:** Non-pure `rawBufferLoad` SRVs, `textureLoad`, `sample*`, and LDS/TGSM `Op::Load` (`space == 3`) are `HoistSafety::Never`. - **Hard wave-uniformity invariant:** `createHandleFromHeap`, non-binding `annotateHandle`, `cbufferLoadLegacy`, `getDimensions`, and `pure_loads` are `MustExecOnly`; `must_exec_limit` covers only the unconditional linear header prefix before any `dx.op.discard` or `CondBr`. - **Hard trap/UB invariant (aside from `[P1]` #2):** Shifts require const RHS `< bits` (`MustExecOnly`), `UDiv`/`URem` require const `!= 0` (`MustExecOnly`), `SDiv` requires const `!= 0 && != -1` (`MustExecOnly`); `Effect::Lanes`, `wave*`/`quad*`/`deriv*`/`isHelperLane`/`unary.f32` 83..=86, `Op::Phi`, and `Effect::Writes` are `Never`. - **Cache key & policy:** `SIMPLIFY_CFG (256)` and `LICM (512)` wired into `MODULE`/`ALL`/`DEFAULT = 2047`, hashed via `shader_opt()` + `VICTORY_TRANSLATOR`; 100% title-neutral, zero local paths, all 5 touched files well under the 655,360 B CRLF cap (max `emit/mod.rs` = 234,788 B).
Androtim commented 2026-12-04 10:12:33 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T10:12:33Z.


Gate 2 Adversarial Pure-Reasoning Audit — PR #430 (fix/w11c-flicker-ambient, 6eb80e0)

Verdict: BLOCKED — 3 [P0], 3 [P1]

Clean / Verified Areas

  • VICTORY_OCCLUSION_FAR (descriptor/host.rs:1125-1244, 1344-1360, resource.rs:1931-1946): Clean. ResourceDesc layout is statically asserted (56 B = 14 u32), 128x72 R32_FLOAT (512 B 256-byte-aligned row pitch, 36 KiB single OnceLock allocation on DEFAULT heap via synchronous COPY queue decay back to COMMON) matches make_neutral lifetime/lock ordering, never replaces real uploaded textures (neutral_for only runs on pending/unlanded/evicted slots), and host-filled targets are excluded by waits_gray (title_fills).
  • VICTORY_PLACED_BY_VIEW (descriptor/host.rs:6836-6878, 7793-7800): Clean. Both buffer_extent and make_twinned_res agree on placed_width(view) when resource width is 0.
  • ambient.rs HLSL & dispatch (CELL_BYTES, RS_STENCIL, place_stencil, gather_stencil, mean, clear_air, bound_alpha): Clean internally. CELL_BYTES matches INT_MEAN_IDX/INT_META_IDX, RS_STENCIL root params 0..=5 match after() and cleanly rebind &pass.root before raise, gather_stencil groupshared barriers are unconditional, VICTORY_HW_RT=1 (!hwrt_active) gating is untouched, and VICTORY_AMBIENT_ALPHA non-stencil fallback is preserved.
  • ds_hold lock ordering: Deadlock-free (PENDING, RECENT_WRITES, HOLDS, SHORT are never nested).
  • Policy & Clean-Room: 100% title-neutral, proper GPL-3.0 attribution (ReTerryDavis/ReVIctory cac3d3c), all Rust files comfortably under 655,360 B CRLF (host.rs: 649,393 B; descriptor/host.rs: 587,468 B).

[P0] Findings (Must Fix Before Merge)

  1. [P0] Out-of-bounds dynamic snapshot handle & unmirrored slot in stencil fallback scan — crates/victory-gpu/src/draw.rs:4792-4818

    • When from_used returns None, the fallback scans offset in (0..1600u32).step_by(8) (slots 0..200) in title table 0 and computes heap.gpu_handle((start + offset * 4) / 32) where start comes from self.ambient_tables.iter().find(|m| m.0 == 0).
    • self.ambient_tables holds the dynamic snapshot base first * 32 of length ONLY n = (group.max_dword / 8) + 1 (and with VICTORY_SNAPSHOT_UAV_TABLES on by default, table 0 is snapshotted whenever it has a CBV or UAV). If the stencil view sits at offset / 8 >= n, (start + offset * 4) / 32 = first + offset / 8 reads past the end of the snapshot — binding either an unrelated draw's descriptor (CBV/UAV/float SRV/uninitialized) or a GPU handle past the end of the D3D12 descriptor heap (gpu_handle has no bounds check) -> D3D12 validation error / TDR / Device Removed.
    • Even when table 0 is not snapshotted, slots outside t.used were never mirrored into the host descriptor heap by table_entry(), so the host slot can be null or stale.
    • Required fix: Resolve the bound title heap (crate::descriptor::heap(self.heaps[0] as This)), verify let Some(index) = title_heap.index(table + u64::from(offset) * 4) else { continue }; (in-bounds of the bound heap's mirrored title region [0..host.count()), never offsetting off a dynamic snapshot), explicitly mirror that slot into the host heap (heap.mirror_for_table_with(index, table + u64::from(offset) * 4, |_| {}) / heap.mirror) and verify it is non-null before returning heap.gpu_handle(index).
  2. [P0] Overly broad stencil_view predicate can bind non-uint2 / non-Texture2D / MSAA SRVs to Texture2D<uint2> stencil_tex : register(t1) — crates/victory-gpu/src/draw.rs:4547-4555, 4783-4818

    • stencil_view() (matches!(pc_format(d[0]), 22 | 47) || (d[1] == 4 && d[6] == 1)) was written as a depth-exclusion filter, not a strict Texture2D<uint2> inclusion check:
      • d[1] == 4 && d[6] == 1 matches non-UINT planar plane-1 SRVs (e.g., NV12/P010 UNORM chroma planes).
      • matches!(pc_format(d[0]), 22 | 47) does not check d[1] == 4 (D3D12_SRV_DIMENSION_TEXTURE2D), allowing TEXTURE2DARRAY (5) or TEXTURE2DMS (6) SRVs whose underlying ID3D12Resource still reports D3D12_RESOURCE_DIMENSION_TEXTURE2D.
      • Neither from_used (which omits d.Dimension altogether at :4790) nor the fallback checks d.SampleDesc.Count == 1 or that the host resource format has a stencil plane (R32G8X24_TYPELESS, D32_FLOAT_S8X24_UINT, R24G8_TYPELESS, D24_UNORM_S8_UINT).
    • Binding any mismatched format/dimension/MSAA SRV to Texture2D<uint2> triggers D3D12 validation errors and/or Device Removed.
    • Required fix: Use a dedicated strict inclusion predicate for Role::Resolve stencil selection requiring View::Shader(_, Some(d)) (after placed_texture) with d[1] == 4 (TEXTURE2D) AND matches!(crate::resource::pc_format(d[0]), 22 | 47), AND require on the host resource d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && d.SampleDesc.Count == 1 && d.Width == seen.Width && d.Height == seen.Height && matches!(d.Format, DXGI_FORMAT_R32G8X24_TYPELESS | DXGI_FORMAT_D32_FLOAT_S8X24_UINT | DXGI_FORMAT_R24G8_TYPELESS | DXGI_FORMAT_D24_UNORM_S8_UINT) in both from_used and the fallback.
  3. [P0] prepare_prelude_upload uploads unpopulated all-zero CpuStaging on first upload when VICTORY_COMING_WAITS defers refresh() — crates/victory-gpu/src/texture.rs:2553-2566

    • When VICTORY_COMING_WAITS defers a refresh on a new texture (self.uploaded == false), it returns 0 without calling detile(), leaving guard.cpu().is_populated() == false. On the ahead path, texture/ahead.rs:395,471 skips recording and falls back to ahead = LISTED (prelude upload).
    • When that unuploaded texture enters prepare_prelude_upload (texture.rs:2554-2565) and self.refresh() defers again, line 2557 checks if self.uploaded.load(Acquire) && !guard.cpu().is_populated() — which is false because self.uploaded == false. Execution proceeds to claim_upload, sets self.uploaded = true and self.dirty = false, and copies the unpopulated all-zero staging buffer into VRAM (corrupting/blacking out the texture).
    • Required fix: Guard prepare_prelude_upload (texture.rs:2557) on !guard.cpu().is_populated() regardless of self.uploaded (abort and return None without calling claim_upload whenever refresh() left CpuStaging unpopulated).

[P1] Findings (Should Fix Before Merge)

  1. [P1] ds_hold::RECENT_WRITES ring overflow check under-counts multi-range PAGE_DESTINATION writes — crates/victory-gpu/src/ds_hold.rs:105-116, 157-166

    • register_at increments WRITE_SEQ by 1 per call but pushes one ring slot per non-empty range into the 64-entry RECENT_WRITES ring. dstorage.rs:1717-1724 (PAGE_DESTINATION) passes shown_at(&pages, ...), which frequently contains dozens to >64 scattered page ranges. A single >64-range request (or a few multi-range requests) wraps RECENT_WRITES while current.saturating_sub(before) <= 64, silently bypassing the overflow guard at ds_hold.rs:161 and missing racing writes.
    • Required fix: Advance WRITE_SEQ by the exact number of non-empty ranges written (under the RECENT_WRITES lock so sequence numbers and ring slots advance in lockstep, storing base + 1 + idx per slot).
  2. [P1] read_short (SHORT_IN_A_ROW = 8) is never reset on normal refreshes and is double-counted on deferred ahead uploads — crates/victory-gpu/src/texture.rs:2036-2056, 2283-2383, crates/victory-gpu/src/descriptor/host.rs:1463-1481, crates/victory-gpu/src/texture/ahead.rs:472

    • VICTORY_COMING_WAITS calls read_short(start) on every deferred refresh, and texture/ahead.rs:472 calls read_short a second time for the same deferred job (+2 per deferred ahead upload). Meanwhile read_all(start) is ONLY called in Staging::fill (texture.rs:2391), never on normal successful refreshes.
    • After 4 deferred ahead uploads (or 8 total deferrals on a reused streaming-pool address over a session), SHORT.1[start] permanently exceeds SHORT_IN_A_ROW (8) and stops re-queueing start, leaving textures permanently stuck grey/unuploaded.
    • Required fix: Call read_all(start) on normal successful (non-raced) refreshes (gated by a lock-free AtomicUsize count of SHORT.1 so the common path takes no lock), and avoid double-incrementing SHORT.1 between texture.rs and texture/ahead.rs:472.
  3. [P1] In-place detile(tiled) reads live self.memory after raced_coming, and refresh_exact_unlocked returns size on race — crates/victory-gpu/src/texture.rs:2233-2247, 2145-2151, 2332-2337

    • On the in-place committed path (texture.rs:2233-2247), raced_coming(last) runs after digest(tiled) but before self.detile(tiled) reads self.memory a second time without a private scratch copy. A streaming write starting during detile writes torn bytes into CpuStaging and commits last.hash with no retry.
    • On race in refresh_exact_unlocked (texture.rs:2336), returning Some(false) causes refresh_timed (texture.rs:2145-2151) to return size instead of 0.
    • Required fix: Re-check raced_coming(last) after self.detile(tiled) (or copy into scratch when ds_hold::coming_waits() is enabled / clear last.hash and mark cpu unpopulated if raced during detile), and return 0 from refresh_timed when refresh_exact_unlocked defers on a race.
<!-- greyfinch-sync:Androtim/MiniVI:comment:7408385417 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7408385417). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T10:12:33Z. --- ## Gate 2 Adversarial Pure-Reasoning Audit — PR #430 (`fix/w11c-flicker-ambient`, `6eb80e0`) **Verdict: BLOCKED — 3 `[P0]`, 3 `[P1]`** ### Clean / Verified Areas - **`VICTORY_OCCLUSION_FAR` (`descriptor/host.rs:1125-1244, 1344-1360`, `resource.rs:1931-1946`)**: Clean. `ResourceDesc` layout is statically asserted (`56 B = 14 u32`), `128x72` `R32_FLOAT` (`512 B` 256-byte-aligned row pitch, `36 KiB` single `OnceLock` allocation on `DEFAULT` heap via synchronous `COPY` queue decay back to `COMMON`) matches `make_neutral` lifetime/lock ordering, never replaces real uploaded textures (`neutral_for` only runs on pending/unlanded/evicted slots), and host-filled targets are excluded by `waits_gray` (`title_fills`). - **`VICTORY_PLACED_BY_VIEW` (`descriptor/host.rs:6836-6878, 7793-7800`)**: Clean. Both `buffer_extent` and `make_twinned_res` agree on `placed_width(view)` when resource width is `0`. - **`ambient.rs` HLSL & dispatch (`CELL_BYTES`, `RS_STENCIL`, `place_stencil`, `gather_stencil`, `mean`, `clear_air`, `bound_alpha`)**: Clean internally. `CELL_BYTES` matches `INT_MEAN_IDX`/`INT_META_IDX`, `RS_STENCIL` root params `0..=5` match `after()` and cleanly rebind `&pass.root` before `raise`, `gather_stencil` groupshared barriers are unconditional, `VICTORY_HW_RT=1` (`!hwrt_active`) gating is untouched, and `VICTORY_AMBIENT_ALPHA` non-stencil fallback is preserved. - **`ds_hold` lock ordering**: Deadlock-free (`PENDING`, `RECENT_WRITES`, `HOLDS`, `SHORT` are never nested). - **Policy & Clean-Room**: 100% title-neutral, proper `GPL-3.0` attribution (`ReTerryDavis/ReVIctory` `cac3d3c`), all Rust files comfortably under `655,360 B` CRLF (`host.rs`: `649,393 B`; `descriptor/host.rs`: `587,468 B`). --- ### `[P0]` Findings (Must Fix Before Merge) 1. **`[P0]` Out-of-bounds dynamic snapshot handle & unmirrored slot in stencil fallback scan — `crates/victory-gpu/src/draw.rs:4792-4818`** - When `from_used` returns `None`, the fallback scans `offset in (0..1600u32).step_by(8)` (slots `0..200`) in title table `0` and computes `heap.gpu_handle((start + offset * 4) / 32)` where `start` comes from `self.ambient_tables.iter().find(|m| m.0 == 0)`. - `self.ambient_tables` holds the dynamic snapshot base `first * 32` of length ONLY `n = (group.max_dword / 8) + 1` (and with `VICTORY_SNAPSHOT_UAV_TABLES` on by default, table `0` is snapshotted whenever it has a CBV or UAV). If the stencil view sits at `offset / 8 >= n`, `(start + offset * 4) / 32 = first + offset / 8` reads **past the end of the snapshot** — binding either an unrelated draw's descriptor (CBV/UAV/float SRV/uninitialized) or a GPU handle **past the end of the D3D12 descriptor heap** (`gpu_handle` has no bounds check) -> D3D12 validation error / TDR / Device Removed. - Even when table `0` is not snapshotted, slots outside `t.used` were never mirrored into the host descriptor heap by `table_entry()`, so the host slot can be null or stale. - **Required fix:** Resolve the bound title heap (`crate::descriptor::heap(self.heaps[0] as This)`), verify `let Some(index) = title_heap.index(table + u64::from(offset) * 4) else { continue };` (in-bounds of the bound heap's mirrored title region `[0..host.count())`, never offsetting off a dynamic snapshot), explicitly mirror that slot into the host heap (`heap.mirror_for_table_with(index, table + u64::from(offset) * 4, |_| {})` / `heap.mirror`) and verify it is non-null before returning `heap.gpu_handle(index)`. 2. **`[P0]` Overly broad `stencil_view` predicate can bind non-`uint2` / non-`Texture2D` / MSAA SRVs to `Texture2D<uint2> stencil_tex : register(t1)` — `crates/victory-gpu/src/draw.rs:4547-4555, 4783-4818`** - `stencil_view()` (`matches!(pc_format(d[0]), 22 | 47) || (d[1] == 4 && d[6] == 1)`) was written as a depth-*exclusion* filter, not a strict `Texture2D<uint2>` inclusion check: - `d[1] == 4 && d[6] == 1` matches non-UINT planar plane-1 SRVs (e.g., `NV12`/`P010` UNORM chroma planes). - `matches!(pc_format(d[0]), 22 | 47)` does **not** check `d[1] == 4` (`D3D12_SRV_DIMENSION_TEXTURE2D`), allowing `TEXTURE2DARRAY` (`5`) or `TEXTURE2DMS` (`6`) SRVs whose underlying `ID3D12Resource` still reports `D3D12_RESOURCE_DIMENSION_TEXTURE2D`. - Neither `from_used` (which omits `d.Dimension` altogether at `:4790`) nor the fallback checks `d.SampleDesc.Count == 1` or that the host resource format has a stencil plane (`R32G8X24_TYPELESS`, `D32_FLOAT_S8X24_UINT`, `R24G8_TYPELESS`, `D24_UNORM_S8_UINT`). - Binding any mismatched format/dimension/MSAA SRV to `Texture2D<uint2>` triggers D3D12 validation errors and/or Device Removed. - **Required fix:** Use a dedicated strict inclusion predicate for `Role::Resolve` stencil selection requiring `View::Shader(_, Some(d))` (after `placed_texture`) with `d[1] == 4` (`TEXTURE2D`) AND `matches!(crate::resource::pc_format(d[0]), 22 | 47)`, AND require on the host resource `d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && d.SampleDesc.Count == 1 && d.Width == seen.Width && d.Height == seen.Height && matches!(d.Format, DXGI_FORMAT_R32G8X24_TYPELESS | DXGI_FORMAT_D32_FLOAT_S8X24_UINT | DXGI_FORMAT_R24G8_TYPELESS | DXGI_FORMAT_D24_UNORM_S8_UINT)` in both `from_used` and the fallback. 3. **`[P0]` `prepare_prelude_upload` uploads unpopulated all-zero `CpuStaging` on first upload when `VICTORY_COMING_WAITS` defers `refresh()` — `crates/victory-gpu/src/texture.rs:2553-2566`** - When `VICTORY_COMING_WAITS` defers a refresh on a new texture (`self.uploaded == false`), it returns `0` without calling `detile()`, leaving `guard.cpu().is_populated() == false`. On the ahead path, `texture/ahead.rs:395,471` skips recording and falls back to `ahead = LISTED` (prelude upload). - When that unuploaded texture enters `prepare_prelude_upload` (`texture.rs:2554-2565`) and `self.refresh()` defers again, line `2557` checks `if self.uploaded.load(Acquire) && !guard.cpu().is_populated()` — which is **false** because `self.uploaded == false`. Execution proceeds to `claim_upload`, sets `self.uploaded = true` and `self.dirty = false`, and copies the **unpopulated all-zero staging buffer** into VRAM (corrupting/blacking out the texture). - **Required fix:** Guard `prepare_prelude_upload` (`texture.rs:2557`) on `!guard.cpu().is_populated()` regardless of `self.uploaded` (abort and return `None` without calling `claim_upload` whenever `refresh()` left `CpuStaging` unpopulated). --- ### `[P1]` Findings (Should Fix Before Merge) 4. **`[P1]` `ds_hold::RECENT_WRITES` ring overflow check under-counts multi-range `PAGE_DESTINATION` writes — `crates/victory-gpu/src/ds_hold.rs:105-116, 157-166`** - `register_at` increments `WRITE_SEQ` by `1` per call but pushes **one ring slot per non-empty range** into the 64-entry `RECENT_WRITES` ring. `dstorage.rs:1717-1724` (`PAGE_DESTINATION`) passes `shown_at(&pages, ...)`, which frequently contains dozens to >64 scattered page ranges. A single >64-range request (or a few multi-range requests) wraps `RECENT_WRITES` while `current.saturating_sub(before) <= 64`, silently bypassing the overflow guard at `ds_hold.rs:161` and missing racing writes. - **Required fix:** Advance `WRITE_SEQ` by the exact number of non-empty ranges written (under the `RECENT_WRITES` lock so sequence numbers and ring slots advance in lockstep, storing `base + 1 + idx` per slot). 5. **`[P1]` `read_short` (`SHORT_IN_A_ROW = 8`) is never reset on normal refreshes and is double-counted on deferred `ahead` uploads — `crates/victory-gpu/src/texture.rs:2036-2056, 2283-2383`, `crates/victory-gpu/src/descriptor/host.rs:1463-1481`, `crates/victory-gpu/src/texture/ahead.rs:472`** - `VICTORY_COMING_WAITS` calls `read_short(start)` on every deferred refresh, and `texture/ahead.rs:472` calls `read_short` a second time for the same deferred job (+2 per deferred ahead upload). Meanwhile `read_all(start)` is ONLY called in `Staging::fill` (`texture.rs:2391`), never on normal successful refreshes. - After 4 deferred ahead uploads (or 8 total deferrals on a reused streaming-pool address over a session), `SHORT.1[start]` permanently exceeds `SHORT_IN_A_ROW (8)` and stops re-queueing `start`, leaving textures permanently stuck grey/unuploaded. - **Required fix:** Call `read_all(start)` on normal successful (non-raced) refreshes (gated by a lock-free `AtomicUsize` count of `SHORT.1` so the common path takes no lock), and avoid double-incrementing `SHORT.1` between `texture.rs` and `texture/ahead.rs:472`. 6. **`[P1]` In-place `detile(tiled)` reads live `self.memory` after `raced_coming`, and `refresh_exact_unlocked` returns `size` on race — `crates/victory-gpu/src/texture.rs:2233-2247, 2145-2151, 2332-2337`** - On the in-place committed path (`texture.rs:2233-2247`), `raced_coming(last)` runs after `digest(tiled)` but **before** `self.detile(tiled)` reads `self.memory` a second time without a private scratch copy. A streaming write starting during `detile` writes torn bytes into `CpuStaging` and commits `last.hash` with no retry. - On race in `refresh_exact_unlocked` (`texture.rs:2336`), returning `Some(false)` causes `refresh_timed` (`texture.rs:2145-2151`) to return `size` instead of `0`. - **Required fix:** Re-check `raced_coming(last)` after `self.detile(tiled)` (or copy into scratch when `ds_hold::coming_waits()` is enabled / clear `last.hash` and mark `cpu` unpopulated if raced during `detile`), and return `0` from `refresh_timed` when `refresh_exact_unlocked` defers on a race.
Androtim commented 2026-12-04 10:15:14 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T10:15:14Z.


Gate 2 Pure-Reasoning Re-Audit — PR #429 (perf/w11a-shader-opt-m2, dd6b2f0)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Re-audited delta 2e44fc9..dd6b2f0 (merge 457db7b + fix dd6b2f0) and full origin/main..dd6b2f0 (6c9e70c..dd6b2f0, 5 touched files in crates/victory-shader) via pure reasoning (zero builds, zero edits, zero GPU runs).

Prior Findings Resolution (ref: comment 7408048958)

  1. [P0] Guard diamond coalescing cross-lane & derivative safety — RESOLVED
    • crates/victory-shader/src/emit/bitcode/opt/cfg.rs:40-67 (blocks_guard_coalescing) and 722-732 (coalesce_guard_diamonds):
      • Rejects coalescing unconditionally (for both same-guard and complementary-guard diamonds, checking both T1.body and T2.body; J1.body can only be empty or a single Op::Cmp/Op::Bin(Bin::Xor)).
      • Blocks Effect::Lanes, barrier, discard*, wave*, quad*, deriv*, isHelperLane*, calculateLOD*, implicit-derivative sample* (everything except sampleLevel*, sampleGrad*, sampleCmpLevelZero*), and unary.f32 opcodes 83..=86 (DerivCoarseX/Y, DerivFineX/Y). Verified against all dx.op.* intrinsics emitted in crates/victory-shader/src/emit/ (including lower.rs and lower/image.rs; no unary.f16 exists).
      • Unit test simplify_cfg_skips_coalescing_cross_lane_wave_quad_and_implicit_deriv_sample_ops (cfg.rs:1391-1510) verifies rejection for both same_guard = true and same_guard = false across quadReadLaneAt.i32, waveReadLaneAt.i32, sample.f32, unary.f32 (83), calculateLOD, and isHelperLane with a pure T1, plus a positive control confirming explicit-LOD dx.op.sampleLevel.f32 still coalesces in both polarities.
  2. [P1] Speculative constant-global Op::Load in LICM — RESOLVED
    • crates/victory-shader/src/emit/bitcode/opt/licm.rs:166-177 (hoist_safety):
      • Reclassified constant-global Op::Load (space == 0 && init.is_some()) from HoistSafety::Speculative to HoistSafety::MustExecOnly, restricting hoisting strictly to pos < must_exec_limit (unconditional linear header prefix before any discard or CondBr). Confirmed Op::Gep encodes non-inbounds (flag = 0 in bitcode.rs:991), so hoisting GEP alone cannot cause UB.
      • Unit test licm_constant_global_load_hoists_from_must_exec_but_not_cond_branch (licm.rs:1058-1128) verifies must_exec header LUT load hoists into entry while guarded conditional LUT load stays in cond_then.

Merge & Regression Check

  • Clean merge with origin/main (6c9e70c is a direct ancestor via 457db7b, zero conflict diffs on PR files, origin/main..dd6b2f0 touches only the 5 expected victory-shader files; 6c9e70c's lower.rs conditional export discard is orthogonal and respected by both cfg.rs and licm.rs).
  • Zero new [P0] or [P1] regressions introduced in dd6b2f0; file sizes well below the 655,360 B CRLF cap (cfg.rs 65,322 B, licm.rs 46,538 B).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7408448066 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7408448066). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T10:15:14Z. --- ### Gate 2 Pure-Reasoning Re-Audit — PR #429 (`perf/w11a-shader-opt-m2`, `dd6b2f0`) **Verdict: VERIFIED CLEAN (0 P0, 0 P1)** Re-audited delta `2e44fc9..dd6b2f0` (merge `457db7b` + fix `dd6b2f0`) and full `origin/main..dd6b2f0` (`6c9e70c..dd6b2f0`, 5 touched files in `crates/victory-shader`) via pure reasoning (zero builds, zero edits, zero GPU runs). #### Prior Findings Resolution (ref: comment `7408048958`) 1. **`[P0]` Guard diamond coalescing cross-lane & derivative safety — RESOLVED** - `crates/victory-shader/src/emit/bitcode/opt/cfg.rs:40-67` (`blocks_guard_coalescing`) and `722-732` (`coalesce_guard_diamonds`): - Rejects coalescing unconditionally (for both same-guard and complementary-guard diamonds, checking both `T1.body` and `T2.body`; `J1.body` can only be empty or a single `Op::Cmp`/`Op::Bin(Bin::Xor)`). - Blocks `Effect::Lanes`, `barrier`, `discard*`, `wave*`, `quad*`, `deriv*`, `isHelperLane*`, `calculateLOD*`, implicit-derivative `sample*` (everything except `sampleLevel*`, `sampleGrad*`, `sampleCmpLevelZero*`), and `unary.f32` opcodes `83..=86` (`DerivCoarseX/Y`, `DerivFineX/Y`). Verified against all `dx.op.*` intrinsics emitted in `crates/victory-shader/src/emit/` (including `lower.rs` and `lower/image.rs`; no `unary.f16` exists). - Unit test `simplify_cfg_skips_coalescing_cross_lane_wave_quad_and_implicit_deriv_sample_ops` (`cfg.rs:1391-1510`) verifies rejection for both `same_guard = true` and `same_guard = false` across `quadReadLaneAt.i32`, `waveReadLaneAt.i32`, `sample.f32`, `unary.f32` (83), `calculateLOD`, and `isHelperLane` with a pure `T1`, plus a positive control confirming explicit-LOD `dx.op.sampleLevel.f32` still coalesces in both polarities. 2. **`[P1]` Speculative constant-global `Op::Load` in LICM — RESOLVED** - `crates/victory-shader/src/emit/bitcode/opt/licm.rs:166-177` (`hoist_safety`): - Reclassified constant-global `Op::Load` (`space == 0 && init.is_some()`) from `HoistSafety::Speculative` to `HoistSafety::MustExecOnly`, restricting hoisting strictly to `pos < must_exec_limit` (unconditional linear header prefix before any `discard` or `CondBr`). Confirmed `Op::Gep` encodes non-`inbounds` (`flag = 0` in `bitcode.rs:991`), so hoisting GEP alone cannot cause UB. - Unit test `licm_constant_global_load_hoists_from_must_exec_but_not_cond_branch` (`licm.rs:1058-1128`) verifies `must_exec` header LUT load hoists into `entry` while guarded conditional LUT load stays in `cond_then`. #### Merge & Regression Check - Clean merge with `origin/main` (`6c9e70c` is a direct ancestor via `457db7b`, zero conflict diffs on PR files, `origin/main..dd6b2f0` touches only the 5 expected `victory-shader` files; `6c9e70c`'s `lower.rs` conditional export `discard` is orthogonal and respected by both `cfg.rs` and `licm.rs`). - Zero new `[P0]` or `[P1]` regressions introduced in `dd6b2f0`; file sizes well below the 655,360 B CRLF cap (`cfg.rs` 65,322 B, `licm.rs` 46,538 B).
Androtim commented 2026-12-04 10:44:58 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T10:44:58Z.


Gate 2 Pure-Reasoning Re-Audit — PR #430 (fix/w11c-flicker-ambient, 88fe4d2)

Verdict: VERIFIED CLEAN (0 P0, 0 P1)

Inspected fix delta 6eb80e0..47cc44a, merge commit 88fe4d2 (clean merge of origin/main dc55250, zero conflict edits in victory-gpu), and full PR diff origin/main..88fe4d2 by pure reasoning only (no builds, edits, or GPU runs).

Verification of All 6 Findings from Comment 7408385417

  1. [P0] Stencil fallback OOB dynamic snapshot handle & unmirrored slot (crates/victory-gpu/src/draw.rs:4492-4498, 4801-4833) — FIXED

    • Resolves title_heap via crate::descriptor::heap(self.heaps[0] as This) and heap = title_heap.host()?.
    • Fallback computes slot_handle = table + u64::from(offset) * 4 and validates title_heap.index(slot_handle).filter(|&i| i < heap.count()), eliminating all dynamic snapshot offsetting (self.ambient_tables) and heap OOB risk.
    • Explicitly mirrors the slot via heap.mirror_for_table_with(index, slot_handle, |_| ()) (skipping on None) and verifies handle.ptr != 0 before returning heap.gpu_handle(index).
  2. [P0] Strict Role::Resolve stencil predicates (crates/victory-gpu/src/draw.rs:4787-4820, 7109-7137, 7187-7256) — FIXED

    • is_resolve_stencil_view resolves placed_texture and strictly requires View::Shader(_, Some(d)) with d[1] == 4 (TEXTURE2D) AND matches!(crate::resource::pc_format(d[0]), 22 | 47).
    • is_resolve_stencil_resource strictly requires D3D12_RESOURCE_DIMENSION_TEXTURE2D, SampleDesc.Count == 1, Width == width && Height == height, and stencil-bearing DXGI format (R32G8X24_TYPELESS | D32_FLOAT_S8X24_UINT | R24G8_TYPELESS | D24_UNORM_S8_UINT).
    • Enforced identically in both from_used and the table-0 fallback, with unit test coverage (resolve_stencil_view_and_resource_predicates_are_strict).
  3. [P0] prepare_prelude_upload all-zero unpopulated CpuStaging (crates/victory-gpu/src/texture.rs:2576-2598, crates/victory-gpu/src/texture_detile_tests.rs:612-669) — FIXED

    • Unconditionally guards on if !guard.cpu().is_populated() { drop(guard); return None; } regardless of self.uploaded, preventing claim_upload (uploaded = true, dirty = false) or copying unpopulated zero staging on deferred first uploads.
    • Covered by first_upload_prelude_aborts_when_coming_write_defers_refresh.
  4. [P1] ds_hold::RECENT_WRITES multi-range sequence overflow (crates/victory-gpu/src/ds_hold.rs:105-124, 158-177, 350-377) — FIXED

    • register_at acquires RECENT_WRITES (strictly after dropping PENDING, preserving deadlock-free lock ordering), assigns seq = base + 1 + written for each non-empty range, and publishes WRITE_SEQ.store(base + written, Release) under the lock.
    • active_or_raced_since_at checks > 64 both lock-free and again under RECENT_WRITES lock so multi-range PAGE_DESTINATION wraps are never missed.
    • Covered by multi_range_register_advances_seq_per_non_empty_range_and_detects_ring_overflow.
  5. [P1] read_short reset & no double-count (crates/victory-gpu/src/descriptor/host.rs:1460-1488, 13271-13316, crates/victory-gpu/src/texture.rs:1972-2426, crates/victory-gpu/src/texture/ahead.rs:68, 222, 392-400, 475-478, 519-522) — FIXED

    • SHORT_TRACKED: AtomicUsize tracks SHORT.1.len() under SHORT lock (Release), giving read_all a lock-free Acquire fast path when empty and clearing both SHORT.1 and SHORT.0 when tracked.
    • read_all(start) is called on all normal successful (non-raced, non-all-zero) refresh paths (writes_since, !committed, through_copy, in-place committed, refresh_unlocked, refresh_exact_unlocked, fill).
    • Staging::refresh_noted_short() propagates whether read_short was already invoked into Job::short_noted, preventing double-increment in ahead::finish() (both skipped-record and failure paths).
    • Covered by read_short_caps_at_short_in_a_row_and_read_all_resets_tracking.
  6. [P1] In-place detile race re-check & refresh_timed return 0 on race (crates/victory-gpu/src/texture.rs:2154-2164, 2261-2268, 2333-2371, 2785-2789) — FIXED

    • On the in-place committed path, raced_coming(last) is re-checked after self.detile(tiled), clearing last.hash = None and cpu.populated.store(false, Release) and returning (0, true) if a streaming write raced during detile.
    • refresh_exact_unlocked returns ExactUnlocked::{Read { changed }, Raced, Missing}, and refresh_timed returns (0, true) on ExactUnlocked::Raced.

Regressions, Policy & File-Size Check

  • New [P0]/[P1] regressions in 88fe4d2: None (0 P0, 0 P1).
  • Non-blocking [P2] note: In crates/victory-gpu/src/texture.rs:2044-2050, let coming_before = crate::ds_hold::write_seq(); runs immediately after ds_hold::active(start, end). Moving write_seq() above active(start, end) would close the ~2-instruction preemption window between active() == false and write_seq() (pure polish, non-blocking).
  • Clean-room / Attribution: Title-neutral throughout, proper GPL-3.0 attribution (ReTerryDavis/ReVIctory).
  • Rust file size limit (< 655,360 B CRLF): PASS — largest in repo is crates/victory-gpu/src/host.rs (649,399 B CRLF, untouched); largest modified in PR #430 is crates/victory-gpu/src/descriptor/host.rs (589,862 B CRLF).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7409140143 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7409140143). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T10:44:58Z. --- ## Gate 2 Pure-Reasoning Re-Audit — PR #430 (`fix/w11c-flicker-ambient`, `88fe4d2`) **Verdict: `VERIFIED CLEAN (0 P0, 0 P1)`** Inspected fix delta `6eb80e0..47cc44a`, merge commit `88fe4d2` (clean merge of `origin/main` `dc55250`, zero conflict edits in `victory-gpu`), and full PR diff `origin/main..88fe4d2` by pure reasoning only (no builds, edits, or GPU runs). ### Verification of All 6 Findings from Comment `7408385417` 1. **`[P0]` Stencil fallback OOB dynamic snapshot handle & unmirrored slot (`crates/victory-gpu/src/draw.rs:4492-4498, 4801-4833`) — FIXED** - Resolves `title_heap` via `crate::descriptor::heap(self.heaps[0] as This)` and `heap = title_heap.host()?`. - Fallback computes `slot_handle = table + u64::from(offset) * 4` and validates `title_heap.index(slot_handle).filter(|&i| i < heap.count())`, eliminating all dynamic snapshot offsetting (`self.ambient_tables`) and heap OOB risk. - Explicitly mirrors the slot via `heap.mirror_for_table_with(index, slot_handle, |_| ())` (skipping on `None`) and verifies `handle.ptr != 0` before returning `heap.gpu_handle(index)`. 2. **`[P0]` Strict `Role::Resolve` stencil predicates (`crates/victory-gpu/src/draw.rs:4787-4820, 7109-7137, 7187-7256`) — FIXED** - `is_resolve_stencil_view` resolves `placed_texture` and strictly requires `View::Shader(_, Some(d))` with `d[1] == 4` (`TEXTURE2D`) AND `matches!(crate::resource::pc_format(d[0]), 22 | 47)`. - `is_resolve_stencil_resource` strictly requires `D3D12_RESOURCE_DIMENSION_TEXTURE2D`, `SampleDesc.Count == 1`, `Width == width && Height == height`, and stencil-bearing DXGI format (`R32G8X24_TYPELESS | D32_FLOAT_S8X24_UINT | R24G8_TYPELESS | D24_UNORM_S8_UINT`). - Enforced identically in both `from_used` and the table-0 fallback, with unit test coverage (`resolve_stencil_view_and_resource_predicates_are_strict`). 3. **`[P0]` `prepare_prelude_upload` all-zero unpopulated `CpuStaging` (`crates/victory-gpu/src/texture.rs:2576-2598`, `crates/victory-gpu/src/texture_detile_tests.rs:612-669`) — FIXED** - Unconditionally guards on `if !guard.cpu().is_populated() { drop(guard); return None; }` regardless of `self.uploaded`, preventing `claim_upload` (`uploaded = true`, `dirty = false`) or copying unpopulated zero staging on deferred first uploads. - Covered by `first_upload_prelude_aborts_when_coming_write_defers_refresh`. 4. **`[P1]` `ds_hold::RECENT_WRITES` multi-range sequence overflow (`crates/victory-gpu/src/ds_hold.rs:105-124, 158-177, 350-377`) — FIXED** - `register_at` acquires `RECENT_WRITES` (strictly after dropping `PENDING`, preserving deadlock-free lock ordering), assigns `seq = base + 1 + written` for each non-empty range, and publishes `WRITE_SEQ.store(base + written, Release)` under the lock. - `active_or_raced_since_at` checks `> 64` both lock-free and again under `RECENT_WRITES` lock so multi-range `PAGE_DESTINATION` wraps are never missed. - Covered by `multi_range_register_advances_seq_per_non_empty_range_and_detects_ring_overflow`. 5. **`[P1]` `read_short` reset & no double-count (`crates/victory-gpu/src/descriptor/host.rs:1460-1488, 13271-13316`, `crates/victory-gpu/src/texture.rs:1972-2426`, `crates/victory-gpu/src/texture/ahead.rs:68, 222, 392-400, 475-478, 519-522`) — FIXED** - `SHORT_TRACKED: AtomicUsize` tracks `SHORT.1.len()` under `SHORT` lock (`Release`), giving `read_all` a lock-free `Acquire` fast path when empty and clearing both `SHORT.1` and `SHORT.0` when tracked. - `read_all(start)` is called on all normal successful (non-raced, non-all-zero) refresh paths (`writes_since`, `!committed`, `through_copy`, in-place committed, `refresh_unlocked`, `refresh_exact_unlocked`, `fill`). - `Staging::refresh_noted_short()` propagates whether `read_short` was already invoked into `Job::short_noted`, preventing double-increment in `ahead::finish()` (both skipped-record and failure paths). - Covered by `read_short_caps_at_short_in_a_row_and_read_all_resets_tracking`. 6. **`[P1]` In-place `detile` race re-check & `refresh_timed` return 0 on race (`crates/victory-gpu/src/texture.rs:2154-2164, 2261-2268, 2333-2371, 2785-2789`) — FIXED** - On the in-place committed path, `raced_coming(last)` is re-checked after `self.detile(tiled)`, clearing `last.hash = None` and `cpu.populated.store(false, Release)` and returning `(0, true)` if a streaming write raced during `detile`. - `refresh_exact_unlocked` returns `ExactUnlocked::{Read { changed }, Raced, Missing}`, and `refresh_timed` returns `(0, true)` on `ExactUnlocked::Raced`. ### Regressions, Policy & File-Size Check - **New `[P0]`/`[P1]` regressions in `88fe4d2`:** None (`0 P0`, `0 P1`). - **Non-blocking `[P2]` note:** In `crates/victory-gpu/src/texture.rs:2044-2050`, `let coming_before = crate::ds_hold::write_seq();` runs immediately after `ds_hold::active(start, end)`. Moving `write_seq()` above `active(start, end)` would close the ~2-instruction preemption window between `active() == false` and `write_seq()` (pure polish, non-blocking). - **Clean-room / Attribution:** Title-neutral throughout, proper `GPL-3.0` attribution (`ReTerryDavis/ReVIctory`). - **Rust file size limit (`< 655,360 B` CRLF):** PASS — largest in repo is `crates/victory-gpu/src/host.rs` (`649,399 B` CRLF, untouched); largest modified in PR #430 is `crates/victory-gpu/src/descriptor/host.rs` (`589,862 B` CRLF).
Androtim commented 2026-12-04 11:00:14 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T11:00:14Z.


Gate 2 Adversarial Pure-Reasoning Soundness Audit — PR #431 (perf/w11b-rayquery-phase3 @ 2fb54dc)

Verdict: CHANGES REQUESTED — 5 [P0], 2 [P1]

Audited the full diff (origin/main...HEAD, 2fb54dc) alongside full surrounding context in crates/victory-shader/src/emit/lower/rayquery/analyze.rs, emit_rq.rs, structure.rs, ir.rs, emit/lower.rs, and rayquery_tests.rs.

  • Clean-room / Title-neutrality: PASS (0 forbidden terms or local paths).
  • File sizes (CRLF): PASS — analyze.rs 403,852 B, rayquery_tests.rs 308,824 B, emit_rq.rs 59,455 B (all comfortably under 655,360 B).

[P0] Findings (Miscompiled Ray Queries — Must Fix Before Merge)

1. [P0] Inverted dynamic-opacity s_and_saveexec_b32/64 callback entry (!(1 == v_opaque)) constant-folds EVERY callback commit & mask to false

  • Locations: analyze.rs:3596-3638 (is_non_opaque_mask / nonop_idx), analyze.rs:6922-6944 (collect_bool_atoms), analyze.rs:7170-7249 (eval_pre_callback_lane_bit), emit_rq.rs:327-333, emit_rq.rs:648-660.
  • Proof:
    1. v_cmp_eq_u32 vcc, 1, v_opaque defines lv with st.masks[&lv] = E0 & Atom::Lane(lv) (structure.rs:1384-1386).
    2. s_xor_b32/64(..., -1) + s_and_saveexec_b32/64 sets callback entry EXEC to ce = E0 & !Atom::Lane(lv).
    3. Inside the callback, every v_cmp_* (including Pattern B's commit mask v_cmp_ne_u32 vcc, 0, v0 and any internal v_cndmask condition) builds st.masks[&m] = EXEC & Atom::Lane(m) = E0 & !Atom::Lane(lv) & Atom::Lane(m) (unsimplified by given(..., reach)).
    4. collect_bool_atoms encounters Atom::Lane(lv) and calls eval_pre_callback_lane_bit. "v_cmp_eq_u32" has no matching arm, falling through to _ => PreboundLane::Const(true) (analyze.rs:7247)!
    5. emit_rq.rs:328 binds lane_bits[lv] = true. At runtime, self.boolean(E0 & !lv & m) evaluates true & !true & m == false.
    6. Result: Every CommitDecision::Mask (dx.op.rayQuery_CommitNonOpaqueTriangleHit) and every v_cndmask inside such a callback is silently constant-folded to false (including in PR #431's own test s_and_saveexec_inverted_opacity_callback_entry_lifts_and_rejects_unrelated, which only checked rq.lifted == [1, 0] and DXIL validity).
  • Required Fix:
    • In collect_bool_atoms (analyze.rs:6925), check ce against Atom::Lane(lv) (via st.masks.get(&lv) when ce implies the compare's EXEC, or directly from st.bools support polarity under ce) so any atom forced false by ce (including v_cmp_eq_u32(1, v_opaque)) is prebound to PreboundLane::Const(false).
    • Explicitly handle v_cmp_eq_u32(1, v_opaque) -> Const(false) / v_cmp_eq_u32(0, v_opaque) -> Const(true) in eval_pre_callback_lane_bit, and fail closed (Err) on unknown pre-callback Atom::Lanes whose truth value under ce is not proven instead of defaulting to Const(true).
    • Strengthen s_and_saveexec_inverted_opacity_callback_entry_lifts_and_rejects_unrelated to assert the pre-callback opacity compare atom is bound to false (and/or that the lowered commit branch is not constant false).

2. [P0] Opaque-lane mutations & post-merge discards of user accumulators are silently dropped in find_callback_accumulator_next (Inline & Case 1b Blocks) and is_callback_only_user_accumulator (Case 1b Blocks)

  • Locations: analyze.rs:9633-9649, 9702-9725 (find_callback_accumulator_next); analyze.rs:4824-4837 (is_callback_only_user_accumulator).
  • Proof:
    1. CallbackKind::Inline in find_callback_accumulator_next (analyze.rs:9635-9646): Accepts any site in cb_sites with st.guards[site.0][site.1].is_some() and sets found = Some(v) without checking old_dst (read_old_dst_inactive). If search_blk[..ni] saves v44 = v41_hdr and mutates v41 on opaque hits (v_add_nc_u32 v41, 2, v41), and the inline callback executes v_add_nc_u32 v41, 1, v44 (guarded by ce, whose old_dst on opaque lanes is v41_hdr + 2), find_callback_accumulator_next returns Some(v41_cb) and emit_rq emits valid DXIL that silently drops every opaque hit's +2 update.
    2. Case 1b CallbackKind::Blocks (without_execz_skips, no opaque skip edge to tri_merge_block): Every predecessor of tri_merge_block is in cb_block_set, while opaque lanes flow through cb_blocks with EXEC = ce masked OFF (preserving old_dst). Both find_callback_accumulator_next (analyze.rs:9637-9646, 9702-9713) and is_callback_only_user_accumulator (analyze.rs:4824-4837) accept without walking read_old_dst_inactive, silently dropping opaque-lane updates to hp.
    3. Post-merge branch discard in find_callback_accumulator_next (analyze.rs:9714-9724): For CallbackKind::Inline (where unvisited_non_cand / verify_post_merge_flow_unconditional does not run on non-commit accumulators), a post-merge branch after tri_merge_block that discards a callback update back to hp on one arm has its arg == hp arm skipped at line 9720 even when its predecessor is post_merge_reachable, causing emit_rq to apply updates on lanes that discarded them.
  • Required Fix:
    • In find_callback_accumulator_next: for Inline (and for guarded defs / Case 1b in Blocks), require cb_exec_within_entry, walk read_old_dst_inactive onto work so inactive/opaque lanes are proven to preserve hp (or fail closed if unguarded when st.reach[site.0] does not imply ce). Also compute post_merge_reachable from tri_merge_block and reject any loop_blocks \ cb_blocks PHI where a post_merge_reachable predecessor drops the update back to hp.
    • In is_callback_only_user_accumulator (analyze.rs:4824-4837): if st.guards[ds.0][ds.1].is_some(), walk read_old_dst_inactive(ds, di, v) onto work; if unguarded, require !st.bools.meet(&[(st.reach[ds.0], true), (ce, false)]).
    • Add negative unit tests for Inline and Case 1b opaque-mutated accumulators.

3. [P0] cb_val_routes_raw_bvh_ptr only inspects v_mov_b32/v_cndmask_b32, allowing user accumulators to compute on fake k8 / 0 / ±1.0 sentinels

  • Locations: analyze.rs:4685-4746 (cb_val_routes_raw_bvh_ptr), analyze.rs:6003-6014 (validate_tri_merge_phi), emit_rq.rs:227-234, 255-264.
  • Proof:
    • emit_rq.rs binds cb.cand_tris and cb.cand_insts to the fake sentinel constant 8 (k8), cb.cand_flags to fake 0, and cb.cand_inv_d to synthetic ±1.0f32.
    • cb_val_routes_raw_bvh_ptr only recurses into "v_mov_b32" and "v_cndmask_b32", ignoring all other VALU instructions (_ => {} at line 4740).
    • If a callback computes v_or_b32 v41, cur_tri, 0, v_add_nc_u32 v41, cur_tri, 4, v_min_u32 v41, v41, cur_tri, or arithmetic on inv_d/cand_flags into a user accumulator v41 flowing through a tri_merge_block PHI, cb_val_routes_raw_bvh_ptr returns false, validate_tri_merge_phi accepts it, and emit_rq emits valid DXIL computing on fake 8 / 0 / ±1.0.
  • Required Fix:
    • In cb_val_routes_raw_bvh_ptr, for any Fields::Valu (and scalar Fields::Sop) instruction in cb_block_set, push all explicit data reads (and old_dst if guarded) onto work — stopping only at Fields::Flat loads (which are already validated/replaced by attr_loads).
    • Also reject values matching inv_d (outside cand_u/cand_v/front-face compare) or flags_vals_roots / cand_flags.
    • Add a negative unit test with v_add_nc_u32 v41, v36 (cur_tri), 4 flowing through a tri_merge_block PHI.

4. [P0] val_has_explicit_read treats cross-lane reads under guard ug => eg as dead on inactive !eg lanes

  • Locations: analyze.rs:7628-7639 (val_has_explicit_read); also analyze.rs:4635-4645 (read_old_dst_inactive).
  • Proof:
    • After a guarded full-32-bit overwrite (db, di) of v45 under guard eg, lanes where !eg still hold start (the loop header PHI value).
    • If a later instruction (db, u.1 > di) under guard ug (ug => eg) is a cross-lane read — e.g. v_mov_b32_dpp (or any VALU with dpp.is_some()), v_readlane_b32, v_readfirstlane_b32, v_permlane16_b32 / v_permlanex16_b32, ds_swizzle_b32, ds_permute_b32, ds_bpermute_b32, or image_sample* with implicit quad derivatives — active ug lanes observe inactive !eg lanes' start value!
    • val_has_explicit_read does not check that ui is lane-local before setting read_dead_on_old_lanes = true, so it falsely returns false ("dead") and skips validating a live header PHI.
    • Similarly, read_old_dst_inactive (analyze.rs:4635-4645) does not stop on v_writelane_b32 (which writes its target lane ignoring EXEC).
  • Required Fix:
    • In val_has_explicit_read (analyze.rs:7629), require ui to be strictly lane-local (reject Fields::Valu with dpp.is_some() or cross-lane/M0-indexed ops v_readlane_b32/v_readfirstlane_b32/v_permlane*/v_writelane_b32/v_movrel*/v_swaprel*, any Fields::Ds, and any Fields::Mimg with implicit derivatives) before setting read_dead_on_old_lanes = true.
    • In read_old_dst_inactive, break if pi.name() == "v_writelane_b32".

5. [P0] classify_live_outs + value_touches_cb_sites (pb != header) silently freezes non-invariant header PHIs read in callback at their pre-loop init

  • Locations: analyze.rs:9160-9210 (classify_live_outs), analyze.rs:9520-9527 (value_touches_cb_sites), emit_rq.rs:16-33.
  • Proof:
    • Any non-live-out header PHI hp with read_in_cb == true that is NOT added to q.accumulators is bound by emit_rq.rs:16-33 to its pre-loop entry value for every Proceed() call. That is ONLY sound if hp is loop-invariant.
    • Because value_touches_cb_sites now stops at pb != header (analyze.rs:9522), a 2-PHI callback shift-register (v41_next = v42_hdr, v42_next = v_add_nc_u32(v41_hdr, 1) inside callback, where only v41_hdr is read inside the callback and neither is live-out) has find_callback_accumulator_next == None AND value_touches_cb_sites(v42_hdr) == false. Likewise, any header PHI mutated outside the callback (e.g. a traversal or opaque-hit counter) and read inside the callback to gate commit has value_touches_cb_sites == false.
    • Both silently skip q.accumulators without erroring, freezing hp at its pre-loop initial value in DXIL!
  • Required Fix:
    • At analyze.rs:9180-9210, whenever read_in_cb is true and find_callback_accumulator_next returns None, require is_invariant_header_phi(ir, st, hp, header, &back_edge_indices, loop_blocks) — otherwise fail closed with Err(...). (Pre-bound candidate PHIs such as cur_tri already have read_in_cb == false via !cb_bound_vals.contains(ev) and will continue to lift.)

[P1] Findings (Edge-Case Soundness Holes & Missing Guards/Tests)

6. [P1] is_iter_overflow_state_cndmask checks c0 >= threshold instead of threshold - c0 < 1024, and opaque_sets_state_zero passes empty_cb

  • Locations: analyze.rs:7376, 7400, 7446 (is_iter_overflow_state_cndmask); analyze.rs:3710-3724 (opaque_sets_state_zero).
  • Proof:
    1. Checking threshold >= 1024 and c0 < threshold accepts c0 = 65534, threshold = 65535 (or c0 = 1023, threshold = 1024), which terminates after 1 iteration on GFX10 — dropping the clamp changes observable traversal results. Must require threshold.saturating_sub(c0) >= 1024 (i.e., fail if c0 > threshold.saturating_sub(1024)).
    2. opaque_sets_state_zero (analyze.rs:3710-3724) calls feeds_latch_state_direct_or_iter_cap with empty_cb before extract_callback_region runs. If v_iter is mutated inside the callback while v_state is only written on opaque hits before ni, is_iter_overflow_state_cndmask never sees cb_site_set. Re-verify with the real cb_site_set after extract_callback_region.
    3. Add a negative unit test for c0 = 65534, K = 65535.

7. [P1] Wave64 half-mask mismatch in is_non_opaque_mask/nonop_idx and s_mov_b64 high-dword word-0 bug in collapse_scalar_mov_phi

  • Locations: analyze.rs:3596-3638 (is_non_opaque_mask / nonop_idx); analyze.rs:4260-4264, 4282-4286 (collapse_scalar_mov_phi).
  • Proof:
    1. is_non_opaque_mask / nonop_idx matches "s_and_saveexec_b32" | "s_and_saveexec_b64" and "s_xor_b32" | "s_xor_b64" without checking p.wave64 or verifying that the high dword (src+1) in Wave64 matches the producer's high write (read_op only checks the low dword). Fix: match _b64 vs _b32 by p.wave64 and verify the Wave64 high-dword pair matches.
    2. collapse_scalar_mov_phi matches "s_mov_b64" and unconditionally calls read_op_word(si, &src[0], 0), which maps the high dword (dst+1) of an s_mov_b64 to word 0 (the low source dword) instead of word 1. Since exec_chain_proves_neg_cmp already bails on p.wave64, restrict collapse_scalar_mov_phi to "s_mov_b32" (or look up the matching write word index 0/1).
<!-- greyfinch-sync:Androtim/MiniVI:comment:7409489168 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7409489168). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T11:00:14Z. --- ## Gate 2 Adversarial Pure-Reasoning Soundness Audit — PR #431 (`perf/w11b-rayquery-phase3` @ `2fb54dc`) **Verdict: CHANGES REQUESTED — 5 `[P0]`, 2 `[P1]`** Audited the full diff (`origin/main...HEAD`, `2fb54dc`) alongside full surrounding context in `crates/victory-shader/src/emit/lower/rayquery/analyze.rs`, `emit_rq.rs`, `structure.rs`, `ir.rs`, `emit/lower.rs`, and `rayquery_tests.rs`. - **Clean-room / Title-neutrality:** PASS (0 forbidden terms or local paths). - **File sizes (CRLF):** PASS — `analyze.rs` `403,852 B`, `rayquery_tests.rs` `308,824 B`, `emit_rq.rs` `59,455 B` (all comfortably under `655,360 B`). --- ### `[P0]` Findings (Miscompiled Ray Queries — Must Fix Before Merge) #### 1. `[P0]` Inverted dynamic-opacity `s_and_saveexec_b32/64` callback entry (`!(1 == v_opaque)`) constant-folds EVERY callback commit & mask to `false` - **Locations:** `analyze.rs:3596-3638` (`is_non_opaque_mask` / `nonop_idx`), `analyze.rs:6922-6944` (`collect_bool_atoms`), `analyze.rs:7170-7249` (`eval_pre_callback_lane_bit`), `emit_rq.rs:327-333`, `emit_rq.rs:648-660`. - **Proof:** 1. `v_cmp_eq_u32 vcc, 1, v_opaque` defines `lv` with `st.masks[&lv] = E0 & Atom::Lane(lv)` (`structure.rs:1384-1386`). 2. `s_xor_b32/64(..., -1)` + `s_and_saveexec_b32/64` sets callback entry `EXEC` to `ce = E0 & !Atom::Lane(lv)`. 3. Inside the callback, **every** `v_cmp_*` (including Pattern B's commit mask `v_cmp_ne_u32 vcc, 0, v0` and any internal `v_cndmask` condition) builds `st.masks[&m] = EXEC & Atom::Lane(m) = E0 & !Atom::Lane(lv) & Atom::Lane(m)` (unsimplified by `given(..., reach)`). 4. `collect_bool_atoms` encounters `Atom::Lane(lv)` and calls `eval_pre_callback_lane_bit`. `"v_cmp_eq_u32"` has **no matching arm**, falling through to `_ => PreboundLane::Const(true)` (`analyze.rs:7247`)! 5. `emit_rq.rs:328` binds `lane_bits[lv] = true`. At runtime, `self.boolean(E0 & !lv & m)` evaluates `true & !true & m == false`. 6. **Result:** Every `CommitDecision::Mask` (`dx.op.rayQuery_CommitNonOpaqueTriangleHit`) and every `v_cndmask` inside such a callback is silently constant-folded to `false` (including in PR #431's own test `s_and_saveexec_inverted_opacity_callback_entry_lifts_and_rejects_unrelated`, which only checked `rq.lifted == [1, 0]` and DXIL validity). - **Required Fix:** - In `collect_bool_atoms` (`analyze.rs:6925`), check `ce` against `Atom::Lane(lv)` (via `st.masks.get(&lv)` when `ce` implies the compare's EXEC, or directly from `st.bools` support polarity under `ce`) so any atom forced false by `ce` (including `v_cmp_eq_u32(1, v_opaque)`) is prebound to `PreboundLane::Const(false)`. - Explicitly handle `v_cmp_eq_u32(1, v_opaque)` -> `Const(false)` / `v_cmp_eq_u32(0, v_opaque)` -> `Const(true)` in `eval_pre_callback_lane_bit`, and fail closed (`Err`) on unknown pre-callback `Atom::Lane`s whose truth value under `ce` is not proven instead of defaulting to `Const(true)`. - Strengthen `s_and_saveexec_inverted_opacity_callback_entry_lifts_and_rejects_unrelated` to assert the pre-callback opacity compare atom is bound to `false` (and/or that the lowered commit branch is not constant `false`). #### 2. `[P0]` Opaque-lane mutations & post-merge discards of user accumulators are silently dropped in `find_callback_accumulator_next` (Inline & Case 1b Blocks) and `is_callback_only_user_accumulator` (Case 1b Blocks) - **Locations:** `analyze.rs:9633-9649`, `9702-9725` (`find_callback_accumulator_next`); `analyze.rs:4824-4837` (`is_callback_only_user_accumulator`). - **Proof:** 1. **`CallbackKind::Inline` in `find_callback_accumulator_next` (`analyze.rs:9635-9646`):** Accepts any `site` in `cb_sites` with `st.guards[site.0][site.1].is_some()` and sets `found = Some(v)` **without checking `old_dst`** (`read_old_dst_inactive`). If `search_blk[..ni]` saves `v44 = v41_hdr` and mutates `v41` on opaque hits (`v_add_nc_u32 v41, 2, v41`), and the inline callback executes `v_add_nc_u32 v41, 1, v44` (guarded by `ce`, whose `old_dst` on opaque lanes is `v41_hdr + 2`), `find_callback_accumulator_next` returns `Some(v41_cb)` and `emit_rq` emits valid DXIL that **silently drops every opaque hit's `+2` update**. 2. **Case 1b `CallbackKind::Blocks` (`without_execz_skips`, no opaque skip edge to `tri_merge_block`):** Every predecessor of `tri_merge_block` is in `cb_block_set`, while opaque lanes flow through `cb_blocks` with `EXEC = ce` masked OFF (preserving `old_dst`). Both `find_callback_accumulator_next` (`analyze.rs:9637-9646`, `9702-9713`) and `is_callback_only_user_accumulator` (`analyze.rs:4824-4837`) accept without walking `read_old_dst_inactive`, silently dropping opaque-lane updates to `hp`. 3. **Post-merge branch discard in `find_callback_accumulator_next` (`analyze.rs:9714-9724`):** For `CallbackKind::Inline` (where `unvisited_non_cand` / `verify_post_merge_flow_unconditional` does not run on non-commit accumulators), a post-merge branch after `tri_merge_block` that discards a callback update back to `hp` on one arm has its `arg == hp` arm skipped at line 9720 even when its predecessor is `post_merge_reachable`, causing `emit_rq` to apply updates on lanes that discarded them. - **Required Fix:** - In `find_callback_accumulator_next`: for `Inline` (and for guarded defs / Case 1b in `Blocks`), require `cb_exec_within_entry`, walk `read_old_dst_inactive` onto `work` so inactive/opaque lanes are proven to preserve `hp` (or fail closed if unguarded when `st.reach[site.0]` does not imply `ce`). Also compute `post_merge_reachable` from `tri_merge_block` and reject any `loop_blocks \ cb_blocks` PHI where a `post_merge_reachable` predecessor drops the update back to `hp`. - In `is_callback_only_user_accumulator` (`analyze.rs:4824-4837`): if `st.guards[ds.0][ds.1].is_some()`, walk `read_old_dst_inactive(ds, di, v)` onto `work`; if unguarded, require `!st.bools.meet(&[(st.reach[ds.0], true), (ce, false)])`. - Add negative unit tests for Inline and Case 1b opaque-mutated accumulators. #### 3. `[P0]` `cb_val_routes_raw_bvh_ptr` only inspects `v_mov_b32`/`v_cndmask_b32`, allowing user accumulators to compute on fake `k8` / `0` / `±1.0` sentinels - **Locations:** `analyze.rs:4685-4746` (`cb_val_routes_raw_bvh_ptr`), `analyze.rs:6003-6014` (`validate_tri_merge_phi`), `emit_rq.rs:227-234`, `255-264`. - **Proof:** - `emit_rq.rs` binds `cb.cand_tris` and `cb.cand_insts` to the fake sentinel constant `8` (`k8`), `cb.cand_flags` to fake `0`, and `cb.cand_inv_d` to synthetic `±1.0f32`. - `cb_val_routes_raw_bvh_ptr` only recurses into `"v_mov_b32"` and `"v_cndmask_b32"`, ignoring all other VALU instructions (`_ => {}` at line 4740). - If a callback computes `v_or_b32 v41, cur_tri, 0`, `v_add_nc_u32 v41, cur_tri, 4`, `v_min_u32 v41, v41, cur_tri`, or arithmetic on `inv_d`/`cand_flags` into a user accumulator `v41` flowing through a `tri_merge_block` PHI, `cb_val_routes_raw_bvh_ptr` returns `false`, `validate_tri_merge_phi` accepts it, and `emit_rq` emits valid DXIL computing on fake `8` / `0` / `±1.0`. - **Required Fix:** - In `cb_val_routes_raw_bvh_ptr`, for **any** `Fields::Valu` (and scalar `Fields::Sop`) instruction in `cb_block_set`, push all explicit data reads (and `old_dst` if guarded) onto `work` — stopping only at `Fields::Flat` loads (which are already validated/replaced by `attr_loads`). - Also reject values matching `inv_d` (outside `cand_u`/`cand_v`/front-face compare) or `flags_vals_roots` / `cand_flags`. - Add a negative unit test with `v_add_nc_u32 v41, v36 (cur_tri), 4` flowing through a `tri_merge_block` PHI. #### 4. `[P0]` `val_has_explicit_read` treats cross-lane reads under guard `ug => eg` as dead on inactive `!eg` lanes - **Locations:** `analyze.rs:7628-7639` (`val_has_explicit_read`); also `analyze.rs:4635-4645` (`read_old_dst_inactive`). - **Proof:** - After a guarded full-32-bit overwrite `(db, di)` of `v45` under guard `eg`, lanes where `!eg` still hold `start` (the loop header PHI value). - If a later instruction `(db, u.1 > di)` under guard `ug` (`ug => eg`) is a **cross-lane** read — e.g. `v_mov_b32_dpp` (or any VALU with `dpp.is_some()`), `v_readlane_b32`, `v_readfirstlane_b32`, `v_permlane16_b32` / `v_permlanex16_b32`, `ds_swizzle_b32`, `ds_permute_b32`, `ds_bpermute_b32`, or `image_sample*` with implicit quad derivatives — active `ug` lanes observe inactive `!eg` lanes' `start` value! - `val_has_explicit_read` does not check that `ui` is lane-local before setting `read_dead_on_old_lanes = true`, so it falsely returns `false` ("dead") and skips validating a live header PHI. - Similarly, `read_old_dst_inactive` (`analyze.rs:4635-4645`) does not stop on `v_writelane_b32` (which writes its target lane ignoring `EXEC`). - **Required Fix:** - In `val_has_explicit_read` (`analyze.rs:7629`), require `ui` to be strictly lane-local (reject `Fields::Valu` with `dpp.is_some()` or cross-lane/M0-indexed ops `v_readlane_b32`/`v_readfirstlane_b32`/`v_permlane*`/`v_writelane_b32`/`v_movrel*`/`v_swaprel*`, any `Fields::Ds`, and any `Fields::Mimg` with implicit derivatives) before setting `read_dead_on_old_lanes = true`. - In `read_old_dst_inactive`, break if `pi.name() == "v_writelane_b32"`. #### 5. `[P0]` `classify_live_outs` + `value_touches_cb_sites` (`pb != header`) silently freezes non-invariant header PHIs read in callback at their pre-loop init - **Locations:** `analyze.rs:9160-9210` (`classify_live_outs`), `analyze.rs:9520-9527` (`value_touches_cb_sites`), `emit_rq.rs:16-33`. - **Proof:** - Any non-live-out header PHI `hp` with `read_in_cb == true` that is NOT added to `q.accumulators` is bound by `emit_rq.rs:16-33` to its **pre-loop entry value** for every `Proceed()` call. That is ONLY sound if `hp` is loop-invariant. - Because `value_touches_cb_sites` now stops at `pb != header` (`analyze.rs:9522`), a 2-PHI callback shift-register (`v41_next = v42_hdr`, `v42_next = v_add_nc_u32(v41_hdr, 1)` inside callback, where only `v41_hdr` is read inside the callback and neither is live-out) has `find_callback_accumulator_next == None` AND `value_touches_cb_sites(v42_hdr) == false`. Likewise, any header PHI mutated outside the callback (e.g. a traversal or opaque-hit counter) and read inside the callback to gate commit has `value_touches_cb_sites == false`. - Both silently skip `q.accumulators` without erroring, freezing `hp` at its pre-loop initial value in DXIL! - **Required Fix:** - At `analyze.rs:9180-9210`, whenever `read_in_cb` is `true` and `find_callback_accumulator_next` returns `None`, require `is_invariant_header_phi(ir, st, hp, header, &back_edge_indices, loop_blocks)` — otherwise fail closed with `Err(...)`. (Pre-bound candidate PHIs such as `cur_tri` already have `read_in_cb == false` via `!cb_bound_vals.contains(ev)` and will continue to lift.) --- ### `[P1]` Findings (Edge-Case Soundness Holes & Missing Guards/Tests) #### 6. `[P1]` `is_iter_overflow_state_cndmask` checks `c0 >= threshold` instead of `threshold - c0 < 1024`, and `opaque_sets_state_zero` passes `empty_cb` - **Locations:** `analyze.rs:7376`, `7400`, `7446` (`is_iter_overflow_state_cndmask`); `analyze.rs:3710-3724` (`opaque_sets_state_zero`). - **Proof:** 1. Checking `threshold >= 1024` and `c0 < threshold` accepts `c0 = 65534, threshold = 65535` (or `c0 = 1023, threshold = 1024`), which terminates after **1 iteration** on GFX10 — dropping the clamp changes observable traversal results. Must require `threshold.saturating_sub(c0) >= 1024` (i.e., fail if `c0 > threshold.saturating_sub(1024)`). 2. `opaque_sets_state_zero` (`analyze.rs:3710-3724`) calls `feeds_latch_state_direct_or_iter_cap` with `empty_cb` before `extract_callback_region` runs. If `v_iter` is mutated inside the callback while `v_state` is only written on opaque hits before `ni`, `is_iter_overflow_state_cndmask` never sees `cb_site_set`. Re-verify with the real `cb_site_set` after `extract_callback_region`. 3. Add a negative unit test for `c0 = 65534, K = 65535`. #### 7. `[P1]` Wave64 half-mask mismatch in `is_non_opaque_mask`/`nonop_idx` and `s_mov_b64` high-dword word-0 bug in `collapse_scalar_mov_phi` - **Locations:** `analyze.rs:3596-3638` (`is_non_opaque_mask` / `nonop_idx`); `analyze.rs:4260-4264`, `4282-4286` (`collapse_scalar_mov_phi`). - **Proof:** 1. `is_non_opaque_mask` / `nonop_idx` matches `"s_and_saveexec_b32" | "s_and_saveexec_b64"` and `"s_xor_b32" | "s_xor_b64"` without checking `p.wave64` or verifying that the high dword (`src+1`) in Wave64 matches the producer's high write (`read_op` only checks the low dword). Fix: match `_b64` vs `_b32` by `p.wave64` and verify the Wave64 high-dword pair matches. 2. `collapse_scalar_mov_phi` matches `"s_mov_b64"` and unconditionally calls `read_op_word(si, &src[0], 0)`, which maps the high dword (`dst+1`) of an `s_mov_b64` to word 0 (the low source dword) instead of word 1. Since `exec_chain_proves_neg_cmp` already bails on `p.wave64`, restrict `collapse_scalar_mov_phi` to `"s_mov_b32"` (or look up the matching write word index `0`/`1`).
Androtim commented 2026-12-04 11:04:44 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T11:04:44Z.


Gate 2 Adversarial Audit — PR #432 (5c16e97)

Pure reasoning audit of perf/w12a-hwrt-quant24-gpu (5c16e97) across crates/victory-gpu/src/hwrt.rs, crates/victory-gpu/src/hwrt/decoders.rs, and crates/victory-gpu/src/hwrt/sanitize.rs.

Findings

1. [P1] Unbounded vbytes in read_quant24_header bypasses MAX_DECODE_READ_BYTES on the GPU path

  • Location: crates/victory-gpu/src/hwrt/decoders.rs:474-480, called at crates/victory-gpu/src/hwrt.rs:2705-2712
  • Failure mechanic:
    • read_quant24_header bounds stage_bytes = vcount * 12 <= MAX_DECODE_READ_BYTES (64 MiB, so vcount <= 5_592_405), but only checks usize::try_from(vbytes).is_err() for vbytes = (vcount - 1) * actual_stride + 8. It does not check vbytes > MAX_DECODE_READ_BYTES as u64, contradicting both its own doc comment (decoders.rs:462-463) and the CPU fallback (decode_title_quant24_vb_with_header -> with_scan_scratch at decoders.rs:182,523).
    • With a large or corrupted stride up to 0x7FFC (32,764 B) and e.g. vcount = 10_000, stage_bytes is only 120 KiB (<= 64 MiB), so read_quant24_header returns Some(hdr) with hdr.vbytes = 327_607_244 (~312 MiB; up to ~170.6 GiB at max vcount).
    • hwrt.rs:2712 immediately passes this unbounded hdr.vbytes into crate::shadow::find(vertex_buffer, hdr.vbytes). Outside an existing registered buffer covering that span, shadow::find falls back to loose_for -> made_window, attempting to allocate and retain a multi-hundred-MiB (or multi-GiB) loose D3D12 shadow buffer / virtual mirror reservation and copy it on sh.refresh, whereas the pre-PR CPU path (and the CPU fallback) fail closed with None for any vbytes > MAX_DECODE_READ_BYTES.
  • Exact fix:
    • In crates/victory-gpu/src/hwrt/decoders.rs:478, enforce the vbytes cap alongside stage_bytes:
      if vbytes > MAX_DECODE_READ_BYTES as u64 || stage_bytes > MAX_DECODE_READ_BYTES {
          return None;
      }
      
    • Add a unit test in read_quant24_header_validates_bounds_stride_and_finite_coefficients with e.g. vcount = 10_000, stride = 0x7FFC (stage_bytes <= MAX_DECODE_READ_BYTES but vbytes > MAX_DECODE_READ_BYTES) asserting None.

2. [P1] Torn-read coherence split between record-time CPU header read and submission-time GPU shadow vertex read

  • Location: crates/victory-gpu/src/hwrt.rs:2705-2739 and crates/victory-gpu/src/hwrt/sanitize.rs:430-441,484-513
  • Failure mechanic:
    • read_quant24_header (hwrt.rs:2705) snapshots the 32-byte quantization header (bias, scale, swizzle) from CPU title memory at vb_va - 0x20 during execute_op (command-list recording / thin replay time) and bakes those values into compute root constants (b1, hwrt.rs:1472-1485).
    • Meanwhile, the packed vertex payload [vb_va, vb_va + hdr.vbytes) is refreshed lazily via sh.refresh(list, vertex_buffer, hdr.vbytes) (hwrt.rs:2729) at ExecuteCommandLists submission time and read from sh.buffer when the GPU executes decode_quant24_vb.
    • If a title populates or updates [vb_va - 0x20, vb_va + vbytes) after recording the BLAS build and before submission — e.g.:
      1. An earlier CopyBufferRegion into the quant24 VB in the same command list (list.defer_copy, which runs at submission time before Step::Refresh),
      2. CPU writes to a reused/ring quant24 VB between command-list recording and ExecuteCommandLists (valid D3D12), or
      3. GPU writes to sh.buffer (Shadow::gpu_writes / VICTORY_WC_NO_BACK) —
        then decode_quant24_vb decodes the new packed vertices with the old (or all-zero on a fresh buffer, since 0.0f32.is_finite() passes!) (bias, scale, swizzle) root constants, producing wrong axis swizzle, wrong scale/translation, or collapsed [0, 0, 0] geometry and corrupted BLAS bounds. Previously, the CPU decoder read header and vertices together at the same instant and could not mix mismatched generations.
  • Exact fix:
    • Require [vb_va - 0x20, vb_va + hdr.vbytes) to be covered by the shadow buffer in quant24_shadow_eligible (or fall back to CPU when vb_va - 0x20 < sh_start), call sh.refresh(list, vertex_buffer - 0x20, hdr.vbytes + 0x20), and read the 7 header dwords (bias[0..3], swizzle, scale[0..3]) directly from g_src in decode_quant24_vb (at hdr_bias relative to (host_hdr & !15)).
    • Inside decode_quant24_vb, validate that all 6 bias/scale dwords are finite ((bits & 0x7FFFFFFFu) < 0x7F800000u), emitting quiet NaN (0x7FC00000u, 0x7FC00000u, 0x7FC00000u) (DXR inactive primitive) if any header coefficient is non-finite. (This also shrinks RS_QUANT24 from 10 root constants down to 4–5 dwords.)

Non-blocking Hardening Note

  • quant24_shadow_eligible (crates/victory-gpu/src/hwrt/sanitize.rs:545-568) does not check actual_stride >= 8 (safe today because read_quant24_header clamps .max(8), but adding actual_stride < 8 makes the helper self-contained against future callers).

Verified Clean Areas

  • D3D12 resource states & barriers: Shadow::buffer stays implicitly promoted from D3D12_RESOURCE_STATE_COMMON (decaying back to COMMON after Host::card_before's prelude command list), matching copy_vb / clamp_ib. Destination work leases start in UNORDERED_ACCESS, receive disjoint 16-byte-aligned bump slices per geometry and per sanitize_chunks batch, are transitioned UAV -> NON_PIXEL_SHADER_RESOURCE before BuildRaytracingAccelerationStructure and back NON_PIXEL_SHADER_RESOURCE -> UAV after flush_blas_waves (hwrt.rs:2082-2111), and are held on list via Lease until post-fence list.reset().
  • HLSL bit-unpacking & float/NaN/Inf math: ByteAddressBuffer::Load2(at) offsets are guaranteed 4-byte aligned (host_vb % 4 == 0, actual_stride % 4 == 0, q_src_bias = chunk_src & 15, chunk_src & !15 >= buffer_base_va). Unsigned 24/24/16 bit extraction (q0, q1, q2) is exact in f32 and matches decoders.rs:430-435. Swizzle branches (0 -> (c,b,a), 1 -> (b,c,a), _ -> (a,b,c)) match CPU. Unsigned bit-magnitude check (asuint(pos) & 0x7FFFFFFFu) > 0x501502F9u catches |x| > 1e10, ±Inf, and all NaNs without suffering from HLSL NaN > 1e10 == false, scrubbing to quiet NaN 0x7FC00000u.
  • Root signature, chunking & fallback paths: RS_QUANT24 (10 scalar dwords at b1, SRV(t0), UAV(u0)) has zero cbuffer vector-padding drift and matches quant24_root_params and SetComputeRoot* indices 0/1/2. sanitize_chunks keeps Dispatch <= 65535 groups, u32 byte offsets in-bounds, and chunk_dst 16-byte aligned. Fallback branches short-circuit cleanly before allocating work or setting *bound; *bound = true triggers state.replay(host) after execute_op. STATS length (17) and report_line formatting match.
  • File size & title neutrality policy: All touched files are well below the 655,360 B CRLF cap (hwrt.rs 223,522 B, decoders.rs 30,116 B, sanitize.rs 29,824 B) and strictly title-neutral.

VERDICT: NEEDS FIXES (0 P0, 2 P1)

<!-- greyfinch-sync:Androtim/MiniVI:comment:7409603587 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7409603587). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T11:04:44Z. --- ## Gate 2 Adversarial Audit — PR #432 (5c16e97) Pure reasoning audit of `perf/w12a-hwrt-quant24-gpu` (`5c16e97`) across `crates/victory-gpu/src/hwrt.rs`, `crates/victory-gpu/src/hwrt/decoders.rs`, and `crates/victory-gpu/src/hwrt/sanitize.rs`. ### Findings #### 1. `[P1]` Unbounded `vbytes` in `read_quant24_header` bypasses `MAX_DECODE_READ_BYTES` on the GPU path - **Location:** `crates/victory-gpu/src/hwrt/decoders.rs:474-480`, called at `crates/victory-gpu/src/hwrt.rs:2705-2712` - **Failure mechanic:** - `read_quant24_header` bounds `stage_bytes = vcount * 12 <= MAX_DECODE_READ_BYTES` (64 MiB, so `vcount <= 5_592_405`), but only checks `usize::try_from(vbytes).is_err()` for `vbytes = (vcount - 1) * actual_stride + 8`. It does **not** check `vbytes > MAX_DECODE_READ_BYTES as u64`, contradicting both its own doc comment (`decoders.rs:462-463`) and the CPU fallback (`decode_title_quant24_vb_with_header` -> `with_scan_scratch` at `decoders.rs:182,523`). - With a large or corrupted stride up to `0x7FFC` (32,764 B) and e.g. `vcount = 10_000`, `stage_bytes` is only 120 KiB (`<= 64 MiB`), so `read_quant24_header` returns `Some(hdr)` with `hdr.vbytes = 327_607_244` (~312 MiB; up to ~170.6 GiB at max `vcount`). - `hwrt.rs:2712` immediately passes this unbounded `hdr.vbytes` into `crate::shadow::find(vertex_buffer, hdr.vbytes)`. Outside an existing registered buffer covering that span, `shadow::find` falls back to `loose_for` -> `made_window`, attempting to allocate and retain a multi-hundred-MiB (or multi-GiB) loose D3D12 shadow buffer / virtual mirror reservation and copy it on `sh.refresh`, whereas the pre-PR CPU path (and the CPU fallback) fail closed with `None` for any `vbytes > MAX_DECODE_READ_BYTES`. - **Exact fix:** - In `crates/victory-gpu/src/hwrt/decoders.rs:478`, enforce the `vbytes` cap alongside `stage_bytes`: ```rust if vbytes > MAX_DECODE_READ_BYTES as u64 || stage_bytes > MAX_DECODE_READ_BYTES { return None; } ``` - Add a unit test in `read_quant24_header_validates_bounds_stride_and_finite_coefficients` with e.g. `vcount = 10_000, stride = 0x7FFC` (`stage_bytes <= MAX_DECODE_READ_BYTES` but `vbytes > MAX_DECODE_READ_BYTES`) asserting `None`. #### 2. `[P1]` Torn-read coherence split between record-time CPU header read and submission-time GPU shadow vertex read - **Location:** `crates/victory-gpu/src/hwrt.rs:2705-2739` and `crates/victory-gpu/src/hwrt/sanitize.rs:430-441,484-513` - **Failure mechanic:** - `read_quant24_header` (`hwrt.rs:2705`) snapshots the 32-byte quantization header (`bias`, `scale`, `swizzle`) from CPU title memory at `vb_va - 0x20` during `execute_op` (command-list recording / `thin` replay time) and bakes those values into compute root constants (`b1`, `hwrt.rs:1472-1485`). - Meanwhile, the packed vertex payload `[vb_va, vb_va + hdr.vbytes)` is refreshed lazily via `sh.refresh(list, vertex_buffer, hdr.vbytes)` (`hwrt.rs:2729`) at `ExecuteCommandLists` submission time and read from `sh.buffer` when the GPU executes `decode_quant24_vb`. - If a title populates or updates `[vb_va - 0x20, vb_va + vbytes)` after recording the BLAS build and before submission — e.g.: 1. An earlier `CopyBufferRegion` into the quant24 VB in the same command list (`list.defer_copy`, which runs at submission time before `Step::Refresh`), 2. CPU writes to a reused/ring quant24 VB between command-list recording and `ExecuteCommandLists` (valid D3D12), or 3. GPU writes to `sh.buffer` (`Shadow::gpu_writes` / `VICTORY_WC_NO_BACK`) — then `decode_quant24_vb` decodes the **new** packed vertices with the **old** (or all-zero on a fresh buffer, since `0.0f32.is_finite()` passes!) `(bias, scale, swizzle)` root constants, producing wrong axis swizzle, wrong scale/translation, or collapsed `[0, 0, 0]` geometry and corrupted BLAS bounds. Previously, the CPU decoder read header and vertices together at the same instant and could not mix mismatched generations. - **Exact fix:** - Require `[vb_va - 0x20, vb_va + hdr.vbytes)` to be covered by the shadow buffer in `quant24_shadow_eligible` (or fall back to CPU when `vb_va - 0x20 < sh_start`), call `sh.refresh(list, vertex_buffer - 0x20, hdr.vbytes + 0x20)`, and read the 7 header dwords (`bias[0..3]`, `swizzle`, `scale[0..3]`) directly from `g_src` in `decode_quant24_vb` (at `hdr_bias` relative to `(host_hdr & !15)`). - Inside `decode_quant24_vb`, validate that all 6 `bias`/`scale` dwords are finite (`(bits & 0x7FFFFFFFu) < 0x7F800000u`), emitting quiet NaN `(0x7FC00000u, 0x7FC00000u, 0x7FC00000u)` (DXR inactive primitive) if any header coefficient is non-finite. (This also shrinks `RS_QUANT24` from 10 root constants down to 4–5 dwords.) ### Non-blocking Hardening Note - `quant24_shadow_eligible` (`crates/victory-gpu/src/hwrt/sanitize.rs:545-568`) does not check `actual_stride >= 8` (safe today because `read_quant24_header` clamps `.max(8)`, but adding `actual_stride < 8` makes the helper self-contained against future callers). ### Verified Clean Areas - **D3D12 resource states & barriers:** `Shadow::buffer` stays implicitly promoted from `D3D12_RESOURCE_STATE_COMMON` (decaying back to `COMMON` after `Host::card_before`'s prelude command list), matching `copy_vb` / `clamp_ib`. Destination `work` leases start in `UNORDERED_ACCESS`, receive disjoint 16-byte-aligned bump slices per geometry and per `sanitize_chunks` batch, are transitioned `UAV -> NON_PIXEL_SHADER_RESOURCE` before `BuildRaytracingAccelerationStructure` and back `NON_PIXEL_SHADER_RESOURCE -> UAV` after `flush_blas_waves` (`hwrt.rs:2082-2111`), and are held on `list` via `Lease` until post-fence `list.reset()`. - **HLSL bit-unpacking & float/NaN/Inf math:** `ByteAddressBuffer::Load2(at)` offsets are guaranteed 4-byte aligned (`host_vb % 4 == 0`, `actual_stride % 4 == 0`, `q_src_bias = chunk_src & 15`, `chunk_src & !15 >= buffer_base_va`). Unsigned 24/24/16 bit extraction (`q0`, `q1`, `q2`) is exact in `f32` and matches `decoders.rs:430-435`. Swizzle branches (`0 -> (c,b,a)`, `1 -> (b,c,a)`, `_ -> (a,b,c)`) match CPU. Unsigned bit-magnitude check `(asuint(pos) & 0x7FFFFFFFu) > 0x501502F9u` catches `|x| > 1e10`, `±Inf`, and all `NaN`s without suffering from HLSL `NaN > 1e10 == false`, scrubbing to quiet NaN `0x7FC00000u`. - **Root signature, chunking & fallback paths:** `RS_QUANT24` (`10` scalar dwords at `b1`, `SRV(t0)`, `UAV(u0)`) has zero cbuffer vector-padding drift and matches `quant24_root_params` and `SetComputeRoot*` indices `0/1/2`. `sanitize_chunks` keeps `Dispatch` `<= 65535` groups, `u32` byte offsets in-bounds, and `chunk_dst` 16-byte aligned. Fallback branches short-circuit cleanly before allocating `work` or setting `*bound`; `*bound = true` triggers `state.replay(host)` after `execute_op`. `STATS` length (`17`) and `report_line` formatting match. - **File size & title neutrality policy:** All touched files are well below the 655,360 B CRLF cap (`hwrt.rs` 223,522 B, `decoders.rs` 30,116 B, `sanitize.rs` 29,824 B) and strictly title-neutral. VERDICT: NEEDS FIXES (0 P0, 2 P1)
Androtim commented 2026-12-04 11:22:04 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T11:22:04Z.


Gate 2 Pure-Reasoning Re-Audit — PR #432 (8efed66)

Pure-reasoning re-audit of perf/w12a-hwrt-quant24-gpu (8efed66, fix commit 5c16e97..8efed66, full diff dc55250..8efed66) across crates/victory-gpu/src/hwrt.rs, crates/victory-gpu/src/hwrt/decoders.rs, and crates/victory-gpu/src/hwrt/sanitize.rs.

Prior [P1] Findings Verification (comment 7409603587)

  1. [P1] Unbounded vbytes bypassing MAX_DECODE_READ_BYTES — RESOLVED
    • quant24_bounds (decoders.rs:453-466) now enforces vb_va >= 0x20, vcount > 0, checked arithmetic, and vbytes > MAX_DECODE_READ_BYTES as u64 || stage_bytes > MAX_DECODE_READ_BYTES, shared by both the GPU path (hwrt.rs:2700) and CPU fallback (read_quant24_header, decoders.rs:487).
    • total_bytes = vbytes + 0x20 passed to crate::shadow::find (hwrt.rs:2707-2709) is strictly bounded to <= 64 MiB + 32 B, preventing multi-hundred-MiB/GiB loose window reservations on large strides.
    • Regression test added for stride-amplified vbytes > MAX_DECODE_READ_BYTES (decoders.rs:782-783).
  2. [P1] Torn-read coherence between record-time CPU header and submission-time GPU vertices — RESOLVED
    • Removed record-time CPU read_quant24_header from the GPU path; decode_quant24_vb (sanitize.rs:480-519) reads the 32-byte header and packed vertices together from the same shadow SRV (g_src) at GPU execution time.
    • hwrt.rs:2706-2738 resolves crate::shadow::find(hdr_va, total_bytes) and calls sh.refresh(list, hdr_va, total_bytes) over the full [vb_va - 0x20, vb_va + vbytes) span, guarded by quant24_shadow_eligible.
    • Submission-time mutation coherence and non-finite GPU header scrubbing are explicitly tested (hwrt.rs:5509-5632).
  • Prior non-blocking hardening note (actual_stride < 8 in quant24_shadow_eligible) was also addressed (sanitize.rs:553).

Adversarial Verification of Fix Commit (5c16e97..8efed66)

  • Header VA underflow, alignment, and shadow coverage:
    • vb_va < 0x20 fails closed in both quant24_bounds and quant24_shadow_eligible (vb_va.checked_sub(0x20)).
    • host_hdr is guarded by if hdr_va >= sh_start { sh.gpu(hdr_va) } else { 0 } (hwrt.rs:2712-2716) and validated for host_hdr != 0, 4-byte alignment, and full [hdr_va, vb_va + vbytes) ⊆ [sh_start, sh_start + sh_len) coverage (sanitize.rs:548-568).
    • hdr_base = host_hdr & !15 (hwrt.rs:1468) is always 16-byte aligned and >= sh.buffer.GetGPUVirtualAddress() because all committed/placed D3D12 shadow buffers have 64 KiB-aligned base GPU VAs (including Shadow::placed via inplace.rs:122,130).
  • ByteAddressBuffer offsets, chunking, and layout/endianness:
    • hdr_bias = (host_hdr & 15) as u32 ∈ {0, 4, 8, 12} (4-byte aligned). Load4(q_hdr_bias) reads [0..16) (bias[0..3] in h0.xyz, swizzle in h0.w) and Load3(q_hdr_bias + 16u) reads [16..28) (scale[0..3] in h1.xyz), matching read_quant24_header (decoders.rs:492-502) little-endian layout identically.
    • Across sanitize_chunks(vcount, stride), SRV(t0) stays pinned at hdr_base while vb_offset = hdr_bias + 0x20 + (u64::from(done).saturating_mul(stride) as u32) advances per chunk; vbytes <= MAX_DECODE_READ_BYTES (and quant24_shadow_eligible's vbytes <= u32::MAX - 0x30) prevents any u32 overflow in vb_offset or at = q_vb_offset + v * q_stride + 8. chunk_dst stays 16-byte aligned (done is a multiple of 64 for stride <= 0x7FFC, so done * 12 is a multiple of 768).
  • HLSL NaN/Inf validation under FXC fast-math (D3DCompile flags = 0):
    • Header finiteness checks raw uint loads directly ((h0.xyz & 0x7FFFFFFFu) >= 0x7F800000u || (h1 & 0x7FFFFFFFu) >= 0x7F800000u), catching ±Inf and all qNaN/sNaN via unsigned integer comparisons immune to FXC fast-math, writing quiet NaN 0x7FC00000u (DXR inactive primitive) for every vertex.
    • Post-mad range/finiteness scrubbing uses (asuint(pos) & 0x7FFFFFFFu) > 0x501502F9u (1e10f32), also pure integer bit comparison immune to fast-math.
  • Root signature & Rust parameter matching:
    • RS_QUANT24 (RootConstants(num32BitConstants=4, b1), SRV(t0), UAV(u0)) and cbuffer Quant24Params (4 uints: q_count, q_stride, q_hdr_bias, q_vb_offset, zero padding) match quant24_root_params ([u32; 4]) and SetComputeRoot32BitConstants(0, 4, ...) / SRV(1, hdr_base) / UAV(2, chunk_dst) (hwrt.rs:1473-1482). RS for clamp_ib/copy_vb is untouched.
  • D3D12 resource states, lifetimes, and fallback coherence:
    • sh.buffer remains implicitly promoted from COMMON and pinned via list.keep(&sh.buffer); work leases start in UNORDERED_ACCESS, transition UAV -> NON_PIXEL_SHADER_RESOURCE before BuildRaytracingAccelerationStructure and back NON_PIXEL_SHADER_RESOURCE -> UAV after flush_blas_waves (hwrt.rs:2076-2105).
    • has_vb_shadow = false prevents out-of-bounds eff_vc expansion (hwrt.rs:2964) and redundant copy_vb (hwrt.rs:3018); *bound = true triggers state replay.
    • CPU fallback (decode_title_quant24_vb) shares quant24_bounds, swizzle modes, bit unpacking, and sane_position.
  • CRLF file sizes & title neutrality:
    • crates/victory-gpu/src/hwrt.rs: 229,594 B CRLF (raw 223,961 B) <= 655,360 B
    • crates/victory-gpu/src/hwrt/decoders.rs: 30,822 B CRLF (raw 30,023 B) <= 655,360 B
    • crates/victory-gpu/src/hwrt/sanitize.rs: 30,567 B CRLF (raw 29,706 B) <= 655,360 B
    • Strictly title-neutral across all touched files.

VERDICT: VERIFIED CLEAN (0 P0, 0 P1)

<!-- greyfinch-sync:Androtim/MiniVI:comment:7410000152 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7410000152). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T11:22:04Z. --- ## Gate 2 Pure-Reasoning Re-Audit — PR #432 (8efed66) Pure-reasoning re-audit of `perf/w12a-hwrt-quant24-gpu` (`8efed66`, fix commit `5c16e97..8efed66`, full diff `dc55250..8efed66`) across `crates/victory-gpu/src/hwrt.rs`, `crates/victory-gpu/src/hwrt/decoders.rs`, and `crates/victory-gpu/src/hwrt/sanitize.rs`. ### Prior `[P1]` Findings Verification (comment `7409603587`) 1. **`[P1]` Unbounded `vbytes` bypassing `MAX_DECODE_READ_BYTES` — RESOLVED** - `quant24_bounds` (`decoders.rs:453-466`) now enforces `vb_va >= 0x20`, `vcount > 0`, checked arithmetic, and `vbytes > MAX_DECODE_READ_BYTES as u64 || stage_bytes > MAX_DECODE_READ_BYTES`, shared by both the GPU path (`hwrt.rs:2700`) and CPU fallback (`read_quant24_header`, `decoders.rs:487`). - `total_bytes = vbytes + 0x20` passed to `crate::shadow::find` (`hwrt.rs:2707-2709`) is strictly bounded to `<= 64 MiB + 32 B`, preventing multi-hundred-MiB/GiB loose window reservations on large strides. - Regression test added for stride-amplified `vbytes > MAX_DECODE_READ_BYTES` (`decoders.rs:782-783`). 2. **`[P1]` Torn-read coherence between record-time CPU header and submission-time GPU vertices — RESOLVED** - Removed record-time CPU `read_quant24_header` from the GPU path; `decode_quant24_vb` (`sanitize.rs:480-519`) reads the 32-byte header and packed vertices together from the same shadow SRV (`g_src`) at GPU execution time. - `hwrt.rs:2706-2738` resolves `crate::shadow::find(hdr_va, total_bytes)` and calls `sh.refresh(list, hdr_va, total_bytes)` over the full `[vb_va - 0x20, vb_va + vbytes)` span, guarded by `quant24_shadow_eligible`. - Submission-time mutation coherence and non-finite GPU header scrubbing are explicitly tested (`hwrt.rs:5509-5632`). - Prior non-blocking hardening note (`actual_stride < 8` in `quant24_shadow_eligible`) was also addressed (`sanitize.rs:553`). ### Adversarial Verification of Fix Commit (`5c16e97..8efed66`) - **Header VA underflow, alignment, and shadow coverage:** - `vb_va < 0x20` fails closed in both `quant24_bounds` and `quant24_shadow_eligible` (`vb_va.checked_sub(0x20)`). - `host_hdr` is guarded by `if hdr_va >= sh_start { sh.gpu(hdr_va) } else { 0 }` (`hwrt.rs:2712-2716`) and validated for `host_hdr != 0`, 4-byte alignment, and full `[hdr_va, vb_va + vbytes) ⊆ [sh_start, sh_start + sh_len)` coverage (`sanitize.rs:548-568`). - `hdr_base = host_hdr & !15` (`hwrt.rs:1468`) is always 16-byte aligned and `>= sh.buffer.GetGPUVirtualAddress()` because all committed/placed D3D12 shadow buffers have 64 KiB-aligned base GPU VAs (including `Shadow::placed` via `inplace.rs:122,130`). - **`ByteAddressBuffer` offsets, chunking, and layout/endianness:** - `hdr_bias = (host_hdr & 15) as u32` ∈ `{0, 4, 8, 12}` (4-byte aligned). `Load4(q_hdr_bias)` reads `[0..16)` (`bias[0..3]` in `h0.xyz`, `swizzle` in `h0.w`) and `Load3(q_hdr_bias + 16u)` reads `[16..28)` (`scale[0..3]` in `h1.xyz`), matching `read_quant24_header` (`decoders.rs:492-502`) little-endian layout identically. - Across `sanitize_chunks(vcount, stride)`, `SRV(t0)` stays pinned at `hdr_base` while `vb_offset = hdr_bias + 0x20 + (u64::from(done).saturating_mul(stride) as u32)` advances per chunk; `vbytes <= MAX_DECODE_READ_BYTES` (and `quant24_shadow_eligible`'s `vbytes <= u32::MAX - 0x30`) prevents any `u32` overflow in `vb_offset` or `at = q_vb_offset + v * q_stride` + 8. `chunk_dst` stays 16-byte aligned (`done` is a multiple of 64 for `stride <= 0x7FFC`, so `done * 12` is a multiple of 768). - **HLSL NaN/Inf validation under FXC fast-math (`D3DCompile` flags = `0`):** - Header finiteness checks raw `uint` loads directly (`(h0.xyz & 0x7FFFFFFFu) >= 0x7F800000u || (h1 & 0x7FFFFFFFu) >= 0x7F800000u`), catching `±Inf` and all `qNaN`/`sNaN` via unsigned integer comparisons immune to FXC fast-math, writing quiet NaN `0x7FC00000u` (DXR inactive primitive) for every vertex. - Post-`mad` range/finiteness scrubbing uses `(asuint(pos) & 0x7FFFFFFFu) > 0x501502F9u` (`1e10f32`), also pure integer bit comparison immune to fast-math. - **Root signature & Rust parameter matching:** - `RS_QUANT24` (`RootConstants(num32BitConstants=4, b1), SRV(t0), UAV(u0)`) and `cbuffer Quant24Params` (4 `uint`s: `q_count`, `q_stride`, `q_hdr_bias`, `q_vb_offset`, zero padding) match `quant24_root_params` (`[u32; 4]`) and `SetComputeRoot32BitConstants(0, 4, ...)` / `SRV(1, hdr_base)` / `UAV(2, chunk_dst)` (`hwrt.rs:1473-1482`). `RS` for `clamp_ib`/`copy_vb` is untouched. - **D3D12 resource states, lifetimes, and fallback coherence:** - `sh.buffer` remains implicitly promoted from `COMMON` and pinned via `list.keep(&sh.buffer)`; `work` leases start in `UNORDERED_ACCESS`, transition `UAV -> NON_PIXEL_SHADER_RESOURCE` before `BuildRaytracingAccelerationStructure` and back `NON_PIXEL_SHADER_RESOURCE -> UAV` after `flush_blas_waves` (`hwrt.rs:2076-2105`). - `has_vb_shadow = false` prevents out-of-bounds `eff_vc` expansion (`hwrt.rs:2964`) and redundant `copy_vb` (`hwrt.rs:3018`); `*bound = true` triggers state replay. - CPU fallback (`decode_title_quant24_vb`) shares `quant24_bounds`, swizzle modes, bit unpacking, and `sane_position`. - **CRLF file sizes & title neutrality:** - `crates/victory-gpu/src/hwrt.rs`: 229,594 B CRLF (raw 223,961 B) `<= 655,360 B` - `crates/victory-gpu/src/hwrt/decoders.rs`: 30,822 B CRLF (raw 30,023 B) `<= 655,360 B` - `crates/victory-gpu/src/hwrt/sanitize.rs`: 30,567 B CRLF (raw 29,706 B) `<= 655,360 B` - Strictly title-neutral across all touched files. VERDICT: VERIFIED CLEAN (0 P0, 0 P1)
Androtim commented 2026-12-04 11:59:51 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T11:59:51Z.


Gate 2 Pure-Reasoning Re-Audit — PR #431 (c652351)

Re-audited fix commit 81b07f8 and clean merge c652351 (zero conflict hunks against origin/main @ 8503d1d; PR diff touches only rayquery.rs, analyze.rs, and rayquery_tests.rs).

  • Clean-room / Title-neutrality: PASS (zero forbidden terms or local paths).
  • File sizes (CRLF <= 655,360 B): PASS — rayquery.rs 29,866 B, analyze.rs 421,799 B, rayquery_tests.rs 329,874 B.

Verification of Prior Findings (5 [P0] + 2 [P1])

  1. [P0] #1 Inverted dynamic-opacity s_and_saveexec_b32/64 & eval_pre_callback_lane_bit — RESOLVED

    • atom_forced_by (analyze.rs:3374-3412) performs exact memoized ROBDD satisfiability restriction for both target_val = true and false, returning Some(true) iff cond => target and Some(false) iff cond => !target (so E0 & !Atom::Lane(lv) yields Some(false)).
    • collect_bool_atoms (analyze.rs:7396-7450) checks both ce and st.reach[search_blk], rejects contradictory polarities, and propagates Result from eval_pre_callback_lane_bit.
    • eval_pre_callback_lane_bit (analyze.rs:7657-7785) explicitly handles v_cmp_{eq,ne}_u32 on is_tri_opacity_val, rejects non-VALU / modified VALU ops, and fails closed (Err) on unproven pre-callback Atom::Lanes.
  2. [P0] #2 Opaque-lane mutations & post-merge discards in find_callback_accumulator_next / is_callback_only_user_accumulator — RESOLVED

    • collect_opaque_preserved_vals + read_old_dst_inactive_val (analyze.rs:3539-3650) trace !ce lanes through guarded callback writes and Case 1b callback PHIs, failing closed on v_writelane_b32, unguarded writes reachable by !ce, or EXEC masks exceeding ce.
    • Both find_callback_accumulator_next and is_callback_only_user_accumulator verify cb_exec_within_entry_mask and opaque_lanes_preserve_hp for Inline and Case 1b Blocks, and find_callback_accumulator_next uses compute_post_merge_reachable to reject post-merge branch discards back to hp.
  3. [P0] #3 Raw BVH pointer / synthetic sentinel flow into user accumulators — RESOLVED

    • cb_val_routes_synthetic (analyze.rs:3721-3858) walks all Fields::Valu, Fields::Sop, and Fields::Ds explicit non-mask reads and guarded old_dst inputs (stopping only at Fields::Flat loads, lane masks, and real hardware attributes cand_t/cand_u/cand_v/cand_ff), rejecting cur_tri/cur_inst/cand_flags/inv_d/committed_{tri,inst}_old in both validate_tri_merge_phi and find_callback_accumulator_next (cb_acc_routes_synthetic_sentinel). Path-sensitive pruning via st.bools.meet_seen fails closed on step/constraint limits.
  4. [P0] #4 Cross-lane reads in val_has_explicit_read & v_writelane_b32 in read_old_dst_inactive — RESOLVED

    • is_lane_local_read_inst (analyze.rs:3416-3467) rejects DPP VALU, v_readlane_b32/v_readfirstlane_b32/v_writelane_b32/v_permlane*/v_movrel*/v_swaprel*, all Fields::Ds, image_get_lod, implicit-derivative image_sample*, and image_gather4*_b before allowing read_dead_on_old_lanes or read_unreachable_on_path.
    • read_old_dst_inactive_val breaks on pi.name() == v_writelane_b32.
  5. [P0] #5 Non-invariant header PHIs read in callback silently frozen — RESOLVED

    • classify_live_outs (analyze.rs:9739-9808) allows skipping accumulators only when !val_has_explicit_read or is_invariant_header_phi; otherwise verifies every back-edge either resolves to the same callback accumulator next_val or is a non-post-merge back-edge preserving hp, failing closed with Err otherwise.
  6. [P1] #6 is_iter_overflow_state_cndmask boundary & opaque_sets_state_zero — RESOLVED

    • Both init checks now enforce c0 <= threshold.saturating_sub(1024) (rejecting c0 = 65534, K = 65535).
    • opaque_sets_state_zero check for callbacks moved after cb_site_set construction (analyze.rs:4506-4524) and passes &cb_site_set. Covered by new negative unit tests.
  7. [P1] #7 Wave64 half-mask checks & collapse_scalar_mov_phi s_mov_b64 — RESOLVED

    • is_non_opaque_mask / nonop_idx (analyze.rs:4022-4165) dispatch _b64 vs _b32 by p.wave64, verify both low and high dwords via read_mask_pair / matches_mask_dst_pair / strip_mask_mov_pair, and require inline -1 (Operand::Const(193)) for Wave64 s_xor_b64 (rejecting 32-bit zero-extended literals).
    • collapse_scalar_mov_phi restricted to s_mov_b32. Covered by wave64_inverted_opacity_callback_entry_mask_matching.

VERDICT: VERIFIED CLEAN (0 P0, 0 P1)

<!-- greyfinch-sync:Androtim/MiniVI:comment:7410830192 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7410830192). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T11:59:51Z. --- ## Gate 2 Pure-Reasoning Re-Audit — PR #431 (c652351) Re-audited fix commit `81b07f8` and clean merge `c652351` (zero conflict hunks against `origin/main` @ `8503d1d`; PR diff touches only `rayquery.rs`, `analyze.rs`, and `rayquery_tests.rs`). - **Clean-room / Title-neutrality:** PASS (zero forbidden terms or local paths). - **File sizes (CRLF `<= 655,360 B`):** PASS — `rayquery.rs` `29,866 B`, `analyze.rs` `421,799 B`, `rayquery_tests.rs` `329,874 B`. ### Verification of Prior Findings (5 `[P0]` + 2 `[P1]`) 1. **`[P0] #1` Inverted dynamic-opacity `s_and_saveexec_b32/64` & `eval_pre_callback_lane_bit` — RESOLVED** - `atom_forced_by` (`analyze.rs:3374-3412`) performs exact memoized ROBDD satisfiability restriction for both `target_val = true` and `false`, returning `Some(true)` iff `cond => target` and `Some(false)` iff `cond => !target` (so `E0 & !Atom::Lane(lv)` yields `Some(false)`). - `collect_bool_atoms` (`analyze.rs:7396-7450`) checks both `ce` and `st.reach[search_blk]`, rejects contradictory polarities, and propagates `Result` from `eval_pre_callback_lane_bit`. - `eval_pre_callback_lane_bit` (`analyze.rs:7657-7785`) explicitly handles `v_cmp_{eq,ne}_u32` on `is_tri_opacity_val`, rejects non-VALU / modified VALU ops, and fails closed (`Err`) on unproven pre-callback `Atom::Lane`s. 2. **`[P0] #2` Opaque-lane mutations & post-merge discards in `find_callback_accumulator_next` / `is_callback_only_user_accumulator` — RESOLVED** - `collect_opaque_preserved_vals` + `read_old_dst_inactive_val` (`analyze.rs:3539-3650`) trace `!ce` lanes through guarded callback writes and Case 1b callback PHIs, failing closed on `v_writelane_b32`, unguarded writes reachable by `!ce`, or `EXEC` masks exceeding `ce`. - Both `find_callback_accumulator_next` and `is_callback_only_user_accumulator` verify `cb_exec_within_entry_mask` and `opaque_lanes_preserve_hp` for Inline and Case 1b Blocks, and `find_callback_accumulator_next` uses `compute_post_merge_reachable` to reject post-merge branch discards back to `hp`. 3. **`[P0] #3` Raw BVH pointer / synthetic sentinel flow into user accumulators — RESOLVED** - `cb_val_routes_synthetic` (`analyze.rs:3721-3858`) walks all `Fields::Valu`, `Fields::Sop`, and `Fields::Ds` explicit non-mask reads and guarded `old_dst` inputs (stopping only at `Fields::Flat` loads, lane masks, and real hardware attributes `cand_t`/`cand_u`/`cand_v`/`cand_ff`), rejecting `cur_tri`/`cur_inst`/`cand_flags`/`inv_d`/`committed_{tri,inst}_old` in both `validate_tri_merge_phi` and `find_callback_accumulator_next` (`cb_acc_routes_synthetic_sentinel`). Path-sensitive pruning via `st.bools.meet_seen` fails closed on step/constraint limits. 4. **`[P0] #4` Cross-lane reads in `val_has_explicit_read` & `v_writelane_b32` in `read_old_dst_inactive` — RESOLVED** - `is_lane_local_read_inst` (`analyze.rs:3416-3467`) rejects DPP VALU, `v_readlane_b32`/`v_readfirstlane_b32`/`v_writelane_b32`/`v_permlane*`/`v_movrel*`/`v_swaprel*`, all `Fields::Ds`, `image_get_lod`, implicit-derivative `image_sample*`, and `image_gather4*_b` before allowing `read_dead_on_old_lanes` or `read_unreachable_on_path`. - `read_old_dst_inactive_val` breaks on `pi.name() == v_writelane_b32`. 5. **`[P0] #5` Non-invariant header PHIs read in callback silently frozen — RESOLVED** - `classify_live_outs` (`analyze.rs:9739-9808`) allows skipping `accumulators` only when `!val_has_explicit_read` or `is_invariant_header_phi`; otherwise verifies every back-edge either resolves to the same callback accumulator `next_val` or is a non-post-merge back-edge preserving `hp`, failing closed with `Err` otherwise. 6. **`[P1] #6` `is_iter_overflow_state_cndmask` boundary & `opaque_sets_state_zero` — RESOLVED** - Both init checks now enforce `c0 <= threshold.saturating_sub(1024)` (rejecting `c0 = 65534, K = 65535`). - `opaque_sets_state_zero` check for callbacks moved after `cb_site_set` construction (`analyze.rs:4506-4524`) and passes `&cb_site_set`. Covered by new negative unit tests. 7. **`[P1] #7` Wave64 half-mask checks & `collapse_scalar_mov_phi` `s_mov_b64` — RESOLVED** - `is_non_opaque_mask` / `nonop_idx` (`analyze.rs:4022-4165`) dispatch `_b64` vs `_b32` by `p.wave64`, verify both low and high dwords via `read_mask_pair` / `matches_mask_dst_pair` / `strip_mask_mov_pair`, and require inline `-1` (`Operand::Const(193)`) for Wave64 `s_xor_b64` (rejecting 32-bit zero-extended literals). - `collapse_scalar_mov_phi` restricted to `s_mov_b32`. Covered by `wave64_inverted_opacity_callback_entry_mask_matching`. VERDICT: VERIFIED CLEAN (0 P0, 0 P1)
Androtim commented 2026-12-04 15:34:59 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-04T15:34:59Z.


Gate 2 Pure-Reasoning Audit — PR #434 (e110687)

Scope: fix/high-vram-rt-buffer-caps (e110687, 2 files, +26 / -10) — pure-reasoning review of git diff origin/main...HEAD and surrounding code in apps/victory/src/play.rs, crates/victory-gpu/src/hwrt/budget.rs, shadow.rs, and memory.rs.

Checklist

  1. 8 GiB low_vram path untouched: PASS — LOW_VRAM_THRESHOLD_MB (9216), the entire if low_vram { ... } block in play.rs:443-485 (VICTORY_CARD_BUFFERS_MB = 320/512/1024, VICTORY_RT_MEMORY_MB=768, VICTORY_BVH_FAULTS_ALL=8192), and BLAS_BUDGET_DEFAULT_LOW (512 MiB) / MID (768 MiB) in budget.rs are 100% untouched.
  2. 10–12 GiB mid-VRAM path (9216 < vram_mb <= 13 * 1024): PASS — play.rs:491-498 leaves VICTORY_CARD_BUFFERS_MB unset (delegating to shadow.rs::resolve_card_limits()) while preserving VICTORY_RT_MEMORY_MB=1024 and VICTORY_BVH_FAULTS_ALL=8192. Covered by hw_rt_without_bvh_builder_applies_rt_vram_caps_and_honors_overrides at Some(12288).
  3. >= 14 GiB high-VRAM path & vram_mb: None edge case: PASS — For Some(mb) with mb > 13312 (16/24/32 GB cards) and for vram_mb: None, both low_vram and vram_mb.is_some_and(|mb| mb <= 13 * 1024) evaluate to false, leaving VICTORY_CARD_BUFFERS_MB, VICTORY_RT_MEMORY_MB, and VICTORY_BVH_FAULTS_ALL unset so runtime DXGI-scaled defaults apply (with conservative fallbacks in shadow.rs / budget.rs if DXGI is also unavailable). Explicit --set overrides still win on both low- and high-VRAM paths.
  4. BLAS_BUDGET_DEFAULT_HIGH = 1536 << 20: PASS — 1536 MiB (~10–12% of a 13–16 GiB effective budget, evicting down to 90% / 1382 MiB) is safe on 13–16 GiB cards while keeping 12 GiB cards in MID (768 MiB). Doc comment (budget.rs:169) and unit tests (budget.rs:1288-1289, 1325) match.
  5. CRLF file sizes & title-neutrality: PASS — apps/victory/src/play.rs is 80,071 B CRLF and crates/victory-gpu/src/hwrt/budget.rs is 64,251 B CRLF (both well under 655,360 B). Diff is 100% title-neutral.

VERDICT: VERIFIED CLEAN (0 P0, 0 P1)

<!-- greyfinch-sync:Androtim/MiniVI:comment:7416082600 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/issues/282#issuecomment-7416082600). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-04T15:34:59Z. --- ## Gate 2 Pure-Reasoning Audit — PR #434 (e110687) **Scope:** `fix/high-vram-rt-buffer-caps` (`e110687`, 2 files, +26 / -10) — pure-reasoning review of `git diff origin/main...HEAD` and surrounding code in `apps/victory/src/play.rs`, `crates/victory-gpu/src/hwrt/budget.rs`, `shadow.rs`, and `memory.rs`. ### Checklist 1. **8 GiB `low_vram` path untouched:** **PASS** — `LOW_VRAM_THRESHOLD_MB` (`9216`), the entire `if low_vram { ... }` block in `play.rs:443-485` (`VICTORY_CARD_BUFFERS_MB` = `320/512/1024`, `VICTORY_RT_MEMORY_MB=768`, `VICTORY_BVH_FAULTS_ALL=8192`), and `BLAS_BUDGET_DEFAULT_LOW` (`512 MiB`) / `MID` (`768 MiB`) in `budget.rs` are 100% untouched. 2. **10–12 GiB mid-VRAM path (`9216 < vram_mb <= 13 * 1024`):** **PASS** — `play.rs:491-498` leaves `VICTORY_CARD_BUFFERS_MB` unset (delegating to `shadow.rs::resolve_card_limits()`) while preserving `VICTORY_RT_MEMORY_MB=1024` and `VICTORY_BVH_FAULTS_ALL=8192`. Covered by `hw_rt_without_bvh_builder_applies_rt_vram_caps_and_honors_overrides` at `Some(12288)`. 3. **`>= 14 GiB` high-VRAM path & `vram_mb: None` edge case:** **PASS** — For `Some(mb)` with `mb > 13312` (16/24/32 GB cards) and for `vram_mb: None`, both `low_vram` and `vram_mb.is_some_and(|mb| mb <= 13 * 1024)` evaluate to `false`, leaving `VICTORY_CARD_BUFFERS_MB`, `VICTORY_RT_MEMORY_MB`, and `VICTORY_BVH_FAULTS_ALL` unset so runtime DXGI-scaled defaults apply (with conservative fallbacks in `shadow.rs` / `budget.rs` if DXGI is also unavailable). Explicit `--set` overrides still win on both low- and high-VRAM paths. 4. **`BLAS_BUDGET_DEFAULT_HIGH = 1536 << 20`:** **PASS** — `1536 MiB` (~10–12% of a 13–16 GiB effective budget, evicting down to 90% / `1382 MiB`) is safe on 13–16 GiB cards while keeping 12 GiB cards in `MID` (`768 MiB`). Doc comment (`budget.rs:169`) and unit tests (`budget.rs:1288-1289, 1325`) match. 5. **CRLF file sizes & title-neutrality:** **PASS** — `apps/victory/src/play.rs` is `80,071 B` CRLF and `crates/victory-gpu/src/hwrt/budget.rs` is `64,251 B` CRLF (both well under `655,360 B`). Diff is 100% title-neutral. VERDICT: VERIFIED CLEAN (0 P0, 0 P1)
Sign in to join this conversation.
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Androtim/MiniVI#282
No description provided.