Commit Graph

4163 Commits

Author SHA1 Message Date
1dd08900f6 process: the run's cleanup holds one lock, as the UCRT's exit lock; a throwing handler terminates
Review follow-up for #1564:
- Registration and the cleanup of exit, quick_exit and _cexit hold one recursive lock of the run's own, from before the thread-local callback through the table's drain (and _cexit's stream flush), as the UCRT holds its exit lock: two threads never clean up at once, and a registration from another thread waits for the cleanup. The exiting thread may still register from a handler, _cexit still returns, and the lock is released before the run ends (end_run), also when a handler ends the run from inside a drain.
- Each guest cleanup callback (atexit, at_quick_exit, the thread-local destructor callback) runs inside a C++ exception boundary: one that throws ends the run through game_abort, as the UCRT's terminate() would (exit code 3), instead of leaving the process with 0xE06D7363.

tiny_atexit gains four modes, held to the native sequence: concurrent_cexit (a second thread's _cexit, with a thread_local of its own, waits for the cleanup), quick_exit_register (an at_quick_exit from a second thread during a quick_exit drain waits, so its handler never runs), quick_exit_throw and exit_throw (exit code 3). In the concurrent modes the slow handler waits until the second thread is about to call, so the sequence is fixed under any scheduling with the lock. All four fail on c5b51e9 through --run.
2026-11-27 16:10:51 -03:00
6f7963abdd process: the game's at_quick_exit handlers and thread-local exit callback are the run's own
The game's at_quick_exit() (_crt_at_quick_exit) and _register_thread_local_exe_atexit_callback still
reached the host CRT, which the game shares with gta6rt. Under `gta6rt --run`:
  - quick_exit() ran none of the game's at_quick_exit handlers;
  - exit() and _cexit() never ran the exiting thread's thread_local destructors, and a second
    registration in the host's one-slot callback would terminate gta6rt.

Now _crt_at_quick_exit goes to a second table of the run's own, which quick_exit() runs newest first
under the exit lock; _exit() and _Exit() run none (they no longer share game_quick_exit). The thread-local
callback is the run's own: exit() and _cexit() call it with DLL_PROCESS_DETACH before the atexit handlers,
as the UCRT does, and a second registration aborts, as the UCRT's terminate() does. Both reset per run.

tiny_atexit gains five modes (at_quick_exit, at_quick_exit_exit, at_quick_exit__exit, thread_local_exit,
thread_local_cexit). Their expected sequences in check_atexit.cmake were measured by running the fixture
natively on Windows 11; before this change --run differed on at_quick_exit, thread_local_exit and
thread_local_cexit. run_tiny_atexit now holds 13 paths to the Windows sequence.
2026-11-27 16:09:18 -03:00
53ed711b85 xs proxy mock: check queue and fence ownership during forwarding 2026-11-27 12:53:48 -06:00
f7f766145b gfx10: preserve the separate volume filter in sampler words 2026-11-27 12:49:19 -06:00
5e8d3349c8 Merge origin/main into window-retire-on-1920
submit_write keeps main's second root UAV (va2) and our wait flag: (s, va, va2 = 0, wait = true); the two callers that only execute pass va2 = 0 explicitly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gt9hwSKP7weM2P7sk5skto
2026-11-27 19:25:41 +01:00
09d232fb61 Merge r12/heap-mirror 2026-11-27 13:23:24 -05:00
fdd58296f7 d3d12: fix console heap in-place filtering and TitleMirror home.sums sync
Root-cause fixes for four audited bugs in console heap in-place filtering
and TitleMirror:

1. finish_in_place() not_tsharp zeroing & record clear:
   Check gfx10::is_image(words) and TitleImage::not_tsharp in
   finish_in_place(), zeroing w[0..3] and clearing heap.records on
   (w[3] >> 30) slots with d.texture == Records::none (matching
   fix_console_slot) so non-T# overwrites of deferred slots never leak
   raw words into home[slot] or leave stale texture records.

2. Record-answered / batch_answers mirror write-back tracking:
   Call note_title_write(base, span) outside page_mirror.mutex when
   apply_answer() (in finish_in_place) or answered_by_record() (in
   fix_vsharp) returns a mirror-resolved identity target
   (to == base && base >= arena.size), matching vsharp_address path 6.

3. reachable_as_written() & filter_slot_locked() semantic parity:
   - Reject base == 0 in reachable_as_written(), check encodable() +
     gpu_backings + geometry.lookup, and accept bit-47 base | ~mask
     direct backings even when signed_vsharp_offsets() is off (matching
     vsharp_address:4367, 4392). Track non-sparse direct backings as
     Records::resolved so target_gone re-filters them if freed.
   - Keep O(1) permanent rejection (Records::none) only for null base,
     unbacked bit-47, and out-of-arena-span offsets (base < arena.size
     not in title_memory, aliases, or stream-pool GPU views).
   - For unresolvable base >= arena.size halves (not in title_memory
     within span, no alias, no stream-pool GPU view), null in O(1) and
     record Records::waiting directly without deferring so a later
     SlotChange::source_added still wakes and re-filters them.

4. TitleMirror single-snapshot home/sums/copy sync:
   Unify home, home.sums[], and filtered copy updates through a single
   fill_scratch_ snapshot across map() (initial aliased fill & alias
   handoff), make_copy(), and finish_write_back(), preserving GPU-only
   pieces on existing homes so A -> B -> A writes never leave stale
   filtered copies and avoiding duplicate guarded copies.

Tests:
- title_mirror_hooks_test: added make_copy_aba_staleness (make_copy,
  alias handoff, finish_write_back A->B->A) and updated
  filter_pieces_mask_and_scratch for unified single-copy initial map.
- console_heap_slot_records_test: added waiting_source_added_and_tsharp_clear.
- d3d12_heap_in_place_test: added deterministic finish_in_place not_tsharp
  zeroing and late-alias wake-up regressions.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 13:22:49 -05:00
b0419cefad runtime: preserve sync ExecuteCommandLists, drop unsafe batch coalescing, track active_seq_
Fix queue-sync bugs in VulkanQueue (runtime/src/vulkan_backend.h):

1. Synchronous execute_sync_impl(): when executing_ is active and this
   batch is not blocked by an unmet Wait (blocked_by_wait_locked()), wait
   on exec_cv_ with state_mutex_ unlocked instead of silently deferring
   into held_. When !executing_ && !blocked_by_wait_locked(), take
   executing_ and drain any already-ready held ops ahead of us first
   (closing the gap between QueueHolds::signaled() and pump_ready()
   reaching this queue), then hold behind a wait-blocked front if
   must_hold() remains true or execute synchronously with before_execute_()
   before returning. Wait, Signal, Marker, and genuinely wait-blocked
   batches still enqueue under state_mutex_ without blocking on
   before_execute_() or replay.
2. active_seq_ tracking: assign active_seq_ under state_mutex_ for direct
   unheld execute_sync_impl(), signal_sync(), marker_sync(), update_tiles(),
   and copy_tile_mappings(), clear active_seq_ before drain/release,
   linearize oldest_held_seq() under state_mutex_, and flush
   QueueHolds::pump_ready() after releasing state_mutex_ so after_held()
   barriers never overtake active unheld submissions.
3. Remove unsafe cross-batch coalescing in drain_held_while_executing() and
   async_worker() (along with batch_breaks, barrier_after,
   run_single_held_batch, and run_coalesced_execute*) so every
   ExecuteCommandLists runs its own before_execute_(), bindless_prepare_(),
   prelude_record_(), and fault markers in strict FIFO order.
4. Fix stale prepared[] iteration in execute_now() statistics->mesh setup
   by iterating only i < lists.size().

Update and expand submit_frame_test to cover sync exec_cv_ waiting,
unlocked wait-blocked enqueue, releaser-drain sync ordering, ready-front
drain while pump_mutex_ is held by another thread, active_seq_ protection
of after_held() across unheld execute() and signal(), per-batch FIFO
drain without coalescing, zero-copy CommandList Reset(), and QueueHolds
progress tracking.

Tested on Linux (AMD Ryzen 9 7950X3D iGPU, RADV RAPHAEL_MENDOCINO,
MESA_VK_DEVICE_SELECT=1002:164e!): 9/9 required queue ctest targets passed
(2.92s) plus 5/5 submit_frame_test stress runs.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 13:19:48 -05:00
28829e0aab gameinput: let go of the cursor clip while the window is dragged
The keyboard pad clips the cursor to the foreground window's client
area and re-applies the clip every 100 ms. A press on the title bar was
pulled into the client area, and during the modal move loop each re-clip
pulled the cursor, and the window with it, down the screen instead of
letting it be dragged.

The clip is now released while the window's thread is in a move/size or
menu loop (GetGUIThreadInfo: GUI_INMOVESIZE, GUI_INMENUMODE,
GUI_SYSTEMMENUMODE), and while a mouse press that began outside the
client area is held, including one that activated the window. A press
in the client area keeps the clip, so a click still cannot land on
another window. The decision is CursorClipGate (shims/gameinput_clip.h),
covered by the new gameinput_clip test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 12:13:35 -06:00
03f1cd7f43 Merge r11/mirror-policy 2026-11-27 11:44:59 -05:00
4442c5b646 runtime: restore kPromote=6/8, drop frame_hot over-copying, and wire region-batched MEM_WRITE_WATCH
- TitleWritePolicy (runtime/src/title_write_policy.h): restore kPromote = 6
  (of kHistory = 8) and cleanly remove the frame_hot / present_frame() tier
  and its dead fields/counters so 1/frame pages never trigger per-submission
  over-copying or copies on empty submissions. Keep O(dirty + hot + recent)
  active lists and sorted Guard::arm_batch() batching.
- HotColdTracking (runtime/src/title_mirror_hot_cold.h) & d3d12_vulkan_device.cpp:
  remove the dead on_present() / last_present_serial hook (coordinated with
  gate-async-fixer) and unused write_watched_* getters, and cache
  region-batched MEM_WRITE_WATCH runs (bridging verified MEM_COMMIT gaps <=
  1 MiB, capped at 64 MiB per GetWriteWatch call, never bridging uncommitted
  holes, with O(1) unordered_set dirty filtering and conservative dirty
  recording + split-retry on mid-run refusal so no journaled write is lost)
  so steady-state collect() runs in O(regions + dirty) without walking
  ww_pages_.
- TitleHeap (runtime/src/title_heap.h) & xmem.cpp: upgrade for_each_committed()
  to emit maximal coalesced committed extents (exact complement of free_runs_,
  O(free_runs_.size()) instead of scanning all 32k span slots, never spanning
  uncommitted holes) and wire MEM_WRITE_WATCH with silent MEM_RESERVE fallback
  + title_write_watch registration/marks in mirror_heap_ready() (never
  combined with MEM_LARGE_PAGES, MEM_PHYSICAL, or section views).
- Tests: update title_write_policy_test.cpp (kPromote = 6/8 and zero copies
  of 1/frame pages on empty submissions) and title_heap_test.cpp (coalesced
  for_each_committed() tracking around decommitted holes).

AI-assisted: Antigravity, Gemini 4 Neon
2026-11-27 11:44:26 -05:00
2e00ea6c13 runtime: track active async, executing, and GPU queue progress for list-value gates
Fixes premature unmet release of console list-value gates at Present under
LEONIDA_SUBMIT_ASYNC and unlocked queue execution:

- QueueHolds (runtime/src/queue_holds.h): add process-wide queue_holds::any_progress()
  backed by a lock-free active CPU/async work counter (WorkGuard / work_changed),
  signaled_unpumped_ tracking across signaled() -> pump_ready(), and per-holder
  lock-free has_pending_gpu_work() protected against detach() via holders_use_mutex_.
- VulkanQueue (runtime/src/vulkan_backend.h): account for queued async inbox calls,
  active async_worker turns (through pump_ready()), pending release_requested_ flags
  (with async_stop_ guard), synchronous/draining executing_ passes (through pump_ready()),
  VulkanFence::signal() -> pump_ready(), and unretired GPU tickets (submitted_gpu_ vs
  progress_ counter). Stop cross-queue release_ready() ping-pong by waking only when
  held_front_seq_ != 0 and calling pump_ready() in async_worker() only when a call
  ran or a held op was released.
- Pump::choose_release (runtime/shims/d3d12_xs_list_values.h): treat
  leonida::queue_holds::any_progress() as active queue progress so held waits are
  never broken unmet while a producer async worker, executing pass, or GPU submission
  is still progressing; advance last_progress_ms_ so kStalledMs measures genuine quiet
  time. Genuine deadlocks (cycles, idle queues + idle GPU at Present, stalled title)
  still break cleanly.
- Tests: add CPU-only QueueHolds + list_value_progress tests in
  list_value_progress_test.cpp and real VulkanQueue async-depth=4 + Present + busy
  producer + genuine deadlock + synchronous executing_ tests in submit_frame_test.cpp.

AI-assisted: Antigravity, Gemini 4 Neon.
Tested on Linux (RADV RAPHAEL_MENDOCINO, MESA_VK_DEVICE_SELECT=1002:164e!):
8/8 passed (list_value_progress, submit_frame, vk_queue, vk_queue_query_sync,
vk_queue_constructor_oom, vk_fence_dispatcher_sync, vk_semaphore_lifetime,
vk_fence_lost_by_counter).
2026-11-27 11:37:59 -05:00
c0201a806b Merge pull request #2467 from OreoFR/rt-async-min-bytes-graphics
d3d12: LEONIDA_ASYNC_MIN_BYTES_GRAPHICS, a separate async threshold for graphics (RT-ASYNC-MIN-BYTES-GRAPHICS)
2026-11-27 17:26:46 +01:00
d7b81dd43b Merge upstream/main (with #2468) into rt-title-writeback-same-page-ranges
#2468 (RT-WRITEBACK-TILE-REOPEN) took write_back's per-page held decision
before the copies for one range. This branch takes it for all of a tracker's
ranges in one call, so the two are now one snapshot over every range, kept in
#2468's host-heap member held_pages_ (sized before lock_ is taken). Both tests
stay: d3d12_title_window_write_back_fault_tile and
d3d12_title_window_write_back_ranges; submit_write takes both va2 and base.

Also from lixonik's review: a run whose pages an earlier range already
reopened (none still kProtected) skips reopen_locked and its VirtualQuery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:08:23 -06:00
55bd6f4f1b Merge pull request #2468 from OreoFR/rt-writeback-tile-reopen
d3d12: a write-back's later runs in a tile its faulting copy reopened still go back (RT-WRITEBACK-TILE-REOPEN)
2026-11-27 17:01:56 +01:00
5cbd3e557b Merge branch 'r1/queue-async' of /tmp/swarm-r1-queue-async into r1/windows-and-heaps 2026-11-27 11:00:21 -05:00
50c5eddcd2 runtime: unlock VulkanQueue state_mutex_ across execution, coalesce ready batches, zero-copy CommandList
Round 1D runtime CPU optimization:
1. Split VulkanQueue state bookkeeping (state_mutex_, microsecond hold) from
   execution serialization (executing_ + exec_cv_ + execution-local wait/pin
   staging). Callers arriving while executing_ is active append to held_ in
   strict FIFO order without blocking on before_execute_() or replay, and the
   executing thread drains ready held work before releasing executing_.
2. Coalesce consecutive ready Deferred::Kind::batch ops in release_held() /
   drain_held_while_executing() and consecutive Call::Kind::execute ops in
   async_worker() (stopping on Signal, Wait, Marker, or Present after_held
   barrier_after), inserting D3D12 inter-batch full memory barriers and
   falling back to per-batch execution on validation failure.
3. Pass closed CommandList snapshots via std::shared_ptr<const CommandList>
   from GraphicsCommandList to VulkanQueue (zero deep copies on submit;
   Reset() reuses storage with an acquire fence when unique or allocates
   fresh storage while in flight), and skip redundant visible_heaps
   scan_title_table() recording for console descriptor heaps when table-scan
   diagnostics are off.
4. Add unit tests in submit_frame_test covering unlocked before_execute_(),
   strict FIFO order, held-batch coalescing and Signal/Wait splits, invalid
   batch fallback, zero-copy Reset(), and async worker (depth=4) coalescing
   with Present barrier ordering.

AI-assisted: Antigravity (Gemini 4 Neon).
Tested on Linux (RADV RAPHAEL_MENDOCINO): 15/15 queue/submit/replay ctest
targets pass (list_value_progress, vk_queue, vk_queue_query_sync,
submit_frame, vk_queue_constructor_oom, vk_semaphore_lifetime,
vk_fence_dispatcher_sync, vk_fence_lost_by_counter, vk_command_replay,
vk_predicated_copy, vk_predicate_capture, vk_overlapping_occlusion,
vk_host_at_aliasing, vk_host_texture_order).
2026-11-27 10:59:34 -05:00
bede0e73e4 d3d12_xs: derived PSO overlays reach DEPTH_STENCIL2 and RASTERIZER1/2 (RT-STATE-PSO-OVERLAY-DS2-RS12)
derive_stream (device slot 55) patches a base PSO stream with records that
carry D3D12 v0 descriptions: tag 0 a D3D12_DEPTH_STENCIL_DESC, tag 1 a
D3D12_RASTERIZER_DESC, tag 5 the two stencil masks. They only matched
DEPTH_STENCIL/DEPTH_STENCIL1 and RASTERIZER, so on a base that uses
DEPTH_STENCIL2 or RASTERIZER1/2 the derive failed as missing state. Found by
kevincommits in #1608 (RT-STATE-AUDIT-PIPELINE, item 6).

Those versions have other layouts, so the record is converted rather than
copied:
- tag 0 on DEPTH_STENCIL2: depth fields and face ops set, the one pair of
  masks on both faces, the base's DepthBoundsTestEnable kept (as for
  DEPTH_STENCIL1);
- tag 5 on DEPTH_STENCIL2: both faces' masks;
- tag 1 on RASTERIZER1: DepthBias as a float; on RASTERIZER2 also the line
  mode from MultisampleEnable/AntialiasedLineEnable, as D3D12 maps them.
DEPTH_STENCIL, DEPTH_STENCIL1 and RASTERIZER are patched as before.

pso_stream_test: bases with DEPTH_STENCIL2 plus RASTERIZER1 or RASTERIZER2
take tags 0, 1 and 5 with every field checked. All 14 new checks fail on main.

AI-assisted (Claude Code)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:58:05 -06:00
7ffaaf0757 Merge branch 'r1/mirror-policy' of /tmp/swarm-r1-mirror-policy into r1/windows-and-heaps 2026-11-27 10:53:03 -05:00
37fcb9f7c0 Runtime: two-tier mirror hot/cold policy, batched guards, fast fill & filter_pieces hook
- TitleWritePolicy (runtime/src/title_write_policy.h): lower submission-hot
  threshold (kPromote 6 -> 3 of 8), add O(active) present_frame() frame-hot
  tier (kFramePromote = 3 of 4, kFrameProbe = 16, unguarded on low-sub frames
  <= 4 subs/frame and guarded on high-sub frames so mid-frame CPU writes are
  never missed and 1-write/frame pages never copy 30x/frame), and sort/batch
  page arms via optional Guard::arm_batch().
- HotColdTracking (runtime/src/title_mirror_hot_cold.h): expose on_present(),
  coalesce contiguous 64 KiB VirtualProtect re-arms in CellGuard::arm_batch(),
  and route MEM_WRITE_WATCH pages through title_write_watch::ask() with zero
  guard faults or hot_tiles conflicts.
- TitleMirror (runtime/src/title_mirror.h): add optional TitleMirrorHooks::
  filter_pieces hook passing fill_scratch_ and the 256-bit changed-piece mask
  from fill() (eliminating duplicate 64 KiB guarded copies), and coalesce
  contiguous changed pieces into single WC-friendly memcpy bursts while
  preserving exact home.sums conflict detection.
- TitleHeap (runtime/src/title_heap.h): add portable reserve() helper for
  MEM_WRITE_WATCH with silent fallback and write_watched() tracking.
- Tests: add unit tests in title_write_policy_test.cpp,
  title_mirror_hooks_test.cpp, and title_heap_test.cpp.

AI-assisted: Antigravity (Gemini 4 Neon)
2026-11-27 10:52:32 -05:00
5543ba9f5f d3d12: eliminate orphan title windows, align mirror chunks, and speed up in-place heap filtering
Round 1A:
- Use VsharpPath::scratch for in-place console heaps in finish_in_place and fix_console_slot so they never allocate general-purpose title windows.
- Never fall through to make_title_window / ShadowPages in resolve_title_memory for addresses already covered by the page mirror.
- Guard vsharp_address's window-creation fallback with bytes <= kTitleWindowMax so oversized V# spans cannot allocate and reject orphan windows.
- Advance <= 2 GiB reservations in title_mirror_space::take past chunk boundaries so placed buffers stay within a single 2 GiB sparse chunk.
- Track arena-backed title windows and slot-133 shadows under ArenaUse::arena_window and report them in memory_breakdown.

Round 1C:
- Add re-entrancy-safe two-pass filter_heap_page_pieces() ready for TitleMirrorHooks::filter_pieces changed-piece mask.
- Reject guaranteed-unresolvable V# halves (null, unbacked bit-47, out-of-arena spans, non-title addresses without an alias) in O(1) inside filter_slot_locked without inserting into heap.records or deferring.
- Clear deferred slot records before finish_in_place and answer repeated V# halves from heap.records under page_mirror.mutex plus a per-batch dedup cache.

Tests:
- Added Linux unit tests in console_heap_slot_records_test (chunk alignment, arena window breakdown, deferred record clearing/answering).
- Added Wine regression tests in d3d12_heap_in_place_test and d3d12_page_mirror_test.

AI-assisted: Antigravity, Gemini 4 Neon
2026-11-27 10:51:23 -05:00
8aaea30c77 native_pso: a single-sided stencil PSO keeps its depth/stencil/raster state (RT-STATE-DEPTH-RASTER-BACKFACE-MASK)
np::d3d12_depth_raster refused any stencil state whose DB_STENCILREFMASK_BF
masks differ from DB_STENCILREFMASK, even with DB_DEPTH_CONTROL.BACKFACE_ENABLE
clear, where RDNA2 ignores the _BF register and the back face uses the front
one (as the function already did for the back face's ops and function). The
empty result made fill_depth_raster_state fall back to its defaults for the
whole PSO: depth ALWAYS with writes, no culling, stencil off. Found by
kevincommits in #1608 (RT-STATE-AUDIT-PIPELINE, item 1).

The masks are now compared only when BACKFACE_ENABLE is set. Two-sided stencil
with differing masks is still refused, since D3D12_DEPTH_STENCIL_DESC has one
pair.

native_pso_depth_test: a single-sided stencil state with
DB_STENCILREFMASK_BF = 0, and one with a differing back write mask, are built
with their depth, cull and front stencil state. Both checks fail on main.

AI-assisted (Claude Code)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:40:25 -06:00
4392670a76 d3d12: a freed window's last bytes reach the live copies too (RT-TITLE-WINDOW-RETIRE)
retire_orphan_windows frees the retired windows whose submissions have
completed after this submission's refresh_shadows, and freeing writes
the window's copy back to the title's pages once more
(free_retired_shadow). The refresh had already copied those pages to
the live copies, so the slot-133 buffer that replaced the window read
the older bytes until the next submission.

Moving the free ahead of the refresh, as suggested, is not enough on
its own: the write-back opens the pages it writes, and the refresh's own
copy back of the live copies' batches (write_back_titles) then takes
those pages for ones the title wrote and drops the buffer's GPU results
there (measured with this test: with the free moved first, the words
written through the buffer did not all reach the pages). So the free stays after the refresh, and a
retired copy's bytes that go back are written into every other copy over
them that still held the title's older bytes, as the next refresh would;
a copy that changed a byte keeps its own. Under lock_, in place, no
allocation. The epoch/ticket gating (src/command_list_epochs.h,
stamp_retired_windows) is untouched.

d3d12_title_va_test --window-orphans: the submission that frees the
window reads the held words through the buffer placed over the ring.
With LEONIDA_TITLE_WRITEBACK=0 (d3d12_title_window_orphans_free) it read
0 of 64 before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gt9hwNPurxyJ9LAfUbNiYr
2026-11-27 16:38:53 +01:00
7afb87266f d3d12: a retired window's copy goes back byte by byte (RT-TITLE-WINDOW-RETIRE)
ShadowPages::write_back compared the copies in 256-byte pieces and kept
one flag per piece: once a live copy had changed any byte of it, a
retired window's copy was left out of the whole piece. A retired window
and the slot-133 buffer that replaced it can have written disjoint
bytes of one piece (the window [384, 512), the buffer [256, 384)), so
the window's bytes were dropped. The batch path (`only` null) had the
same flag (`live = live || pass == 0`).

The piece now keeps a fixed 256-entry mask on the stack (no heap under
lock_) of the bytes a live copy changed, set in the first pass; a
retired copy goes back on every byte it changed that no live copy did,
in runs. Copies are still compared against the title's bytes as they
were before any copy went back, and a live copy now writes only the
bytes it changed, so one live copy no longer writes the title's older
bytes over another's result in the same piece.

d3d12_title_va_test --window-orphans: the held submission writes through
the window from ring + 384, a later one through the buffer placed over
the ring from ring + 128, and all the held words must reach the title's
pages (32 of 64 did before). The ring is write-combined so the buffer is
a copy on every driver. New ctest entry d3d12_title_window_orphans_free
runs it with LEONIDA_TITLE_WRITEBACK=0, where the window's free is the
only way back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gt9hwNPurxyJ9LAfUbNiYr
2026-11-27 16:38:40 +01:00
e1f82510a0 d3d12: a pool cover replaces only the windows it planned to (RT-TITLE-WINDOW-RETIRE)
cover_pool_request planned its cover (title_pool_cover) under short
shared locks of the alias table, then made the mapping and entered it
with replace_twin, which erased every range in the span unconditionally.
A slot-133 buffer is entered (Resource::alias_title_va) without
title_window_mutex, so one placed in either view of the span in between
was erased with the windows. And replace_twin's result was ignored: the
cover was recorded in pool_spans and returned as made either way.

replace_twin now takes the caller's predicate and, under the same
unique lock as the replacement, refuses with nothing changed when a
range it would erase is not one the caller planned to replace. The
cover passes the windows its plan found. On refusal the window it made
is dropped at once (drop_title_window: nothing answered from it, so no
submission names it) and the request falls back to the zero-size view
as before. The same drop now follows add_twin's refusal in
resolve_pool_memory, which left its new window charged to the budget
and refreshed with nothing answering from it.

title_window_plan_test: a non-window range entered in the cover's span
(CPU view, then twin view) between title_pool_cover and replace_twin is
refused and left intact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gt9hwNPurxyJ9LAfUbNiYr
2026-11-27 16:38:40 +01:00
b8754f630f title_window_plan: bound the twin view without modular arithmetic (RT-TITLE-WINDOW-RETIRE)
title_pool_cover translated a mapping found in the pool's other view back
with `x - (twin - va)` modulo 2^64. A window that starts below the twin
view (m.title_va < twin - va) wrapped to near UINT64_MAX, passed the
pool bounds check, and replace_twin then erased it whole, leaving the
part of it outside the cover unanswered. A twin view that does not fit
in 64 bits (twin < va - pool_lo, or pool_hi - va > UINT64_MAX - twin)
made the twin-view query wrap into an empty range, so a range in the way
was not seen at all.

The twin view's bounds [twin_lo, twin_hi) are now checked up front,
queried in non-wrapping coordinates, and a hit outside the view it was
found in refuses the cover like one outside the pool.

title_window_plan_test: check_pool_cover_bounds with the review's
example (pool [0x100000, 0x500000), va 0x120000, twin 0x420000, window
[0x200000, 0x440000)) and the two overflow cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gt9hwNPurxyJ9LAfUbNiYr
2026-11-27 16:38:40 +01:00
3c48b68c3f Merge branch 'fix/policy-and-alias' of /tmp/swarm-policy-alias into fix/device-writeback 2026-11-27 09:41:01 -05:00
e4b3d1e627 Merge branch 'fix/mirror-and-heap' of /tmp/swarm-mirror-author into fix/device-writeback 2026-11-27 09:41:01 -05:00
ace94aef23 Fix page mirror write-back ordering, batching, lock scope, and phase accounting
Run write_back_titles() first in before_execute_() before refresh_page_mirror()
and refresh_console_heaps(), never force-drain unretired batches, coalesce
intervals in note_title_write() and across retired batches, batch GPU readback
copies without holding page_mirror.mutex across vkWaitSemaphores, stop marking
read-only CBVs/SRVs writable, hoist page_mirror.mutex in finish_in_place(),
reuse filter_heap_page scratch, gate diagnostic VirtualQuery behind
LEONIDA_VSHARP_NOTHING_DETAIL=1, and attribute mirror refresh/flush/lock waits
to submit_phases.

AI-assisted: Antigravity (Gemini 4 Neon)
2026-11-27 09:41:01 -05:00
e6031df106 O(dirty+hot) TitleWritePolicy and read-only root view / GPU write tracking
- Replace TitleWritePolicy's O(N) std::map full scans in collect() and frame()
  with unordered_map + O(1) swap-and-pop active vectors (hot_list_, dirty_list_,
  history_active_), preserving promotion/demotion/probe/arm-failure semantics
  and address-ordered collect() delivery (~0.001 ms/iter for 200k cold + 100 hot).
- Add writable flag (default true) to TitleVaAliases::resolve() plus optional
  AccessResolver hook; call note_reached() iff writable && to != 0 so read-only
  CBV/SRV root views do not queue GPU write-back for either aliases or mirrored
  pages.
- Pass writable=false for root CBV/SRV and writable=true only for root UAVs in
  d3d12_com.cpp; record explicit GPU buffer-write destinations (CopyBufferRegion,
  CopyTiles, CopyTextureRegion to footprint, CopyResource buffer dst,
  WriteBufferImmediate, AtomicCopyBuffer, ClearUnorderedAccessView buffer,
  ResolveQueryData) and note them for write-back at ExecuteCommandLists.
- Add scale/correctness tests in title_write_policy_test.cpp and read-only vs
  writable tests in title_va_alias_test.cpp.

AI-assisted: Antigravity (Gemini 4 Neon).
2026-11-27 09:38:50 -05:00
0ae59b2423 Fix TitleMirror write-back remap corruption and harden TitleHeap
- TitleMirror (runtime/src/title_mirror.h):
  - Add has_pending(va) and skip pages with unflushed pending_ binds in
    homes_in(), homes_in_ranges(), write_back(), and write_back_batch() so
    write-back never copies stale/unbound sparse chunk bindings over live CPU
    memory.
  - Pass each page's physical frame address (mapped->second + k * kPiece) to
    the write-back callback instead of its virtual address so concurrent CPU
    remaps cannot receive a previous mapping's bytes.
  - Replace the unconditional O(homes_.size()) refilter scan at the end of
    write_back() with an O(changed) local list of touched aliased homes.
  - Add HomeRef, homes_in_ranges(), and write_back_batch() for batched
    multi-range GPU readback with concurrent-remap frame validation.
  - Copy a full 64 KiB page in one hooks_.copy call inside fill() via a
    reusable member scratch buffer, falling back to 256-byte pieces only if
    the whole-page copy fails.
- TitleHeap (runtime/src/title_heap.h):
  - Add a per-span live-slot occupancy bitmap so release() rejects small-block
    double-frees without duplicating the freelist, and size_of()/release()
    reject freed slots, interior pointers, and unused span tails.
- Unit tests (title_mirror_hooks_test, title_heap_test):
  - Add regressions covering pending_ skip, physical-frame destination,
    O(changed) refilter scaling over 10k+ homes, 1-shot fill + per-piece
    fallback, batched multi-range coalescing/conflicts/remap skip, and
    TitleHeap double-free / interior-pointer / tail-slot rejection.

AI-assisted: Antigravity, Gemini 4 Neon
2026-11-27 09:36:10 -05:00
27c1673761 d3d12: every title write-back range on one guarded page goes back (RT-TITLE-WRITEBACK-SAME-PAGE-RANGES)
DeviceState::write_back_titles handed each finished range to
ShadowPages::write_back on its own. The first range that differed reopened
its guarded page (kProtected cleared), and every later disjoint range on that
page then read as written by the title and was dropped, though only the
write-back itself had written there.

Each shadow now takes all of its finished ranges in one call, sorted by
address, and decides which pages are held once for all of them, before the
first copy. The per-page decisions are allocated before the tracker's lock is
taken.

New test d3d12_title_window_write_back_ranges: 16 four-byte ranges 16 bytes
apart on one guarded page of a title window. On main 1/16 reach the page
(3/3 runs); with the fix 16/16, and the words between them keep the title's.

Found by 73N1X in #1608.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:34:01 -06:00
cd219e63bc Local test merge: heap pages hold the title's bytes in the mirror; the filtered descriptors live in a copy of their own at the table address (920173613, 3a4222e0f)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 08:49:43 -05:00
4e87841d8a Merge remote-tracking branch 'upstream/main' into d3d-sample-positions
# Conflicts:
#	runtime/src/vulkan_replay.h
2026-11-27 13:43:58 +00:00
920173613c heaps in place: the title's bytes at the title's address, a filtered copy of each page at the table address
The title keeps plain data inline in its descriptor heap pages and points V#s at it. With one filtered home bound
at both addresses, the filter's output reached those V#s: four words a compute program reads as sizes looked like
a V# with a base nothing holds, three of them were nulled, the program read [0 0 0 720] and spun until the ring
timeout.

title_mirror.h: alias(lo, hi, buffer, offset) gives each page of the range a second home, the filtered copy, bound
at the alias in the same batches as the mirror's binds and filled by hooks.filter whenever the title's bytes change
(a piece's sum, or write-back); the page's own home is always the title's bytes. filter_range, unfilter_range and
filtered_at are gone; copy_bytes(va) is the copy the filter's caller writes slots into; unalias takes the ticket its
copies are freed after; write_back and homes_in take every home again.

The device writes slots into the copy (apply_in_place_changes, finish_in_place). An unreachable V# half is null
whole, all four words, in the filter and in fix_vsharp.

d3d12_heap_in_place_test: inline data after a table, a V# of the title pointing at it, and a rewrite on the same
page: the V# reads the title's four words, the table the filtered entries ([0 0 0 0] for the data), the title's
bytes unchanged; on the previous commit it read [0 0 0 720] at both addresses. A GPU store into the heap's page
now goes back to the title's bytes. title_mirror_hooks_test covers the alias's own homes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:43:30 -05:00
462de0e187 geometry watch: a page the mirror leaves writable is hot in its cell, written for every copy of it, and written once more when it turns cold (RT-TITLE-TEXTURE-WRITE-TRACKED)
Two trackers guarded the same 64 KiB pages through the same cells: the page mirror's HotColdTracking and the
title texture watch. When the mirror found a page hot it reopened the cell behind the other's back; the texture
watch then armed it again, so the page faulted at every write for one tracker while the other meant it to be
writable (two guards racing on one page), and when the mirror turned a hot page cold for a probe, a write made
while it was hot reached no other tracker at all (the video plane's write of that interval was never uploaded).

One owner of the guard now: the cell. An owner that leaves a page writable holds it hot (geometry_writes::
set_hot); a hot cell is not armed by anyone and hot_tiles() lists it, so the texture watch takes it as written
at every pass; when the last owner lets go, the cell counts as written once more for every subscriber.
HotColdTracking holds its hot pages that way and ignores its own hot-to-cold turn (a cell that has not moved
since it was armed was not written).

Also: the FSDRAW census reset the refresh line's passes, changed and filled counters, which then read 0 uploads.

Test: title_mirror_hot_cold now runs the texture watch over the same cells as the mirror's tracking: the plane
written every interval is named at every interval, probes included, and its page stops faulting once hot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:34:14 -05:00
d42c37335b d3d12: LEONIDA_ASYNC_MIN_BYTES_GRAPHICS, a separate async threshold for graphics (RT-ASYNC-MIN-BYTES-GRAPHICS)
With LEONIDA_ASYNC_PIPELINES=1, graphics and mesh pipelines (all their stages) now take
LEONIDA_ASYNC_MIN_BYTES_GRAPHICS when it is set, and LEONIDA_ASYNC_MIN_BYTES otherwise, so
nothing changes while it is unset. Compute keeps LEONIDA_ASYNC_MIN_BYTES. 0 makes every graphics
pipeline asynchronous. One startup line states both thresholds; text that is not a number is
ignored with a log line.

Thread dumps from a retail run showed the draw thread building lazy graphics variants under the
1 MiB threshold in place, 2.5-11 s each, back to back, with no present for about 100 s. A skipped
draw costs one draw. The image needs the small lighting and post compute programs, and those
are still built in place.

Tests: async_pipeline_size_test covers the per-kind decision and the unset fallback;
d3d12_pipeline_workers_test --async-graphics-zero / --async-graphics-unset (new ctests) hold
the compile worker with compute over its threshold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:24:29 +01:00
f380834f90 d3d12: a write-back's later runs in a tile its faulting copy reopened still go back (RT-WRITEBACK-TILE-REOPEN)
ShadowPages::write_back decided page by page, inside its loop, whether a page's GPU result goes back. A copy
that faults on another guard (a geometry watch cell) makes the handler reopen the whole 64 KiB tile on the
write-back's own thread (reopen_range, under the lock #2418 lets it reuse), which clears kClean and kProtected
there. The runs after it in the tile then read as written by the title: their GPU results were dropped from
a batch already taken off the queue, and the next forward copy put the title's older bytes over them.

The decision is now taken for every page of the range before the first copy, into a host-heap vector the
tracker keeps. A page the title wrote before the write-back (not guarded and not clean after the asking)
is still held, so the title's words win as before.

Test: d3d12_title_window_write_back_fault_tile (d3d12_title_va_test --window-writeback-fault-tile), the
#2418 fault case with a second dispatch on the third page of the tile and a title write on the second.
Found by DadaCap's review of #2418.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:20:49 +01:00
d0636fc7af title textures: a retired slot-70 texture forgets its address only while it still owns it
A slot-133 texture placed where a slot-70 view had made a texture of the layer's takes the address over
(place_at_title_address); register_title_texture then retires the slot-70 entry, and retire_title_texture erased the
address from images_by_address unconditionally - the placed texture's key. Every T# naming that address found no
texture ("no texture at the T# address: title memory"), the texture was never named, so never filled, and the slot
read the fallback.

forget_image_of(address, owner) erases the address and its views only while `owner` is registered there, under one
descriptor_mutex hold; retire_title_texture and ~Resource use it (the latter checked in two steps before). The views
of the retired texture left when the address was taken over.

d3d12_heap_in_place_test: a slot-70 view, then a slot-133 texture at the same address in a reservation at 16 TiB and
up, named by a T# the title writes into a heap read in place: it binds with the tag and its index, reads the fallback
(index 0, the 1x1 zeros) when the texture goes, and binds again when a texture is placed there again. It failed
(index word 0) before the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 08:17:20 -05:00
d483077913 Merge main into claude/pipeline-prewarm-order
Resolve runtime/README.md conflict after #2220 and #2233 landed on main.
2026-11-27 08:11:54 -05:00
17d3af0b65 Merge pull request #2462 from OreoFR/rt-compile-gate-auto
compile gate: `auto` default, calibrated per driver at device creation (RT-COMPILE-GATE-AUTO)
2026-11-27 14:08:00 +01:00
c1148ff101 page mirror: the write-back copies homes out with the GPU instead of reading them over the bus (RT-PAGE-MIRROR)
Run 64w spent a constant 14.5 s in a submission's shadows phase whenever new V# ranges reached the write-back. A
console V# has no read/write bit, so each new range is noted as possibly written, up to the 64 MiB cap a submission.
page_mirror_write_back then summed every 256-byte piece of those homes on the CPU. The homes are in device-local,
host-visible memory, and an uncached CPU read over the bus costs about 1.7 us per 8 bytes: 64 MiB takes 14.5 s. It
was measured here at 1.6 s for 16 MiB on the RX 7900 XTX. The bind wait was not the cause: it is a GPU-side wait.

Now the homes of the mirrored pages in the range are copied by the GPU into a host-cached buffer, 16 MiB at a time,
on the device's staging queue. The copy waits for the mirror's last bind batch and signals a timeline semaphore of
its own. The merge then reads the copy (TitleMirror::homes_in, and write_back with a staged copy). Under the
mirror's lock nothing is filled between the copy and the merge. The CPU never reads a home now.

The mirror's 10 s line gives the write-back's calls, ms each, the GPU copy's share, the longest, and the MiB copied
out.

Test: d3d12_page_mirror part 9 runs the write-back over 64 MiB with one piece written by the GPU. That piece goes
back, and the call must take under a second. It took 10 ms here, and 6.3 s before the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 07:56:20 -05:00
8bab5f2811 Merge main into claude/rt-async-compile-pool and refresh compile-gate doc note
Resolve runtime/README.md conflict with #2220 (LEONIDA_PIPELINE_ORDER_LOG)
and note in docs/d3d12_vulkan.md that LEONIDA_COMPILE_GATE=adaptive and 1
gate graphics creates as well (#2412).
2026-11-27 07:50:01 -05:00
e31f50bbcc compile gate calibration: keep no unclear verdict, drain a timed-out fence
Review of #2462:
- An unclear calibration (a slow submission the create does not explain) is no
  longer written to compile_gate_calibration.txt, and an unclear line an
  earlier build wrote is not read as a cached verdict: the next launch measures
  again instead of staying classic until the driver changes
  (compile_gate_policy::cache_verdict, tested in compile_gate_policy_test).
- After a fence wait that fails, the fence and command pool are destroyed only
  once the pending submission's fence signals (up to 60 s); on a lost device or
  if it still has not, they are left alive. The verdict stays classic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 13:49:07 +01:00
6af3b1dac6 Merge remote-tracking branch 'origin/main' into rt-compile-gate-auto 2026-11-27 13:43:49 +01:00
690dea5193 Merge pull request #2220 from MoonEyes/feat/pipeline-order-recorder
runtime: record the order of first pipeline requests (LEONIDA_PIPELINE_ORDER_LOG=1, RT-PIPELINE-PREWARM-ORDER phase 1)
2026-11-27 13:43:04 +01:00
1d7c662b4b compile gate: auto default, calibrated at device creation
With LEONIDA_COMPILE_GATE unset or `auto`, the device measures the driver once
before the VulkanContext exists: a worker creates a synthetic compute pipeline
(SPIR-V written in code, new specialization seed each run, no pipeline cache)
while the queue gets empty submissions waited on a fence. Quick submissions with
the create still in the driver give the adaptive gate; a held one, a create too
fast to tell, an unexplained slow submission or any failure give classic. The
verdict is cached per vendor/device/driver/pipelineCacheUUID in
compile_gate_calibration.txt beside the pipeline cache;
LEONIDA_COMPILE_GATE_RECALIBRATE=1 measures again. Only the title process
calibrates; build hosts and tests keep classic. `classic`, `adaptive`, `1`, `0`
still force a mode.

Tests: compile_gate_policy_test (no GPU: settings, NVIDIA version decode,
verdicts, cache file, SPIR-V shape) and vk_compile_gate_calibration_test (GPU:
a verdict within 20 s, adaptive on NVIDIA 621.40).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 13:24:49 +01:00
ad1789d7e9 Merge main into mesh-serial-waves
docs/design.md: keep the new row and take main's text of the row below it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 20:11:21 +08:00
e578518c8f check_module_names: mock _is_windows instead of global os.name for Linux CI 2026-11-27 19:56:25 +08:00
4ca6d97a8c check_argv_modes: mock _is_windows instead of global os.name for Linux CI 2026-11-27 19:56:00 +08:00