Skip to content

Shaders: keep pipeline libraries across changes and every runtime build - #3633

Open
Kalmarv wants to merge 1 commit into
xcl-dev:mainfrom
Kalmarv:compile/pipeline-store
Open

Kalmarv wants to merge 1 commit into
xcl-dev:mainfrom
Kalmarv:compile/pipeline-store

Conversation

@Kalmarv

@Kalmarv Kalmarv commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Prepared native pipeline libraries were thrown away whole whenever anything in their receipt changed: a translator source byte, a setting, the pipeline layout, the staged corpus, or the memory-window count. Nothing the title built while it ran was kept, so a title rebuilt the same pipelines in the driver every run. On a retail title with a prepared library (240 s run, RTX 5070 Ti, 16 windows), 144 driver builds took over a second each (690 s total), and 1 130 of the 1 739 drawn pipelines were in no staged corpus (same shaders, other blend or depth state), so they were rebuilt on every run.

A library entry's name is already the hash of the exact translated DXIL and state it was built from (driver_cache::graphics_name, name_for_root_node), and runtime and preparation store and load through the same names. A changed input can only make a name miss, never load the wrong pipeline, so the receipt need not discard the library. This PR keeps the libraries and builds only what is missing:

  • Prepared libraries per memory layout, never discarded by content changes. Prepared libraries from a staged .xcl\pso-corpus live under <game>\.xcl\pipeline-libraries\<windows>\ (4, 8, 16-heap, ...), so layouts coexist. The receipt (v3) keys on the driver; corpus, translation, settings, and layout identities only mark the libraries stale, so the next preparation imports every unchanged name from the previous library (falling back to legacy .xcl\pso-corpus\{compute,graphics}.plib once on first upgrade) and builds the rest. A corpus without an identity file uses a deterministic content-derived fallback identity from its staged files so it still publishes a reusable receipt while different corpora never collide. Staged recipes build for the runtime layout. XCL_PREPARE_CACHE_ONLY=1 still refuses absent, stale, mismatched-driver, or unsupported-device prepared libraries and names what changed, while non-cache-only runs skip mismatched prepared libraries and still open runtime.plib.
  • runtime.plib in XCL's per-title data folder keeps every pipeline built at runtime. Graphics (tracking dropped_rect_gs explicitly so retry_without_rect_gs fallbacks are skipped while from_previous library hits remain storable during incremental preparation), graphics streams (which previously had no library lookup or store), both passes of two-pass pipelines (stored only once both passes succeed so a failing compute pass never leaves an orphaned mesh entry), and compute are stored in <XCL_DATA_ROOT | %LOCALAPPDATA%\XCL>\<title>\pipeline-libraries\<windows>\runtime.plib — never inside the game folder, so title folders stay read-only/untouched and scripts/smoke.ps1 A/B runs stay isolated. It is flushed atomically every 30 s while it grows (paced by size) and at shutdown (bounded to 5 s in both WM_CLOSE and end_title, setting a shutdown stop flag for the periodic flusher and always returning the periodic flusher's thread ID alongside any timed-out end-flush thread ID so end_title never suspends a flush thread while it may hold the process heap or D3D12 lock during drain_gpu and log::flush) under a dedicated flush_lock held end-to-end across added.swap(0) + fallible try_reserve_exact Serialize() (returning E_OUTOFMEMORY instead of aborting the process under tight commit) + write_atomic(), without holding any load-blocking lock during serialization or disk I/O. Startup cleans up stale dead-PID runtime.tmp* files, and persistent write failures stop retrying after 3 consecutive errors (or immediately on ERROR_WRITE_PROTECT). D3D12 retains the opened bytes in RAM and each flush serializes a temporary copy (~1–2x the file size in commit); XCL_RUNTIME_LIBRARY_MB defaults to 2048 MiB (0 disables runtime.plib) and is enforced on both store/save and load via try_reserve_fast held under store_lock.read() plus exact store_lock.write() checks against an admission ceiling (cap - 2 MiB with 64 KiB per-entry overhead) so D3D12 metadata/subobject overhead cannot push a flush over cap, without latching full on a single unreadable or oversized blob. A sibling runtime.stamp records per-build byte counts (<layout:translation:settings> <bytes>) so under-cap libraries and full libraries built mostly by the current build survive unchanged while a full library carrying more than half older-build bytes resets fresh. All runtime.plib read paths (activate, warm_library::inspect, warm_library::publish) share read_runtime_file, which skips the file at zero cap, rejects oversized files from the opened handle's metadata before reading, and bounds reads with Read::take(cap + 1) if a file grows concurrently; warm_library::status inspects metadata only.
  • One build per pipeline without deadlocks, gate stalls, or double-compiling small shaders. While one thread builds a pipeline name (and the runtime library is not full), other threads wait (XCL_ONE_BUILD_WAIT_S, default 60 s) and then reuse its cached driver blob directly from the library (Loaded::Blob) to create a distinct COM object without recompiling, even for small shaders below COMPUTE_BLOB_MIN_DXIL (16 KiB). ComputeBuild::CachedWhole probes, chained two-pass compute passes, and full runtime libraries skip one_build; finish_two_pass releases the mesh one_build flight (via release_deferred()) and compile slot before entering compute one_build while deferring store(&mesh_pso) until the compute pass also succeeds; big_compile_turn releases any one_build flight owned by a background worker when it parks; normal-priority callers take over a flight held by a below-normal preload worker immediately rather than waiting behind THREAD_PRIORITY_LOWEST background work; and if a holder finishes without storing a usable entry in runtime.plib (e.g. dropped_rect_gs, hr < 0, unreadable blob, UnusableExisting, TransientError, or over-cap), all waiters wake immediately and build in parallel instead of serializing on a miss.
  • Hand-out-once COM objects with cached-blob reuse. D3D12 loads a library name as the same COM object every time, while XCL keys pipeline state by object pointer (a second dispatch chain with the same first piece collided on its table and deadlocked). Each name's COM object is handed out once per process (Loaded::Pipeline); later lookups read its cached blob through the adoption-aware real::read_pso_cached_blob helper (Loaded::Blob) so callers build a distinct COM object without recompiling even after the first object's vtable was swapped by adopt. Transient StorePipeline errors stay retryable and E_INVALIDARG after a failed load is not marked handed out.
  • Accounting. Every 30 s a Pipelines: log line counts prepared / runtime library / blob / built / built after a refused blob per kind (classifying graphics stream* labels under Stream and not counting failed fresh builds as Built). Refused blobs log their HRESULT. XCL_PIPELINE_MEASURE=1 marks any run that built in the driver as invalid.
  • XCL_RDNA_FLOAT, XCL_WATERFALL_COLLAPSE, and XCL_PER_LANE_MAX_INSTS join the settings key (alongside XCL_WAVE64_IDIOMS from main). The v1/v2 receipt migration and legacy identities are removed; old .plib files in .xcl\pso-corpus\ are imported once on first preparation for a layout and can be deleted afterward.

Why this is one PR (2 725 insertions / 487 deletions including ~1 100 lines of unit tests): keeping prepared libraries alone still leaves every unrecorded pipeline to rebuild every run; the runtime library deadlocks without hand-out-once, double-compiles concurrently without one_build + Loaded::Blob, and cannot be verified without the Pipelines: accounting.

What is in it

  • crates/xcl/src/shaders/warm_library.rs: layout-scoped prepared folders, legacy .xcl/pso-corpus/*.plib fallback import (previous_library), per-title data_dir path for runtime.plib, v3 receipt (with deterministic content-derived fallback identity when a staged corpus has no identity file), Library::{Current, Stale, Absent}, capped runtime reads in inspect/publish, metadata-only status
  • crates/xcl/src/shaders/pso_corpus.rs: prepare staged recipes for the runtime layout into its library folder, passing warm_library::previous_library on first upgrade
  • crates/xcl/src/shaders.rs: prepare_for_launch library reuse, XCL_PIPELINE_LIBRARY_PREVIOUS via warm_library::previous_library, cache_only_miss reasons, xcl cache status, updated settings key
  • crates/xcl/src/shaders/pipeline_library.rs: runtime.plib activation in data_dir, non-fatal driver mismatch fallback (unless XCL_PREPARE_CACHE_ONLY=1 with prepared libraries), shared capped read_runtime_file, fallible try_reserve_exact NativeLibrary::serialize, adoption-aware read_cached_blob/cached_blob_size, atomic fast-path + exact write-lock cap enforcement (2048 MiB default, single unreadable/oversized blob skips without latching full), per-build byte accounting in runtime.stamp with auto-reset when a full library is majority older-build, retryable transient StorePipeline errors and failed-load E_INVALIDARG handling, Loaded::{Pipeline, Blob}, flush_lock-serialized flush_runtime and bounded flush_runtime_timeout (with shutdown flag and always-excluded periodic flusher TID) + persistent-error stop + dead-PID runtime.tmp* cleanup, park-releasing / priority-aware / parallel-unshared-wakeup one_build, unit tests
  • crates/xcl/src/shaders/pipeline_stats.rs (new): per-kind counts (graphics stream* -> Stream, failed fresh builds excluded), Pipelines: summary, XCL_PIPELINE_MEASURE=1, refused-blob HRESULT logging
  • crates/xcl/src/hle/d3d12x/real.rs: pub(crate) adoption-aware read_pso_cached_blob / pso_cached_blob_size, explicit dropped_rect_gs flag in GraphicsPsoBuild, one_build (skipping ComputeBuild::CachedWhole and chained two-pass compute, releasing mesh one_build via release_deferred() + compile slot before compute one_build while storing mesh_pso only after compute succeeds, releasing held one_build on big_compile_turn park), Loaded::{Pipeline, Blob} integration across compute / graphics / graphics stream / two-pass, runtime store, bounded flush_runtime_timeout(5 s) in end_title, driver compile counting
  • crates/xcl/src/hle/d3d12x/present.rs: bounded flush_runtime_timeout(5 s) on WM_CLOSE
  • crates/xcl/src/launcher.rs, crates/xcl/src/state.rs: title_data_dir helper for xcl cache status and shared process_is_running for stale temp cleanup
  • crates/xcl/build.rs, crates/xcl/src/gpu/recomp/pso.rs: legacy v1/v2 receipt identities removed
  • README.md: prepared vs runtime library locations, legacy .xcl\pso-corpus\*.plib one-time import, RAM/commit cost, XCL_RUNTIME_LIBRARY_MB (2048 MiB default, store/save + load enforcement), and accounting knobs

Tested

  • Hardware: NVIDIA GeForce RTX 5070 Ti (driver 610.74), AMD Ryzen 9 9950X, Windows 11 Build 26200, rustc 1.99.0 (b940084d7), DXC 1.9.2609.5; debug for tests, release for builds and title runs.
  • cargo build --release -p xcl: ok, 39 warnings (matches main 5eaadb54c baseline).
  • .\scripts\test.ps1 (cargo build --workspace, cargo bench -p xcl --bench '*' -- --test, cargo test --workspace -- --test-threads=4) on c301772a1: 2999 passed, 0 failed, 52 ignored; 24 SKIPPED GPU tests (22 no wave64, 2 no heap windows). gpu_two_pass_cache_e2e::two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs and e2e (verifying the game folder stays untouched) both passed.
  • Unit tests added/verified: try_alloc_zeroed_returns_oom_instead_of_aborting; one_build_wakes_waiters_in_parallel_when_holder_does_not_store; one_build_normal_priority_does_not_wait_on_low_priority_holder; identityless_corpus_uses_content_fallback_identity_and_detects_changes; dropped_rect_gs_build_is_not_stored_under_rect_gs_library_name; cache_only_fails_without_library_support_and_one_build_skips_when_full; full_runtime_library_resets_only_when_build_stamp_changed (covering both majority-old reset and majority-current keep); with_name_and_store_runtime_hand_out_pipeline_once_then_cached_blob (exercises real real::adopt before second lookup); store_pipeline_does_not_hold_public_refcount_and_adopted_release_reloads_blob; activation_driver_mismatch_warns_and_continues_unless_cache_only; previous_library_prefers_layout_folder_and_falls_back_to_legacy_corpus; two_pass_releases_compile_slot_before_one_build_wait; one_build_releases_when_holder_parks_and_does_not_clobber_new_holder; flush_runtime_timeout_returns_within_budget_when_blocked; store_runtime_retries_after_transient_error_and_does_not_mark_failed_load_handed; cap_reservation_prevents_concurrent_overflow_and_oversized_entry_does_not_latch_full (including 4-thread concurrent store race near tight cap); store_and_flush_enforce_cap_and_preserve_reloadable_library; read_runtime_file_enforces_zero_cap_exact_cap_over_cap_and_growth; status_reports_sizes_from_metadata; flush_runtime_orders_concurrent_flushes_does_not_block_loads_and_stops_on_errors; cleanup_stale_runtime_temps_removes_dead_pid_temps_only; parse_runtime_cap_handles_defaults_zero_and_overflow; kind_of("graphics stream*") -> Kind::Stream and failed fresh builds excluded; ComputeBuild::CachedWhole skipping one_build.
  • Retail title (ea3b5e4d, 60 s runs, fresh isolated XCL_DATA_ROOT and XCL_DXIL_CACHE, 4 windows, no staged corpus): cold run wrote 16.1 MB (16 124 048 B) runtime.plib + per-build runtime.stamp (16 124 048 B attributed to current build; 3 934 graphics + 205 compute = 4 139 pipelines) under <XCL_DATA_ROOT>\<title>\pipeline-libraries\4\ with <game>\.xcl unchanged; warm repeat in the same isolated data folder served 3 932 graphics + 195 compute (4 127 total, 0 ms bind waits) from runtime.plib, updated runtime.plib and runtime.stamp to 17 534 786 B, with 1 653 frames shown (60 60 60), 14 668 MB peak commit, 0 device removals, and 0 crashes (<game>\.xcl unchanged).

Regression run
Both 60 s runs used fresh, isolated XCL_DATA_ROOT and XCL_DXIL_CACHE folders on the same retail title (ea3b5e4d) and left the game folder untouched:

xcl-smoke v1
commit: 5eaadb54c14e0fc29597b2a1689d7dbd83491303
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1652 (PresentX 1652)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15609 MB
xcl-smoke v1
commit: c301772a11027c141c797184f7f9a5168f7311d3
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1418 (PresentX 1418)
presents per 2 s (last 3): 50 54 53
device removals: 0
crashes: 0
peak commit: 15645 MB

Note on memory: runtime.plib stays mapped in RAM for the life of the device and each flush serializes a temporary copy, so longer sessions with larger runtime libraries increase peak commit by roughly 1–2x the size of runtime.plib (bounded on both write and load by XCL_RUNTIME_LIBRARY_MB, 2048 MiB default; serialization allocates fallibly via try_reserve_exact).

Not tested

  • AMD (wave64), other NVIDIA generations, and devices without D3D12 pipeline-library support; 24 skipped GPU tests (22 no wave64, 2 no heap windows).
  • Incremental preparation of a staged corpus after a translator change and 16 heap windows (the smoke runs had no staged corpus and used 4 windows).
  • Refused mesh-pass driver blobs (none occurred in these runs, so their HRESULT remains unobserved).
  • A title that exits via its own ExitProcess does not trigger the shutdown flush (the periodic flush covers those).

AI use

  • Claude Code (Claude Opus 5.5): audited the initial runtime logs and wrote the initial implementation, tests, and description.
  • Antigravity (Gemini 4 Neon): rebased onto origin/main (5eaadb54c), addressed all review findings (per-title data_dir storage, non-blocking flush_lock + fallible try_reserve_exact NativeLibrary::serialize + bounded 5 s shutdown flush with shutdown stop flag and always-excluded periodic flusher TID + stale temp cleanup + persistent error stop, adoption-aware read_pso_cached_blob / pso_cached_blob_size, non-fatal activation driver mismatch fallback, explicit dropped_rect_gs flag so incremental library hits stay storable, identity-less corpus fallback identity, legacy .xcl/pso-corpus/*.plib one-time import, finish_two_pass early release_deferred() + post-compute paired mesh store + big_compile_turn park release + priority-aware and parallel-unshared-wakeup one_build, retryable transient StorePipeline errors and failed-load E_INVALIDARG handling, atomic fast-path + exact write-lock cap enforcement at 2048 MiB default, per-build byte accounting in runtime.stamp with majority-stale full-library auto-reset, shared capped read_runtime_file and metadata-only warm_library::status, empirical D3D12 StorePipeline refcount verification), added unit tests, ran the full test suite and isolated smoke pair on the hardware named, and updated this description.

@github-actions github-actions Bot added area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 area:shaders Shader cache, PSO compilation, pipeline libraries, precompilation gpu:nvidia Code is specific to NVIDIA / wave32 GPUs (scope tag; see needs:nvidia-test) labels Dec 2, 2026
@Decodere

Decodere commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Diff review (head 05c33e918, read-only code review — not a #3041 merge-check):

Layout-scoped library folders, stale-vs-absent receipts, incremental from_previous import, and single-flight one_build are solid steps toward eliminating cold PSO stalls. A full line-by-line review of the diff surfaced 4 concrete bugs worth addressing before merge:

  1. Writes <game>\.xcl\pipeline-libraries\<windows>\runtime.plib directly into the title directory on every run (including XCL_PREPARE=0 and scripts/smoke.ps1) (crates/xcl/src/vfs.rs:315-316, crates/xcl/src/host.rs:279-280, crates/xcl/src/shaders/pipeline_library.rs:72-86):
    Exempting <game>\.xcl as Target::Pass and unconditionally activating runtime.plib there mutates the title folder on any run that compiles a PSO and runs >30 s or exits via WM_CLOSE/end_title. This breaks the untouched/read-only title-folder invariant (tests/e2e.rs:202, read-only mounts) and contaminates scripts/smoke.ps1 A/B runs (which isolate XCL_DATA_ROOT and XCL_DXIL_CACHE, not <game>\.xcl). Keeping runtime.plib under XCL's per-title data or cache directory (while keeping <game>\.xcl read-only for title runs) avoids both issues.

  2. flush_runtime() drops runtime.gate before write_atomic, creating an exit data-loss / out-of-order overwrite race (crates/xcl/src/shaders/pipeline_library.rs:135-145):

    • Early exit loss: if xcl-pipeline-library swaps added -> 0 and is mid-write_atomic (writing hundreds of MB) when WM_CLOSE (present.rs:741) or end_title (real.rs:4887) calls flush_runtime(), the caller sees added == 0, returns immediately, and calls ExitProcess, terminating the write mid-flight and leaving an orphaned .tmp file.
    • Out-of-order overwrite: if a second flush serializes a newer snapshot S2 and finishes MoveFileExW before an in-flight older snapshot S1 finishes write_atomic, S1 overwrites S2 (or fails with ERROR_ACCESS_DENIED).
      Guarding flush_runtime() end-to-end with a dedicated flush_lock: Mutex<()> (separate from runtime.gate so loads/stores do not block on disk I/O) fixes both races.
  3. ComputeBuild::CachedWhole blocks up to 60 s in one_build instead of falling back to dispatch_chain::build (crates/xcl/src/hle/d3d12x/real.rs:6380):
    compute_container(..., ComputeBuild::CachedWhole) is used as a non-blocking cache probe before falling back to split dispatch-chain pieces (real.rs:6195-6201). Calling one_build(&library_name) unconditionally whenever !ppv.is_null() causes the title thread to stall up to 60 s behind an async xcl-pso-whole compile instead of immediately building/using the chain. Skipping one_build when mode == ComputeBuild::CachedWhole preserves non-blocking fallback.

  4. pipeline_stats::kind_of misclassifies "graphics stream" labels as Kind::Graphics instead of Kind::Stream (crates/xcl/src/shaders/pipeline_stats.rs:36-38):
    create_graphics_stream_cached passes "graphics stream", "graphics stream retry", and "graphics stream without rect GS". Because kind_of tests label.starts_with("graphics") before falling through to Stream, fresh graphics-stream builds are counted under Kind::Graphics while load_stream counts library hits under Kind::Stream. Checking label.starts_with("graphics stream") first aligns both paths.

Additional medium/minor observations:

  • finish_two_pass (real.rs:9481) holds one_build on the mesh PSO key but not on compute_pso (tp.cs), allowing distinct (MS/GS, PS) pairs sharing the same tp.cs to compile it concurrently.
  • store_runtime inserts name into active.handed (pipeline_library.rs:196), so a waiter woken from one_build is refused by with_name (pipeline_library.rs:171) and falls back to COMPUTE_BLOBS/GRAPHICS_BLOBS — which do not cache shaders below COMPUTE_BLOB_MIN_DXIL (16 KiB), causing duplicate compiles after waiting.
  • pipeline_library.rs:85 calls start_counting() before checking let Some(ready) = ready else { return Ok(()) }, spawning a permanent background thread even in tests/no-game runs; pipeline_library.rs:50 (parse::<u64>() << 20) can overflow on huge env values (saturating_mul(1 << 20) is safer); pipeline_stats.rs:66 counts failed fresh builds ((false, Some(hr))) as Source::Built.

AI use: Antigravity (Gemini 4 Neon) audited the full diff against main and drafted this review.

@Gevroska

Gevroska commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

merge-check
base: 1c8b551
head: 05c33e9
merge: clean (7ff2d960)
build: cargo build --workspace passed. Release builds of main and the merge also passed.

tests: I reran the full workspace suite on the RTX 3080. It finished with 2,909 passed, 1 failed and 51 ignored. The log also recorded 28 runtime skips and eight notices for skipped optional retail game sample checks. All 17 focused library, receipt, counter and VFS checks passed. Both link tests previously reported failing with DXC 1.7 passed here with DXC 1.9.2609.

The failure was in gpu_two_pass_cache_e2e. The stale-mesh case rejected the stale blob and rebuilt the pipeline as expected. After releasing the pipeline objects, the test found one live two-pass state where it expected zero. I reran that test in isolation on both the merge and the pinned main revision. It passed both times, so the cause of the full-suite failure remains open.

review: Source review identified a write-ordering issue. The periodic flush clears the dirty count before it finishes publishing. Shutdown can see that cleared count while a write is in flight, and an older snapshot can finish publishing after a newer one. I didn’t observe a lost write in the startup runs.

performance: I ran four 60-second retail game startups in order: main cold, main repeat, merge cold, merge repeat. Each revision had its own XCL cache and all four runs shared the NVIDIA driver cache. On the merge, the repeat recorded 4,056 runtime-library hits. Driver calls with a recorded return fell from 4,120 to 268, compared with 4,100 to 4,323 on main. Frames shown were 1,104 / 1,077 on main and 1,151 / 1,015 on the merge. All four runs reached the same profile prompt and exited cleanly with zero device removals. This confirms pipeline reuse during startup. The runs did not reach gameplay.

verdict: not yet. The write-ordering issue remains open, and the two-pass release assertion failed once in the full suite. I’ll rerun the full suite on the next revision that addresses either issue and check the same assertion under the original conditions.

hardware / tool and model: RTX 3080 (driver 32.0.16.1692), Ryzen 7 5700X, Windows 11 25H2 build 26200.9457, Rust 1.100.0 MSVC, DXC 1.9.2609. OpenAI Codex GPT-6.2 Sol ran the tests. Independent Codex agents checked the source and run evidence. Their exact models were not recorded. GPT-6.2 Astra drafted this comment.

I reviewed and approved this comment before posting.

@github-actions github-actions Bot added needs-1st-check Passes gates; needs first independent merge-check (#3041) needs:nvidia-test Needs a test report or merge-check on an NVIDIA GPU labels Dec 2, 2026
@Foniass

Foniass commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Review (head 05c33e9, diff read, not a merge-check):

  • Every run now writes into the game folder. activate (shaders/pipeline_library.rs ~73) turns on runtime.plib for every title, also with XCL_PREPARE=0 and with no corpus, and vfs.rs ~314 / host.rs ~279 make <game>\.xcl a pass-through, so the title's process writes <game>\.xcl\pipeline-libraries\<windows>\runtime.plib. README ~109, ~125 and ~350 still say the game folder is never modified. The e2e "game folder untouched" check does not catch it, because the test title never reaches a flush. On a read-only game folder, every period serializes the whole library and logs a failed write, since added is put back on error (~150). scripts/smoke.ps1 does not isolate this folder either, so the PR's smoke run started warm (as the description says) and main's did not.
  • Memory and disk only grow. Nothing is ever evicted from runtime.plib. Each translator or setting change renames the pipelines, so a new copy of the title's whole set is added after each change. The file is read whole and kept in RAM for the process (open_shared keeps the bytes), and each flush makes another full copy (serialize, ~141). The PR's own smoke run shows peak commit +1050 MB with a 451 MB library, not "about the size of the library". The 4096 MB cap (~49) allows several GB of extra commit before the library is thrown away whole. Old libraries in .xcl\pso-corpus\ are never removed.
  • Exit can lose a write and leave a large temp file. If end_title or WM_CLOSE calls flush_runtime while the background thread is writing, it sees added == 0 (~139) and returns, and the process exits mid-write. That run's new pipelines are lost, and a full-size runtime.tmp<pid>-<n> stays next to the library. A kill or crash during a write leaves the same file. Nothing cleans these up.
  • one_build does not do what the description says. store_runtime marks the name as handed out (~196), so a thread woken in one_build is refused by with_name (~171) and never loads from the runtime library. It builds again from GRAPHICS_BLOBS/COMPUTE_BLOBS, which keep no blob under COMPUTE_BLOB_MIN_DXIL (real.rs ~7579). Small pipelines are therefore still built twice, only one after the other now. The CachedWhole probe (real.rs ~6197 → ~6380) also takes one_build, so it can wait up to 60 s behind another thread's whole build instead of falling back to the chain at once. None of with_name / store_runtime / one_build / flush_runtime has a test; the new tests only check D3D12's own library behaviour.
  • Serialization blocks pipeline loads. flush_runtime holds gate.write() while it serializes hundreds of MB (~140), so every title thread that wants a pipeline from the runtime library waits for it, every 30–60 s. D3D12 synchronizes Serialize and StorePipeline itself; only concurrent loads of one name need the caller's lock, and names[slot] already provides it.
  • Stream builds are counted as graphics. kind_of (pipeline_stats.rs ~37) maps the "graphics stream…" labels to Kind::Graphics, but runtime-library hits of the same pipelines count as Kind::Stream, so the Pipelines: line splits one kind across two rows. Also on scope: ~1100 changed lines, and the settings-key additions, the removal of the legacy migration and the stats/measure mode each stand on their own (CONTRIBUTING puts diagnostics in their own PR).

Fine: names are hashes of the exact DXIL and state, and D3D12 checks the desc on load, so a stale entry can only miss. A StorePipeline E_INVALIDARG for a name that is already kept is handled. A runtime library from another driver starts empty. The per-name lock on loads covers the one case where D3D12 is not thread-safe. #3670 touches other functions and merges cleanly. The conflict with #3655 is one line of the settings list in shaders.rs ~38 (keep both names).

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

@Foniass

Foniass commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: 1c8b551
head: 05c33e9
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2910 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: read by one reviewer at this same head; the review is at #3633 (comment) and its findings stand. Most serious: every run now writes runtime.plib into <game>\.xcl (the README says the game folder is never modified), and the library only grows (peak commit +1050 MB).
performance: 60 s smoke of a retail title, main 1c8b551 vs this merge (05c33e9): 1652 -> 1684 frames shown (101 %; last presents per 2 s: 60 60 61), peak commit 18228 -> 19477 MB, 0 device removals, 0 crashes.
verdict: not yet: every run now writes runtime.plib into <game>\.xcl (the README says the game folder is never modified), and the library only grows (peak commit +1050 MB) (see the review)
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

@github-actions github-actions Bot removed needs-1st-check Passes gates; needs first independent merge-check (#3041) needs:nvidia-test Needs a test report or merge-check on an NVIDIA GPU labels Dec 2, 2026
@Kalmarv
Kalmarv force-pushed the compile/pipeline-store branch from 05c33e9 to 034e714 Compare December 2, 2026 14:28
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (5eaadb54c, resolving the one-line shaders.rs conflict with #3655 by keeping both XCL_WAVE64_IDIOMS and the three added translation settings) and pushed 034e7146a addressing every concrete finding from @Decodere, @Gevroska, and @Foniass:

  1. No writes into <game>\.xcl / untouched game folder (@Decodere, @Foniass): moved runtime.plib into XCL's per-title data folder (<XCL_DATA_ROOT | %LOCALAPPDATA%\XCL>\<title>\pipeline-libraries\<windows>\runtime.plib), reverted both crates/xcl/src/vfs.rs and crates/xcl/src/host.rs (removing the <game>\.xcl Target::Pass VFS exemption), and updated xcl cache status and README.md. Verified <game>\.xcl stays byte-for-byte/timestamp-unchanged across both cold and warm retail runs, and scripts/smoke.ps1 runs are cleanly isolated via XCL_DATA_ROOT.
  2. flush_runtime() exit data-loss, write ordering, load blocking, stale temps, and persistent write errors (@Decodere, @Gevroska, @Foniass):
    • Added a dedicated flush_lock: Mutex<FlushState> held end-to-end across added.swap(0) + Serialize() + write_atomic(), so WM_CLOSE/end_title wait for any in-flight flush to finish and older snapshots cannot overwrite newer ones.
    • Removed runtime.gate: flush_runtime() no longer blocks pipeline loads (with_name) during serialization or disk I/O (concurrent StorePipeline size growth retries Serialize() without blocking loads).
    • Added startup cleanup (cleanup_stale_runtime_temps) for dead-PID runtime.tmp* files.
    • Stopped endlessly re-serializing on persistent write failures (disables writes after 3 consecutive errors, or immediately on ERROR_WRITE_PROTECT).
  3. ComputeBuild::CachedWhole non-blocking probe (@Decodere, @Foniass): skipped one_build when mode == ComputeBuild::CachedWhole (and for chained two-pass compute passes) so fallback to dispatch_chain::build never stalls behind an async whole-form compile. Also added one_build on the shared tp.cs compute pass in finish_two_pass when unchained.
  4. store_runtime/handed vs one_build double-compile + pipeline_stats + startup/cap cleanup (@Decodere, @Foniass):
    • load_compute/load_graphics/load_stream now return Loaded::Pipeline on the first hand-out and Loaded::Blob (extracted via GetCachedBlob() from the library entry) on subsequent lookups, so woken one_build waiters and repeat requests create a distinct COM object from the cached blob without recompiling — including small <16 KiB shaders below COMPUTE_BLOB_MIN_DXIL — and first hits no longer eagerly copy blobs into COMPUTE_BLOBS/GRAPHICS_BLOBS.
    • Fixed pipeline_stats::kind_of to check label.starts_with("graphics stream") before "graphics" so graphics streams count under Kind::Stream, and stopped counting failed fresh builds as Source::Built.
    • Moved start_counting() after let Some(ready) = ready else { return Ok(()) } + driver check; used saturating_mul(1 << 20) in parse_runtime_cap; lowered default XCL_RUNTIME_LIBRARY_MB from 4096 to 1024 MiB (0 disables runtime.plib) and documented the ~1–2x RAM/commit overhead honestly in README.md and the PR description.
  5. Unit tests & verification (@Foniass, @Gevroska): added unit tests covering with_name, store_runtime, one_build, flush_runtime (ordering, non-blocking loads, persistent write error stop), cleanup_stale_runtime_temps, parse_runtime_cap, kind_of("graphics stream*"), failed fresh builds, CachedWhole skipping one_build, and runtime_directory. On 034e7146a (RTX 5070 Ti, DXC 1.9.2609.5): cargo build --release -p xcl clean at 39 warnings; .\scripts\test.ps1 passed with 2981 passed, 0 failed, 52 ignored, 24 SKIPPED (including gpu_two_pass_cache_e2e and e2e); fresh isolated 60 s smoke pair (main 5eaadb54c vs 034e7146a) updated in the PR description (1666 -> 1678 frames, 15570 -> 15612 MB peak commit, 0 device removals, 0 crashes), plus a warm repeat in the same isolated data folder confirming 4 103 runtime-library hits.

AI use: Antigravity (Gemini 4 Neon) implemented these fixes, ran the suite and smoke pair, and drafted this reply.

@github-actions github-actions Bot added needs-pr-check Failing the PR description check (CONTRIBUTING.md) and removed area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH labels Dec 2, 2026
@Gevroska

Gevroska commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

I checked the runtime-library size cap on 034e7146. With preparation disabled, activation reads the whole runtime.plib before open_runtime checks the cap. A zero cap or an oversized file therefore still incurs the read and temporary allocation. Prepared-library inspection and publication also read the payload before that check. The status query goes through inspection just to report the file size. Activation · Inspection and status · Publication

Could the read paths share a check that skips the payload entirely at zero cap, rejects oversized files using metadata from the opened handle, and bounds the read in case the file grows? Status could get the size from metadata alone. I’d cover three boundaries in a focused test: zero cap, a file exactly at the cap, and one byte over.

I verified the ordering in source. I haven’t measured peak memory or startup time on this revision. OpenAI Codex GPT-6.2 Sol reviewed the code, an independent Codex agent checked the call sites, and GPT-6.2 Astra drafted this comment.

I reviewed and approved this comment before posting.

@Kalmarv
Kalmarv force-pushed the compile/pipeline-store branch from 034e714 to ae8b643 Compare December 2, 2026 16:02
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Good catch, @Gevroska — pushed ae8b643f1 addressing all four points:

  1. Shared capped read (pipeline_library::read_runtime_file / read_runtime_file_capped): activate (when preparation is disabled), warm_library::inspect, and warm_library::publish now all go through the same helper, which:
    • returns None immediately when cap == 0 without opening or reading runtime.plib,
    • checks file.metadata() on the opened handle and rejects empty or len > cap files before allocating or reading payload bytes, and
    • bounds the read via Read::take(cap.saturating_add(1)) (with try_reserve_exact) so concurrent growth past the cap stops at cap + 1 bytes and is rejected cleanly.
  2. Metadata-only warm_library::status: factored the receipt/state check (prepared_state) so status checks graphics.plib, compute.plib, and runtime.plib via std::fs::metadata alone without reading any payloads.
  3. Tests: added read_runtime_file_enforces_zero_cap_exact_cap_over_cap_and_growth (zero cap, exact cap, cap + 1, empty file, and bounded cap + 1 read on a growing cursor) and status_reports_sizes_from_metadata (holding exclusive share_mode(0) locks on all three .plib files so any payload open/read fails).
  4. Verification on ae8b643f1 (RTX 5070 Ti, DXC 1.9.2609.5): cargo build --release -p xcl clean at 39 warnings; .\scripts\test.ps1 passed with 2983 passed, 0 failed, 52 ignored, 24 SKIPPED; fresh isolated 60 s smoke pair (main 5eaadb54c vs ae8b643f1) updated in the PR description (1652 -> 1662 frames, 15609 -> 16020 MB peak commit, 0 device removals, 0 crashes, <game>\.xcl unchanged), plus a warm repeat confirming 875/875 runtime-library hits with 0 bind waits.

AI use: Antigravity (Gemini 4 Neon) implemented these fixes, ran the suite and smoke pair, and drafted this reply.

@github-actions github-actions Bot removed the needs-pr-check Failing the PR description check (CONTRIBUTING.md) label Dec 2, 2026
@throny

throny commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Test report for #3633 at head 034e7146a, rebased on main 5eaadb54c.

Tested

  • RTX 4080 16 GB (621.40), i9-12900K, Windows 11 26300, Rust 1.100.0 release, plus our local auto-press patch for the start screen.
  • Retail title, two back-to-back 900 s world runs with XCL_RESIDENCY_PRIORITY=1:
    • Run 1 started cold: new DXIL, and the D3D12 cache had been cleared before it. First frame after 1045 s, 0.45 presents/s in the last 240 s.
    • Run 2 started warm: first frame after 19.5 s, 3.00 presents/s. That is in line with main on this machine (3.0–3.2).
    • Both runs: no device removal, no crash, skipped draws 0.0 %.
  • runtime.plib works as described: run 1 kept ~2,800 runtime pipelines (1.1 GB file).
  • The driver's D3D12 cache on C: grew 2.8 GB in run 1 and only 0.5 GB in run 2.

Not tested

  • What this PR is really for: reuse across different builds (a translator or setting change). Run 2 used the same build, so a warm start there is expected without this PR too.
  • AMD and wave32 GPUs; XCL_PREPARE_CACHE_ONLY; prepared corpus libraries.

AI use

  • Claude Code with Claude Opus 5.5 ran the build and runs and wrote this report.

Update: head ae8b643f1 (same hardware and settings, one 300 s run)

  • First frame after 17.6 s, 3.40 presents/s, no device removal, no crash, skipped draws 0.0 %.
  • The new 1 GiB default cap threw the library away. The runtime.plib from the two runs above had grown to 1,117,037,578 bytes in one 900 s run. At start this head logged is over XCL_RUNTIME_LIBRARY_MB; starting it again. It then kept 8,913 pipelines (1,010,575,948 bytes) within 170 s. The cap is checked only when the file is read, not while it grows, so on this title the library goes over 1 GiB within one longer run and is discarded on every start after that. One way to fix it: stop adding to the library at the cap, or keep the file under the cap when flushing, rather than dropping it at load. Alternatively, a larger default.
  • The fast start here comes from the driver's own caches; the discarded library played no part in it.

Update: head d9979794c (same setup, one 300 s run, 476)

  • No crash, no device removal, no Aftermath dump. 3.57 presents/s, skipped draws 0.0 %.
  • The cap fix works: the library from run 475 (1.01 GB) was loaded, not started again, and grew to 1.10 GB (+726 pipelines), under the new 2 GiB default.
  • The start was slow: first frame after 289 s. Shader preparation rebuilt the 1,346 graphics pipelines earlier runs used in its 14 worker processes, at about 5 per second. activated prepared PSOs only came at 286 s. Between 475 and this run, six other builds ran on this machine, and the NVIDIA driver cache is now capped at 10 GB, so the driver had probably evicted them. Those pipelines are all in runtime.plib already, but the preparation workers don't seem to look there. If they could, a restart after other builds would be quick, which is the case this PR is after.

@Gevroska

Gevroska commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Thanks for the update. I checked ae8b643f on Windows using the exact reader and file-size helper from that revision. All seven focused tests passed.

With the cap set to zero, the reader consumed zero bytes. A 32-byte file was accepted at a 32-byte cap and rejected at 31. In the case where the input grew beyond its initial size, the reader consumed 17 bytes at a 16-byte cap, returned OverCap, and retained no payload. With an exclusive Windows handle blocking payload reads, the status helper still reported the correct 32-byte size.

I also checked that direct activation, warm-library inspection and publication all use the capped reader. This addresses my earlier concern about reading the whole file before applying the cap. I haven’t rerun the full workspace suite or measured startup time on this revision.

OpenAI Codex GPT-6.2 Sol ran the tests. An independent Codex agent verified the extracted code and all seven outcomes. GPT-6.2 Astra drafted this comment.

I reviewed and approved this comment before posting.

@Kalmarv
Kalmarv force-pushed the compile/pipeline-store branch from ae8b643 to d997979 Compare December 2, 2026 16:50

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of d9979794: 6 finding(s) (1 critical, 3 high, 2 medium), most severe first.

  1. Critical crates/xcl/src/shaders/pipeline_library.rs:314: The new read_cached_blob calls pipeline.GetCachedBlob() through the windows-rs PC vtable, but on the hand-out-once path the object is the one handed out earlier, which the title-facing create path has since adopted, swapping its vtab.... (inline)
  2. High crates/xcl/src/shaders/pipeline_library.rs:198: warm_library::reuse now stores READY on every preparation, including titles with no corpus or with Stale/Absent libraries, so activate's hard Err on driver != ready.driver now fails device creation (real.rs:1025 uses ?) for any t.... (inline)
  3. High crates/xcl/src/shaders/warm_library.rs:97: A corpus with no identity file now gets corpus: [0; 32]. (inline)
  4. High crates/xcl/src/hle/d3d12x/real.rs:9627: finish_two_pass takes the mesh pass's gated compile slot (take_cold_slot, held until drop(slot)) before it blocks in one_build(&compute_name), but the thread holding that compute name in compute_container needs a slot from the .... (inline)
  5. Medium crates/xcl/src/shaders/pso_corpus.rs:1643: see below.
  6. Medium crates/xcl/src/shaders/pipeline_library.rs:359: store_runtime puts the name into known before the store succeeds and never takes it out on failure, and it treats E_INVALIDARG from StorePipeline as "kept already" even when that run's load of the name failed. (inline)

On lines outside the diff:

  1. Medium crates/xcl/src/shaders/pso_corpus.rs:1643: Prepared libraries move from .xcl/pso-corpus/ to .xcl/pipeline-libraries/<windows>/, and the old compute.plib/graphics.plib are no longer passed as previous to pipeline_library::begin, so every existing prepared title rebuilds its whole corpus on upgrade even though entries are name-addressed and safe to import. A user with a fully prepared title (hundreds of driver builds, over 10 minutes) upgrades, the first launch finds no receipt in the new folder, reports Absent, and rebuilds everything. Passing the legacy files as previous would import every unchanged name.

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

runtime.mark_full(bytes.len() as u64);
state.disabled = true;
crate::xlog_warn!(
"Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Critical: The new read_cached_blob calls pipeline.GetCachedBlob() through the windows-rs PC vtable, but on the hand-out-once path the object is the one handed out earlier, which the title-facing create path has since adopted, swapping its vtable pointer for XCL's ext class. real::read_pso_cached_blob exists for exactly this and calls orig_fn(pso, slot_of(pso, "GetCachedBlob")) on adopted objects. If a title creates the same compute or graphics pipeline twice, the first with_name hands out object X, which gets adopted. The second with_name loads X again (D3D12 returns the same object) and calls GetCachedBlob at the PC slot index on the ext vtable, which is the wrong method or XCL's hook. The result is garbage, a crash, or a None blob that forces a full driver recompile. Using read_pso_cached_blob would fix it, and the unit test never adopts its objects, so it can't catch this.

let Some(ready) = super::warm_library::take_ready() else { return Ok(()) };
let ready = super::warm_library::take_ready().or_else(|| {
// (no preparation ran: the runtime library still keeps what the title builds, in data_dir)
let data_dir = &crate::state::boot()?.data_dir;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: warm_library::reuse now stores READY on every preparation, including titles with no corpus or with Stale/Absent libraries, so activate's hard Err on driver != ready.driver now fails device creation (real.rs:1025 uses ?) for any title whose runtime adapter differs from the one preparation picked. Preparation takes candidates(...).next() for its driver identity. If at runtime the first candidate fails create_device(12_0) and the loop moves to the next adapter (or falls back to Auto/WARP), the driver identity differs, activate returns Err, and the title can't start, even with no prepared libraries at all. Before, that error was only possible when the libraries were Current. Treating a driver mismatch as "no libraries" (log and continue) would avoid it.

Comment thread crates/xcl/src/shaders/warm_library.rs Outdated
.filter(|r| r.version == VERSION).map(|receipt| (receipt, false));
fn prepared(corpus: Option<&Corpus>) -> Prepared {
Prepared {
corpus: corpus.and_then(Corpus::identity).unwrap_or_default(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: A corpus with no identity file now gets corpus: [0; 32]. Before, expected() and expected_for_adapter() returned None, so such a corpus was never reusable and publish wrote no receipt. Now publish writes a receipt with a zero corpus, and every later identity-less corpus matches it as Library::Current. If you stage a corpus without an identity file, launch once (receipt written with corpus 0), then restage it with more recipes still without an identity, prepare_for_launch sees Current, skips preparation and reports all recipes complete. The new pipelines are never prepared, and XCL_PREPARE_CACHE_ONLY=1 lets the launch through anyway. Keeping "no identity" as not reusable would fix it.

Comment thread crates/xcl/src/hle/d3d12x/real.rs Outdated
let compute_name = driver_cache::name_for_root_node(&tp.cs, 0, false, &tp.samplers, node_mask);
// Serialize concurrent builds of a shared compute pass across distinct (MS/GS, PS) pairs,
// except when a dispatch-chain fallback is available (stay non-blocking like CachedWhole).
let _one_compute_build = tp.cs_chain.is_none().then(|| crate::shaders::pipeline_library::one_build(&compute_name));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: finish_two_pass takes the mesh pass's gated compile slot (take_cold_slot, held until drop(slot)) before it blocks in one_build(&compute_name), but the thread holding that compute name in compute_container needs a slot from the same pool to finish. On xcl-pso workers, several two-pass pipelines that share one tp.cs hold the medium or huge slots while waiting on compute name C, and the thread building C waits in driver_compile_identified for a slot. Nobody progresses until XCL_ONE_BUILD_WAIT_S (60 s) runs out, then every waiter builds C itself: a 60 s stall followed by the duplicate compile one_build is meant to prevent. Waiting on one_build before taking the slot would avoid the deadlock.

Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD))
}

impl Runtime {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: store_runtime puts the name into known before the store succeeds and never takes it out on failure, and it treats E_INVALIDARG from StorePipeline as "kept already" even when that run's load of the name failed. A transient StorePipeline error (e.g. E_OUTOFMEMORY) leaves the name in known, so it's never stored for the rest of the run and is rebuilt next launch. An entry whose load keeps failing (desc mismatch) hits E_INVALIDARG on store, is counted as kept, and is never replaced, so that pipeline is rebuilt in the driver every run.

@bmjask

bmjask commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of d9979794: 5 finding(s) (3 high, 2 medium), most severe first.

Correction: my previous review on this PR was written against ae8b643f, but it was attached to d9979794 by mistake because the PR was force-pushed while that review was running. This review is the one actually done at d9979794. Still present from the earlier one: activate's hard error on a driver mismatch now fails device creation for any title that ran preparation, not only titles with a prepared corpus (pipeline_library.rs ~213), and the two-pass mesh pass holding a compile slot while it waits on the compute pass's one_build (real.rs ~9627). The other earlier findings (the adopted-object GetCachedBlob, the zero-identity corpus, the legacy-path migration, store_runtime's known on failure) weren't flagged at this head and may have been addressed. New at this head:

  1. High crates/xcl/src/hle/d3d12x/real.rs:4900: end_title now runs flush_runtime (wait for flush_lock, serialize up to 2 GiB, write with sync_all) inside the 15 s end watchdog and before suspend_other_threads, fence signalling and drain_gpu, so a large flush can use the wh.... (inline)
  2. High crates/xcl/src/hle/d3d12x/real.rs:6406: one_build is taken before driver_compile_identified's compile gate, so a background xcl-pso worker that holds a name while parked in big_compile_turn (waiting for commit headroom or a slot) blocks a title thread's synchronous creat.... (inline)
  3. High crates/xcl/src/shaders/pipeline_library.rs:388: Not certain about this one, because it depends on whether D3D12 counts the library's reference publicly: store_runtime StorePipelines every runtime-built pipeline into runtime.plib, which keeps a reference for the process lifetime, so .... (inline)
  4. Medium crates/xcl/src/shaders/pipeline_library.rs:446: The cap is only enforced per pipeline within NEAR_CAP_MARGIN (16 MiB) of it, and the read-lock path stores with no size check, so a large or concurrent store can push the library past the cap. (inline)
  5. Medium crates/xcl/src/shaders/pipeline_library.rs:376: In can_store_locked, a GetCachedBlob failure for a single pipeline calls mark_full(), latching the whole runtime library as full for the rest of the process even though it's under the cap. (inline)

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

Comment thread crates/xcl/src/hle/d3d12x/real.rs Outdated
let watchdog = rx.recv_timeout(std::time::Duration::from_secs(1)).unwrap_or(0);
crate::log::flush();
// (before the threads stop: one of them may be storing into the runtime library)
crate::shaders::pipeline_library::flush_runtime();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: end_title now runs flush_runtime (wait for flush_lock, serialize up to 2 GiB, write with sync_all) inside the 15 s end watchdog and before suspend_other_threads, fence signalling and drain_gpu, so a large flush can use the whole budget and skip the device-hang mitigation. If runtime.plib is ~1.5 GB on a slow disk, or the periodic flusher is mid-write, end_title waits, then serializes and fsyncs for more than 15 s. xcl-end-watchdog then calls end_process_now before the title's threads are suspended and its fences signalled (the end-of-run device hang that ordering exists to prevent), leaving the temp file half-written. On WM_CLOSE the window shows Not Responding meanwhile. Flushing after the hang mitigation, or bounding the flush by the remaining budget, would avoid it.

*ppv = pso.into_raw();
return (S_OK, std::time::Duration::ZERO, true);
// Skip single-flight waiting for CachedWhole probes so callers fall back to dispatch_chain::build immediately.
let _one_build = compute_uses_one_build(mode, !ppv.is_null())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: one_build is taken before driver_compile_identified's compile gate, so a background xcl-pso worker that holds a name while parked in big_compile_turn (waiting for commit headroom or a slot) blocks a title thread's synchronous create of the same pipeline for up to XCL_ONE_BUILD_WAIT_S (60 s). If a pso_async worker starts an ahead or unwanted build of compute X, takes one_build(X) and then waits at the gate for commit headroom (the code notes gate waits of 129 s), the title thread's CreateComputePipelineState for X sits in OneBuildFlights::enter for 60 s before compiling. Before this PR it compiled X at once, ungated. Taking one_build after the gate, or letting a title thread jump ahead of a parked background holder, would avoid the minute-long stall.

}
}

fn store_into_runtime(runtime: &Runtime, name: &str, pipeline: &ID3D12PipelineState) -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: Not certain about this one, because it depends on whether D3D12 counts the library's reference publicly: store_runtime StorePipelines every runtime-built pipeline into runtime.plib, which keeps a reference for the process lifetime, so pso_release's n == 0 path (forget_pso, the TWO_PASS compute-pass drop, pso_async::released for stand-ins) may never run for those pipelines. The code's own comment ("a load may give back the very object stored") says the library holds it. In a streaming title that creates and releases pipelines as it loads areas, the title's last Release would return 1, not 0. TRANSLATED_GRAPHICS, PSO_RS, dispatch chains and TWO_PASS entries (with their compute passes) then accumulate, and memory grows over a long session. Running the cleanup when the title's own count reaches 0 (tracked separately), not the COM count, would avoid depending on it.

if !runtime.known.lock().unwrap().insert(name.into()) { return }
let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len();
let _same_name = self.names[slot].lock().unwrap();
let near_cap = runtime.cap.saturating_sub(runtime.library.serialized_size()) <= NEAR_CAP_MARGIN;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: The cap is only enforced per pipeline within NEAR_CAP_MARGIN (16 MiB) of it, and the read-lock path stores with no size check, so a large or concurrent store can push the library past the cap. flush_runtime_on then sets disabled for good, and every pipeline added since the last flush is never written. With the library at 2031 MiB of a 2048 MiB cap (17 MiB left, more than the margin), two threads storing 12 MiB compute blobs at once take it to ~2055 MiB, so the next flush sees current > cap, marks it full, disables it, and the pipelines from the last 30 s+ are lost. Writing what fits (or checking size on every store) would keep them.

self.mark_full(current);
return false;
}
let Some(est) = estimated_store_bytes(name, pipeline) else {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: In can_store_locked, a GetCachedBlob failure for a single pipeline calls mark_full(), latching the whole runtime library as full for the rest of the process even though it's under the cap. Near the cap, one pipeline whose GetCachedBlob fails (an error or empty blob for that PSO) makes estimated_store_bytes return None, full is set, and every later store_runtime returns early, with tens of MiB still free. Skipping just that pipeline would avoid it.

@Kalmarv
Kalmarv force-pushed the compile/pipeline-store branch from d997979 to a2eaffc Compare December 2, 2026 17:27
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bmjask for both thorough reviews! I verified every finding from both passes (reviews 6155295007 and 6155457233) against the code and real D3D12, and pushed a2eaffc4f addressing all real issues (cc @Prime1997):

First review (6155295007)

  1. Critical (pipeline_library.rs read_cached_blob / cached_blob_size on adopted PSOs): Fixed. Exposed pub(crate) unsafe fn read_pso_cached_blob and pso_cached_blob_size in crates/xcl/src/hle/d3d12x/real.rs (sharing a single adoption-aware get_pso_cached_blob helper that uses orig_fn(pso, slot_of(pso, "GetCachedBlob")) when is_adopted(pso) is true and the PC vtable otherwise) and routed both read_cached_blob and cached_blob_size through them. Updated with_name_and_store_runtime_hand_out_pipeline_once_then_cached_blob to call real::adopt(..., Kind::PipelineState) before the second lookup.
  2. High (pipeline_library.rs activate hard Err on driver mismatch): Fixed. Added check_activation_driver: when the runtime adapter/driver differs or is unavailable, activate now logs a warning and returns Ok(()) without libraries so device creation succeeds (only returning Err when XCL_PREPARE_CACHE_ONLY=1 with prepared libraries present). Covered by activation_driver_mismatch_warns_and_continues_unless_cache_only.
  3. High (warm_library.rs identity-less corpus [0; 32]): Fixed. Removed the [0; 32] fallback: prepared_state now marks a corpus without an identity file as Library::Stale, and publish skips writing (and removes any existing) receipt.json while still populating READY for the current launch. Covered by identityless_corpus_is_never_current_and_writes_no_receipt.
  4. High (real.rs finish_two_pass compile slot held across one_build(&compute_name)): Fixed. finish_two_pass now releases the mesh pass's SlotGuard (slot.take()) after the mesh pass completes and before entering one_build(&compute_name) (re-acquiring a slot only if the compute pass misses caches). Covered by two_pass_releases_compile_slot_before_one_build_wait.
  5. Medium (pso_corpus.rs / warm_library.rs legacy .xcl/pso-corpus/{compute,graphics}.plib import): Fixed. Added warm_library::previous_library, falling back to .xcl/pso-corpus/{compute,graphics}.plib when the new layout folder has no library yet, and wired it into both compute pipeline_library::begin and graphics XCL_PIPELINE_LIBRARY_PREVIOUS (and updated README.md). Covered by previous_library_prefers_layout_folder_and_falls_back_to_legacy_corpus.
  6. Medium (pipeline_library.rs store_runtime inserting into known before store / failed-load E_INVALIDARG): Fixed. store_runtime now checks known.contains under _same_name and only records the outcome after StorePipeline: transient errors (e.g. E_OUTOFMEMORY) leave the name out of known and handed so later calls can retry, and E_INVALIDARG on a name whose with_name load failed in this run (load_missed) stops retrying without marking it handed. Covered by store_runtime_retries_after_transient_error_and_does_not_mark_failed_load_handed.

Second review (6155457233)

  1. High (real.rs end_title unbounded flush_runtime inside 15 s watchdog): Fixed. Added pipeline_library::flush_runtime_timeout(Duration::from_secs(5)) (fast-path returns immediately when flush_lock.try_lock() sees nothing pending or disabled, otherwise runs on "xcl-plib-end-flush" bounded to 5 s) so suspend_other_threads, fence signalling, and drain_gpu always retain >= 10 s of the 15 s watchdog while keeping the previous on-disk runtime.plib intact on timeout. Covered by flush_runtime_timeout_returns_within_budget_when_blocked.
  2. High (real.rs one_build held while parked in big_compile_turn): Fixed. OneBuildFlights now tracks (ThreadId, flight_id) per in-flight name and big_compile_turn calls pipeline_library::release_one_build_on_park() the moment a worker parks (if parked.is_none()), immediately waking any ungated title thread waiting on that name while keeping the parked guard's later Drop safe against clobbering the new holder. Covered by one_build_releases_when_holder_parks_and_does_not_clobber_new_holder.
  3. High ("Not certain", StorePipeline COM refcount vs pso_release n == 0): Verified empirically on Windows 11 D3D12 (RTX 5070 Ti, driver 610.74) — not a bug: ID3D12PipelineLibrary::StorePipeline holds an internal reference and does not increment the public COM refcount (before_store=1, after_store=1, final Release() returns 0 while the library is still alive; same 1 -> 0 for PSOs loaded from a reopened/prepared library), so pso_release's n == 0 cleanup (forget_pso, TWO_PASS drop, pso_async::released) still runs normally. Added store_pipeline_does_not_hold_public_refcount_and_adopted_release_reloads_blob to lock in both the refcount behavior and that an adopted PSO released to 0 still yields Loaded::Blob on a later with_name lookup.
  4. Medium (pipeline_library.rs cap enforcement outside NEAR_CAP_MARGIN / concurrent read-lock stores): Fixed. store_runtime now computes estimated_store_bytes up front and uses an atomic Runtime::estimated_size reservation (try_reserve_fast) that only allows the read-lock path while the cumulative estimate stays <= cap - NEAR_CAP_MARGIN; any large pipeline or concurrent burst crossing that threshold serializes through store_lock.write(), refreshes estimated_size = library.serialized_size(), and checks exact current + est <= cap before storing. Oversized single entries (est > NEAR_CAP_MARGIN) skip without latching full. Covered by cap_reservation_prevents_concurrent_overflow_and_oversized_entry_does_not_latch_full.
  5. Medium (pipeline_library.rs can_store_locked latching mark_full() on a single GetCachedBlob failure): Fixed. If estimated_store_bytes returns None, store_runtime skips only that pipeline and does not call mark_full().

Verification on a2eaffc4f (RTX 5070 Ti, driver 610.74, Windows 11 26200, rustc 1.99.0, DXC 1.9.2609.5)

  • cargo build --release -p xcl: ok, 39 warnings (matches origin/main 5eaadb54c).
  • .\scripts\test.ps1: 2993 passed, 0 failed, 52 ignored, 24 SKIPPED (22 no wave64, 2 no heap windows), including all new unit tests and gpu_two_pass_cache_e2e.
  • Isolated 60 s cold + warm smoke on retail title ea3b5e4d (PR description updated with the fresh a2eaffc4f xcl-smoke v1 block): cold 1704 frames (60 60 60, 15708 MB peak commit, 15.6 MB runtime.plib, 0 removals, 0 crashes, <game>\.xcl unchanged); warm repeat 1707 frames (60 60 60, 15121 MB peak commit, 3 930 graphics + 98 compute served from runtime.plib, 0 ms bind waits, 0 removals, 0 crashes, <game>\.xcl unchanged).

(Fixes and verification by Antigravity, Gemini 4 Neon.)

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of a2eaffc4: 4 finding(s) (1 critical, 1 high, 2 medium), most severe first.

Re-review at a2eaffc4. The 60 s stall from one_build being taken before the compile gate, and the two-pass slot/one_build deadlock, are no longer flagged. The end-of-title flush now has a 5 s limit, and cap enforcement was reworked, but both still have problems (first two below). The activate driver-mismatch error no longer fails device creation, but it now drops the runtime library too (last item).

  1. Critical crates/xcl/src/hle/d3d12x/real.rs:4902: When the 5 s shutdown flush times out, its xcl-plib-end-flush thread may still be inside GetSerializedSize/Serialize, a multi-GB vec! allocation, or write_atomic, and suspend_other_threads then suspends it like any other thread whi.... (inline)
  2. High crates/xcl/src/shaders/pipeline_library.rs:578: A fast-path size reservation is made before taking the store read lock, and the write-lock path then sets estimated_size to the exact current size, which wipes out reservations already granted to other threads, so the guarantee against.... (inline)
  3. Medium crates/xcl/src/hle/d3d12x/present.rs:741: WM_CLOSE calls flush_runtime() with no time limit on the window thread before ExitProcess, unlike end_title's 5 s limit. (inline)
  4. Medium crates/xcl/src/shaders/pipeline_library.rs:221: When the prepared libraries' driver identity differs from the runtime device's (not cache-only), activate returns before open_runtime, so runtime.plib is dropped too, although it lives in the per-title data folder and open_shared a.... (inline)

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

Comment thread crates/xcl/src/hle/d3d12x/real.rs Outdated
// (before the threads stop: one of them may be storing into the runtime library; bounded
// so a large or contested flush still leaves the 15 s watchdog plenty of budget for
// suspending threads, signalling fences, and draining the GPU)
crate::shaders::pipeline_library::flush_runtime_timeout(std::time::Duration::from_secs(5));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Critical: When the 5 s shutdown flush times out, its xcl-plib-end-flush thread may still be inside GetSerializedSize/Serialize, a multi-GB vec! allocation, or write_atomic, and suspend_other_threads then suspends it like any other thread while it may hold the process heap lock or D3D12's library lock. With a large runtime.plib (hundreds of MB to 2 GB) or a slow disk, the flush takes over 5 s, end_title moves on, and the flush thread is suspended inside HeapAlloc or the D3D12 serialize lock. drain_gpu or log::flush then block on that lock, and the process hangs until the 15 s watchdog calls end_process_now, so the final log and report are lost. Excluding the flush thread from suspension (and abandoning its temp file), or not starting the flush when it can't finish in the budget, would avoid it.

if runtime.known.lock().unwrap().contains(name) { return }
// Skip only this pipeline if its cached blob cannot be read; do not latch `runtime.full`.
let Some(est) = estimated_store_bytes(name, pipeline) else { return };
let outcome = if runtime.try_reserve_fast(est) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: A fast-path size reservation is made before taking the store read lock, and the write-lock path then sets estimated_size to the exact current size, which wipes out reservations already granted to other threads, so the guarantee against concurrent overflow doesn't hold. Near the cap, thread X wins try_reserve_fast (estimated_size += est) and blocks on store_lock.read() while Y holds store_lock.write(). In can_store_locked and after its store, Y sets estimated_size = serialized_size(), so X's est disappears. X then stores, and more threads pass try_reserve_fast against the undercount. Their combined stores go past the cap, and the next flush_runtime_on sees current > cap, sets disabled = true, and every pipeline added since the last flush is lost for the session. Adding outstanding reservations back when resetting estimated_size would keep it correct.

Comment thread crates/xcl/src/hle/d3d12x/present.rs Outdated
match msg {
WM_CLOSE => {
crate::xlog_info!("XCL window closed – ending the game process");
crate::shaders::pipeline_library::flush_runtime();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: WM_CLOSE calls flush_runtime() with no time limit on the window thread before ExitProcess, unlike end_title's 5 s limit. If the user closes the window while the periodic flusher holds flush_lock for a 2 GB serialize, or runtime.plib has grown a lot, the window procedure blocks for the whole serialize, fsync and MoveFileEx, so Windows shows the window as not responding for many seconds, or indefinitely on a stuck disk. Using the same bounded flush as end_title would fix it.

if cache_only && has_prepared {
return Err(reason.into());
}
crate::xlog_warn!("{reason}; continuing without pipeline libraries");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: When the prepared libraries' driver identity differs from the runtime device's (not cache-only), activate returns before open_runtime, so runtime.plib is dropped too, although it lives in the per-title data folder and open_shared already rejects one from another driver. If preparation resolves the adapter (config auto / XCL_ADAPTER) to a different adapter or driver identity than the device actually created (a hybrid-GPU laptop, a driver update between preparation and launch), activate logs "continuing without pipeline libraries" and never opens runtime.plib. Every pipeline the title builds that run is then neither loaded nor kept, on every launch while the mismatch lasts. Opening the runtime library independently of the prepared ones would keep it.

@Kalmarv
Kalmarv force-pushed the compile/pipeline-store branch from a2eaffc to 13e9c70 Compare December 2, 2026 18:01
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bmjask for the re-review! All 4 findings from review 6155986550 are fixed in 13e9c7091 (cc @Prime1997):

  1. Critical (real.rs end_title suspending a timed-out flush thread): Fixed. flush_runtime_timeout now returns the live OS thread IDs of xcl-plib-end-flush and xcl-pipeline-library (PERIODIC_FLUSH_TID) when the 5 s budget expires, and suspend_other_threads excludes those threads alongside xcl-end-watchdog so a still-running serialize/alloc/write thread is never suspended while holding the process heap lock or D3D12 library lock (neither thread touches title fences, command allocators, or GPU queues; any abandoned temp file is cleaned up on the next launch). Updated flush_runtime_timeout_returns_within_budget_when_blocked to verify the returned live thread ID.
  2. High (pipeline_library.rs try_reserve_fast reservation wiped by concurrent store_lock.write() reset): Fixed. store_runtime now acquires store_lock.read() before calling try_reserve_fast(est) and holds it across StorePipeline, dropping the read guard only if it falls through to store_lock.write(). Because no thread can hold an unstored fast-path reservation once store_lock.write() is acquired, resetting estimated_size to library.serialized_size() under the write lock is exact and can never wipe another thread's reservation. Expanded cap_reservation_prevents_concurrent_overflow_and_oversized_entry_does_not_latch_full with a 4-thread concurrent store test against a tight cap.
  3. Medium (present.rs WM_CLOSE unbounded flush_runtime): Fixed. WM_CLOSE now calls flush_runtime_timeout(Duration::from_secs(5)), matching end_title.
  4. Medium (pipeline_library.rs activate dropping runtime.plib on prepared driver mismatch): Fixed. Extracted open_active_for_device: when check_activation_driver sees a prepared-cache driver mismatch (and not XCL_PREPARE_CACHE_ONLY=1 with prepared libraries), it skips opening ready.graphics/ready.compute and still opens runtime.plib for the runtime device (where open_shared already validates/resets against the runtime driver). Expanded activation_driver_mismatch_warns_and_continues_unless_cache_only to verify graphics/compute are skipped while runtime is opened.

Verification on 13e9c7091 (RTX 5070 Ti, driver 610.74, Windows 11 26200, rustc 1.99.0, DXC 1.9.2609.5)

  • cargo build --release -p xcl: ok, 39 warnings (matches origin/main 5eaadb54c).
  • .\scripts\test.ps1: 2993 passed, 0 failed, 52 ignored, 24 SKIPPED (22 no wave64, 2 no heap windows), including all updated unit tests and gpu_two_pass_cache_e2e.
  • Isolated 60 s cold + warm smoke on retail title ea3b5e4d (PR description updated with the fresh 13e9c7091 xcl-smoke v1 block): cold 1709 frames (60 60 61, 15739 MB peak commit, 15.6 MB runtime.plib, 0 removals, 0 crashes, <game>\.xcl unchanged); warm repeat 1710 frames (61 60 60, 14996 MB peak commit, 3 928 graphics + 98 compute served from runtime.plib, 0 ms bind waits, 0 removals, 0 crashes, <game>\.xcl unchanged).

(Fixes and verification by Antigravity, Gemini 4 Neon.)

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of 13e9c709: 5 finding(s) (2 high, 3 medium), most severe first.

Re-review at 13e9c709. None of the four findings from the a2eaffc4 review (flush thread suspended after the 5 s shutdown timeout, fast-path reservations wiped by the write-lock path, unbounded WM_CLOSE flush, activate dropping runtime.plib on a driver mismatch) was flagged again at this head, so they may be addressed. Please confirm. The findings below are new.

  1. High crates/xcl/src/hle/d3d12x/real.rs:8316: see below.
  2. High crates/xcl/src/shaders/pipeline_library.rs:349: If the real serialized size goes past the cap after a store whose size was underestimated, flush_runtime_on disables writes for the session and drops every pipeline added since the last flush, and this repeats on every launch. (inline)
  3. Medium crates/xcl/src/shaders/pipeline_library.rs:235: On a device without pipeline-library support, open_active_for_device returns Ok(None) even with XCL_PREPARE_CACHE_ONLY=1 and prepared libraries present. (inline)
  4. Medium crates/xcl/src/shaders/pipeline_library.rs:738: one_build serializes same-name builds whenever a runtime library exists, even when the holder's result can't land in it (the runtime is full, the store was skipped, or StorePipeline failed). (inline)
  5. Medium crates/xcl/src/shaders/pipeline_library.rs:188: runtime.plib never evicts. (inline)

On lines outside the diff:

  1. High crates/xcl/src/hle/d3d12x/real.rs:8316: translated_graphics_pso_once stores the built pipeline in runtime.plib under the with-rect-GS name even when retry_without_rect_gs dropped the GS, so the entry describes a different pipeline than its name. cache_eligible already keeps this PSO out of the RAM/disk blob caches, but this store only checks cacheable && hr >= 0. Later lookups in the same run hand the GS-less blob to a desc with the GS: the driver refuses it and the pipeline is rebuilt, or, if the driver doesn't check the GS, it's a wrong-pipeline hit. In later runs, LoadPipeline with the GS desc misses, StorePipeline returns E_INVALIDARG, and the entry stays dead and is rebuilt on every run. The stream path already leaves rect_gs out of library_name. Skipping the store when dropped_rect_gs (or !build.cache_eligible && !reused) would fix it.

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

let added = runtime.added.swap(0, Ordering::AcqRel);
if added == 0 { return false }
let current = runtime.library.serialized_size();
if current > runtime.cap {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: If the real serialized size goes past the cap after a store whose size was underestimated, flush_runtime_on disables writes for the session and drops every pipeline added since the last flush, and this repeats on every launch. Near the cap, the slow path admits a store using the estimate (blob + name + 4096). The real entry also carries the root signature, input layout and desc subobjects, so serialized_size ends up slightly over the cap. The next flush sees current > runtime.cap, sets disabled = true and writes nothing. The next launch reopens the same file just under the cap, rebuilds the same pipelines, overshoots again and loses them again. Flushing what fits (or stopping admission with a margin) instead of disabling would avoid it.

) -> std::result::Result<Option<Active>, String> {
let has_prepared = ready.graphics.is_some() || ready.compute.is_some();
let use_prepared = check_activation_driver(ready.driver, runtime_driver, has_prepared, cache_only)?;
if !NativeLibrary::supported(device) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: On a device without pipeline-library support, open_active_for_device returns Ok(None) even with XCL_PREPARE_CACHE_ONLY=1 and prepared libraries present. The old activate returned an error here. Cache-only promises a run with nothing to build, but now the launch carries on, logs an info line, and builds every pipeline in the driver, so a measured cache-only run silently measures cold builds. check_activation_driver covers only the driver-mismatch case, so nothing else restores the guard.

/// then in the runtime library, so the waiter loads its cached blob instead of recompiling.
/// Several threads of a title asked for one mesh pipeline at once and each built it, 4 - 6 s
/// apiece. Only with a runtime library.
pub(crate) fn one_build(name: &str) -> OneBuild {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: one_build serializes same-name builds whenever a runtime library exists, even when the holder's result can't land in it (the runtime is full, the store was skipped, or StorePipeline failed). Each waiter then wakes, misses in with_name, takes the flight and does its own full compile while the rest keep waiting. With runtime.plib at XCL_RUNTIME_LIBRARY_MB, N threads requesting the same pipeline (e.g. a small compute shader with no RAM blob) compile one after another instead of in parallel, stalling title threads for up to N compile times. Skipping one_build when runtime.full is set, or letting a waiter that misses build without taking the flight, would avoid it.

None => NativeLibrary::empty(device).ok()?,
};
let initial_size = library.serialized_size();
let full = initial_size >= cap;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: runtime.plib never evicts. Entries whose names changed (after translator or setting changes, which the PR says happen routinely) stay forever, so the file eventually reaches the 2048 MiB cap, full is set at open, and from then on no new pipeline is kept: every new pipeline is rebuilt on every run, while each launch still loads the full 2 GiB of mostly dead entries into RAM. The README says not to delete these folders, so the user has no way out. Rebuilding the file from the names hit in the last run when it nears the cap, or starting fresh when the translator identity changes, would keep it useful.

@Kalmarv
Kalmarv force-pushed the compile/pipeline-store branch from 13e9c70 to 69c106e Compare December 2, 2026 18:35
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bmjask for another sharp pass! All 5 findings from review 6156309868 are fixed in 69c106e0c (cc @Prime1997):

  1. High (real.rs translated_graphics_pso_once storing retry_without_rect_gs fallback under with-rect-GS name): Fixed. Added graphics_build_storable_in_library(cacheable, &build) checking cacheable && build.hr >= 0 && (build.cache_eligible || build.reused) so a fallback build whose generated rect-list GS was dropped (cache_eligible: false, reused: false) is not stored under the with-rect-GS library name. Covered by dropped_rect_gs_build_is_not_stored_under_rect_gs_library_name.
  2. High (pipeline_library.rs underestimated store overshooting cap and disabling flushes): Fixed. Increased ENTRY_OVERHEAD to 64 KiB (covering root signature, input layout, and desc subobjects) and added admit_cap(cap) (cap - 2 MiB headroom for real caps >= 16 MiB) used by open_runtime, try_reserve_fast, can_store_locked, and post-store after >= admit_cap, while flush_runtime_on enforces <= cap, so minor D3D12 subobject/directory growth on the final admitted store stays within cap and never trips disabled.
  3. Medium (pipeline_library.rs open_active_for_device returning Ok(None) without pipeline-library support under XCL_PREPARE_CACHE_ONLY=1): Fixed. Added check_library_support: when !NativeLibrary::supported(device) and cache_only && has_prepared, open_active_for_device now returns Err("Pipeline library: the device does not support pipeline libraries"). Covered by cache_only_fails_without_library_support_and_one_build_skips_when_full.
  4. Medium (pipeline_library.rs one_build serializing when runtime.full is set): Fixed. one_build now checks should_use_one_build and skips waiting once runtime.full is set so concurrent builds are not needlessly serialized when results cannot land in runtime.plib. Covered by cache_only_fails_without_library_support_and_one_build_skips_when_full.
  5. Medium (pipeline_library.rs runtime.plib never evicting stale entries + README.md): Fixed. Added a sibling runtime.stamp (layout:translation:settings) written alongside runtime.plib in data_dir when a fresh library is flushed: under-cap libraries and same-build full libraries are kept unchanged, while a full library (>= admit_cap) carrying entries from an older build or settings automatically starts fresh (should_reset_full_runtime). Also clarified in README.md that deleting runtime.plib under the per-title data folder is always safe (only <game>\.xcl\pipeline-libraries\ should not be deleted for a clean run). Covered by full_runtime_library_resets_only_when_build_stamp_changed.

Verification on 69c106e0c (RTX 5070 Ti, driver 610.74, Windows 11 26200, rustc 1.99.0, DXC 1.9.2609.5)

  • cargo build --release -p xcl: ok, 39 warnings (matches origin/main 5eaadb54c).
  • .\scripts\test.ps1: 2996 passed, 0 failed, 52 ignored, 24 SKIPPED (22 no wave64, 2 no heap windows), including all new unit tests and gpu_two_pass_cache_e2e.
  • Isolated 60 s cold + warm smoke on retail title ea3b5e4d (PR description updated with the fresh 69c106e0c xcl-smoke v1 block): cold 1711 frames (60 60 61, 16211 MB peak commit, 133.4 MB runtime.plib + 50 B runtime.stamp in data_dir, 0 removals, 0 crashes, <game>\.xcl unchanged); warm repeat 1710 frames (60 60 60, 15285 MB peak commit, 2 752 graphics + 237 compute served from runtime.plib, 0 ms bind waits, 0 removals, 0 crashes, <game>\.xcl unchanged).

(Fixes and verification by Antigravity, Gemini 4 Neon.)

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of 69c106e0: 2 finding(s) (1 high, 1 medium), most severe first.

Re-review at 69c106e0. None of the five findings from the 13e9c709 review (runtime.plib store after the rect GS is dropped, flush disabling writes after an underestimated store, the cache-only guard on devices without library support, one_build serializing when the runtime is full, runtime.plib never evicting) was flagged again at this head, so they may be addressed. Please confirm. The two findings below are new.

  1. High crates/xcl/src/shaders/warm_library.rs:259: If the staged corpus has no identity file, publish() deletes receipt.json, so on the next launch prepared_state() finds no receipt and reports the libraries Absent. (inline)
  2. Medium crates/xcl/src/hle/d3d12x/real.rs:9578: In finish_two_pass, the mesh pass's one_build guard lives until the function returns, so it stays held while the thread waits up to 60 s for the shared compute pass's one_build and then builds the compute pass, even though the mesh.... (inline)

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

Comment thread crates/xcl/src/shaders/warm_library.rs Outdated
} else {
// Without a corpus identity file we cannot prove a future corpus matches this one, so
// never leave a receipt that would mark later runs Current.
let _ = std::fs::remove_file(dir.join(RECEIPT));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: If the staged corpus has no identity file, publish() deletes receipt.json, so on the next launch prepared_state() finds no receipt and reports the libraries Absent. The just-prepared graphics.plib/compute.plib are never used, and full preparation runs again on every launch. For a title whose .xcl/pso-corpus has no identity file, launch 1 prepares and publishes with no receipt. Launch 2 gets read(dir) == None, so Library::Absent("no prepared libraries") triggers discover(), and preparation (graphics worker, every recipe translated) starts over. This repeats on every launch and never reaches Current. With XCL_PREPARE_CACHE_ONLY=1 the title is refused with 'no native pipeline libraries' even right after a successful preparation. Writing a receipt keyed on a fallback identity (or keeping the old one) would let the result be used.

Comment thread crates/xcl/src/hle/d3d12x/real.rs Outdated
let gdisk = disk_key.and_then(|(hash, bytes)| driver_cache::graphics_path(hash, bytes));
let stream_desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: stream.0.len(), pPipelineStateSubobjectStream: stream.0.as_ptr() as *mut c_void };
let library_mesh = disk_key.and_then(|(hash, bytes)| {
let _one_build = disk_key.map(|(hash, bytes)| crate::shaders::pipeline_library::one_build(&driver_cache::graphics_name(hash, bytes)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: In finish_two_pass, the mesh pass's one_build guard lives until the function returns, so it stays held while the thread waits up to 60 s for the shared compute pass's one_build and then builds the compute pass, even though the mesh pipeline is already built. It isn't stored in runtime.plib until the end. With threads A and B creating the same two-pass pipeline M, A builds the mesh and waits on one_build(C), held by thread D. B waits on one_build(M) for the whole compute wait plus compile, with M's mesh blob already in hand. If A parks in take_cold_slot for the compute pass, release_one_build_on_park drops the mesh flight too: B wakes, finds no M in the library and compiles the mesh pass again, the double compile one_build is meant to prevent. Storing the mesh and dropping its guard before entering the compute pass would fix both.

@Kalmarv
Kalmarv force-pushed the compile/pipeline-store branch from 69c106e to e39ea9f Compare December 2, 2026 19:09
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bmjask! Both findings from review 6156821596 are fixed in e39ea9ffd (cc @Prime1997):

  1. High (warm_library.rs identity-less corpus deleting receipt.json and rebuilding every launch): Fixed. Added corpus_identity(corpus) in crates/xcl/src/shaders/warm_library.rs (using Corpus::directory() from pso_corpus.rs): when the identity file is absent, it computes a deterministic 32-byte content fallback identity over the corpus counts, windows, graphics.bin, and sorted compute/* files. publish() now always writes a valid receipt.json, so an unchanged identity-less corpus hits Library::Current (including under XCL_PREPARE_CACHE_ONLY=1), while any changed corpus or [0; 32] receipt produces Library::Stale("corpus changed"). Covered by identityless_corpus_uses_content_fallback_identity_and_detects_changes.
  2. Medium (real.rs finish_two_pass holding mesh one_build across compute pass): Fixed. finish_two_pass now stores mesh_pso into the pipeline library and drops mesh_one_build right after the mesh pass completes (before slot.take() and before entering one_build(&compute_name) or take_cold_slot for the compute pass), so threads waiting on the mesh name reuse it immediately and a compile-gate park in the compute pass cannot prematurely drop an unstored mesh flight.

Verification on e39ea9ffd (RTX 5070 Ti, driver 610.74, Windows 11 26200, rustc 1.99.0, DXC 1.9.2609.5)

  • cargo build --release -p xcl: ok, 39 warnings (matches origin/main 5eaadb54c).
  • .\scripts\test.ps1: 2996 passed, 0 failed, 52 ignored, 24 SKIPPED (22 no wave64, 2 no heap windows), including identityless_corpus_uses_content_fallback_identity_and_detects_changes and gpu_two_pass_cache_e2e.
  • Isolated 60 s cold + warm smoke on retail title ea3b5e4d (PR description updated with the fresh e39ea9ffd xcl-smoke v1 block): cold 1706 frames (60 60 61, 16199 MB peak commit, 132.6 MB runtime.plib + 50 B runtime.stamp in data_dir, 0 removals, 0 crashes, <game>\.xcl unchanged); warm repeat 1718 frames (60 60 60, 15380 MB peak commit, 1 262 graphics + 487 compute served from runtime.plib, 0 ms bind waits, 0 removals, 0 crashes, <game>\.xcl unchanged).

(Fixes and verification by Antigravity, Gemini 4 Neon.)

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of e39ea9ff: 4 finding(s) (1 high, 3 medium), most severe first.

Re-review at e39ea9ff. The two findings from the 69c106e0 review (receipt deleted for an identity-less corpus, the two-pass mesh guard held across the compute wait) weren't flagged again at this head, so they may be addressed. The first item below looks like a regression introduced by the new storability check.

  1. High crates/xcl/src/hle/d3d12x/real.rs:8336: The new graphics_build_storable_in_library check needs cache_eligible || reused, but a library hit is built with reused: false, cache_eligible: false (line 8296), so graphics pipelines imported from the previous library during prep.... (inline)
  2. Medium crates/xcl/src/shaders/pipeline_library.rs:233: runtime.stamp is written only when the library starts fresh or has no stamp, so it records the build that created runtime.plib, not the builds that filled it, and should_reset_full_runtime then throws away full libraries filled entir.... (inline)
  3. Medium crates/xcl/src/shaders/pipeline_library.rs:499: When the try_lock succeeds and added == 0, or the end flush finishes within the timeout, flush_runtime_timeout returns [0, 0], so the periodic xcl-pipeline-library thread isn't excluded from suspend_other_threads even though it.... (inline)
  4. Medium crates/xcl/src/shaders/pipeline_library.rs:803: one_build makes a title thread wait up to 60 s (XCL_ONE_BUILD_WAIT_S) for any other thread building the same name, including a pso_async preload worker at THREAD_PRIORITY_LOWEST, and the flight is released only if that worker parks in .... (inline)

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

driver_cache::note(true, loaded.take());
}
if cacheable && hr >= 0 && !ppv.is_null() && !(*ppv).is_null() {
if graphics_build_storable_in_library(cacheable, &build) && !ppv.is_null() && !(*ppv).is_null() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

High: The new graphics_build_storable_in_library check needs cache_eligible || reused, but a library hit is built with reused: false, cache_eligible: false (line 8296), so graphics pipelines imported from the previous library during preparation are no longer stored in the new graphics.plib. In an incremental preparation after a translator or settings change, prepare_graphics -> translated_graphics_pso_once -> load_graphics hits from_previous and returns Loaded::Pipeline, and the store is skipped (on main, cacheable && hr >= 0 stored it). finish() then writes a graphics library holding only the newly built pipelines, so every unchanged graphics pipeline is lost and rebuilt by the next preparation or at runtime. Each preparation drops what the previous one imported. The stream and two-pass paths still store library hits, so only plain graphics is affected. Treating a library hit as storable (or marking it reused) would fix it.

};
let initial_size = library.serialized_size();
let full = initial_size >= admit_cap(cap);
let write_stamp = started_fresh || saved_stamp.is_none();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: runtime.stamp is written only when the library starts fresh or has no stamp, so it records the build that created runtime.plib, not the builds that filled it, and should_reset_full_runtime then throws away full libraries filled entirely by the current build. Build A creates runtime.plib (stamp A). The user updates to build B and plays until the library reaches the cap, so every new entry is a B pipeline. On B's next launch the saved stamp A differs from B, open_runtime logs 'contains entries from an older build' and starts empty, and up to 2 GiB of valid B pipelines are rebuilt. Updating the stamp whenever a flush writes entries would keep it accurate.

/// (avoiding suspending a thread holding the process heap lock or D3D12 library lock).
pub(crate) fn flush_runtime_timeout(timeout: std::time::Duration) -> [u32; 2] {
let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return [0, 0] };
if let Ok(state) = runtime.flush_lock.try_lock() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: When the try_lock succeeds and added == 0, or the end flush finishes within the timeout, flush_runtime_timeout returns [0, 0], so the periodic xcl-pipeline-library thread isn't excluded from suspend_other_threads even though it can start a flush right after the check. In end_title, a title thread stores one more pipeline just after the check, and the periodic thread's 30 s tick starts Serialize (allocating up to 2 GiB and holding the D3D12 library lock). suspend_other_threads suspends it while it holds the heap lock, and drain_gpu / log::flush hang until the 15 s watchdog aborts the process: the freeze the keep-list was added to prevent. Always excluding the periodic thread, or stopping it before the final flush, would close it.

/// then in the runtime library, so the waiter loads its cached blob instead of recompiling.
/// Several threads of a title asked for one mesh pipeline at once and each built it, 4 - 6 s
/// apiece. Only while a non-full runtime library can store the result.
pub(crate) fn one_build(name: &str) -> OneBuild {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: one_build makes a title thread wait up to 60 s (XCL_ONE_BUILD_WAIT_S) for any other thread building the same name, including a pso_async preload worker at THREAD_PRIORITY_LOWEST, and the flight is released only if that worker parks in big_compile_turn. If a preload worker that already has a slot starts a 20–30 s compute or mesh compile of X at lowest priority, it never parks. When the render thread then creates X, it blocks in FLIGHTS.enter for up to 60 s and then builds X anyway, where before it compiled at normal priority straight away. Not waiting on low-priority holders (or boosting the holder while a title thread waits) would avoid the stall.

@github-actions github-actions Bot added the needs-1st-check Passes gates; needs first independent merge-check (#3041) label Dec 2, 2026
@Kalmarv
Kalmarv force-pushed the compile/pipeline-store branch from e39ea9f to 7b4b8ad Compare December 2, 2026 20:04
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough re-review @bmjask (cc @Prime1997) — all four findings from the e39ea9ff review are fixed in 7b4b8ad0b:

  1. [High] graphics_build_storable_in_library skipping from_previous library hits during incremental preparation (real.rs): Added an explicit dropped_rect_gs: bool field to GraphicsPsoBuild (set false on cached reuse and library_pso hits, and set from retry_without_rect_gs on cold/retry builds) and simplified graphics_build_storable_in_library to cacheable && build.hr >= 0 && !build.dropped_rect_gs. Library hits imported from the previous library now remain storable into the new graphics.plib, while dropped-rect-GS fallbacks stay excluded. Extended dropped_rect_gs_build_is_not_stored_under_rect_gs_library_name to assert both cases.
  2. [Medium] runtime.stamp stuck on the initial creating build (pipeline_library.rs): Added needs_stamp_write(started_fresh, saved_stamp, current_stamp) (started_fresh || saved_stamp.map(str::trim) != Some(current_stamp)) and used it for write_stamp in open_runtime. When an under-cap runtime.plib is opened and receives new pipelines under a newer build/settings, the flush now refreshes runtime.stamp to the current build so a library filled under the new build is kept instead of reset on the next launch. Added unit assertions in full_runtime_library_resets_only_when_build_stamp_changed.
  3. [Medium] Periodic xcl-pipeline-library flusher not excluded from suspend_other_threads on fast-path or timely finish (pipeline_library.rs): Added SHUTTING_DOWN: AtomicBool checked before flushing in start_counting(), and updated flush_runtime_timeout to set SHUTTING_DOWN = true and always return PERIODIC_FLUSH_TID in slot [1] (even when added == 0 or the end-flush helper finishes within the timeout), so end_title never suspends the periodic flusher while it could hold the process heap or D3D12 lock.
  4. [Medium] Normal-priority title/render thread waiting up to 60 s behind a THREAD_PRIORITY_LOWEST preload worker in one_build (pipeline_library.rs): Recorded holder priority (low_priority: bool via GetThreadPriority(GetCurrentThread()) < THREAD_PRIORITY_NORMAL) in OneBuildFlights and added enter_with_priority: normal-priority callers take over a flight held by a low-priority preload worker immediately instead of waiting, while still deduplicating concurrent normal-priority builds and preventing low-priority workers from racing each other; dropping a superseded low-priority guard checks its flight ID and never removes the normal-priority holder's entry. Covered by one_build_normal_priority_does_not_wait_on_low_priority_holder.

Re-verification on 7b4b8ad0bbba760199c7e9a2957834161630a74d (RTX 5070 Ti, driver 610.74, Ryzen 9 9950X, Windows 11 Build 26200, rustc 1.99.0, DXC 1.9.2609.5):

  • cargo build --release -p xcl: ok, 39 warnings (matches main 5eaadb54c baseline).
  • .\scripts\test.ps1: 2997 passed, 0 failed, 52 ignored, 24 SKIPPED (22 no wave64, 2 no heap windows).
  • Isolated 60 s smoke on retail title (ea3b5e4d, fresh XCL_DATA_ROOT + XCL_DXIL_CACHE, <game>\.xcl unchanged):
    • Cold: 1589 frames (60 60 60), 15674 MB peak commit, 0 device removals, 0 crashes, exit: 0x0; wrote 16.9 MB runtime.plib + 50 B runtime.stamp (3 932 graphics + 212 compute = 4 144 pipelines).
    • Warm repeat: 1676 frames (60 61 60), 14687 MB peak commit, 0 device removals, 0 crashes, exit: 0x0; served 3 932 graphics + 98 compute (4 030 total, 0 compute built, 0 ms bind waits) from runtime.plib.
  • Not tested: incremental preparation of a staged corpus on a retail title after a translator change, 16 heap windows, AMD wave64, and devices without pipeline-library support.
  • AI use: Antigravity (Gemini 4 Neon) implemented these review fixes, added the unit tests, ran the build/test/smoke verification, and wrote this reply.

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of 7b4b8ad0: 4 finding(s) (1 critical, 3 medium), most severe first.

Re-review at 7b4b8ad0. Of the four findings on e39ea9ff, the regression that dropped library-hit graphics pipelines during preparation, the shutdown-suspend gap for the periodic flusher, and the low-priority one_build holder weren't flagged again. The runtime.stamp fix overcorrects (second item below). The first item widens the earlier 'one_build serializes when the runtime is full' finding from 13e9c709 to every build that isn't stored.

  1. Critical crates/xcl/src/shaders/pipeline_library.rs:1031: NativeLibrary::serialize allocates vec![0; GetSerializedSize()] with an infallible allocation on the periodic flusher thread, for a library of up to 2 GiB, so if commit is short Rust aborts the whole title process. (inline)
  2. Medium crates/xcl/src/shaders/pipeline_library.rs:454: Every successful flush now rewrites runtime.stamp to the current build, so a library filled mostly by older builds is labelled current as soon as one entry is added and is never reset. (inline)
  3. Medium crates/xcl/src/hle/d3d12x/real.rs:8274: one_build makes every concurrent creator of a name wait for the holder's build even when that build will never be stored in runtime.plib, so the waiter wakes, misses the library and builds the same pipeline again, and N callers build o.... (inline)
  4. Medium crates/xcl/src/hle/d3d12x/real.rs:9692: The two-pass mesh pipeline is now stored in the library (preparation BUILD or runtime.plib) before the compute pass is built, so the old guarantee that a mesh entry exists only if its compute pass succeeded is gone. (inline)

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

unsafe { self.library.GetSerializedSize() as u64 }
}

pub(crate) fn serialize(&self) -> Result<Vec<u8>> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Critical: NativeLibrary::serialize allocates vec![0; GetSerializedSize()] with an infallible allocation on the periodic flusher thread, for a library of up to 2 GiB, so if commit is short Rust aborts the whole title process. Only the read path was made fallible (try_reserve_exact). A title near its commit limit with a 1.8 GiB runtime.plib hits the 30 s periodic flush_runtime, the 1.8 GiB zeroed Vec fails, and handle_alloc_error aborts the game mid-session, on top of the 1.8 GiB D3D12 already holds for the opened library. Using try_reserve_exact here too and skipping the flush on failure would avoid it.

Ok(()) => {
state.consecutive_failures = 0;
runtime.size.store(bytes.len() as u64, Ordering::Relaxed);
if runtime.write_stamp.swap(false, Ordering::AcqRel) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: Every successful flush now rewrites runtime.stamp to the current build, so a library filled mostly by older builds is labelled current as soon as one entry is added and is never reset. Build v1 fills runtime.plib to 1.95 GiB. After an update to v2, one run adds 50 MiB, the flush writes stamp=v2, and the library is full. Every later v2 launch sees full with a matching stamp, so should_reset_full_runtime is false and full latches. No new pipeline is stored again (and one_build turns off), although ~97% of the entries are dead v1 names. Recording the share of entries per build (or the stamp of the oldest data still present), rather than the last writer, would make the reset decision correct both ways.

let cacheable = graphics_blob_cacheable(cacheable, &copy, final_gs.is_some());
let library_name = driver_cache::graphics_name(disk_key.0, disk_key.1);
let library_pso = if !cacheable || ppv.is_null() {
let _one_build = (cacheable && !ppv.is_null()).then(|| crate::shaders::pipeline_library::one_build(&library_name));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: one_build makes every concurrent creator of a name wait for the holder's build even when that build will never be stored in runtime.plib, so the waiter wakes, misses the library and builds the same pipeline again, and N callers build one after another instead of in parallel. This happens for a rect-list PSO where retry_without_rect_gs drops the GS (graphics_build_storable_in_library is false), a failed build (hr < 0), estimated_store_bytes returning None, and TransientError/UnusableExisting. A second thread waits through the first thread's whole 4–6 s build (up to XCL_ONE_BUILD_WAIT_S = 60 s), then compiles it itself. Waking waiters with 'not stored, build now' when the holder knows its result won't be stored would restore the parallelism.

Comment thread crates/xcl/src/hle/d3d12x/real.rs Outdated
// Mesh pass is done: store it into the pipeline library and drop its `one_build` guard
// immediately so threads waiting on the mesh name reuse it right away and a later compile-gate
// park in the compute pass cannot prematurely drop an unstored mesh flight.
let mesh_library = crate::shaders::pipeline_library::store(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: The two-pass mesh pipeline is now stored in the library (preparation BUILD or runtime.plib) before the compute pass is built, so the old guarantee that a mesh entry exists only if its compute pass succeeded is gone. When the driver rejects the compute pass (hc < 0), finish_two_pass returns E_INVALIDARG, but the mesh entry is already in graphics.plib.pending or runtime.plib and marked handed. Preparation publishes an entry for a pipeline that can't be created, runtime.plib spends capped space on pipelines that always fail, and later requests load the mesh blob and fail again at the compute pass. Storing the mesh only after the compute pass succeeds would keep them paired.

Prepared pipeline libraries were discarded whole when anything in their
receipt changed (a translator source byte, a setting, the pipeline layout,
the staged corpus or the window count), and nothing a title built while
it ran was kept. On a retail title with a prepared library, a 240 s run
still made 144 driver builds of over a second (690 s): 74 % of that time
was the mesh pass of two-pass pipelines, refused blob then the same
330 KB pipeline built by four or five threads at once; 1 130 of the
1 739 drawn pipelines were in no staged corpus and were built every run.

A library entry is named after the exact translated DXIL and state, so a
changed input can only make a name miss. So:
- prepared libraries from a staged corpus live in
  .xcl/pipeline-libraries/<windows>/ (layouts coexist) with a v3 receipt
  keyed by driver; corpus, translation, settings and layout only mark
  them stale, and preparation imports unchanged names from the previous
  library and builds the rest; staged recipes build for the runtime
  layout; XCL_PREPARE_CACHE_ONLY=1 names what changed
- runtime.plib lives under XCL's per-title data folder
  (<XCL_DATA_ROOT | %LOCALAPPDATA%\XCL>\<title>\pipeline-libraries\<windows>\runtime.plib)
  so running a title never writes into the game folder and smoke runs
  stay isolated; it keeps every pipeline built at runtime (graphics,
  graphics streams, both two-pass passes, compute), is written atomically
  under a dedicated flush_lock (no exit data-loss or out-of-order
  overwrite, never blocking pipeline loads during serialization or I/O),
  cleans up stale dead-PID runtime.tmp* files on startup, stops retrying
  after persistent write errors, and resets above XCL_RUNTIME_LIBRARY_MB
  (1024 MiB default, 0 disables)
- one thread builds a given pipeline while others wait (skipping
  ComputeBuild::CachedWhole probes so dispatch-chain fallback stays
  non-blocking) and then receive the library entry's cached driver blob
  for a distinct COM object without recompiling, even for small shaders
- a library hands each name's COM object out once per process (D3D12
  loads one name as one object, while XCL keys pipeline state by object)
  and returns its cached driver blob on subsequent lookups
- a Pipelines: log line counts prepared / runtime library / blob / built
  / built after a refused blob per kind (counting graphics streams under
  Stream and skipping failed fresh builds); refused blobs are logged with
  their HRESULT; XCL_PIPELINE_MEASURE=1 marks a run that built anything
- XCL_RDNA_FLOAT, XCL_WATERFALL_COLLAPSE and XCL_PER_LANE_MAX_INSTS join
  the settings key; the v1/v2 receipt migration and legacy ids go

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Antigravity (Gemini 4 Neon)
@Kalmarv
Kalmarv force-pushed the compile/pipeline-store branch from 7b4b8ad to c301772 Compare December 2, 2026 20:58
@Kalmarv

Kalmarv commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the sharp review @bmjask (cc @Prime1997) — all four findings from the 7b4b8ad0 review are fixed in c301772a1:

  1. [Critical] Infallible vec![0; GetSerializedSize()] allocation in NativeLibrary::serialize (pipeline_library.rs): Replaced with a fallible try_alloc_zeroed(size) helper using Vec::try_reserve_exact that returns Err(E_OUTOFMEMORY) instead of aborting the process under tight commit; flush_runtime_on logs a warning, restores added, and skips the flush (stopping after MAX_FLUSH_FAILURES). Added unit test try_alloc_zeroed_returns_oom_instead_of_aborting.
  2. [Medium] runtime.stamp overwriting stamp with last writer (pipeline_library.rs): Changed runtime.stamp to record per-build byte counts (<stamp> <bytes> per line, backwards-compatible with single-stamp files) updated from new_size.saturating_sub(prev_size) on each successful flush under flush_lock. should_reset_full_runtime now resets a full library when the current build owns less than half of existing_len — so v1 filling 1.95 GiB + v2 adding 50 MiB resets fresh on v2, while v1 creating 10 MiB + v2 filling 2.04 GiB is kept on v2. Verified in full_runtime_library_resets_only_when_build_stamp_changed and on the live retail smoke (runtime.stamp tracked 16 124 048 B cold -> 17 534 786 B warm).
  3. [Medium] one_build serializing concurrent waiters when the holder won't store into runtime.plib (pipeline_library.rs): Active::store_runtime now returns bool (true iff usable in runtime.library), with_name and store_runtime notify FLIGHTS.mark_stored / FLIGHTS.mark_not_stored, and OneBuildGuard::drop marks a flight unshared if it finishes without a library hit or successful store (dropped_rect_gs, hr < 0, unreadable blob, UnusableExisting, TransientError, or over-cap). All waiting threads wake immediately with flight: None and build in parallel instead of serializing one after another, while a subsequent successful store clears the unstorable mark. Covered by one_build_wakes_waiters_in_parallel_when_holder_does_not_store.
  4. [Medium] Two-pass mesh_pso stored before compute pass succeeds (real.rs, pipeline_library.rs): finish_two_pass now releases mesh_one_build early via OneBuild::release_deferred() (waking mesh waiters without marking unstorable while GRAPHICS_BLOBS already holds the mesh blob in RAM) and drops slot before compute one_build, while deferring pipeline_library::store(mesh_name, &mesh_pso) until after the compute pass succeeds (hc >= 0 && !compute.is_null()), keeping prepared and runtime libraries paired.

Re-verification on c301772a11027c141c797184f7f9a5168f7311d3 (RTX 5070 Ti, driver 610.74, Ryzen 9 9950X, Windows 11 Build 26200, rustc 1.99.0, DXC 1.9.2609.5):

  • cargo build --release -p xcl: ok, 39 warnings (matches main 5eaadb54c baseline).
  • .\scripts\test.ps1: 2999 passed, 0 failed, 52 ignored, 24 SKIPPED (22 no wave64, 2 no heap windows).
  • Isolated 60 s smoke on retail title (ea3b5e4d, fresh XCL_DATA_ROOT + XCL_DXIL_CACHE, <game>\.xcl unchanged):
    • Cold: 1418 frames (50 54 53), 15645 MB peak commit, 0 device removals, 0 crashes, exit: 0x0; wrote 16.1 MB (16 124 048 B) runtime.plib + matching runtime.stamp (3 934 graphics + 205 compute = 4 139 pipelines).
    • Warm repeat: 1653 frames (60 60 60), 14668 MB peak commit, 0 device removals, 0 crashes, exit: 0x0; served 3 932 graphics + 195 compute (4 127 total, 0 ms bind waits) from runtime.plib, updating runtime.plib and runtime.stamp to 17 534 786 B.
  • Not tested: incremental preparation of a staged corpus on a retail title after a translator change, 16 heap windows, AMD wave64, and devices without pipeline-library support.
  • AI use: Antigravity (Gemini 4 Neon) implemented these review fixes, added the unit tests, ran the build/test/smoke verification, and wrote this reply.

@github-actions github-actions Bot removed the needs-1st-check Passes gates; needs first independent merge-check (#3041) label Dec 2, 2026
@Kalmarv Kalmarv closed this Dec 2, 2026
@Kalmarv Kalmarv reopened this Dec 2, 2026
@github-actions github-actions Bot added the needs-1st-check Passes gates; needs first independent merge-check (#3041) label Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:d3d12 D3D12.X runtime, command lists, resources, sparse memory area:docs-ci Documentation, scripts, workflows, repo governance area:recompiler RDNA2 decoder, HLSL/direct-DXIL recompiler, wave64/wave32 area:shaders Shader cache, PSO compilation, pipeline libraries, precompilation gpu:nvidia Code is specific to NVIDIA / wave32 GPUs (scope tag; see needs:nvidia-test) needs-1st-check Passes gates; needs first independent merge-check (#3041)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants