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

Open
Kalmarv wants to merge 1 commit from upstream-pr/3633 into main
Kalmarv commented 2026-12-02 02:30:52 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T02:30:52Z.


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, with independent graphics/compute freshness. Prepared libraries from a staged .xcl\pso-corpus live under <game>\.xcl\pipeline-libraries\<windows>\ (4, 8, 16-heap, ...), so layouts coexist; layout_name strips both HEAP_WINDOWS and HEAP_FLAT so 16 | HEAP_WINDOWS | HEAP_FLAT stays 16-heap rather than 528-heap. The receipt (v4) keys on the driver and tracks graphics_prepared and compute_prepared separately, with semantic settings split into graphics-only (XCL_DEBUG_LOD0, XCL_DEBUG_MAGENTA, XCL_DEBUG_NO_CULL, XCL_DEBUG_NO_STENCIL, XCL_DEBUG_PS_EXPR, XCL_DEBUG_PS_SUB, XCL_PIXEL), compute-only (XCL_DEBUG_CS_SUB, XCL_DIRECT_SPLIT_INSTRUCTIONS, XCL_HEAP_FLAT, XCL_HW_RT_TRAVERSE, XCL_PER_LANE, XCL_PER_LANE_MAX_INSTS), and shared switches. Corpus, translation, settings, and layout changes only mark the affected stage(s) stale: preparation skips any stage already current on disk (leaving its .plib untouched) and only rebuilds stale/absent stages (importing unchanged names from the previous library, falling back once to legacy .xcl\pso-corpus\{compute,graphics}.plib on first upgrade). xcl cache status reports per-stage state. 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 (including HEAP_FLAT for compute when XCL_HEAP_FLAT=1, while passing the stripped window count to the graphics worker). 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_stages) 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, XCL_PER_LANE_MAX_INSTS, and XCL_HW_RT_TRAVERSE 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 (3 240 insertions / 509 deletions including ~1 300 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 (layout_name strips HEAP_WINDOWS | HEAP_FLAT; window_count helper; runtime_windows delegates to recomp::pso::windows_for), legacy .xcl/pso-corpus/*.plib fallback import (previous_library), per-title data_dir path for runtime.plib, v4 receipt with independent graphics_prepared / compute_prepared (and deterministic content-derived fallback identity when a staged corpus has no identity file), StageState / CurrentStages / current_stages / publish_stages preserving untouched current .plib files, Library::{Current, Stale, Absent}, capped runtime reads in inspect/publish_stages, metadata-only per-stage status
  • crates/xcl/src/shaders/pso_corpus.rs: prepare staged recipes for the runtime layout into its library folder, skipping already-current graphics or compute stages in 0 s via warm_library::current_stages, passing stripped window_count(windows) to the graphics worker and warm_library::previous_library on first upgrade, and publishing only rebuilt stages via warm_library::publish_stages
  • 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, graphics/compute/shared split in semantic_pipeline_setting (warm_graphics_settings_key, warm_compute_settings_key, warm_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 5894838c8: 3002 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: each_memory_layout_has_its_own_folder (asserting layout_name(16 | HEAP_WINDOWS | HEAP_FLAT) == "16-heap" and window_count == 16); warm_settings_separate_graphics_and_compute_flags; stage_freshness_tracks_graphics_and_compute_settings_independently; skipping_current_stage_preserves_untouched_library_file; 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 24.8 MB (24 811 070 B) runtime.plib + per-build runtime.stamp (24 811 070 B attributed to current build; 3 903 graphics + 280 compute = 4 183 pipelines) under <XCL_DATA_ROOT>\<title>\pipeline-libraries\4\ with <game>\.xcl unchanged; warm repeat in the same isolated data folder served 3 903 graphics + 98 compute (4 001 total, 0 ms bind waits) from runtime.plib, updated runtime.plib and runtime.stamp to 24 953 778 B, with 1 705 frames shown (60 61 60), 15 093 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: 5894838c8b5897d7243048eab1987159eea246c6
gpu: NVIDIA GeForce RTX 5070 Ti
title: ea3b5e4d
seconds: 60
exit: 0x0
frames shown: 1703 (PresentX 1703)
presents per 2 s (last 3): 60 61 60
device removals: 0
crashes: 0
peak commit: 15884 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).
  • End-to-end staged-corpus preparation under 16 heap windows with XCL_HEAP_FLAT=1 on a full retail corpus (stage skipping, layout_name stripping HEAP_FLAT, and graphics/compute setting isolation are covered by unit tests; 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 and fixed the 16-heap HEAP_FLAT layout-naming / per-stage cache-busting bug (v4 receipt with independent graphics/compute freshness, graphics/compute semantic settings split, 0 s stage skipping in prepare_corpus, per-stage xcl cache status, layout_name stripping HEAP_WINDOWS | HEAP_FLAT, per-title data_dir storage, non-blocking flush_lock + fallible try_reserve_exact NativeLibrary::serialize + bounded 5 s shutdown flush + stale temp cleanup + persistent error stop, adoption-aware read_pso_cached_blob, non-fatal activation driver mismatch fallback, explicit dropped_rect_gs flag, 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), added unit tests, ran the full test suite and isolated smoke pair on the hardware named, and updated this description.
<!-- greyfinch-sync:ivall/xcl:issue:5598628201 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T02:30:52Z. --- 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, with independent graphics/compute freshness.** Prepared libraries from a staged `.xcl\pso-corpus` live under `<game>\.xcl\pipeline-libraries\<windows>\` (`4`, `8`, `16-heap`, ...), so layouts coexist; `layout_name` strips both `HEAP_WINDOWS` and `HEAP_FLAT` so `16 | HEAP_WINDOWS | HEAP_FLAT` stays `16-heap` rather than `528-heap`. The receipt (v4) keys on the driver and tracks `graphics_prepared` and `compute_prepared` separately, with semantic settings split into graphics-only (`XCL_DEBUG_LOD0`, `XCL_DEBUG_MAGENTA`, `XCL_DEBUG_NO_CULL`, `XCL_DEBUG_NO_STENCIL`, `XCL_DEBUG_PS_EXPR`, `XCL_DEBUG_PS_SUB`, `XCL_PIXEL`), compute-only (`XCL_DEBUG_CS_SUB`, `XCL_DIRECT_SPLIT_INSTRUCTIONS`, `XCL_HEAP_FLAT`, `XCL_HW_RT_TRAVERSE`, `XCL_PER_LANE`, `XCL_PER_LANE_MAX_INSTS`), and shared switches. Corpus, translation, settings, and layout changes only mark the affected stage(s) *stale*: preparation skips any stage already current on disk (leaving its `.plib` untouched) and only rebuilds stale/absent stages (importing unchanged names from the previous library, falling back once to legacy `.xcl\pso-corpus\{compute,graphics}.plib` on first upgrade). `xcl cache status` reports per-stage state. 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 (including `HEAP_FLAT` for compute when `XCL_HEAP_FLAT=1`, while passing the stripped window count to the graphics worker). `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_stages`) 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`, `XCL_PER_LANE_MAX_INSTS`, and `XCL_HW_RT_TRAVERSE` 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 (3 240 insertions / 509 deletions including ~1 300 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 (`layout_name` strips `HEAP_WINDOWS | HEAP_FLAT`; `window_count` helper; `runtime_windows` delegates to `recomp::pso::windows_for`), legacy `.xcl/pso-corpus/*.plib` fallback import (`previous_library`), per-title `data_dir` path for `runtime.plib`, v4 receipt with independent `graphics_prepared` / `compute_prepared` (and deterministic content-derived fallback identity when a staged corpus has no `identity` file), `StageState` / `CurrentStages` / `current_stages` / `publish_stages` preserving untouched current `.plib` files, `Library::{Current, Stale, Absent}`, capped runtime reads in `inspect`/`publish_stages`, metadata-only per-stage `status` - `crates/xcl/src/shaders/pso_corpus.rs`: prepare staged recipes for the runtime layout into its library folder, skipping already-current graphics or compute stages in 0 s via `warm_library::current_stages`, passing stripped `window_count(windows)` to the graphics worker and `warm_library::previous_library` on first upgrade, and publishing only rebuilt stages via `warm_library::publish_stages` - `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`, graphics/compute/shared split in `semantic_pipeline_setting` (`warm_graphics_settings_key`, `warm_compute_settings_key`, `warm_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 `5894838c8`: 3002 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: `each_memory_layout_has_its_own_folder` (asserting `layout_name(16 | HEAP_WINDOWS | HEAP_FLAT) == "16-heap"` and `window_count == 16`); `warm_settings_separate_graphics_and_compute_flags`; `stage_freshness_tracks_graphics_and_compute_settings_independently`; `skipping_current_stage_preserves_untouched_library_file`; `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 `24.8 MB` (`24 811 070` B) `runtime.plib` + per-build `runtime.stamp` (`24 811 070` B attributed to current build; `3 903` graphics + `280` compute = `4 183` pipelines) under `<XCL_DATA_ROOT>\<title>\pipeline-libraries\4\` with `<game>\.xcl` unchanged; warm repeat in the same isolated data folder served `3 903` graphics + `98` compute (`4 001` total, `0 ms` bind waits) from `runtime.plib`, updated `runtime.plib` and `runtime.stamp` to `24 953 778` B, with `1 705` frames shown (`60 61 60`), `15 093 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: 5894838c8b5897d7243048eab1987159eea246c6 gpu: NVIDIA GeForce RTX 5070 Ti title: ea3b5e4d seconds: 60 exit: 0x0 frames shown: 1703 (PresentX 1703) presents per 2 s (last 3): 60 61 60 device removals: 0 crashes: 0 peak commit: 15884 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`). - End-to-end staged-corpus preparation under 16 heap windows with `XCL_HEAP_FLAT=1` on a full retail corpus (stage skipping, `layout_name` stripping `HEAP_FLAT`, and graphics/compute setting isolation are covered by unit tests; 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 and fixed the 16-heap `HEAP_FLAT` layout-naming / per-stage cache-busting bug (v4 receipt with independent graphics/compute freshness, graphics/compute semantic settings split, 0 s stage skipping in `prepare_corpus`, per-stage `xcl cache status`, `layout_name` stripping `HEAP_WINDOWS | HEAP_FLAT`, per-title `data_dir` storage, non-blocking `flush_lock` + fallible `try_reserve_exact` `NativeLibrary::serialize` + bounded 5 s shutdown flush + stale temp cleanup + persistent error stop, adoption-aware `read_pso_cached_blob`, non-fatal activation driver mismatch fallback, explicit `dropped_rect_gs` flag, 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`), added unit tests, ran the full test suite and isolated smoke pair on the hardware named, and updated this description.
Decodere commented 2026-12-02 08:40:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Decodere on 2026-12-02T08:40:05Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7339760757 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7339760757). Originally posted by [Decodere](https://github.com/Decodere) on 2026-12-02T08:40:05Z. --- 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 commented 2026-12-02 08:58:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Gevroska on 2026-12-02T08:58:00Z.


merge-check
base: 1c8b551475
head: 05c33e918b
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.

<!-- greyfinch-sync:ivall/xcl:comment:7340173662 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7340173662). Originally posted by [Gevroska](https://github.com/Gevroska) on 2026-12-02T08:58:00Z. --- merge-check base: 1c8b551475e1e7bfe48f94448492a4c3544a2e0f head: 05c33e918be5a8caeb857f135de449e01f67b483 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.
Foniass commented 2026-12-02 08:58:59 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T08:58:59Z.


Review (head 05c33e91, 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.

<!-- greyfinch-sync:ivall/xcl:comment:7340197023 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7340197023). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T08:58:59Z. --- Review (head 05c33e91, 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 commented 2026-12-02 10:40:57 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T10:40:57Z.


merge-check
base: 1c8b551475
head: 05c33e918b
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 https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7340197023 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 1c8b5514 vs this merge (05c33e91): 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.

<!-- greyfinch-sync:ivall/xcl:comment:7342827398 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7342827398). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T10:40:57Z. --- merge-check base: 1c8b551475e1e7bfe48f94448492a4c3544a2e0f head: 05c33e918be5a8caeb857f135de449e01f67b483 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 https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7340197023 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 1c8b5514 vs this merge (05c33e91): 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.
Kalmarv commented 2026-12-02 14:29:05 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T14:29:05Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7348619915 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7348619915). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T14:29:05Z. --- 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.
Gevroska commented 2026-12-02 15:26:37 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Gevroska on 2026-12-02T15:26:37Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7350332391 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7350332391). Originally posted by [Gevroska](https://github.com/Gevroska) on 2026-12-02T15:26:37Z. --- 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](https://github.com/xcl-dev/xcl/blob/034e7146aa0962051035c9e1bbe2c258123b75f1/crates/xcl/src/shaders/pipeline_library.rs#L103-L145) · [Inspection and status](https://github.com/xcl-dev/xcl/blob/034e7146aa0962051035c9e1bbe2c258123b75f1/crates/xcl/src/shaders/warm_library.rs#L123-L181) · [Publication](https://github.com/xcl-dev/xcl/blob/034e7146aa0962051035c9e1bbe2c258123b75f1/crates/xcl/src/shaders/warm_library.rs#L224-L230) 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 commented 2026-12-02 16:02:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T16:02:51Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7351356673 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7351356673). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T16:02:51Z. --- 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.
throny commented 2026-12-02 16:19:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by throny on 2026-12-02T16:19:27Z.


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.
<!-- greyfinch-sync:ivall/xcl:comment:7351773245 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7351773245). Originally posted by [throny](https://github.com/throny) on 2026-12-02T16:19:27Z. --- 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 commented 2026-12-02 16:44:15 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Gevroska on 2026-12-02T16:44:15Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7352382779 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7352382779). Originally posted by [Gevroska](https://github.com/Gevroska) on 2026-12-02T16:44:15Z. --- 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 commented 2026-12-02 16:50:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T16:50:28Z.


Thank you for catching that, @throny — pushed d9979794c with both fixes (keeping @Gevroska's capped reader and metadata-only status intact):

  1. Default XCL_RUNTIME_LIBRARY_MB raised from 1024 MiB to 2048 MiB so longer world runs (~1.12 GB at 900 s) fit comfortably while remaining bounded.
  2. Store- and flush-side cap enforcement (no self-discard on next launch):
    • Runtime now tracks its configured cap and a latched full flag. Once within 16 MiB of cap, store_runtime serializes additions under store_lock.write() and checks GetSerializedSize() + estimated_store_bytes(name, pipeline) <= cap; when full, it latches full and stops adding further pipelines so the in-memory library stays <= cap and flushes cleanly.
    • flush_runtime_on also checks GetSerializedSize() <= cap before serializing and bytes.len() <= cap before calling write_atomic, so an over-cap snapshot can never overwrite an existing valid <= cap runtime.plib on disk.
    • Lowering XCL_RUNTIME_LIBRARY_MB below an existing on-disk file still rejects it on load via read_runtime_file as before.
  3. Tests & verification (d9979794c, RTX 5070 Ti, DXC 1.9.2609.5):
    • Added store_and_flush_enforce_cap_and_preserve_reloadable_library verifying store stops at cap, flushes <= cap, reloads cleanly on next startup at the same cap, still rejects when the cap is lowered, and flush_runtime_on never overwrites an existing <= cap file with an over-cap library.
    • cargo build --release -p xcl: ok, 39 warnings (matches main 5eaadb54c).
    • .\scripts\test.ps1: 2984 passed, 0 failed, 52 ignored, 24 SKIPPED (22 no wave64, 2 no heap windows).
    • Fresh isolated 60 s smoke on d9979794c updated in the PR description (1652 -> 1707 frames, 15609 -> 16214 MB peak commit, 0 device removals, 0 crashes, <game>\.xcl unchanged), plus a warm repeat confirming 2 133 runtime-library hits (0 compute pipelines rebuilt) and 15 324 MB peak commit.

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

<!-- greyfinch-sync:ivall/xcl:comment:7352532936 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7352532936). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T16:50:28Z. --- Thank you for catching that, @throny — pushed `d9979794c` with both fixes (keeping @Gevroska's capped reader and metadata-only `status` intact): 1. **Default `XCL_RUNTIME_LIBRARY_MB` raised from `1024` MiB to `2048` MiB** so longer world runs (~1.12 GB at 900 s) fit comfortably while remaining bounded. 2. **Store- and flush-side cap enforcement (no self-discard on next launch):** - `Runtime` now tracks its configured `cap` and a latched `full` flag. Once within 16 MiB of `cap`, `store_runtime` serializes additions under `store_lock.write()` and checks `GetSerializedSize() + estimated_store_bytes(name, pipeline) <= cap`; when full, it latches `full` and stops adding further pipelines so the in-memory library stays `<= cap` and flushes cleanly. - `flush_runtime_on` also checks `GetSerializedSize() <= cap` before serializing and `bytes.len() <= cap` before calling `write_atomic`, so an over-cap snapshot can never overwrite an existing valid `<= cap` `runtime.plib` on disk. - Lowering `XCL_RUNTIME_LIBRARY_MB` below an existing on-disk file still rejects it on load via `read_runtime_file` as before. 3. **Tests & verification (`d9979794c`, RTX 5070 Ti, DXC 1.9.2609.5):** - Added `store_and_flush_enforce_cap_and_preserve_reloadable_library` verifying store stops at cap, flushes `<= cap`, reloads cleanly on next startup at the same cap, still rejects when the cap is lowered, and `flush_runtime_on` never overwrites an existing `<= cap` file with an over-cap library. - `cargo build --release -p xcl`: ok, 39 warnings (matches `main` `5eaadb54c`). - `.\scripts\test.ps1`: `2984 passed, 0 failed, 52 ignored, 24 SKIPPED` (22 `no wave64`, 2 `no heap windows`). - Fresh isolated 60 s smoke on `d9979794c` updated in the PR description (`1652 -> 1707` frames, `15609 -> 16214` MB peak commit, 0 device removals, 0 crashes, `<game>\.xcl` unchanged), plus a warm repeat confirming 2 133 runtime-library hits (0 compute pipelines rebuilt) and 15 324 MB peak commit. AI use: Antigravity (Gemini 4 Neon) implemented these fixes, ran the suite and smoke runs, and drafted this reply.
bmjask commented 2026-12-02 16:53:45 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T16:53:45Z.

Review: COMMENTED


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.

<!-- greyfinch-sync:ivall/xcl:review:6155295007 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#pullrequestreview-6155295007). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T16:53:45Z. **Review:** COMMENTED --- 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:** 5. **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._
bmjask commented 2026-12-02 16:53:45 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T16:53:45Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 314

@@ -20,39 +20,521 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let full = library.serialized_size() >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        full: full.into(),
+    })
+}
+
 pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
     let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
         .ok_or("Pipeline library: runtime driver identity is unavailable")?;
     if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
+    start_counting();
+    if !NativeLibrary::supported(device) {
+        crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+        return Ok(());
+    }
     let open = |bytes| NativeLibrary::open_shared(device, bytes);
     let graphics = ready.graphics.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
     let compute = ready.compute.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
-    }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() {
         crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                since += 1;
+                if since >= flush_every() {
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {
+        runtime.mark_full(current);
+        state.disabled = true;
+        crate::xlog_warn!(
+            "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",
+            runtime.path.display(), current, runtime.cap
+        );
+        return false;
+    }
+    let bytes = match serialize_runtime(runtime) {
+        Ok(b) => b,
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display());
+            }
+            return false;
+        }
+    };
+    if bytes.len() as u64 > runtime.cap {
+        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",

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773074461 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773074461). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T16:53:45Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 314 ~~~~diff @@ -20,39 +20,521 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let full = library.serialized_size() >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + full: full.into(), + }) +} + pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) .ok_or("Pipeline library: runtime driver identity is unavailable")?; if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } + start_counting(); + if !NativeLibrary::supported(device) { + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + return Ok(()); + } let open = |bytes| NativeLibrary::open_shared(device, bytes); let graphics = ready.graphics.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; let compute = ready.compute.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; - } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() { crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + since += 1; + if since >= flush_every() { + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { + runtime.mark_full(current); + state.disabled = true; + crate::xlog_warn!( + "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library", + runtime.path.display(), current, runtime.cap + ); + return false; + } + let bytes = match serialize_runtime(runtime) { + Ok(b) => b, + Err(e) => { + state.consecutive_failures += 1; + if state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display()); + } + return false; + } + }; + if bytes.len() as u64 > runtime.cap { + 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", ~~~~ --- **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.
bmjask commented 2026-12-02 16:53:45 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T16:53:45Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 198

@@ -20,39 +20,521 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let full = library.serialized_size() >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        full: full.into(),
+    })
+}
+
 pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    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;

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773074472 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773074472). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T16:53:45Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 198 ~~~~diff @@ -20,39 +20,521 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let full = library.serialized_size() >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + full: full.into(), + }) +} + pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - 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; ~~~~ --- **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.
bmjask commented 2026-12-02 16:53:45 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T16:53:45Z.

Code review location: crates/xcl/src/shaders/warm_library.rs; line 97

@@ -8,245 +21,193 @@ use std::path::{Path, PathBuf};
 use std::sync::{Arc, Mutex};
 use windows::Win32::Graphics::Direct3D12::ID3D12Device;
 
-const VERSION: u32 = 2;
-const RECEIPT: &str = "pipeline-libraries-v2.json";
-const LEGACY_RECEIPT: &str = "pipeline-libraries-v1.json";
+const VERSION: u32 = 3;
+const RECEIPT: &str = "receipt.json";
 const GRAPHICS: &str = "graphics.plib";
 const COMPUTE: &str = "compute.plib";
+pub(crate) const RUNTIME: &str = "runtime.plib";
 
+/// What the prepared libraries were built from. A difference makes them stale, not invalid.
 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
-struct Compatibility {
+struct Prepared {
+    corpus: [u8; 32],
     layout: u64,
     translation: u64,
     settings: u64,
-    windows: u32,
-    driver: u64,
 }
 
 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
 struct Receipt {
     version: u32,
-    corpus: [u8; 32],
-    graphics: Option<Component>,
-    compute: Option<Component>,
-}
-
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
-struct Component {
-    compatibility: Compatibility,
-    bytes: u64,
-}
-
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
-struct LegacySemantic {
-    version: u32,
-    corpus: [u8; 32],
-    layout: u64,
-    translation: u64,
-    settings: u64,
-    windows: u32,
     driver: u64,
+    windows: u32,
+    prepared: Prepared,
+    graphics: Option<u64>,
+    compute: Option<u64>,
 }
 
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
-struct LegacyReceipt {
-    semantic: LegacySemantic,
-    graphics_bytes: Option<u64>,
-    compute_bytes: Option<u64>,
-}
-
-#[allow(dead_code)] // Consumed by the stacked lazy runtime integration.
 pub(crate) struct Ready {
     pub(crate) graphics: Option<Arc<[u8]>>,
     pub(crate) compute: Option<Arc<[u8]>>,
+    pub(crate) runtime: Option<Arc<[u8]>>,
+    pub(crate) runtime_path: PathBuf,
     pub(crate) driver: u64,
-    pub(crate) migration: Option<(PathBuf, Vec<u8>)>,
+}
+
+/// The state of the prepared libraries at launch.
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) enum Library {
+    /// Prepared from the current corpus, translation and settings.
+    Current,
+    /// Usable, but prepared from something else (the reason): preparation builds what changed.
+    Stale(String),
+    /// None for this driver and memory layout (the reason): preparation builds them.
+    Absent(String),
 }
 
 static READY: Mutex<Option<Ready>> = Mutex::new(None);
 
-#[allow(dead_code)] // Consumed by the stacked lazy runtime integration.
 pub(crate) fn take_ready() -> Option<Ready> { READY.lock().unwrap().take() }
 
-fn compatibility(windows: u32, driver: u64) -> Compatibility {
-    Compatibility {
-        layout: u64::from_str_radix(env!("XCL_PIPELINE_LAYOUT_ID"), 16).expect("pipeline layout id"),
-        translation: crate::gpu::recomp::pso::translation_cache_identity(),
-        settings: super::warm_settings_key(),
-        windows,
-        driver,
-    }
+/// The title's memory windows as the caches encode them (`HEAP_WINDOWS` for heap windows).
+pub(crate) fn runtime_windows() -> u32 {
+    let mut windows = crate::gpu::uma::configured_runtime_windows() as u32;
+    if windows > 1 && crate::gpu::recomp::pso::heap_windows() { windows |= crate::gpu::recomp::HEAP_WINDOWS; }
+    windows
 }
 
-fn expected(corpus: &Corpus, device: &ID3D12Device) -> Option<([u8; 32], Compatibility)> {
-    Some((
-        corpus.identity()?,
-        compatibility(corpus.windows(), crate::hle::d3d12x::real::preparation_driver_identity(device)?),
-    ))
+fn layout_name(windows: u32) -> String {
+    let count = windows & !crate::gpu::recomp::HEAP_WINDOWS;
+    let heap = if windows & crate::gpu::recomp::HEAP_WINDOWS != 0 { "-heap" } else { "" };
+    format!("{count}{heap}")
 }
 
-fn expected_for_adapter(corpus: &Corpus, adapter: &str) -> Option<([u8; 32], Compatibility)> {
-    Some((
-        corpus.identity()?,
-        compatibility(corpus.windows(), crate::hle::d3d12x::real::preparation_driver_identity_for_adapter(adapter)?),
-    ))
+/// `<title>/.xcl/pipeline-libraries/<windows>`: `4`, `8`, `16-heap`, … (4 and 16 windows coexist).
+pub(crate) fn directory(root: &Path, windows: u32) -> PathBuf {
+    root.join(".xcl").join("pipeline-libraries").join(layout_name(windows))
 }
 
-fn paths(dir: &Path) -> (PathBuf, PathBuf, PathBuf) {
-    (dir.join(GRAPHICS), dir.join(COMPUTE), dir.join(RECEIPT))
+/// `<data_dir>/pipeline-libraries/<windows>`: where `runtime.plib` lives (outside the game folder).
+pub(crate) fn runtime_directory(data_dir: &Path, windows: u32) -> PathBuf {
+    data_dir.join("pipeline-libraries").join(layout_name(windows))
 }
 
-fn read(dir: &Path) -> Option<(Receipt, bool)> {
-    let (_, _, path) = paths(dir);
-    if path.exists() {
-        return super::warm_replay::read_receipt::<Receipt>(&path)
-            .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(),

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773074477 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773074477). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T16:53:45Z. **Code review location:** `crates/xcl/src/shaders/warm_library.rs`; line 97 ~~~~diff @@ -8,245 +21,193 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use windows::Win32::Graphics::Direct3D12::ID3D12Device; -const VERSION: u32 = 2; -const RECEIPT: &str = "pipeline-libraries-v2.json"; -const LEGACY_RECEIPT: &str = "pipeline-libraries-v1.json"; +const VERSION: u32 = 3; +const RECEIPT: &str = "receipt.json"; const GRAPHICS: &str = "graphics.plib"; const COMPUTE: &str = "compute.plib"; +pub(crate) const RUNTIME: &str = "runtime.plib"; +/// What the prepared libraries were built from. A difference makes them stale, not invalid. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct Compatibility { +struct Prepared { + corpus: [u8; 32], layout: u64, translation: u64, settings: u64, - windows: u32, - driver: u64, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] struct Receipt { version: u32, - corpus: [u8; 32], - graphics: Option<Component>, - compute: Option<Component>, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct Component { - compatibility: Compatibility, - bytes: u64, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct LegacySemantic { - version: u32, - corpus: [u8; 32], - layout: u64, - translation: u64, - settings: u64, - windows: u32, driver: u64, + windows: u32, + prepared: Prepared, + graphics: Option<u64>, + compute: Option<u64>, } -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct LegacyReceipt { - semantic: LegacySemantic, - graphics_bytes: Option<u64>, - compute_bytes: Option<u64>, -} - -#[allow(dead_code)] // Consumed by the stacked lazy runtime integration. pub(crate) struct Ready { pub(crate) graphics: Option<Arc<[u8]>>, pub(crate) compute: Option<Arc<[u8]>>, + pub(crate) runtime: Option<Arc<[u8]>>, + pub(crate) runtime_path: PathBuf, pub(crate) driver: u64, - pub(crate) migration: Option<(PathBuf, Vec<u8>)>, +} + +/// The state of the prepared libraries at launch. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Library { + /// Prepared from the current corpus, translation and settings. + Current, + /// Usable, but prepared from something else (the reason): preparation builds what changed. + Stale(String), + /// None for this driver and memory layout (the reason): preparation builds them. + Absent(String), } static READY: Mutex<Option<Ready>> = Mutex::new(None); -#[allow(dead_code)] // Consumed by the stacked lazy runtime integration. pub(crate) fn take_ready() -> Option<Ready> { READY.lock().unwrap().take() } -fn compatibility(windows: u32, driver: u64) -> Compatibility { - Compatibility { - layout: u64::from_str_radix(env!("XCL_PIPELINE_LAYOUT_ID"), 16).expect("pipeline layout id"), - translation: crate::gpu::recomp::pso::translation_cache_identity(), - settings: super::warm_settings_key(), - windows, - driver, - } +/// The title's memory windows as the caches encode them (`HEAP_WINDOWS` for heap windows). +pub(crate) fn runtime_windows() -> u32 { + let mut windows = crate::gpu::uma::configured_runtime_windows() as u32; + if windows > 1 && crate::gpu::recomp::pso::heap_windows() { windows |= crate::gpu::recomp::HEAP_WINDOWS; } + windows } -fn expected(corpus: &Corpus, device: &ID3D12Device) -> Option<([u8; 32], Compatibility)> { - Some(( - corpus.identity()?, - compatibility(corpus.windows(), crate::hle::d3d12x::real::preparation_driver_identity(device)?), - )) +fn layout_name(windows: u32) -> String { + let count = windows & !crate::gpu::recomp::HEAP_WINDOWS; + let heap = if windows & crate::gpu::recomp::HEAP_WINDOWS != 0 { "-heap" } else { "" }; + format!("{count}{heap}") } -fn expected_for_adapter(corpus: &Corpus, adapter: &str) -> Option<([u8; 32], Compatibility)> { - Some(( - corpus.identity()?, - compatibility(corpus.windows(), crate::hle::d3d12x::real::preparation_driver_identity_for_adapter(adapter)?), - )) +/// `<title>/.xcl/pipeline-libraries/<windows>`: `4`, `8`, `16-heap`, … (4 and 16 windows coexist). +pub(crate) fn directory(root: &Path, windows: u32) -> PathBuf { + root.join(".xcl").join("pipeline-libraries").join(layout_name(windows)) } -fn paths(dir: &Path) -> (PathBuf, PathBuf, PathBuf) { - (dir.join(GRAPHICS), dir.join(COMPUTE), dir.join(RECEIPT)) +/// `<data_dir>/pipeline-libraries/<windows>`: where `runtime.plib` lives (outside the game folder). +pub(crate) fn runtime_directory(data_dir: &Path, windows: u32) -> PathBuf { + data_dir.join("pipeline-libraries").join(layout_name(windows)) } -fn read(dir: &Path) -> Option<(Receipt, bool)> { - let (_, _, path) = paths(dir); - if path.exists() { - return super::warm_replay::read_receipt::<Receipt>(&path) - .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(), ~~~~ --- **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.
bmjask commented 2026-12-02 16:53:45 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T16:53:45Z.

Code review location: crates/xcl/src/hle/d3d12x/real.rs; line 9627

@@ -9576,12 +9621,18 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu:
     // Reuse the compiled driver blob of the compute pass across all `(MS/GS, PS)` pipelines that
     // share `tp.cs` (in memory and on disk), matching `translated_compute_pso_once`.
     let ckey = compute_blob_key_for(&tp.cs, rs as usize, 0, node_mask);
-    let library_compute = crate::shaders::pipeline_library::load_compute(
-        &driver_cache::name_for_root_node(&tp.cs, 0, false, &tp.samplers, node_mask),
-        &cdesc,
-    );
+    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));

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773074485 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773074485). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T16:53:45Z. **Code review location:** `crates/xcl/src/hle/d3d12x/real.rs`; line 9627 ~~~~diff @@ -9576,12 +9621,18 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: // Reuse the compiled driver blob of the compute pass across all `(MS/GS, PS)` pipelines that // share `tp.cs` (in memory and on disk), matching `translated_compute_pso_once`. let ckey = compute_blob_key_for(&tp.cs, rs as usize, 0, node_mask); - let library_compute = crate::shaders::pipeline_library::load_compute( - &driver_cache::name_for_root_node(&tp.cs, 0, false, &tp.samplers, node_mask), - &cdesc, - ); + 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)); ~~~~ --- **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.
bmjask commented 2026-12-02 16:53:45 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T16:53:45Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 359

@@ -20,39 +20,521 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let full = library.serialized_size() >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        full: full.into(),
+    })
+}
+
 pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
     let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
         .ok_or("Pipeline library: runtime driver identity is unavailable")?;
     if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
+    start_counting();
+    if !NativeLibrary::supported(device) {
+        crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+        return Ok(());
+    }
     let open = |bytes| NativeLibrary::open_shared(device, bytes);
     let graphics = ready.graphics.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
     let compute = ready.compute.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
-    }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() {
         crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                since += 1;
+                if since >= flush_every() {
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {
+        runtime.mark_full(current);
+        state.disabled = true;
+        crate::xlog_warn!(
+            "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",
+            runtime.path.display(), current, runtime.cap
+        );
+        return false;
+    }
+    let bytes = match serialize_runtime(runtime) {
+        Ok(b) => b,
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display());
+            }
+            return false;
+        }
+    };
+    if bytes.len() as u64 > runtime.cap {
+        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",
+            runtime.path.display(), bytes.len(), runtime.cap
+        );
+        return false;
+    }
+    match write(&runtime.path, &bytes) {
+        Ok(()) => {
+            state.consecutive_failures = 0;
+            runtime.size.store(bytes.len() as u64, Ordering::Relaxed);
+            crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})",
+                bytes.len(), runtime.path.display());
+            true
+        }
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display());
+            }
+            false
+        }
+    }
+}
+
+/// Writes `runtime.plib` again when pipelines were added to it since it was last written.
+pub(crate) fn flush_runtime() {
+    let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return };
+    flush_runtime_on(runtime, write_atomic);
+}
+
+fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = unsafe { pipeline.GetCachedBlob().ok()? };
+    Some(unsafe { blob.GetBufferSize() } as u64)
+}
+
+fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = cached_blob_size(pipeline)?;
+    let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2);
+    Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD))
+}
+
+impl Runtime {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773074493 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773074493). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T16:53:45Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 359 ~~~~diff @@ -20,39 +20,521 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let full = library.serialized_size() >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + full: full.into(), + }) +} + pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) .ok_or("Pipeline library: runtime driver identity is unavailable")?; if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } + start_counting(); + if !NativeLibrary::supported(device) { + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + return Ok(()); + } let open = |bytes| NativeLibrary::open_shared(device, bytes); let graphics = ready.graphics.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; let compute = ready.compute.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; - } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() { crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + since += 1; + if since >= flush_every() { + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { + runtime.mark_full(current); + state.disabled = true; + crate::xlog_warn!( + "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library", + runtime.path.display(), current, runtime.cap + ); + return false; + } + let bytes = match serialize_runtime(runtime) { + Ok(b) => b, + Err(e) => { + state.consecutive_failures += 1; + if state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display()); + } + return false; + } + }; + if bytes.len() as u64 > runtime.cap { + 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", + runtime.path.display(), bytes.len(), runtime.cap + ); + return false; + } + match write(&runtime.path, &bytes) { + Ok(()) => { + state.consecutive_failures = 0; + runtime.size.store(bytes.len() as u64, Ordering::Relaxed); + crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})", + bytes.len(), runtime.path.display()); + true + } + Err(e) => { + state.consecutive_failures += 1; + if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display()); + } + false + } + } +} + +/// Writes `runtime.plib` again when pipelines were added to it since it was last written. +pub(crate) fn flush_runtime() { + let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return }; + flush_runtime_on(runtime, write_atomic); +} + +fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = unsafe { pipeline.GetCachedBlob().ok()? }; + Some(unsafe { blob.GetBufferSize() } as u64) +} + +fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = cached_blob_size(pipeline)?; + let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2); + Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD)) +} + +impl Runtime { ~~~~ --- **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 commented 2026-12-02 16:53:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T16:53:48Z.


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

<!-- greyfinch-sync:ivall/xcl:comment:7352611601 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7352611601). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T16:53:48Z. --- @Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.
bmjask commented 2026-12-02 17:03:02 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:03:02Z.

Code review location: crates/xcl/src/hle/d3d12x/real.rs; line 4900

@@ -4896,6 +4896,8 @@ pub fn end_title(code: u32) -> ! {
         });
         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();

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773181297 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773181297). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:03:02Z. **Code review location:** `crates/xcl/src/hle/d3d12x/real.rs`; line 4900 ~~~~diff @@ -4896,6 +4896,8 @@ pub fn end_title(code: u32) -> ! { }); 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(); ~~~~ --- **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.
bmjask commented 2026-12-02 17:03:02 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:03:02Z.

Code review location: crates/xcl/src/hle/d3d12x/real.rs; line 6406

@@ -6383,16 +6402,25 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL
             dxil, copy.Flags.0, driver_cache::ChainRoot::DirectConstants, samplers, copy.NodeMask),
         _ => driver_cache::name_for_root_node(dxil, copy.Flags.0, false, samplers, copy.NodeMask),
     };
-    if !ppv.is_null() {
-        if let Some(pso) = crate::shaders::pipeline_library::load_compute(&library_name, &copy) {
-            *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())

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773181310 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773181310). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:03:02Z. **Code review location:** `crates/xcl/src/hle/d3d12x/real.rs`; line 6406 ~~~~diff @@ -6383,16 +6402,25 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL dxil, copy.Flags.0, driver_cache::ChainRoot::DirectConstants, samplers, copy.NodeMask), _ => driver_cache::name_for_root_node(dxil, copy.Flags.0, false, samplers, copy.NodeMask), }; - if !ppv.is_null() { - if let Some(pso) = crate::shaders::pipeline_library::load_compute(&library_name, &copy) { - *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()) ~~~~ --- **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.
bmjask commented 2026-12-02 17:03:02 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:03:02Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 388

@@ -20,39 +20,521 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let full = library.serialized_size() >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        full: full.into(),
+    })
+}
+
 pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
     let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
         .ok_or("Pipeline library: runtime driver identity is unavailable")?;
     if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
+    start_counting();
+    if !NativeLibrary::supported(device) {
+        crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+        return Ok(());
+    }
     let open = |bytes| NativeLibrary::open_shared(device, bytes);
     let graphics = ready.graphics.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
     let compute = ready.compute.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
-    }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() {
         crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                since += 1;
+                if since >= flush_every() {
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {
+        runtime.mark_full(current);
+        state.disabled = true;
+        crate::xlog_warn!(
+            "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",
+            runtime.path.display(), current, runtime.cap
+        );
+        return false;
+    }
+    let bytes = match serialize_runtime(runtime) {
+        Ok(b) => b,
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display());
+            }
+            return false;
+        }
+    };
+    if bytes.len() as u64 > runtime.cap {
+        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",
+            runtime.path.display(), bytes.len(), runtime.cap
+        );
+        return false;
+    }
+    match write(&runtime.path, &bytes) {
+        Ok(()) => {
+            state.consecutive_failures = 0;
+            runtime.size.store(bytes.len() as u64, Ordering::Relaxed);
+            crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})",
+                bytes.len(), runtime.path.display());
+            true
+        }
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display());
+            }
+            false
+        }
+    }
+}
+
+/// Writes `runtime.plib` again when pipelines were added to it since it was last written.
+pub(crate) fn flush_runtime() {
+    let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return };
+    flush_runtime_on(runtime, write_atomic);
+}
+
+fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = unsafe { pipeline.GetCachedBlob().ok()? };
+    Some(unsafe { blob.GetBufferSize() } as u64)
+}
+
+fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = cached_blob_size(pipeline)?;
+    let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2);
+    Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD))
+}
+
+impl Runtime {
+    fn mark_full(&self, bytes: u64) {
+        if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) {
+            crate::xlog_info!(
+                "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions",
+                self.path.display(), bytes, self.cap
+            );
+        }
+    }
+
+    fn can_store_locked(&self, name: &str, pipeline: &ID3D12PipelineState) -> bool {
+        if self.full.load(std::sync::atomic::Ordering::Acquire) { return false; }
+        let current = self.library.serialized_size();
+        if current >= self.cap {
+            self.mark_full(current);
+            return false;
+        }
+        let Some(est) = estimated_store_bytes(name, pipeline) else {
+            self.mark_full(current);
+            return false;
+        };
+        if current.saturating_add(est) > self.cap {
+            self.mark_full(current);
+            return false;
+        }
+        true
+    }
+}
+
+fn store_into_runtime(runtime: &Runtime, name: &str, pipeline: &ID3D12PipelineState) -> bool {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773181323 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773181323). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:03:02Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 388 ~~~~diff @@ -20,39 +20,521 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let full = library.serialized_size() >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + full: full.into(), + }) +} + pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) .ok_or("Pipeline library: runtime driver identity is unavailable")?; if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } + start_counting(); + if !NativeLibrary::supported(device) { + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + return Ok(()); + } let open = |bytes| NativeLibrary::open_shared(device, bytes); let graphics = ready.graphics.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; let compute = ready.compute.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; - } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() { crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + since += 1; + if since >= flush_every() { + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { + runtime.mark_full(current); + state.disabled = true; + crate::xlog_warn!( + "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library", + runtime.path.display(), current, runtime.cap + ); + return false; + } + let bytes = match serialize_runtime(runtime) { + Ok(b) => b, + Err(e) => { + state.consecutive_failures += 1; + if state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display()); + } + return false; + } + }; + if bytes.len() as u64 > runtime.cap { + 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", + runtime.path.display(), bytes.len(), runtime.cap + ); + return false; + } + match write(&runtime.path, &bytes) { + Ok(()) => { + state.consecutive_failures = 0; + runtime.size.store(bytes.len() as u64, Ordering::Relaxed); + crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})", + bytes.len(), runtime.path.display()); + true + } + Err(e) => { + state.consecutive_failures += 1; + if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display()); + } + false + } + } +} + +/// Writes `runtime.plib` again when pipelines were added to it since it was last written. +pub(crate) fn flush_runtime() { + let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return }; + flush_runtime_on(runtime, write_atomic); +} + +fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = unsafe { pipeline.GetCachedBlob().ok()? }; + Some(unsafe { blob.GetBufferSize() } as u64) +} + +fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = cached_blob_size(pipeline)?; + let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2); + Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD)) +} + +impl Runtime { + fn mark_full(&self, bytes: u64) { + if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) { + crate::xlog_info!( + "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions", + self.path.display(), bytes, self.cap + ); + } + } + + fn can_store_locked(&self, name: &str, pipeline: &ID3D12PipelineState) -> bool { + if self.full.load(std::sync::atomic::Ordering::Acquire) { return false; } + let current = self.library.serialized_size(); + if current >= self.cap { + self.mark_full(current); + return false; + } + let Some(est) = estimated_store_bytes(name, pipeline) else { + self.mark_full(current); + return false; + }; + if current.saturating_add(est) > self.cap { + self.mark_full(current); + return false; + } + true + } +} + +fn store_into_runtime(runtime: &Runtime, name: &str, pipeline: &ID3D12PipelineState) -> bool { ~~~~ --- **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.
bmjask commented 2026-12-02 17:03:02 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:03:02Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 446

@@ -20,39 +20,521 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let full = library.serialized_size() >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        full: full.into(),
+    })
+}
+
 pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
     let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
         .ok_or("Pipeline library: runtime driver identity is unavailable")?;
     if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
+    start_counting();
+    if !NativeLibrary::supported(device) {
+        crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+        return Ok(());
+    }
     let open = |bytes| NativeLibrary::open_shared(device, bytes);
     let graphics = ready.graphics.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
     let compute = ready.compute.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
-    }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() {
         crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                since += 1;
+                if since >= flush_every() {
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {
+        runtime.mark_full(current);
+        state.disabled = true;
+        crate::xlog_warn!(
+            "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",
+            runtime.path.display(), current, runtime.cap
+        );
+        return false;
+    }
+    let bytes = match serialize_runtime(runtime) {
+        Ok(b) => b,
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display());
+            }
+            return false;
+        }
+    };
+    if bytes.len() as u64 > runtime.cap {
+        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",
+            runtime.path.display(), bytes.len(), runtime.cap
+        );
+        return false;
+    }
+    match write(&runtime.path, &bytes) {
+        Ok(()) => {
+            state.consecutive_failures = 0;
+            runtime.size.store(bytes.len() as u64, Ordering::Relaxed);
+            crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})",
+                bytes.len(), runtime.path.display());
+            true
+        }
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display());
+            }
+            false
+        }
+    }
+}
+
+/// Writes `runtime.plib` again when pipelines were added to it since it was last written.
+pub(crate) fn flush_runtime() {
+    let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return };
+    flush_runtime_on(runtime, write_atomic);
+}
+
+fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = unsafe { pipeline.GetCachedBlob().ok()? };
+    Some(unsafe { blob.GetBufferSize() } as u64)
+}
+
+fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = cached_blob_size(pipeline)?;
+    let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2);
+    Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD))
+}
+
+impl Runtime {
+    fn mark_full(&self, bytes: u64) {
+        if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) {
+            crate::xlog_info!(
+                "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions",
+                self.path.display(), bytes, self.cap
+            );
+        }
+    }
+
+    fn can_store_locked(&self, name: &str, pipeline: &ID3D12PipelineState) -> bool {
+        if self.full.load(std::sync::atomic::Ordering::Acquire) { return false; }
+        let current = self.library.serialized_size();
+        if current >= self.cap {
+            self.mark_full(current);
+            return false;
+        }
+        let Some(est) = estimated_store_bytes(name, pipeline) else {
+            self.mark_full(current);
+            return false;
+        };
+        if current.saturating_add(est) > self.cap {
+            self.mark_full(current);
+            return false;
+        }
+        true
+    }
+}
+
+fn store_into_runtime(runtime: &Runtime, name: &str, pipeline: &ID3D12PipelineState) -> bool {
+    match runtime.library.store(name, pipeline) {
+        Ok(()) => { runtime.added.fetch_add(1, std::sync::atomic::Ordering::AcqRel); true }
+        // (E_INVALIDARG: an earlier run kept it already)
+        Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => true,
+        Err(e) => { crate::xlog_warn!("Pipeline library: keeping {name}: {e}"); false }
+    }
+}
+
+fn read_cached_blob(pipeline: &ID3D12PipelineState) -> Option<Vec<u8>> {
+    let blob = unsafe { pipeline.GetCachedBlob().ok()? };
+    let size = unsafe { blob.GetBufferSize() };
+    let data = unsafe { blob.GetBufferPointer().cast::<u8>() };
+    if size == 0 || data.is_null() { return None }
+    Some(unsafe { std::slice::from_raw_parts(data, size) }.to_vec())
+}
+
+impl Active {
+    fn with_name(
+        &self,
+        name: &str,
+        kind: super::pipeline_stats::Kind,
+        f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>,
+        prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>,
+    ) -> Option<Loaded> {
+        use super::pipeline_stats::{library, Source};
+        let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len();
+        let _same_name = self.names[slot].lock().unwrap();
+        let already_handed = self.handed.lock().unwrap().contains(name);
+        let (found, source) = if let Some(found) = prepared(self).and_then(|lib| f(lib).ok()) {
+            (found, Source::Prepared)
+        } else {
+            let runtime = self.runtime.as_ref()?;
+            (f(&runtime.library).ok()?, Source::Runtime)
+        };
+        if let Some(runtime) = &self.runtime { runtime.known.lock().unwrap().insert(name.into()); }
+        if already_handed {
+            // A library loads a name as the same COM object each time, and XCL keys what it knows
+            // of a pipeline by its object (a dispatch chain by its first piece: a second chain
+            // with that piece replaced the first, and the replaced one's release deadlocked on the
+            // chain table). Hand out its cached blob instead so the caller creates a distinct COM
+            // object without recompiling in the driver, even for small shaders below the RAM blob
+            // cache threshold.
+            return read_cached_blob(&found).map(Loaded::Blob);
+        }
+        library(kind, source);
+        self.handed.lock().unwrap().insert(name.into());
+        Some(Loaded::Pipeline(found))
+    }
+
+    /// A pipeline built at runtime, kept in `runtime.plib` (one found in a library is not kept again).
+    fn store_runtime(&self, name: &str, pipeline: &ID3D12PipelineState) {
+        use std::sync::atomic::Ordering;
+        let Some(runtime) = self.runtime.as_ref() else { return };
+        if name.is_empty() || runtime.full.load(Ordering::Acquire) { return }
+        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;

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773181336 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773181336). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:03:02Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 446 ~~~~diff @@ -20,39 +20,521 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let full = library.serialized_size() >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + full: full.into(), + }) +} + pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) .ok_or("Pipeline library: runtime driver identity is unavailable")?; if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } + start_counting(); + if !NativeLibrary::supported(device) { + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + return Ok(()); + } let open = |bytes| NativeLibrary::open_shared(device, bytes); let graphics = ready.graphics.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; let compute = ready.compute.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; - } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() { crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + since += 1; + if since >= flush_every() { + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { + runtime.mark_full(current); + state.disabled = true; + crate::xlog_warn!( + "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library", + runtime.path.display(), current, runtime.cap + ); + return false; + } + let bytes = match serialize_runtime(runtime) { + Ok(b) => b, + Err(e) => { + state.consecutive_failures += 1; + if state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display()); + } + return false; + } + }; + if bytes.len() as u64 > runtime.cap { + 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", + runtime.path.display(), bytes.len(), runtime.cap + ); + return false; + } + match write(&runtime.path, &bytes) { + Ok(()) => { + state.consecutive_failures = 0; + runtime.size.store(bytes.len() as u64, Ordering::Relaxed); + crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})", + bytes.len(), runtime.path.display()); + true + } + Err(e) => { + state.consecutive_failures += 1; + if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display()); + } + false + } + } +} + +/// Writes `runtime.plib` again when pipelines were added to it since it was last written. +pub(crate) fn flush_runtime() { + let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return }; + flush_runtime_on(runtime, write_atomic); +} + +fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = unsafe { pipeline.GetCachedBlob().ok()? }; + Some(unsafe { blob.GetBufferSize() } as u64) +} + +fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = cached_blob_size(pipeline)?; + let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2); + Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD)) +} + +impl Runtime { + fn mark_full(&self, bytes: u64) { + if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) { + crate::xlog_info!( + "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions", + self.path.display(), bytes, self.cap + ); + } + } + + fn can_store_locked(&self, name: &str, pipeline: &ID3D12PipelineState) -> bool { + if self.full.load(std::sync::atomic::Ordering::Acquire) { return false; } + let current = self.library.serialized_size(); + if current >= self.cap { + self.mark_full(current); + return false; + } + let Some(est) = estimated_store_bytes(name, pipeline) else { + self.mark_full(current); + return false; + }; + if current.saturating_add(est) > self.cap { + self.mark_full(current); + return false; + } + true + } +} + +fn store_into_runtime(runtime: &Runtime, name: &str, pipeline: &ID3D12PipelineState) -> bool { + match runtime.library.store(name, pipeline) { + Ok(()) => { runtime.added.fetch_add(1, std::sync::atomic::Ordering::AcqRel); true } + // (E_INVALIDARG: an earlier run kept it already) + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => true, + Err(e) => { crate::xlog_warn!("Pipeline library: keeping {name}: {e}"); false } + } +} + +fn read_cached_blob(pipeline: &ID3D12PipelineState) -> Option<Vec<u8>> { + let blob = unsafe { pipeline.GetCachedBlob().ok()? }; + let size = unsafe { blob.GetBufferSize() }; + let data = unsafe { blob.GetBufferPointer().cast::<u8>() }; + if size == 0 || data.is_null() { return None } + Some(unsafe { std::slice::from_raw_parts(data, size) }.to_vec()) +} + +impl Active { + fn with_name( + &self, + name: &str, + kind: super::pipeline_stats::Kind, + f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>, + prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>, + ) -> Option<Loaded> { + use super::pipeline_stats::{library, Source}; + let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len(); + let _same_name = self.names[slot].lock().unwrap(); + let already_handed = self.handed.lock().unwrap().contains(name); + let (found, source) = if let Some(found) = prepared(self).and_then(|lib| f(lib).ok()) { + (found, Source::Prepared) + } else { + let runtime = self.runtime.as_ref()?; + (f(&runtime.library).ok()?, Source::Runtime) + }; + if let Some(runtime) = &self.runtime { runtime.known.lock().unwrap().insert(name.into()); } + if already_handed { + // A library loads a name as the same COM object each time, and XCL keys what it knows + // of a pipeline by its object (a dispatch chain by its first piece: a second chain + // with that piece replaced the first, and the replaced one's release deadlocked on the + // chain table). Hand out its cached blob instead so the caller creates a distinct COM + // object without recompiling in the driver, even for small shaders below the RAM blob + // cache threshold. + return read_cached_blob(&found).map(Loaded::Blob); + } + library(kind, source); + self.handed.lock().unwrap().insert(name.into()); + Some(Loaded::Pipeline(found)) + } + + /// A pipeline built at runtime, kept in `runtime.plib` (one found in a library is not kept again). + fn store_runtime(&self, name: &str, pipeline: &ID3D12PipelineState) { + use std::sync::atomic::Ordering; + let Some(runtime) = self.runtime.as_ref() else { return }; + if name.is_empty() || runtime.full.load(Ordering::Acquire) { return } + 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; ~~~~ --- **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.
bmjask commented 2026-12-02 17:03:02 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:03:02Z.

Review: COMMENTED


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.

<!-- greyfinch-sync:ivall/xcl:review:6155457233 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#pullrequestreview-6155457233). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:03:02Z. **Review:** COMMENTED --- 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._
bmjask commented 2026-12-02 17:03:03 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:03:03Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 376

@@ -20,39 +20,521 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let full = library.serialized_size() >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        full: full.into(),
+    })
+}
+
 pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
     let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
         .ok_or("Pipeline library: runtime driver identity is unavailable")?;
     if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
+    start_counting();
+    if !NativeLibrary::supported(device) {
+        crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+        return Ok(());
+    }
     let open = |bytes| NativeLibrary::open_shared(device, bytes);
     let graphics = ready.graphics.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
     let compute = ready.compute.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
-    }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() {
         crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                since += 1;
+                if since >= flush_every() {
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {
+        runtime.mark_full(current);
+        state.disabled = true;
+        crate::xlog_warn!(
+            "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",
+            runtime.path.display(), current, runtime.cap
+        );
+        return false;
+    }
+    let bytes = match serialize_runtime(runtime) {
+        Ok(b) => b,
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display());
+            }
+            return false;
+        }
+    };
+    if bytes.len() as u64 > runtime.cap {
+        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",
+            runtime.path.display(), bytes.len(), runtime.cap
+        );
+        return false;
+    }
+    match write(&runtime.path, &bytes) {
+        Ok(()) => {
+            state.consecutive_failures = 0;
+            runtime.size.store(bytes.len() as u64, Ordering::Relaxed);
+            crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})",
+                bytes.len(), runtime.path.display());
+            true
+        }
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display());
+            }
+            false
+        }
+    }
+}
+
+/// Writes `runtime.plib` again when pipelines were added to it since it was last written.
+pub(crate) fn flush_runtime() {
+    let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return };
+    flush_runtime_on(runtime, write_atomic);
+}
+
+fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = unsafe { pipeline.GetCachedBlob().ok()? };
+    Some(unsafe { blob.GetBufferSize() } as u64)
+}
+
+fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = cached_blob_size(pipeline)?;
+    let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2);
+    Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD))
+}
+
+impl Runtime {
+    fn mark_full(&self, bytes: u64) {
+        if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) {
+            crate::xlog_info!(
+                "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions",
+                self.path.display(), bytes, self.cap
+            );
+        }
+    }
+
+    fn can_store_locked(&self, name: &str, pipeline: &ID3D12PipelineState) -> bool {
+        if self.full.load(std::sync::atomic::Ordering::Acquire) { return false; }
+        let current = self.library.serialized_size();
+        if current >= self.cap {
+            self.mark_full(current);
+            return false;
+        }
+        let Some(est) = estimated_store_bytes(name, pipeline) else {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773181347 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773181347). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:03:03Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 376 ~~~~diff @@ -20,39 +20,521 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let full = library.serialized_size() >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + full: full.into(), + }) +} + pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) .ok_or("Pipeline library: runtime driver identity is unavailable")?; if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } + start_counting(); + if !NativeLibrary::supported(device) { + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + return Ok(()); + } let open = |bytes| NativeLibrary::open_shared(device, bytes); let graphics = ready.graphics.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; let compute = ready.compute.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; - } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() { crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + since += 1; + if since >= flush_every() { + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { + runtime.mark_full(current); + state.disabled = true; + crate::xlog_warn!( + "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library", + runtime.path.display(), current, runtime.cap + ); + return false; + } + let bytes = match serialize_runtime(runtime) { + Ok(b) => b, + Err(e) => { + state.consecutive_failures += 1; + if state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display()); + } + return false; + } + }; + if bytes.len() as u64 > runtime.cap { + 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", + runtime.path.display(), bytes.len(), runtime.cap + ); + return false; + } + match write(&runtime.path, &bytes) { + Ok(()) => { + state.consecutive_failures = 0; + runtime.size.store(bytes.len() as u64, Ordering::Relaxed); + crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})", + bytes.len(), runtime.path.display()); + true + } + Err(e) => { + state.consecutive_failures += 1; + if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display()); + } + false + } + } +} + +/// Writes `runtime.plib` again when pipelines were added to it since it was last written. +pub(crate) fn flush_runtime() { + let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return }; + flush_runtime_on(runtime, write_atomic); +} + +fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = unsafe { pipeline.GetCachedBlob().ok()? }; + Some(unsafe { blob.GetBufferSize() } as u64) +} + +fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = cached_blob_size(pipeline)?; + let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2); + Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD)) +} + +impl Runtime { + fn mark_full(&self, bytes: u64) { + if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) { + crate::xlog_info!( + "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions", + self.path.display(), bytes, self.cap + ); + } + } + + fn can_store_locked(&self, name: &str, pipeline: &ID3D12PipelineState) -> bool { + if self.full.load(std::sync::atomic::Ordering::Acquire) { return false; } + let current = self.library.serialized_size(); + if current >= self.cap { + self.mark_full(current); + return false; + } + let Some(est) = estimated_store_bytes(name, pipeline) else { ~~~~ --- **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 commented 2026-12-02 17:27:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T17:27:27Z.


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.)

<!-- greyfinch-sync:ivall/xcl:comment:7353322309 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7353322309). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T17:27:27Z. --- 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 commented 2026-12-02 17:49:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:49:10Z.

Code review location: crates/xcl/src/hle/d3d12x/real.rs; line 4902

@@ -4896,6 +4896,10 @@ pub fn end_title(code: u32) -> ! {
         });
         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; 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));

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773578470 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773578470). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:49:10Z. **Code review location:** `crates/xcl/src/hle/d3d12x/real.rs`; line 4902 ~~~~diff @@ -4896,6 +4896,10 @@ pub fn end_title(code: u32) -> ! { }); 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; 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)); ~~~~ --- **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.
bmjask commented 2026-12-02 17:49:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:49:10Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 578

@@ -20,39 +20,682 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later
+    /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept.
+    load_missed: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the
+    /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`.
+    estimated_size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let initial_size = library.serialized_size();
+    let full = initial_size >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        load_missed: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        estimated_size: initial_size.into(),
+        full: full.into(),
+    })
+}
+
+fn check_activation_driver(
+    ready_driver: u64,
+    runtime_driver: Option<u64>,
+    has_prepared: bool,
+    cache_only: bool,
+) -> std::result::Result<bool, String> {
+    if runtime_driver == Some(ready_driver) {
+        return Ok(true);
+    }
+    let reason = if runtime_driver.is_none() {
+        "Pipeline library: runtime driver identity is unavailable"
+    } else {
+        "Pipeline library: runtime adapter or driver differs from the prepared cache"
+    };
+    if cache_only && has_prepared {
+        return Err(reason.into());
+    }
+    crate::xlog_warn!("{reason}; continuing without pipeline libraries");
+    Ok(false)
+}
+
 pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    let Some(ready) = super::warm_library::take_ready() else { return Ok(()) };
-    let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
-        .ok_or("Pipeline library: runtime driver identity is unavailable")?;
-    if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
+    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
+    let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device);
+    let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1");
+    let has_prepared = ready.graphics.is_some() || ready.compute.is_some();
+    if !check_activation_driver(ready.driver, runtime_driver, has_prepared, cache_only)? {
+        return Ok(());
+    }
+    start_counting();
+    if !NativeLibrary::supported(device) {
+        crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+        return Ok(());
+    }
     let open = |bytes| NativeLibrary::open_shared(device, bytes);
     let graphics = ready.graphics.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
     let compute = ready.compute.map(open).transpose()
         .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
-    }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() {
         crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                since += 1;
+                if since >= flush_every() {
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {
+        runtime.mark_full(current);
+        state.disabled = true;
+        crate::xlog_warn!(
+            "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",
+            runtime.path.display(), current, runtime.cap
+        );
+        return false;
+    }
+    let bytes = match serialize_runtime(runtime) {
+        Ok(b) => b,
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display());
+            }
+            return false;
+        }
+    };
+    if bytes.len() as u64 > runtime.cap {
+        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",
+            runtime.path.display(), bytes.len(), runtime.cap
+        );
+        return false;
+    }
+    match write(&runtime.path, &bytes) {
+        Ok(()) => {
+            state.consecutive_failures = 0;
+            runtime.size.store(bytes.len() as u64, Ordering::Relaxed);
+            crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})",
+                bytes.len(), runtime.path.display());
+            true
+        }
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display());
+            }
+            false
+        }
+    }
+}
+
+/// Writes `runtime.plib` again when pipelines were added to it since it was last written.
+pub(crate) fn flush_runtime() {
+    let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return };
+    flush_runtime_on(runtime, write_atomic);
+}
+
+fn run_with_timeout(name: &str, timeout: std::time::Duration, f: impl FnOnce() + Send + 'static) -> bool {
+    let (tx, rx) = std::sync::mpsc::sync_channel(1);
+    if std::thread::Builder::new().name(name.into()).spawn(move || {
+        f();
+        let _ = tx.send(());
+    }).is_err() {
+        return false;
+    }
+    rx.recv_timeout(timeout).is_ok()
+}
+
+/// Bounded `flush_runtime` for title shutdown (`end_title`): returns immediately when nothing is
+/// pending or in flight, and otherwise caps waiting at `timeout` so a slow disk or periodic flush
+/// cannot consume the end-watchdog budget needed for thread suspension and GPU drain.
+pub(crate) fn flush_runtime_timeout(timeout: std::time::Duration) -> bool {
+    let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return true };
+    if let Ok(state) = runtime.flush_lock.try_lock() {
+        if state.disabled || runtime.added.load(std::sync::atomic::Ordering::Acquire) == 0 {
+            return true;
+        }
+    }
+    let finished = run_with_timeout("xcl-plib-end-flush", timeout, move || {
+        flush_runtime_on(runtime, write_atomic);
+    });
+    if !finished {
+        crate::xlog_warn!(
+            "Pipeline library: shutdown flush of {} did not finish within {} ms; continuing shutdown",
+            runtime.path.display(), timeout.as_millis()
+        );
+    }
+    finished
+}
+
+fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> {
+    unsafe { crate::hle::d3d12x::real::pso_cached_blob_size(pipeline.as_raw()) }
+}
+
+fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = cached_blob_size(pipeline)?;
+    let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2);
+    Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD))
+}
+
+impl Runtime {
+    fn mark_full(&self, bytes: u64) {
+        if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) {
+            crate::xlog_info!(
+                "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions",
+                self.path.display(), bytes, self.cap
+            );
+        }
+    }
+
+    /// Reserves `est` bytes on the lock-free read path only while the cumulative estimate stays at
+    /// least `NEAR_CAP_MARGIN` below `cap`. Large pipelines or concurrent bursts that cross that
+    /// threshold fall through to `store_lock.write()` + exact `serialized_size()`.
+    fn try_reserve_fast(&self, est: u64) -> bool {
+        use std::sync::atomic::Ordering;
+        let fast_limit = self.cap.saturating_sub(NEAR_CAP_MARGIN);
+        if est > fast_limit { return false; }
+        let mut cur = self.estimated_size.load(Ordering::Acquire);
+        loop {
+            let Some(next) = cur.checked_add(est) else { return false };
+            if next > fast_limit { return false; }
+            match self.estimated_size.compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire) {
+                Ok(_) => return true,
+                Err(actual) => cur = actual,
+            }
+        }
+    }
+
+    fn can_store_locked(&self, est: u64) -> bool {
+        use std::sync::atomic::Ordering;
+        if self.full.load(Ordering::Acquire) { return false; }
+        let current = self.library.serialized_size();
+        self.estimated_size.store(current, Ordering::Release);
+        if current >= self.cap {
+            self.mark_full(current);
+            return false;
+        }
+        if current.saturating_add(est) > self.cap {
+            if est <= NEAR_CAP_MARGIN {
+                self.mark_full(current);
+            }
+            return false;
+        }
+        true
+    }
+}
+
+enum StoreOutcome {
+    /// Pipeline is present and usable in `runtime.library` (newly stored or verified existing).
+    Usable,
+    /// `E_INVALIDARG` on a name whose `Load*` failed in this run: existing entry is unusable
+    /// and cannot be replaced in-place, so stop retrying without marking it handed out.
+    UnusableExisting,
+    /// Transient store error (e.g. `E_OUTOFMEMORY`): leave out of `known` so a later call can retry.
+    TransientError,
+}
+
+fn record_store_result(runtime: &Runtime, name: &str, result: Result<()>) -> StoreOutcome {
+    match result {
+        Ok(()) => {
+            runtime.added.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
+            runtime.load_missed.lock().unwrap().remove(name);
+            StoreOutcome::Usable
+        }
+        Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => {
+            if runtime.load_missed.lock().unwrap().contains(name) {
+                crate::xlog_warn!(
+                    "Pipeline library: {name} already exists in {} but failed to load; not marking usable",
+                    runtime.path.display()
+                );
+                StoreOutcome::UnusableExisting
+            } else {
+                StoreOutcome::Usable
+            }
+        }
+        Err(e) => {
+            crate::xlog_warn!("Pipeline library: keeping {name}: {e}");
+            StoreOutcome::TransientError
+        }
+    }
+}
+
+fn read_cached_blob(pipeline: &ID3D12PipelineState) -> Option<Vec<u8>> {
+    // Use the adoption-aware helper because the first hand-out of a COM object from a pipeline
+    // library may have been adopted (swapping its vtable pointer to XCL's console ext class).
+    unsafe { crate::hle::d3d12x::real::read_pso_cached_blob(pipeline.as_raw()) }
+}
+
+impl Active {
+    fn with_name(
+        &self,
+        name: &str,
+        kind: super::pipeline_stats::Kind,
+        f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>,
+        prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>,
+    ) -> Option<Loaded> {
+        use super::pipeline_stats::{library, Source};
+        let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len();
+        let _same_name = self.names[slot].lock().unwrap();
+        let already_handed = self.handed.lock().unwrap().contains(name);
+        let (found, source) = if let Some(found) = prepared(self).and_then(|lib| f(lib).ok()) {
+            (found, Source::Prepared)
+        } else {
+            let runtime = self.runtime.as_ref()?;
+            match f(&runtime.library) {
+                Ok(found) => (found, Source::Runtime),
+                Err(_) => {
+                    runtime.load_missed.lock().unwrap().insert(name.into());
+                    return None;
+                }
+            }
+        };
+        if let Some(runtime) = &self.runtime {
+            runtime.load_missed.lock().unwrap().remove(name);
+            runtime.known.lock().unwrap().insert(name.into());
+        }
+        if already_handed {
+            // A library loads a name as the same COM object each time, and XCL keys what it knows
+            // of a pipeline by its object (a dispatch chain by its first piece: a second chain
+            // with that piece replaced the first, and the replaced one's release deadlocked on the
+            // chain table). Hand out its cached blob instead so the caller creates a distinct COM
+            // object without recompiling in the driver, even for small shaders below the RAM blob
+            // cache threshold.
+            return read_cached_blob(&found).map(Loaded::Blob);
+        }
+        library(kind, source);
+        self.handed.lock().unwrap().insert(name.into());
+        Some(Loaded::Pipeline(found))
+    }
+
+    fn apply_store_outcome(&self, runtime: &Runtime, name: &str, outcome: StoreOutcome) {
+        match outcome {
+            StoreOutcome::Usable => {
+                runtime.known.lock().unwrap().insert(name.into());
+                // (a load may give back the very object stored: this one is out already)
+                self.handed.lock().unwrap().insert(name.into());
+            }
+            StoreOutcome::UnusableExisting => {
+                runtime.known.lock().unwrap().insert(name.into());
+            }
+            StoreOutcome::TransientError => {}
+        }
+    }
+
+    /// A pipeline built at runtime, kept in `runtime.plib` (one found in a library is not kept again).
+    fn store_runtime(&self, name: &str, pipeline: &ID3D12PipelineState) {
+        use std::sync::atomic::Ordering;
+        let Some(runtime) = self.runtime.as_ref() else { return };
+        if name.is_empty() || runtime.full.load(Ordering::Acquire) { return }
+        let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len();
+        let _same_name = self.names[slot].lock().unwrap();
+        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) {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773578478 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773578478). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:49:10Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 578 ~~~~diff @@ -20,39 +20,682 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later + /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept. + load_missed: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the + /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`. + estimated_size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let initial_size = library.serialized_size(); + let full = initial_size >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + load_missed: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + estimated_size: initial_size.into(), + full: full.into(), + }) +} + +fn check_activation_driver( + ready_driver: u64, + runtime_driver: Option<u64>, + has_prepared: bool, + cache_only: bool, +) -> std::result::Result<bool, String> { + if runtime_driver == Some(ready_driver) { + return Ok(true); + } + let reason = if runtime_driver.is_none() { + "Pipeline library: runtime driver identity is unavailable" + } else { + "Pipeline library: runtime adapter or driver differs from the prepared cache" + }; + if cache_only && has_prepared { + return Err(reason.into()); + } + crate::xlog_warn!("{reason}; continuing without pipeline libraries"); + Ok(false) +} + pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - let Some(ready) = super::warm_library::take_ready() else { return Ok(()) }; - let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) - .ok_or("Pipeline library: runtime driver identity is unavailable")?; - if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } + 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; + let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device); + let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1"); + let has_prepared = ready.graphics.is_some() || ready.compute.is_some(); + if !check_activation_driver(ready.driver, runtime_driver, has_prepared, cache_only)? { + return Ok(()); + } + start_counting(); + if !NativeLibrary::supported(device) { + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + return Ok(()); + } let open = |bytes| NativeLibrary::open_shared(device, bytes); let graphics = ready.graphics.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; let compute = ready.compute.map(open).transpose() .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; - } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + if ACTIVE.set(Active { graphics, compute, runtime, names, handed: Default::default() }).is_ok() { crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + since += 1; + if since >= flush_every() { + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { + runtime.mark_full(current); + state.disabled = true; + crate::xlog_warn!( + "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library", + runtime.path.display(), current, runtime.cap + ); + return false; + } + let bytes = match serialize_runtime(runtime) { + Ok(b) => b, + Err(e) => { + state.consecutive_failures += 1; + if state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display()); + } + return false; + } + }; + if bytes.len() as u64 > runtime.cap { + 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", + runtime.path.display(), bytes.len(), runtime.cap + ); + return false; + } + match write(&runtime.path, &bytes) { + Ok(()) => { + state.consecutive_failures = 0; + runtime.size.store(bytes.len() as u64, Ordering::Relaxed); + crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})", + bytes.len(), runtime.path.display()); + true + } + Err(e) => { + state.consecutive_failures += 1; + if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display()); + } + false + } + } +} + +/// Writes `runtime.plib` again when pipelines were added to it since it was last written. +pub(crate) fn flush_runtime() { + let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return }; + flush_runtime_on(runtime, write_atomic); +} + +fn run_with_timeout(name: &str, timeout: std::time::Duration, f: impl FnOnce() + Send + 'static) -> bool { + let (tx, rx) = std::sync::mpsc::sync_channel(1); + if std::thread::Builder::new().name(name.into()).spawn(move || { + f(); + let _ = tx.send(()); + }).is_err() { + return false; + } + rx.recv_timeout(timeout).is_ok() +} + +/// Bounded `flush_runtime` for title shutdown (`end_title`): returns immediately when nothing is +/// pending or in flight, and otherwise caps waiting at `timeout` so a slow disk or periodic flush +/// cannot consume the end-watchdog budget needed for thread suspension and GPU drain. +pub(crate) fn flush_runtime_timeout(timeout: std::time::Duration) -> bool { + let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return true }; + if let Ok(state) = runtime.flush_lock.try_lock() { + if state.disabled || runtime.added.load(std::sync::atomic::Ordering::Acquire) == 0 { + return true; + } + } + let finished = run_with_timeout("xcl-plib-end-flush", timeout, move || { + flush_runtime_on(runtime, write_atomic); + }); + if !finished { + crate::xlog_warn!( + "Pipeline library: shutdown flush of {} did not finish within {} ms; continuing shutdown", + runtime.path.display(), timeout.as_millis() + ); + } + finished +} + +fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> { + unsafe { crate::hle::d3d12x::real::pso_cached_blob_size(pipeline.as_raw()) } +} + +fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = cached_blob_size(pipeline)?; + let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2); + Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD)) +} + +impl Runtime { + fn mark_full(&self, bytes: u64) { + if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) { + crate::xlog_info!( + "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions", + self.path.display(), bytes, self.cap + ); + } + } + + /// Reserves `est` bytes on the lock-free read path only while the cumulative estimate stays at + /// least `NEAR_CAP_MARGIN` below `cap`. Large pipelines or concurrent bursts that cross that + /// threshold fall through to `store_lock.write()` + exact `serialized_size()`. + fn try_reserve_fast(&self, est: u64) -> bool { + use std::sync::atomic::Ordering; + let fast_limit = self.cap.saturating_sub(NEAR_CAP_MARGIN); + if est > fast_limit { return false; } + let mut cur = self.estimated_size.load(Ordering::Acquire); + loop { + let Some(next) = cur.checked_add(est) else { return false }; + if next > fast_limit { return false; } + match self.estimated_size.compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return true, + Err(actual) => cur = actual, + } + } + } + + fn can_store_locked(&self, est: u64) -> bool { + use std::sync::atomic::Ordering; + if self.full.load(Ordering::Acquire) { return false; } + let current = self.library.serialized_size(); + self.estimated_size.store(current, Ordering::Release); + if current >= self.cap { + self.mark_full(current); + return false; + } + if current.saturating_add(est) > self.cap { + if est <= NEAR_CAP_MARGIN { + self.mark_full(current); + } + return false; + } + true + } +} + +enum StoreOutcome { + /// Pipeline is present and usable in `runtime.library` (newly stored or verified existing). + Usable, + /// `E_INVALIDARG` on a name whose `Load*` failed in this run: existing entry is unusable + /// and cannot be replaced in-place, so stop retrying without marking it handed out. + UnusableExisting, + /// Transient store error (e.g. `E_OUTOFMEMORY`): leave out of `known` so a later call can retry. + TransientError, +} + +fn record_store_result(runtime: &Runtime, name: &str, result: Result<()>) -> StoreOutcome { + match result { + Ok(()) => { + runtime.added.fetch_add(1, std::sync::atomic::Ordering::AcqRel); + runtime.load_missed.lock().unwrap().remove(name); + StoreOutcome::Usable + } + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => { + if runtime.load_missed.lock().unwrap().contains(name) { + crate::xlog_warn!( + "Pipeline library: {name} already exists in {} but failed to load; not marking usable", + runtime.path.display() + ); + StoreOutcome::UnusableExisting + } else { + StoreOutcome::Usable + } + } + Err(e) => { + crate::xlog_warn!("Pipeline library: keeping {name}: {e}"); + StoreOutcome::TransientError + } + } +} + +fn read_cached_blob(pipeline: &ID3D12PipelineState) -> Option<Vec<u8>> { + // Use the adoption-aware helper because the first hand-out of a COM object from a pipeline + // library may have been adopted (swapping its vtable pointer to XCL's console ext class). + unsafe { crate::hle::d3d12x::real::read_pso_cached_blob(pipeline.as_raw()) } +} + +impl Active { + fn with_name( + &self, + name: &str, + kind: super::pipeline_stats::Kind, + f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>, + prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>, + ) -> Option<Loaded> { + use super::pipeline_stats::{library, Source}; + let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len(); + let _same_name = self.names[slot].lock().unwrap(); + let already_handed = self.handed.lock().unwrap().contains(name); + let (found, source) = if let Some(found) = prepared(self).and_then(|lib| f(lib).ok()) { + (found, Source::Prepared) + } else { + let runtime = self.runtime.as_ref()?; + match f(&runtime.library) { + Ok(found) => (found, Source::Runtime), + Err(_) => { + runtime.load_missed.lock().unwrap().insert(name.into()); + return None; + } + } + }; + if let Some(runtime) = &self.runtime { + runtime.load_missed.lock().unwrap().remove(name); + runtime.known.lock().unwrap().insert(name.into()); + } + if already_handed { + // A library loads a name as the same COM object each time, and XCL keys what it knows + // of a pipeline by its object (a dispatch chain by its first piece: a second chain + // with that piece replaced the first, and the replaced one's release deadlocked on the + // chain table). Hand out its cached blob instead so the caller creates a distinct COM + // object without recompiling in the driver, even for small shaders below the RAM blob + // cache threshold. + return read_cached_blob(&found).map(Loaded::Blob); + } + library(kind, source); + self.handed.lock().unwrap().insert(name.into()); + Some(Loaded::Pipeline(found)) + } + + fn apply_store_outcome(&self, runtime: &Runtime, name: &str, outcome: StoreOutcome) { + match outcome { + StoreOutcome::Usable => { + runtime.known.lock().unwrap().insert(name.into()); + // (a load may give back the very object stored: this one is out already) + self.handed.lock().unwrap().insert(name.into()); + } + StoreOutcome::UnusableExisting => { + runtime.known.lock().unwrap().insert(name.into()); + } + StoreOutcome::TransientError => {} + } + } + + /// A pipeline built at runtime, kept in `runtime.plib` (one found in a library is not kept again). + fn store_runtime(&self, name: &str, pipeline: &ID3D12PipelineState) { + use std::sync::atomic::Ordering; + let Some(runtime) = self.runtime.as_ref() else { return }; + if name.is_empty() || runtime.full.load(Ordering::Acquire) { return } + let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len(); + let _same_name = self.names[slot].lock().unwrap(); + 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) { ~~~~ --- **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.
bmjask commented 2026-12-02 17:49:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:49:10Z.

Code review location: crates/xcl/src/hle/d3d12x/present.rs; line 741

@@ -738,6 +738,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM)
     match msg {
         WM_CLOSE => {
             crate::xlog_info!("XCL window closed – ending the game process");
+            crate::shaders::pipeline_library::flush_runtime();

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773578487 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773578487). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:49:10Z. **Code review location:** `crates/xcl/src/hle/d3d12x/present.rs`; line 741 ~~~~diff @@ -738,6 +738,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) match msg { WM_CLOSE => { crate::xlog_info!("XCL window closed – ending the game process"); + crate::shaders::pipeline_library::flush_runtime(); ~~~~ --- **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.
bmjask commented 2026-12-02 17:49:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:49:10Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 221

@@ -20,39 +20,682 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later
+    /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept.
+    load_missed: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the
+    /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`.
+    estimated_size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let initial_size = library.serialized_size();
+    let full = initial_size >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        load_missed: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        estimated_size: initial_size.into(),
+        full: full.into(),
+    })
+}
+
+fn check_activation_driver(
+    ready_driver: u64,
+    runtime_driver: Option<u64>,
+    has_prepared: bool,
+    cache_only: bool,
+) -> std::result::Result<bool, String> {
+    if runtime_driver == Some(ready_driver) {
+        return Ok(true);
+    }
+    let reason = if runtime_driver.is_none() {
+        "Pipeline library: runtime driver identity is unavailable"
+    } else {
+        "Pipeline library: runtime adapter or driver differs from the prepared cache"
+    };
+    if cache_only && has_prepared {
+        return Err(reason.into());
+    }
+    crate::xlog_warn!("{reason}; continuing without pipeline libraries");

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773578495 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773578495). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:49:10Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 221 ~~~~diff @@ -20,39 +20,682 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later + /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept. + load_missed: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the + /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`. + estimated_size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let initial_size = library.serialized_size(); + let full = initial_size >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + load_missed: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + estimated_size: initial_size.into(), + full: full.into(), + }) +} + +fn check_activation_driver( + ready_driver: u64, + runtime_driver: Option<u64>, + has_prepared: bool, + cache_only: bool, +) -> std::result::Result<bool, String> { + if runtime_driver == Some(ready_driver) { + return Ok(true); + } + let reason = if runtime_driver.is_none() { + "Pipeline library: runtime driver identity is unavailable" + } else { + "Pipeline library: runtime adapter or driver differs from the prepared cache" + }; + if cache_only && has_prepared { + return Err(reason.into()); + } + crate::xlog_warn!("{reason}; continuing without pipeline libraries"); ~~~~ --- **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.
bmjask commented 2026-12-02 17:49:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:49:10Z.

Review: COMMENTED


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.

<!-- greyfinch-sync:ivall/xcl:review:6155986550 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#pullrequestreview-6155986550). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:49:10Z. **Review:** COMMENTED --- 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._
Kalmarv commented 2026-12-02 18:01:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T18:01:40Z.


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.)

<!-- greyfinch-sync:ivall/xcl:comment:7353873506 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7353873506). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T18:01:40Z. --- 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 commented 2026-12-02 18:17:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T18:17:25Z.

Review: COMMENTED


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.

<!-- greyfinch-sync:ivall/xcl:review:6156309868 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#pullrequestreview-6156309868). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T18:17:25Z. **Review:** COMMENTED --- 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._
bmjask commented 2026-12-02 18:17:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T18:17:25Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 349

@@ -20,39 +20,729 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later
+    /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept.
+    load_missed: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the
+    /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`.
+    estimated_size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
-pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    let Some(ready) = super::warm_library::take_ready() else { return Ok(()) };
-    let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
-        .ok_or("Pipeline library: runtime driver identity is unavailable")?;
-    if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
-    let open = |bytes| NativeLibrary::open_shared(device, bytes);
-    let graphics = ready.graphics.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
-    let compute = ready.compute.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
     }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
-        crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let initial_size = library.serialized_size();
+    let full = initial_size >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        load_missed: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        estimated_size: initial_size.into(),
+        full: full.into(),
+    })
+}
+
+fn check_activation_driver(
+    ready_driver: u64,
+    runtime_driver: Option<u64>,
+    has_prepared: bool,
+    cache_only: bool,
+) -> std::result::Result<bool, String> {
+    if runtime_driver == Some(ready_driver) {
+        return Ok(true);
+    }
+    let reason = if runtime_driver.is_none() {
+        "Pipeline library: runtime driver identity is unavailable"
+    } else {
+        "Pipeline library: runtime adapter or driver differs from the prepared cache"
+    };
+    if cache_only && has_prepared {
+        return Err(reason.into());
+    }
+    if has_prepared {
+        crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib");
+    }
+    Ok(false)
+}
+
+fn open_active_for_device(
+    device: &ID3D12Device,
+    ready: super::warm_library::Ready,
+    runtime_driver: Option<u64>,
+    cache_only: bool,
+) -> 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) {
+        crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+        return Ok(None);
+    }
+    let open = |bytes| NativeLibrary::open_shared(device, bytes);
+    let graphics = if use_prepared {
+        ready.graphics.map(open).transpose()
+            .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?
+    } else {
+        None
+    };
+    let compute = if use_prepared {
+        ready.compute.map(open).transpose()
+            .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?
+    } else {
+        None
+    };
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    Ok(Some(Active { graphics, compute, runtime, names, handed: Default::default() }))
+}
+
+pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
+    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
+    let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device);
+    let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1");
+    let Some(active) = open_active_for_device(device, ready, runtime_driver, cache_only)? else {
+        return Ok(());
+    };
+    start_counting();
+    let has_any_prepared = active.graphics.is_some() || active.compute.is_some();
+    let has_runtime = active.runtime.is_some();
+    if ACTIVE.set(active).is_ok() {
+        if has_any_prepared {
+            crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+        } else if has_runtime {
+            crate::xlog_info!("Pipeline library: activated runtime library for lazy runtime loading");
+        }
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+static PERIODIC_FLUSH_TID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
+            PERIODIC_FLUSH_TID.store(tid, std::sync::atomic::Ordering::Release);
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                since += 1;
+                if since >= flush_every() {
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773829810 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773829810). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T18:17:25Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 349 ~~~~diff @@ -20,39 +20,729 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later + /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept. + load_missed: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the + /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`. + estimated_size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); -pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - let Some(ready) = super::warm_library::take_ready() else { return Ok(()) }; - let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) - .ok_or("Pipeline library: runtime driver identity is unavailable")?; - if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } - let open = |bytes| NativeLibrary::open_shared(device, bytes); - let graphics = ready.graphics.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; - let compute = ready.compute.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { - crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let initial_size = library.serialized_size(); + let full = initial_size >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + load_missed: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + estimated_size: initial_size.into(), + full: full.into(), + }) +} + +fn check_activation_driver( + ready_driver: u64, + runtime_driver: Option<u64>, + has_prepared: bool, + cache_only: bool, +) -> std::result::Result<bool, String> { + if runtime_driver == Some(ready_driver) { + return Ok(true); + } + let reason = if runtime_driver.is_none() { + "Pipeline library: runtime driver identity is unavailable" + } else { + "Pipeline library: runtime adapter or driver differs from the prepared cache" + }; + if cache_only && has_prepared { + return Err(reason.into()); + } + if has_prepared { + crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib"); + } + Ok(false) +} + +fn open_active_for_device( + device: &ID3D12Device, + ready: super::warm_library::Ready, + runtime_driver: Option<u64>, + cache_only: bool, +) -> 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) { + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + return Ok(None); + } + let open = |bytes| NativeLibrary::open_shared(device, bytes); + let graphics = if use_prepared { + ready.graphics.map(open).transpose() + .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))? + } else { + None + }; + let compute = if use_prepared { + ready.compute.map(open).transpose() + .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))? + } else { + None + }; + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + Ok(Some(Active { graphics, compute, runtime, names, handed: Default::default() })) +} + +pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { + 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; + let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device); + let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1"); + let Some(active) = open_active_for_device(device, ready, runtime_driver, cache_only)? else { + return Ok(()); + }; + start_counting(); + let has_any_prepared = active.graphics.is_some() || active.compute.is_some(); + let has_runtime = active.runtime.is_some(); + if ACTIVE.set(active).is_ok() { + if has_any_prepared { + crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); + } else if has_runtime { + crate::xlog_info!("Pipeline library: activated runtime library for lazy runtime loading"); + } } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +static PERIODIC_FLUSH_TID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + PERIODIC_FLUSH_TID.store(tid, std::sync::atomic::Ordering::Release); + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + since += 1; + if since >= flush_every() { + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { ~~~~ --- **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.
bmjask commented 2026-12-02 18:17:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T18:17:25Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 235

@@ -20,39 +20,729 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later
+    /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept.
+    load_missed: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the
+    /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`.
+    estimated_size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
-pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    let Some(ready) = super::warm_library::take_ready() else { return Ok(()) };
-    let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
-        .ok_or("Pipeline library: runtime driver identity is unavailable")?;
-    if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
-    let open = |bytes| NativeLibrary::open_shared(device, bytes);
-    let graphics = ready.graphics.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
-    let compute = ready.compute.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
     }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
-        crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let initial_size = library.serialized_size();
+    let full = initial_size >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        load_missed: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        estimated_size: initial_size.into(),
+        full: full.into(),
+    })
+}
+
+fn check_activation_driver(
+    ready_driver: u64,
+    runtime_driver: Option<u64>,
+    has_prepared: bool,
+    cache_only: bool,
+) -> std::result::Result<bool, String> {
+    if runtime_driver == Some(ready_driver) {
+        return Ok(true);
+    }
+    let reason = if runtime_driver.is_none() {
+        "Pipeline library: runtime driver identity is unavailable"
+    } else {
+        "Pipeline library: runtime adapter or driver differs from the prepared cache"
+    };
+    if cache_only && has_prepared {
+        return Err(reason.into());
+    }
+    if has_prepared {
+        crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib");
+    }
+    Ok(false)
+}
+
+fn open_active_for_device(
+    device: &ID3D12Device,
+    ready: super::warm_library::Ready,
+    runtime_driver: Option<u64>,
+    cache_only: bool,
+) -> 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) {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773829825 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773829825). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T18:17:25Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 235 ~~~~diff @@ -20,39 +20,729 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later + /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept. + load_missed: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the + /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`. + estimated_size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); -pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - let Some(ready) = super::warm_library::take_ready() else { return Ok(()) }; - let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) - .ok_or("Pipeline library: runtime driver identity is unavailable")?; - if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } - let open = |bytes| NativeLibrary::open_shared(device, bytes); - let graphics = ready.graphics.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; - let compute = ready.compute.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { - crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let initial_size = library.serialized_size(); + let full = initial_size >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + load_missed: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + estimated_size: initial_size.into(), + full: full.into(), + }) +} + +fn check_activation_driver( + ready_driver: u64, + runtime_driver: Option<u64>, + has_prepared: bool, + cache_only: bool, +) -> std::result::Result<bool, String> { + if runtime_driver == Some(ready_driver) { + return Ok(true); + } + let reason = if runtime_driver.is_none() { + "Pipeline library: runtime driver identity is unavailable" + } else { + "Pipeline library: runtime adapter or driver differs from the prepared cache" + }; + if cache_only && has_prepared { + return Err(reason.into()); + } + if has_prepared { + crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib"); + } + Ok(false) +} + +fn open_active_for_device( + device: &ID3D12Device, + ready: super::warm_library::Ready, + runtime_driver: Option<u64>, + cache_only: bool, +) -> 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) { ~~~~ --- **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.
bmjask commented 2026-12-02 18:17:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T18:17:25Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 738

@@ -20,39 +20,729 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later
+    /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept.
+    load_missed: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the
+    /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`.
+    estimated_size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
-pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    let Some(ready) = super::warm_library::take_ready() else { return Ok(()) };
-    let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
-        .ok_or("Pipeline library: runtime driver identity is unavailable")?;
-    if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
-    let open = |bytes| NativeLibrary::open_shared(device, bytes);
-    let graphics = ready.graphics.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
-    let compute = ready.compute.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
     }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
-        crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let initial_size = library.serialized_size();
+    let full = initial_size >= cap;
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        load_missed: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        estimated_size: initial_size.into(),
+        full: full.into(),
+    })
+}
+
+fn check_activation_driver(
+    ready_driver: u64,
+    runtime_driver: Option<u64>,
+    has_prepared: bool,
+    cache_only: bool,
+) -> std::result::Result<bool, String> {
+    if runtime_driver == Some(ready_driver) {
+        return Ok(true);
+    }
+    let reason = if runtime_driver.is_none() {
+        "Pipeline library: runtime driver identity is unavailable"
+    } else {
+        "Pipeline library: runtime adapter or driver differs from the prepared cache"
+    };
+    if cache_only && has_prepared {
+        return Err(reason.into());
+    }
+    if has_prepared {
+        crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib");
+    }
+    Ok(false)
+}
+
+fn open_active_for_device(
+    device: &ID3D12Device,
+    ready: super::warm_library::Ready,
+    runtime_driver: Option<u64>,
+    cache_only: bool,
+) -> 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) {
+        crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+        return Ok(None);
+    }
+    let open = |bytes| NativeLibrary::open_shared(device, bytes);
+    let graphics = if use_prepared {
+        ready.graphics.map(open).transpose()
+            .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?
+    } else {
+        None
+    };
+    let compute = if use_prepared {
+        ready.compute.map(open).transpose()
+            .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?
+    } else {
+        None
+    };
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    Ok(Some(Active { graphics, compute, runtime, names, handed: Default::default() }))
+}
+
+pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
+    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
+    let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device);
+    let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1");
+    let Some(active) = open_active_for_device(device, ready, runtime_driver, cache_only)? else {
+        return Ok(());
+    };
+    start_counting();
+    let has_any_prepared = active.graphics.is_some() || active.compute.is_some();
+    let has_runtime = active.runtime.is_some();
+    if ACTIVE.set(active).is_ok() {
+        if has_any_prepared {
+            crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+        } else if has_runtime {
+            crate::xlog_info!("Pipeline library: activated runtime library for lazy runtime loading");
+        }
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+static PERIODIC_FLUSH_TID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
+            PERIODIC_FLUSH_TID.store(tid, std::sync::atomic::Ordering::Release);
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                since += 1;
+                if since >= flush_every() {
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {
+        runtime.mark_full(current);
+        state.disabled = true;
+        crate::xlog_warn!(
+            "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",
+            runtime.path.display(), current, runtime.cap
+        );
+        return false;
+    }
+    let bytes = match serialize_runtime(runtime) {
+        Ok(b) => b,
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display());
+            }
+            return false;
+        }
+    };
+    if bytes.len() as u64 > runtime.cap {
+        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",
+            runtime.path.display(), bytes.len(), runtime.cap
+        );
+        return false;
+    }
+    match write(&runtime.path, &bytes) {
+        Ok(()) => {
+            state.consecutive_failures = 0;
+            runtime.size.store(bytes.len() as u64, Ordering::Relaxed);
+            crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})",
+                bytes.len(), runtime.path.display());
+            true
+        }
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display());
+            }
+            false
+        }
+    }
+}
+
+/// Writes `runtime.plib` again when pipelines were added to it since it was last written.
+pub(crate) fn flush_runtime() {
+    let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return };
+    flush_runtime_on(runtime, write_atomic);
+}
+
+/// Runs `f` on a helper thread up to `timeout`. Returns `None` if it finished (or could not
+/// spawn), or `Some(tid)` with the helper's OS thread ID when it is still running at timeout.
+fn run_with_timeout(name: &str, timeout: std::time::Duration, f: impl FnOnce() + Send + 'static) -> Option<u32> {
+    let (tid_tx, tid_rx) = std::sync::mpsc::sync_channel(1);
+    let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1);
+    if std::thread::Builder::new().name(name.into()).spawn(move || {
+        let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
+        let _ = tid_tx.send(tid);
+        f();
+        let _ = done_tx.send(());
+    }).is_err() {
+        return None;
+    }
+    let deadline = std::time::Instant::now() + timeout;
+    let tid = tid_rx.recv_timeout(timeout).unwrap_or(0);
+    let remaining = deadline.saturating_duration_since(std::time::Instant::now());
+    match done_rx.recv_timeout(remaining) {
+        Ok(()) => None,
+        Err(_) => Some(tid),
+    }
+}
+
+/// Bounded `flush_runtime` for title shutdown (`end_title`, `WM_CLOSE`): returns `[0, 0]` when
+/// nothing is pending/in-flight or the flush finishes within `timeout`. On timeout, returns the OS
+/// thread IDs of the active flush threads so `end_title` can exclude them from thread suspension
+/// (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() {
+        if state.disabled || runtime.added.load(std::sync::atomic::Ordering::Acquire) == 0 {
+            return [0, 0];
+        }
+    }
+    let Some(end_tid) = run_with_timeout("xcl-plib-end-flush", timeout, move || {
+        flush_runtime_on(runtime, write_atomic);
+    }) else {
+        return [0, 0];
+    };
+    crate::xlog_warn!(
+        "Pipeline library: shutdown flush of {} did not finish within {} ms; continuing shutdown",
+        runtime.path.display(), timeout.as_millis()
+    );
+    [end_tid, PERIODIC_FLUSH_TID.load(std::sync::atomic::Ordering::Acquire)]
+}
+
+fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> {
+    unsafe { crate::hle::d3d12x::real::pso_cached_blob_size(pipeline.as_raw()) }
+}
+
+fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = cached_blob_size(pipeline)?;
+    let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2);
+    Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD))
+}
+
+impl Runtime {
+    fn mark_full(&self, bytes: u64) {
+        if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) {
+            crate::xlog_info!(
+                "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions",
+                self.path.display(), bytes, self.cap
+            );
+        }
+    }
+
+    /// Reserves `est` bytes on the lock-free read path only while the cumulative estimate stays at
+    /// least `NEAR_CAP_MARGIN` below `cap`. Large pipelines or concurrent bursts that cross that
+    /// threshold fall through to `store_lock.write()` + exact `serialized_size()`.
+    fn try_reserve_fast(&self, est: u64) -> bool {
+        use std::sync::atomic::Ordering;
+        let fast_limit = self.cap.saturating_sub(NEAR_CAP_MARGIN);
+        if est > fast_limit { return false; }
+        let mut cur = self.estimated_size.load(Ordering::Acquire);
+        loop {
+            let Some(next) = cur.checked_add(est) else { return false };
+            if next > fast_limit { return false; }
+            match self.estimated_size.compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire) {
+                Ok(_) => return true,
+                Err(actual) => cur = actual,
+            }
+        }
+    }
+
+    fn can_store_locked(&self, est: u64) -> bool {
+        use std::sync::atomic::Ordering;
+        if self.full.load(Ordering::Acquire) { return false; }
+        let current = self.library.serialized_size();
+        self.estimated_size.store(current, Ordering::Release);
+        if current >= self.cap {
+            self.mark_full(current);
+            return false;
+        }
+        if current.saturating_add(est) > self.cap {
+            if est <= NEAR_CAP_MARGIN {
+                self.mark_full(current);
+            }
+            return false;
+        }
+        true
+    }
+}
+
+enum StoreOutcome {
+    /// Pipeline is present and usable in `runtime.library` (newly stored or verified existing).
+    Usable,
+    /// `E_INVALIDARG` on a name whose `Load*` failed in this run: existing entry is unusable
+    /// and cannot be replaced in-place, so stop retrying without marking it handed out.
+    UnusableExisting,
+    /// Transient store error (e.g. `E_OUTOFMEMORY`): leave out of `known` so a later call can retry.
+    TransientError,
+}
+
+fn record_store_result(runtime: &Runtime, name: &str, result: Result<()>) -> StoreOutcome {
+    match result {
+        Ok(()) => {
+            runtime.added.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
+            runtime.load_missed.lock().unwrap().remove(name);
+            StoreOutcome::Usable
+        }
+        Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => {
+            if runtime.load_missed.lock().unwrap().contains(name) {
+                crate::xlog_warn!(
+                    "Pipeline library: {name} already exists in {} but failed to load; not marking usable",
+                    runtime.path.display()
+                );
+                StoreOutcome::UnusableExisting
+            } else {
+                StoreOutcome::Usable
+            }
+        }
+        Err(e) => {
+            crate::xlog_warn!("Pipeline library: keeping {name}: {e}");
+            StoreOutcome::TransientError
+        }
+    }
+}
+
+fn read_cached_blob(pipeline: &ID3D12PipelineState) -> Option<Vec<u8>> {
+    // Use the adoption-aware helper because the first hand-out of a COM object from a pipeline
+    // library may have been adopted (swapping its vtable pointer to XCL's console ext class).
+    unsafe { crate::hle::d3d12x::real::read_pso_cached_blob(pipeline.as_raw()) }
+}
+
+impl Active {
+    fn with_name(
+        &self,
+        name: &str,
+        kind: super::pipeline_stats::Kind,
+        f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>,
+        prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>,
+    ) -> Option<Loaded> {
+        use super::pipeline_stats::{library, Source};
+        let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len();
+        let _same_name = self.names[slot].lock().unwrap();
+        let already_handed = self.handed.lock().unwrap().contains(name);
+        let (found, source) = if let Some(found) = prepared(self).and_then(|lib| f(lib).ok()) {
+            (found, Source::Prepared)
+        } else {
+            let runtime = self.runtime.as_ref()?;
+            match f(&runtime.library) {
+                Ok(found) => (found, Source::Runtime),
+                Err(_) => {
+                    runtime.load_missed.lock().unwrap().insert(name.into());
+                    return None;
+                }
+            }
+        };
+        if let Some(runtime) = &self.runtime {
+            runtime.load_missed.lock().unwrap().remove(name);
+            runtime.known.lock().unwrap().insert(name.into());
+        }
+        if already_handed {
+            // A library loads a name as the same COM object each time, and XCL keys what it knows
+            // of a pipeline by its object (a dispatch chain by its first piece: a second chain
+            // with that piece replaced the first, and the replaced one's release deadlocked on the
+            // chain table). Hand out its cached blob instead so the caller creates a distinct COM
+            // object without recompiling in the driver, even for small shaders below the RAM blob
+            // cache threshold.
+            return read_cached_blob(&found).map(Loaded::Blob);
+        }
+        library(kind, source);
+        self.handed.lock().unwrap().insert(name.into());
+        Some(Loaded::Pipeline(found))
+    }
+
+    fn apply_store_outcome(&self, runtime: &Runtime, name: &str, outcome: StoreOutcome) {
+        match outcome {
+            StoreOutcome::Usable => {
+                runtime.known.lock().unwrap().insert(name.into());
+                // (a load may give back the very object stored: this one is out already)
+                self.handed.lock().unwrap().insert(name.into());
+            }
+            StoreOutcome::UnusableExisting => {
+                runtime.known.lock().unwrap().insert(name.into());
+            }
+            StoreOutcome::TransientError => {}
+        }
+    }
+
+    /// A pipeline built at runtime, kept in `runtime.plib` (one found in a library is not kept again).
+    fn store_runtime(&self, name: &str, pipeline: &ID3D12PipelineState) {
+        use std::sync::atomic::Ordering;
+        let Some(runtime) = self.runtime.as_ref() else { return };
+        if name.is_empty() || runtime.full.load(Ordering::Acquire) { return }
+        let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len();
+        let _same_name = self.names[slot].lock().unwrap();
+        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 };
+        // Reserve while holding `store_lock.read()` so a concurrent `store_lock.write()` holder
+        // can never reset `estimated_size` while an unstored fast-path reservation is in flight.
+        let outcome = {
+            let read_guard = runtime.store_lock.read().unwrap();
+            if runtime.full.load(Ordering::Acquire) { return }
+            if runtime.try_reserve_fast(est) {
+                record_store_result(runtime, name, runtime.library.store(name, pipeline))
+            } else {
+                drop(read_guard);
+                let _write_guard = runtime.store_lock.write().unwrap();
+                if !runtime.can_store_locked(est) { return }
+                let outcome = record_store_result(runtime, name, runtime.library.store(name, pipeline));
+                let after = runtime.library.serialized_size();
+                runtime.estimated_size.store(after, Ordering::Release);
+                if matches!(outcome, StoreOutcome::Usable) && after >= runtime.cap {
+                    runtime.mark_full(after);
+                }
+                outcome
+            }
+        };
+        self.apply_store_outcome(runtime, name, outcome);
+    }
+}
+
+fn with_name(
+    name: &str,
+    kind: super::pipeline_stats::Kind,
+    f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>,
+    prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>,
+) -> Option<Loaded> {
+    ACTIVE.get()?.with_name(name, kind, f, prepared)
+}
+
+fn store_runtime(name: &str, pipeline: &ID3D12PipelineState) {
+    if let Some(active) = ACTIVE.get() { active.store_runtime(name, pipeline); }
+}
+
+/// One build of a pipeline at a time while the title runs (`one_build`).
+struct OneBuildFlights {
+    building: std::sync::Mutex<Option<std::collections::HashMap<String, (std::thread::ThreadId, u64)>>>,
+    next_id: std::sync::atomic::AtomicU64,
+    built: std::sync::Condvar,
+}
+
+impl OneBuildFlights {
+    const fn new() -> Self {
+        Self {
+            building: std::sync::Mutex::new(None),
+            next_id: std::sync::atomic::AtomicU64::new(0),
+            built: std::sync::Condvar::new(),
+        }
+    }
+
+    fn enter(&self, name: &str, wait: std::time::Duration) -> OneBuildGuard<'_> {
+        let until = std::time::Instant::now() + wait;
+        let mut building = self.building.lock().unwrap();
+        while building.as_ref().is_some_and(|b| b.contains_key(name)) {
+            let left = until.saturating_duration_since(std::time::Instant::now());
+            if left.is_zero() {
+                crate::xlog_info!("Pipeline library: still waiting for another build of {name} after {} s; building it here too", wait.as_secs());
+                return OneBuildGuard { flights: self, flight: None };
+            }
+            building = self.built.wait_timeout(building, left).unwrap().0;
+        }
+        let id = self.next_id.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
+        building.get_or_insert_with(Default::default).insert(name.to_owned(), (std::thread::current().id(), id));
+        OneBuildGuard { flights: self, flight: Some((name.to_owned(), id)) }
+    }
+
+    /// Releases any in-flight build(s) owned by the current thread so a worker parked at the
+    /// compile gate does not stall an ungated title thread waiting on the same pipeline name.
+    fn release_current_thread(&self) {
+        let me = std::thread::current().id();
+        let mut building = self.building.lock().unwrap();
+        let Some(map) = building.as_mut() else { return };
+        let before = map.len();
+        map.retain(|_, (tid, _)| *tid != me);
+        if map.len() != before {
+            self.built.notify_all();
+        }
+    }
+}
+
+static FLIGHTS: OneBuildFlights = OneBuildFlights::new();
+
+/// While held, no other thread builds the pipeline of this name.
+pub(crate) struct OneBuildGuard<'a> {
+    flights: &'a OneBuildFlights,
+    flight: Option<(String, u64)>,
+}
+
+pub(crate) type OneBuild = OneBuildGuard<'static>;
+
+impl Drop for OneBuildGuard<'_> {
+    fn drop(&mut self) {
+        let Some((name, id)) = self.flight.take() else { return };
+        let mut removed = false;
+        if let Some(building) = self.flights.building.lock().unwrap().as_mut() {
+            if building.get(&name).is_some_and(|&(_, cur)| cur == id) {
+                building.remove(&name);
+                removed = true;
+            }
+        }
+        if removed {
+            self.flights.built.notify_all();
+        }
+    }
+}
+
+/// Releases any `one_build` flight owned by the current thread when it parks in the compile gate.
+pub(crate) fn release_one_build_on_park() {
+    FLIGHTS.release_current_thread();
+}
+
+/// Up to `XCL_ONE_BUILD_WAIT_S` (60) for another thread's build of this name to end: that one is
+/// 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 {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773829837 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773829837). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T18:17:25Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 738 ~~~~diff @@ -20,39 +20,729 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later + /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept. + load_missed: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the + /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`. + estimated_size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); -pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - let Some(ready) = super::warm_library::take_ready() else { return Ok(()) }; - let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) - .ok_or("Pipeline library: runtime driver identity is unavailable")?; - if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } - let open = |bytes| NativeLibrary::open_shared(device, bytes); - let graphics = ready.graphics.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; - let compute = ready.compute.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { - crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let initial_size = library.serialized_size(); + let full = initial_size >= cap; + Some(Runtime { + library, + path, + cap, + known: Default::default(), + load_missed: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + estimated_size: initial_size.into(), + full: full.into(), + }) +} + +fn check_activation_driver( + ready_driver: u64, + runtime_driver: Option<u64>, + has_prepared: bool, + cache_only: bool, +) -> std::result::Result<bool, String> { + if runtime_driver == Some(ready_driver) { + return Ok(true); + } + let reason = if runtime_driver.is_none() { + "Pipeline library: runtime driver identity is unavailable" + } else { + "Pipeline library: runtime adapter or driver differs from the prepared cache" + }; + if cache_only && has_prepared { + return Err(reason.into()); + } + if has_prepared { + crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib"); + } + Ok(false) +} + +fn open_active_for_device( + device: &ID3D12Device, + ready: super::warm_library::Ready, + runtime_driver: Option<u64>, + cache_only: bool, +) -> 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) { + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + return Ok(None); + } + let open = |bytes| NativeLibrary::open_shared(device, bytes); + let graphics = if use_prepared { + ready.graphics.map(open).transpose() + .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))? + } else { + None + }; + let compute = if use_prepared { + ready.compute.map(open).transpose() + .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))? + } else { + None + }; + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + Ok(Some(Active { graphics, compute, runtime, names, handed: Default::default() })) +} + +pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { + 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; + let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device); + let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1"); + let Some(active) = open_active_for_device(device, ready, runtime_driver, cache_only)? else { + return Ok(()); + }; + start_counting(); + let has_any_prepared = active.graphics.is_some() || active.compute.is_some(); + let has_runtime = active.runtime.is_some(); + if ACTIVE.set(active).is_ok() { + if has_any_prepared { + crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); + } else if has_runtime { + crate::xlog_info!("Pipeline library: activated runtime library for lazy runtime loading"); + } } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +static PERIODIC_FLUSH_TID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + PERIODIC_FLUSH_TID.store(tid, std::sync::atomic::Ordering::Release); + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + since += 1; + if since >= flush_every() { + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { + runtime.mark_full(current); + state.disabled = true; + crate::xlog_warn!( + "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library", + runtime.path.display(), current, runtime.cap + ); + return false; + } + let bytes = match serialize_runtime(runtime) { + Ok(b) => b, + Err(e) => { + state.consecutive_failures += 1; + if state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display()); + } + return false; + } + }; + if bytes.len() as u64 > runtime.cap { + 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", + runtime.path.display(), bytes.len(), runtime.cap + ); + return false; + } + match write(&runtime.path, &bytes) { + Ok(()) => { + state.consecutive_failures = 0; + runtime.size.store(bytes.len() as u64, Ordering::Relaxed); + crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})", + bytes.len(), runtime.path.display()); + true + } + Err(e) => { + state.consecutive_failures += 1; + if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display()); + } + false + } + } +} + +/// Writes `runtime.plib` again when pipelines were added to it since it was last written. +pub(crate) fn flush_runtime() { + let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return }; + flush_runtime_on(runtime, write_atomic); +} + +/// Runs `f` on a helper thread up to `timeout`. Returns `None` if it finished (or could not +/// spawn), or `Some(tid)` with the helper's OS thread ID when it is still running at timeout. +fn run_with_timeout(name: &str, timeout: std::time::Duration, f: impl FnOnce() + Send + 'static) -> Option<u32> { + let (tid_tx, tid_rx) = std::sync::mpsc::sync_channel(1); + let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1); + if std::thread::Builder::new().name(name.into()).spawn(move || { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let _ = tid_tx.send(tid); + f(); + let _ = done_tx.send(()); + }).is_err() { + return None; + } + let deadline = std::time::Instant::now() + timeout; + let tid = tid_rx.recv_timeout(timeout).unwrap_or(0); + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); + match done_rx.recv_timeout(remaining) { + Ok(()) => None, + Err(_) => Some(tid), + } +} + +/// Bounded `flush_runtime` for title shutdown (`end_title`, `WM_CLOSE`): returns `[0, 0]` when +/// nothing is pending/in-flight or the flush finishes within `timeout`. On timeout, returns the OS +/// thread IDs of the active flush threads so `end_title` can exclude them from thread suspension +/// (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() { + if state.disabled || runtime.added.load(std::sync::atomic::Ordering::Acquire) == 0 { + return [0, 0]; + } + } + let Some(end_tid) = run_with_timeout("xcl-plib-end-flush", timeout, move || { + flush_runtime_on(runtime, write_atomic); + }) else { + return [0, 0]; + }; + crate::xlog_warn!( + "Pipeline library: shutdown flush of {} did not finish within {} ms; continuing shutdown", + runtime.path.display(), timeout.as_millis() + ); + [end_tid, PERIODIC_FLUSH_TID.load(std::sync::atomic::Ordering::Acquire)] +} + +fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> { + unsafe { crate::hle::d3d12x::real::pso_cached_blob_size(pipeline.as_raw()) } +} + +fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = cached_blob_size(pipeline)?; + let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2); + Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD)) +} + +impl Runtime { + fn mark_full(&self, bytes: u64) { + if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) { + crate::xlog_info!( + "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions", + self.path.display(), bytes, self.cap + ); + } + } + + /// Reserves `est` bytes on the lock-free read path only while the cumulative estimate stays at + /// least `NEAR_CAP_MARGIN` below `cap`. Large pipelines or concurrent bursts that cross that + /// threshold fall through to `store_lock.write()` + exact `serialized_size()`. + fn try_reserve_fast(&self, est: u64) -> bool { + use std::sync::atomic::Ordering; + let fast_limit = self.cap.saturating_sub(NEAR_CAP_MARGIN); + if est > fast_limit { return false; } + let mut cur = self.estimated_size.load(Ordering::Acquire); + loop { + let Some(next) = cur.checked_add(est) else { return false }; + if next > fast_limit { return false; } + match self.estimated_size.compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return true, + Err(actual) => cur = actual, + } + } + } + + fn can_store_locked(&self, est: u64) -> bool { + use std::sync::atomic::Ordering; + if self.full.load(Ordering::Acquire) { return false; } + let current = self.library.serialized_size(); + self.estimated_size.store(current, Ordering::Release); + if current >= self.cap { + self.mark_full(current); + return false; + } + if current.saturating_add(est) > self.cap { + if est <= NEAR_CAP_MARGIN { + self.mark_full(current); + } + return false; + } + true + } +} + +enum StoreOutcome { + /// Pipeline is present and usable in `runtime.library` (newly stored or verified existing). + Usable, + /// `E_INVALIDARG` on a name whose `Load*` failed in this run: existing entry is unusable + /// and cannot be replaced in-place, so stop retrying without marking it handed out. + UnusableExisting, + /// Transient store error (e.g. `E_OUTOFMEMORY`): leave out of `known` so a later call can retry. + TransientError, +} + +fn record_store_result(runtime: &Runtime, name: &str, result: Result<()>) -> StoreOutcome { + match result { + Ok(()) => { + runtime.added.fetch_add(1, std::sync::atomic::Ordering::AcqRel); + runtime.load_missed.lock().unwrap().remove(name); + StoreOutcome::Usable + } + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => { + if runtime.load_missed.lock().unwrap().contains(name) { + crate::xlog_warn!( + "Pipeline library: {name} already exists in {} but failed to load; not marking usable", + runtime.path.display() + ); + StoreOutcome::UnusableExisting + } else { + StoreOutcome::Usable + } + } + Err(e) => { + crate::xlog_warn!("Pipeline library: keeping {name}: {e}"); + StoreOutcome::TransientError + } + } +} + +fn read_cached_blob(pipeline: &ID3D12PipelineState) -> Option<Vec<u8>> { + // Use the adoption-aware helper because the first hand-out of a COM object from a pipeline + // library may have been adopted (swapping its vtable pointer to XCL's console ext class). + unsafe { crate::hle::d3d12x::real::read_pso_cached_blob(pipeline.as_raw()) } +} + +impl Active { + fn with_name( + &self, + name: &str, + kind: super::pipeline_stats::Kind, + f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>, + prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>, + ) -> Option<Loaded> { + use super::pipeline_stats::{library, Source}; + let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len(); + let _same_name = self.names[slot].lock().unwrap(); + let already_handed = self.handed.lock().unwrap().contains(name); + let (found, source) = if let Some(found) = prepared(self).and_then(|lib| f(lib).ok()) { + (found, Source::Prepared) + } else { + let runtime = self.runtime.as_ref()?; + match f(&runtime.library) { + Ok(found) => (found, Source::Runtime), + Err(_) => { + runtime.load_missed.lock().unwrap().insert(name.into()); + return None; + } + } + }; + if let Some(runtime) = &self.runtime { + runtime.load_missed.lock().unwrap().remove(name); + runtime.known.lock().unwrap().insert(name.into()); + } + if already_handed { + // A library loads a name as the same COM object each time, and XCL keys what it knows + // of a pipeline by its object (a dispatch chain by its first piece: a second chain + // with that piece replaced the first, and the replaced one's release deadlocked on the + // chain table). Hand out its cached blob instead so the caller creates a distinct COM + // object without recompiling in the driver, even for small shaders below the RAM blob + // cache threshold. + return read_cached_blob(&found).map(Loaded::Blob); + } + library(kind, source); + self.handed.lock().unwrap().insert(name.into()); + Some(Loaded::Pipeline(found)) + } + + fn apply_store_outcome(&self, runtime: &Runtime, name: &str, outcome: StoreOutcome) { + match outcome { + StoreOutcome::Usable => { + runtime.known.lock().unwrap().insert(name.into()); + // (a load may give back the very object stored: this one is out already) + self.handed.lock().unwrap().insert(name.into()); + } + StoreOutcome::UnusableExisting => { + runtime.known.lock().unwrap().insert(name.into()); + } + StoreOutcome::TransientError => {} + } + } + + /// A pipeline built at runtime, kept in `runtime.plib` (one found in a library is not kept again). + fn store_runtime(&self, name: &str, pipeline: &ID3D12PipelineState) { + use std::sync::atomic::Ordering; + let Some(runtime) = self.runtime.as_ref() else { return }; + if name.is_empty() || runtime.full.load(Ordering::Acquire) { return } + let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len(); + let _same_name = self.names[slot].lock().unwrap(); + 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 }; + // Reserve while holding `store_lock.read()` so a concurrent `store_lock.write()` holder + // can never reset `estimated_size` while an unstored fast-path reservation is in flight. + let outcome = { + let read_guard = runtime.store_lock.read().unwrap(); + if runtime.full.load(Ordering::Acquire) { return } + if runtime.try_reserve_fast(est) { + record_store_result(runtime, name, runtime.library.store(name, pipeline)) + } else { + drop(read_guard); + let _write_guard = runtime.store_lock.write().unwrap(); + if !runtime.can_store_locked(est) { return } + let outcome = record_store_result(runtime, name, runtime.library.store(name, pipeline)); + let after = runtime.library.serialized_size(); + runtime.estimated_size.store(after, Ordering::Release); + if matches!(outcome, StoreOutcome::Usable) && after >= runtime.cap { + runtime.mark_full(after); + } + outcome + } + }; + self.apply_store_outcome(runtime, name, outcome); + } +} + +fn with_name( + name: &str, + kind: super::pipeline_stats::Kind, + f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>, + prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>, +) -> Option<Loaded> { + ACTIVE.get()?.with_name(name, kind, f, prepared) +} + +fn store_runtime(name: &str, pipeline: &ID3D12PipelineState) { + if let Some(active) = ACTIVE.get() { active.store_runtime(name, pipeline); } +} + +/// One build of a pipeline at a time while the title runs (`one_build`). +struct OneBuildFlights { + building: std::sync::Mutex<Option<std::collections::HashMap<String, (std::thread::ThreadId, u64)>>>, + next_id: std::sync::atomic::AtomicU64, + built: std::sync::Condvar, +} + +impl OneBuildFlights { + const fn new() -> Self { + Self { + building: std::sync::Mutex::new(None), + next_id: std::sync::atomic::AtomicU64::new(0), + built: std::sync::Condvar::new(), + } + } + + fn enter(&self, name: &str, wait: std::time::Duration) -> OneBuildGuard<'_> { + let until = std::time::Instant::now() + wait; + let mut building = self.building.lock().unwrap(); + while building.as_ref().is_some_and(|b| b.contains_key(name)) { + let left = until.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + crate::xlog_info!("Pipeline library: still waiting for another build of {name} after {} s; building it here too", wait.as_secs()); + return OneBuildGuard { flights: self, flight: None }; + } + building = self.built.wait_timeout(building, left).unwrap().0; + } + let id = self.next_id.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + building.get_or_insert_with(Default::default).insert(name.to_owned(), (std::thread::current().id(), id)); + OneBuildGuard { flights: self, flight: Some((name.to_owned(), id)) } + } + + /// Releases any in-flight build(s) owned by the current thread so a worker parked at the + /// compile gate does not stall an ungated title thread waiting on the same pipeline name. + fn release_current_thread(&self) { + let me = std::thread::current().id(); + let mut building = self.building.lock().unwrap(); + let Some(map) = building.as_mut() else { return }; + let before = map.len(); + map.retain(|_, (tid, _)| *tid != me); + if map.len() != before { + self.built.notify_all(); + } + } +} + +static FLIGHTS: OneBuildFlights = OneBuildFlights::new(); + +/// While held, no other thread builds the pipeline of this name. +pub(crate) struct OneBuildGuard<'a> { + flights: &'a OneBuildFlights, + flight: Option<(String, u64)>, +} + +pub(crate) type OneBuild = OneBuildGuard<'static>; + +impl Drop for OneBuildGuard<'_> { + fn drop(&mut self) { + let Some((name, id)) = self.flight.take() else { return }; + let mut removed = false; + if let Some(building) = self.flights.building.lock().unwrap().as_mut() { + if building.get(&name).is_some_and(|&(_, cur)| cur == id) { + building.remove(&name); + removed = true; + } + } + if removed { + self.flights.built.notify_all(); + } + } +} + +/// Releases any `one_build` flight owned by the current thread when it parks in the compile gate. +pub(crate) fn release_one_build_on_park() { + FLIGHTS.release_current_thread(); +} + +/// Up to `XCL_ONE_BUILD_WAIT_S` (60) for another thread's build of this name to end: that one is +/// 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 { ~~~~ --- **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.
bmjask commented 2026-12-02 18:17:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T18:17:25Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 188

@@ -20,39 +20,729 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later
+    /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept.
+    load_missed: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the
+    /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`.
+    estimated_size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so
+    /// the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
-pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    let Some(ready) = super::warm_library::take_ready() else { return Ok(()) };
-    let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
-        .ok_or("Pipeline library: runtime driver identity is unavailable")?;
-    if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
-    let open = |bytes| NativeLibrary::open_shared(device, bytes);
-    let graphics = ready.graphics.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
-    let compute = ready.compute.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
+/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+const ENTRY_OVERHEAD: u64 = 4096;
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
     }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
-        crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let bytes = bytes.filter(|b| {
+        let keep = b.len() as u64 <= cap;
+        if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); }
+        keep
+    });
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let initial_size = library.serialized_size();
+    let full = initial_size >= cap;

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773829845 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4773829845). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T18:17:25Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 188 ~~~~diff @@ -20,39 +20,729 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later + /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept. + load_missed: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the + /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`. + estimated_size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `cap`: stops further `StorePipeline` additions so + /// the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); -pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - let Some(ready) = super::warm_library::take_ready() else { return Ok(()) }; - let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) - .ok_or("Pipeline library: runtime driver identity is unavailable")?; - if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } - let open = |bytes| NativeLibrary::open_shared(device, bytes); - let graphics = ready.graphics.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; - let compute = ready.compute.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; +/// Within this distance of `Runtime::cap`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +const ENTRY_OVERHEAD: u64 = 4096; + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { - crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let bytes = bytes.filter(|b| { + let keep = b.len() as u64 <= cap; + if !keep { crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); } + keep + }); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let initial_size = library.serialized_size(); + let full = initial_size >= cap; ~~~~ --- **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 commented 2026-12-02 18:35:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T18:35:28Z.


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.)

<!-- greyfinch-sync:ivall/xcl:comment:7354842199 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7354842199). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T18:35:28Z. --- 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 commented 2026-12-02 18:49:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T18:49:27Z.

Code review location: crates/xcl/src/shaders/warm_library.rs; line 259

@@ -265,21 +242,31 @@ pub(crate) fn publish(corpus: &Corpus, device: &ID3D12Device) -> Result<(), Stri
     if let Some(bytes) = &compute_ready {
         super::pipeline_library::write_atomic(&compute, bytes).map_err(|e| e.to_string())?;
     }
-    let receipt = Receipt {
-        version: VERSION,
-        corpus: corpus_identity,
-        graphics: graphics_ready.as_ref().map(|b| Component { compatibility: compatibility.clone(), bytes: b.len() as u64 }),
-        compute: compute_ready.as_ref().map(|b| Component { compatibility, bytes: b.len() as u64 }),
-    };
-    let encoded = super::warm_replay::receipt_bytes(&receipt).ok_or("Encoding pipeline library receipt")?;
-    super::pipeline_library::write_atomic(&receipt_path, &encoded).map_err(|e| e.to_string())?;
+    if let Some(corpus_id) = corpus.identity() {
+        let receipt = Receipt {
+            version: VERSION,
+            driver,
+            windows,
+            prepared: prepared(corpus_id),
+            graphics: graphics_ready.as_ref().map(|b| b.len() as u64),
+            compute: compute_ready.as_ref().map(|b| b.len() as u64),
+        };
+        let encoded = super::warm_replay::receipt_bytes(&receipt).ok_or("Encoding pipeline library receipt")?;
+        super::pipeline_library::write_atomic(&dir.join(RECEIPT), &encoded).map_err(|e| e.to_string())?;
+    } 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));

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4774287696 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4774287696). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T18:49:27Z. **Code review location:** `crates/xcl/src/shaders/warm_library.rs`; line 259 ~~~~diff @@ -265,21 +242,31 @@ pub(crate) fn publish(corpus: &Corpus, device: &ID3D12Device) -> Result<(), Stri if let Some(bytes) = &compute_ready { super::pipeline_library::write_atomic(&compute, bytes).map_err(|e| e.to_string())?; } - let receipt = Receipt { - version: VERSION, - corpus: corpus_identity, - graphics: graphics_ready.as_ref().map(|b| Component { compatibility: compatibility.clone(), bytes: b.len() as u64 }), - compute: compute_ready.as_ref().map(|b| Component { compatibility, bytes: b.len() as u64 }), - }; - let encoded = super::warm_replay::receipt_bytes(&receipt).ok_or("Encoding pipeline library receipt")?; - super::pipeline_library::write_atomic(&receipt_path, &encoded).map_err(|e| e.to_string())?; + if let Some(corpus_id) = corpus.identity() { + let receipt = Receipt { + version: VERSION, + driver, + windows, + prepared: prepared(corpus_id), + graphics: graphics_ready.as_ref().map(|b| b.len() as u64), + compute: compute_ready.as_ref().map(|b| b.len() as u64), + }; + let encoded = super::warm_replay::receipt_bytes(&receipt).ok_or("Encoding pipeline library receipt")?; + super::pipeline_library::write_atomic(&dir.join(RECEIPT), &encoded).map_err(|e| e.to_string())?; + } 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)); ~~~~ --- **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.
bmjask commented 2026-12-02 18:49:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T18:49:27Z.

Code review location: crates/xcl/src/hle/d3d12x/real.rs; line 9578

@@ -9469,11 +9575,17 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu:
     let gkey = disk_key.map(|(hash, bytes)| (hash, bytes, mesh_rs as usize));
     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)));

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4774287702 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4774287702). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T18:49:27Z. **Code review location:** `crates/xcl/src/hle/d3d12x/real.rs`; line 9578 ~~~~diff @@ -9469,11 +9575,17 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let gkey = disk_key.map(|(hash, bytes)| (hash, bytes, mesh_rs as usize)); 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))); ~~~~ --- **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.
bmjask commented 2026-12-02 18:49:27 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T18:49:27Z.

Review: COMMENTED


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.

<!-- greyfinch-sync:ivall/xcl:review:6156821596 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#pullrequestreview-6156821596). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T18:49:27Z. **Review:** COMMENTED --- 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._
Kalmarv commented 2026-12-02 19:09:04 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T19:09:04Z.


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.)

<!-- greyfinch-sync:ivall/xcl:comment:7355697760 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7355697760). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T19:09:04Z. --- 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 commented 2026-12-02 19:21:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:21:36Z.

Code review location: crates/xcl/src/hle/d3d12x/real.rs; line 8336

@@ -8234,7 +8333,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const
         GRAPHICS_BLOBS.admit(gkey, cached.as_ref().unwrap().clone(), GRAPHICS_BLOBS_MAX);
         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() {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4774712873 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4774712873). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:21:36Z. **Code review location:** `crates/xcl/src/hle/d3d12x/real.rs`; line 8336 ~~~~diff @@ -8234,7 +8333,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const GRAPHICS_BLOBS.admit(gkey, cached.as_ref().unwrap().clone(), GRAPHICS_BLOBS_MAX); 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() { ~~~~ --- **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.
bmjask commented 2026-12-02 19:21:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:21:36Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 233

@@ -20,39 +20,797 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later
+    /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept.
+    load_missed: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the
+    /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`.
+    estimated_size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `admit_cap(cap)`: stops further `StorePipeline`
+    /// additions so the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
+    /// Build/settings stamp written next to `runtime.plib` when a fresh library is first flushed.
+    stamp: String,
+    /// True when `runtime.stamp` should be written on the next successful flush (fresh library
+    /// or upgrade from a library with no stamp file yet).
+    write_stamp: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
-pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    let Some(ready) = super::warm_library::take_ready() else { return Ok(()) };
-    let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
-        .ok_or("Pipeline library: runtime driver identity is unavailable")?;
-    if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
-    let open = |bytes| NativeLibrary::open_shared(device, bytes);
-    let graphics = ready.graphics.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
-    let compute = ready.compute.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
+/// Within this distance of `admit_cap(Runtime::cap)`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+/// Conservative per-entry overhead above `GetCachedBlob()` + UTF-16 name to cover root signature,
+/// input layout, and pipeline-desc subobjects serialized by D3D12.
+const ENTRY_OVERHEAD: u64 = 64 << 10;
+/// Safety buffer below `cap` where admission stops (for real caps >= 16 MiB), so minor D3D12
+/// directory/metadata growth on the final admitted store cannot push `flush_runtime_on` over `cap`.
+const CAP_ADMIT_HEADROOM: u64 = 2 << 20;
+
+fn admit_cap(cap: u64) -> u64 {
+    if cap >= (16 << 20) { cap.saturating_sub(CAP_ADMIT_HEADROOM) } else { cap }
+}
+
+fn runtime_stamp() -> String {
+    format!(
+        "{}:{:016x}:{:016x}",
+        env!("XCL_PIPELINE_LAYOUT_ID"),
+        crate::gpu::recomp::pso::translation_cache_identity(),
+        super::warm_settings_key(),
+    )
+}
+
+fn stamp_path(path: &std::path::Path) -> std::path::PathBuf {
+    path.with_extension("stamp")
+}
+
+fn should_reset_full_runtime(existing_len: u64, cap: u64, saved_stamp: Option<&str>, current_stamp: &str) -> bool {
+    existing_len >= admit_cap(cap) && saved_stamp.map(str::trim) != Some(current_stamp)
+}
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let current_stamp = runtime_stamp();
+    let saved_stamp = std::fs::read_to_string(stamp_path(&path)).ok();
+    let bytes = bytes.filter(|b| {
+        if b.len() as u64 > cap {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            return false;
+        }
+        if should_reset_full_runtime(b.len() as u64, cap, saved_stamp.as_deref(), &current_stamp) {
+            crate::xlog_info!(
+                "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB and contains entries from an older build or settings; starting it fresh",
+                path.display()
+            );
+            return false;
+        }
+        true
+    });
+    let mut started_fresh = bytes.is_none();
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            started_fresh = true;
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let initial_size = library.serialized_size();
+    let full = initial_size >= admit_cap(cap);
+    let write_stamp = started_fresh || saved_stamp.is_none();

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4774712884 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4774712884). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:21:36Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 233 ~~~~diff @@ -20,39 +20,797 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later + /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept. + load_missed: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the + /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`. + estimated_size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `admit_cap(cap)`: stops further `StorePipeline` + /// additions so the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, + /// Build/settings stamp written next to `runtime.plib` when a fresh library is first flushed. + stamp: String, + /// True when `runtime.stamp` should be written on the next successful flush (fresh library + /// or upgrade from a library with no stamp file yet). + write_stamp: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); -pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - let Some(ready) = super::warm_library::take_ready() else { return Ok(()) }; - let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) - .ok_or("Pipeline library: runtime driver identity is unavailable")?; - if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } - let open = |bytes| NativeLibrary::open_shared(device, bytes); - let graphics = ready.graphics.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; - let compute = ready.compute.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; +/// Within this distance of `admit_cap(Runtime::cap)`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +/// Conservative per-entry overhead above `GetCachedBlob()` + UTF-16 name to cover root signature, +/// input layout, and pipeline-desc subobjects serialized by D3D12. +const ENTRY_OVERHEAD: u64 = 64 << 10; +/// Safety buffer below `cap` where admission stops (for real caps >= 16 MiB), so minor D3D12 +/// directory/metadata growth on the final admitted store cannot push `flush_runtime_on` over `cap`. +const CAP_ADMIT_HEADROOM: u64 = 2 << 20; + +fn admit_cap(cap: u64) -> u64 { + if cap >= (16 << 20) { cap.saturating_sub(CAP_ADMIT_HEADROOM) } else { cap } +} + +fn runtime_stamp() -> String { + format!( + "{}:{:016x}:{:016x}", + env!("XCL_PIPELINE_LAYOUT_ID"), + crate::gpu::recomp::pso::translation_cache_identity(), + super::warm_settings_key(), + ) +} + +fn stamp_path(path: &std::path::Path) -> std::path::PathBuf { + path.with_extension("stamp") +} + +fn should_reset_full_runtime(existing_len: u64, cap: u64, saved_stamp: Option<&str>, current_stamp: &str) -> bool { + existing_len >= admit_cap(cap) && saved_stamp.map(str::trim) != Some(current_stamp) +} + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let current_stamp = runtime_stamp(); + let saved_stamp = std::fs::read_to_string(stamp_path(&path)).ok(); + let bytes = bytes.filter(|b| { + if b.len() as u64 > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return false; + } + if should_reset_full_runtime(b.len() as u64, cap, saved_stamp.as_deref(), &current_stamp) { + crate::xlog_info!( + "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB and contains entries from an older build or settings; starting it fresh", + path.display() + ); + return false; + } + true + }); + let mut started_fresh = bytes.is_none(); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + started_fresh = true; + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let initial_size = library.serialized_size(); + let full = initial_size >= admit_cap(cap); + let write_stamp = started_fresh || saved_stamp.is_none(); ~~~~ --- **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.
bmjask commented 2026-12-02 19:21:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:21:36Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 499

@@ -20,39 +20,797 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later
+    /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept.
+    load_missed: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the
+    /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`.
+    estimated_size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `admit_cap(cap)`: stops further `StorePipeline`
+    /// additions so the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
+    /// Build/settings stamp written next to `runtime.plib` when a fresh library is first flushed.
+    stamp: String,
+    /// True when `runtime.stamp` should be written on the next successful flush (fresh library
+    /// or upgrade from a library with no stamp file yet).
+    write_stamp: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
-pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    let Some(ready) = super::warm_library::take_ready() else { return Ok(()) };
-    let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
-        .ok_or("Pipeline library: runtime driver identity is unavailable")?;
-    if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
-    let open = |bytes| NativeLibrary::open_shared(device, bytes);
-    let graphics = ready.graphics.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
-    let compute = ready.compute.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
+/// Within this distance of `admit_cap(Runtime::cap)`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+/// Conservative per-entry overhead above `GetCachedBlob()` + UTF-16 name to cover root signature,
+/// input layout, and pipeline-desc subobjects serialized by D3D12.
+const ENTRY_OVERHEAD: u64 = 64 << 10;
+/// Safety buffer below `cap` where admission stops (for real caps >= 16 MiB), so minor D3D12
+/// directory/metadata growth on the final admitted store cannot push `flush_runtime_on` over `cap`.
+const CAP_ADMIT_HEADROOM: u64 = 2 << 20;
+
+fn admit_cap(cap: u64) -> u64 {
+    if cap >= (16 << 20) { cap.saturating_sub(CAP_ADMIT_HEADROOM) } else { cap }
+}
+
+fn runtime_stamp() -> String {
+    format!(
+        "{}:{:016x}:{:016x}",
+        env!("XCL_PIPELINE_LAYOUT_ID"),
+        crate::gpu::recomp::pso::translation_cache_identity(),
+        super::warm_settings_key(),
+    )
+}
+
+fn stamp_path(path: &std::path::Path) -> std::path::PathBuf {
+    path.with_extension("stamp")
+}
+
+fn should_reset_full_runtime(existing_len: u64, cap: u64, saved_stamp: Option<&str>, current_stamp: &str) -> bool {
+    existing_len >= admit_cap(cap) && saved_stamp.map(str::trim) != Some(current_stamp)
+}
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let current_stamp = runtime_stamp();
+    let saved_stamp = std::fs::read_to_string(stamp_path(&path)).ok();
+    let bytes = bytes.filter(|b| {
+        if b.len() as u64 > cap {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            return false;
+        }
+        if should_reset_full_runtime(b.len() as u64, cap, saved_stamp.as_deref(), &current_stamp) {
+            crate::xlog_info!(
+                "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB and contains entries from an older build or settings; starting it fresh",
+                path.display()
+            );
+            return false;
+        }
+        true
+    });
+    let mut started_fresh = bytes.is_none();
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            started_fresh = true;
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let initial_size = library.serialized_size();
+    let full = initial_size >= admit_cap(cap);
+    let write_stamp = started_fresh || saved_stamp.is_none();
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        load_missed: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        estimated_size: initial_size.into(),
+        full: full.into(),
+        stamp: current_stamp,
+        write_stamp: write_stamp.into(),
+    })
+}
+
+fn check_library_support(supported: bool, has_prepared: bool, cache_only: bool) -> std::result::Result<bool, String> {
+    if supported {
+        return Ok(true);
     }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
-        crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+    if cache_only && has_prepared {
+        return Err("Pipeline library: the device does not support pipeline libraries".into());
+    }
+    crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+    Ok(false)
+}
+
+fn check_activation_driver(
+    ready_driver: u64,
+    runtime_driver: Option<u64>,
+    has_prepared: bool,
+    cache_only: bool,
+) -> std::result::Result<bool, String> {
+    if runtime_driver == Some(ready_driver) {
+        return Ok(true);
+    }
+    let reason = if runtime_driver.is_none() {
+        "Pipeline library: runtime driver identity is unavailable"
+    } else {
+        "Pipeline library: runtime adapter or driver differs from the prepared cache"
+    };
+    if cache_only && has_prepared {
+        return Err(reason.into());
+    }
+    if has_prepared {
+        crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib");
+    }
+    Ok(false)
+}
+
+fn open_active_for_device(
+    device: &ID3D12Device,
+    ready: super::warm_library::Ready,
+    runtime_driver: Option<u64>,
+    cache_only: bool,
+) -> 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 !check_library_support(NativeLibrary::supported(device), has_prepared, cache_only)? {
+        return Ok(None);
+    }
+    let open = |bytes| NativeLibrary::open_shared(device, bytes);
+    let graphics = if use_prepared {
+        ready.graphics.map(open).transpose()
+            .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?
+    } else {
+        None
+    };
+    let compute = if use_prepared {
+        ready.compute.map(open).transpose()
+            .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?
+    } else {
+        None
+    };
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    Ok(Some(Active { graphics, compute, runtime, names, handed: Default::default() }))
+}
+
+pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
+    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
+    let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device);
+    let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1");
+    let Some(active) = open_active_for_device(device, ready, runtime_driver, cache_only)? else {
+        return Ok(());
+    };
+    start_counting();
+    let has_any_prepared = active.graphics.is_some() || active.compute.is_some();
+    let has_runtime = active.runtime.is_some();
+    if ACTIVE.set(active).is_ok() {
+        if has_any_prepared {
+            crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+        } else if has_runtime {
+            crate::xlog_info!("Pipeline library: activated runtime library for lazy runtime loading");
+        }
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+static PERIODIC_FLUSH_TID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
+            PERIODIC_FLUSH_TID.store(tid, std::sync::atomic::Ordering::Release);
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                since += 1;
+                if since >= flush_every() {
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {
+        runtime.mark_full(current);
+        state.disabled = true;
+        crate::xlog_warn!(
+            "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",
+            runtime.path.display(), current, runtime.cap
+        );
+        return false;
+    }
+    let bytes = match serialize_runtime(runtime) {
+        Ok(b) => b,
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display());
+            }
+            return false;
+        }
+    };
+    if bytes.len() as u64 > runtime.cap {
+        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",
+            runtime.path.display(), bytes.len(), runtime.cap
+        );
+        return false;
+    }
+    match write(&runtime.path, &bytes) {
+        Ok(()) => {
+            state.consecutive_failures = 0;
+            runtime.size.store(bytes.len() as u64, Ordering::Relaxed);
+            if runtime.write_stamp.swap(false, Ordering::AcqRel) {
+                let _ = write_atomic(&stamp_path(&runtime.path), runtime.stamp.as_bytes());
+            }
+            crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})",
+                bytes.len(), runtime.path.display());
+            true
+        }
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display());
+            }
+            false
+        }
+    }
+}
+
+/// Writes `runtime.plib` again when pipelines were added to it since it was last written.
+pub(crate) fn flush_runtime() {
+    let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return };
+    flush_runtime_on(runtime, write_atomic);
+}
+
+/// Runs `f` on a helper thread up to `timeout`. Returns `None` if it finished (or could not
+/// spawn), or `Some(tid)` with the helper's OS thread ID when it is still running at timeout.
+fn run_with_timeout(name: &str, timeout: std::time::Duration, f: impl FnOnce() + Send + 'static) -> Option<u32> {
+    let (tid_tx, tid_rx) = std::sync::mpsc::sync_channel(1);
+    let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1);
+    if std::thread::Builder::new().name(name.into()).spawn(move || {
+        let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
+        let _ = tid_tx.send(tid);
+        f();
+        let _ = done_tx.send(());
+    }).is_err() {
+        return None;
+    }
+    let deadline = std::time::Instant::now() + timeout;
+    let tid = tid_rx.recv_timeout(timeout).unwrap_or(0);
+    let remaining = deadline.saturating_duration_since(std::time::Instant::now());
+    match done_rx.recv_timeout(remaining) {
+        Ok(()) => None,
+        Err(_) => Some(tid),
+    }
+}
+
+/// Bounded `flush_runtime` for title shutdown (`end_title`, `WM_CLOSE`): returns `[0, 0]` when
+/// nothing is pending/in-flight or the flush finishes within `timeout`. On timeout, returns the OS
+/// thread IDs of the active flush threads so `end_title` can exclude them from thread suspension
+/// (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() {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4774712893 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4774712893). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:21:36Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 499 ~~~~diff @@ -20,39 +20,797 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later + /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept. + load_missed: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the + /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`. + estimated_size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `admit_cap(cap)`: stops further `StorePipeline` + /// additions so the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, + /// Build/settings stamp written next to `runtime.plib` when a fresh library is first flushed. + stamp: String, + /// True when `runtime.stamp` should be written on the next successful flush (fresh library + /// or upgrade from a library with no stamp file yet). + write_stamp: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); -pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - let Some(ready) = super::warm_library::take_ready() else { return Ok(()) }; - let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) - .ok_or("Pipeline library: runtime driver identity is unavailable")?; - if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } - let open = |bytes| NativeLibrary::open_shared(device, bytes); - let graphics = ready.graphics.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; - let compute = ready.compute.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; +/// Within this distance of `admit_cap(Runtime::cap)`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +/// Conservative per-entry overhead above `GetCachedBlob()` + UTF-16 name to cover root signature, +/// input layout, and pipeline-desc subobjects serialized by D3D12. +const ENTRY_OVERHEAD: u64 = 64 << 10; +/// Safety buffer below `cap` where admission stops (for real caps >= 16 MiB), so minor D3D12 +/// directory/metadata growth on the final admitted store cannot push `flush_runtime_on` over `cap`. +const CAP_ADMIT_HEADROOM: u64 = 2 << 20; + +fn admit_cap(cap: u64) -> u64 { + if cap >= (16 << 20) { cap.saturating_sub(CAP_ADMIT_HEADROOM) } else { cap } +} + +fn runtime_stamp() -> String { + format!( + "{}:{:016x}:{:016x}", + env!("XCL_PIPELINE_LAYOUT_ID"), + crate::gpu::recomp::pso::translation_cache_identity(), + super::warm_settings_key(), + ) +} + +fn stamp_path(path: &std::path::Path) -> std::path::PathBuf { + path.with_extension("stamp") +} + +fn should_reset_full_runtime(existing_len: u64, cap: u64, saved_stamp: Option<&str>, current_stamp: &str) -> bool { + existing_len >= admit_cap(cap) && saved_stamp.map(str::trim) != Some(current_stamp) +} + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let current_stamp = runtime_stamp(); + let saved_stamp = std::fs::read_to_string(stamp_path(&path)).ok(); + let bytes = bytes.filter(|b| { + if b.len() as u64 > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return false; + } + if should_reset_full_runtime(b.len() as u64, cap, saved_stamp.as_deref(), &current_stamp) { + crate::xlog_info!( + "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB and contains entries from an older build or settings; starting it fresh", + path.display() + ); + return false; + } + true + }); + let mut started_fresh = bytes.is_none(); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + started_fresh = true; + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let initial_size = library.serialized_size(); + let full = initial_size >= admit_cap(cap); + let write_stamp = started_fresh || saved_stamp.is_none(); + Some(Runtime { + library, + path, + cap, + known: Default::default(), + load_missed: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + estimated_size: initial_size.into(), + full: full.into(), + stamp: current_stamp, + write_stamp: write_stamp.into(), + }) +} + +fn check_library_support(supported: bool, has_prepared: bool, cache_only: bool) -> std::result::Result<bool, String> { + if supported { + return Ok(true); } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { - crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); + if cache_only && has_prepared { + return Err("Pipeline library: the device does not support pipeline libraries".into()); + } + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + Ok(false) +} + +fn check_activation_driver( + ready_driver: u64, + runtime_driver: Option<u64>, + has_prepared: bool, + cache_only: bool, +) -> std::result::Result<bool, String> { + if runtime_driver == Some(ready_driver) { + return Ok(true); + } + let reason = if runtime_driver.is_none() { + "Pipeline library: runtime driver identity is unavailable" + } else { + "Pipeline library: runtime adapter or driver differs from the prepared cache" + }; + if cache_only && has_prepared { + return Err(reason.into()); + } + if has_prepared { + crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib"); + } + Ok(false) +} + +fn open_active_for_device( + device: &ID3D12Device, + ready: super::warm_library::Ready, + runtime_driver: Option<u64>, + cache_only: bool, +) -> 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 !check_library_support(NativeLibrary::supported(device), has_prepared, cache_only)? { + return Ok(None); + } + let open = |bytes| NativeLibrary::open_shared(device, bytes); + let graphics = if use_prepared { + ready.graphics.map(open).transpose() + .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))? + } else { + None + }; + let compute = if use_prepared { + ready.compute.map(open).transpose() + .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))? + } else { + None + }; + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + Ok(Some(Active { graphics, compute, runtime, names, handed: Default::default() })) +} + +pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { + 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; + let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device); + let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1"); + let Some(active) = open_active_for_device(device, ready, runtime_driver, cache_only)? else { + return Ok(()); + }; + start_counting(); + let has_any_prepared = active.graphics.is_some() || active.compute.is_some(); + let has_runtime = active.runtime.is_some(); + if ACTIVE.set(active).is_ok() { + if has_any_prepared { + crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); + } else if has_runtime { + crate::xlog_info!("Pipeline library: activated runtime library for lazy runtime loading"); + } } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +static PERIODIC_FLUSH_TID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + PERIODIC_FLUSH_TID.store(tid, std::sync::atomic::Ordering::Release); + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + since += 1; + if since >= flush_every() { + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { + runtime.mark_full(current); + state.disabled = true; + crate::xlog_warn!( + "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library", + runtime.path.display(), current, runtime.cap + ); + return false; + } + let bytes = match serialize_runtime(runtime) { + Ok(b) => b, + Err(e) => { + state.consecutive_failures += 1; + if state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display()); + } + return false; + } + }; + if bytes.len() as u64 > runtime.cap { + 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", + runtime.path.display(), bytes.len(), runtime.cap + ); + return false; + } + match write(&runtime.path, &bytes) { + Ok(()) => { + state.consecutive_failures = 0; + runtime.size.store(bytes.len() as u64, Ordering::Relaxed); + if runtime.write_stamp.swap(false, Ordering::AcqRel) { + let _ = write_atomic(&stamp_path(&runtime.path), runtime.stamp.as_bytes()); + } + crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})", + bytes.len(), runtime.path.display()); + true + } + Err(e) => { + state.consecutive_failures += 1; + if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display()); + } + false + } + } +} + +/// Writes `runtime.plib` again when pipelines were added to it since it was last written. +pub(crate) fn flush_runtime() { + let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return }; + flush_runtime_on(runtime, write_atomic); +} + +/// Runs `f` on a helper thread up to `timeout`. Returns `None` if it finished (or could not +/// spawn), or `Some(tid)` with the helper's OS thread ID when it is still running at timeout. +fn run_with_timeout(name: &str, timeout: std::time::Duration, f: impl FnOnce() + Send + 'static) -> Option<u32> { + let (tid_tx, tid_rx) = std::sync::mpsc::sync_channel(1); + let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1); + if std::thread::Builder::new().name(name.into()).spawn(move || { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let _ = tid_tx.send(tid); + f(); + let _ = done_tx.send(()); + }).is_err() { + return None; + } + let deadline = std::time::Instant::now() + timeout; + let tid = tid_rx.recv_timeout(timeout).unwrap_or(0); + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); + match done_rx.recv_timeout(remaining) { + Ok(()) => None, + Err(_) => Some(tid), + } +} + +/// Bounded `flush_runtime` for title shutdown (`end_title`, `WM_CLOSE`): returns `[0, 0]` when +/// nothing is pending/in-flight or the flush finishes within `timeout`. On timeout, returns the OS +/// thread IDs of the active flush threads so `end_title` can exclude them from thread suspension +/// (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() { ~~~~ --- **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.
bmjask commented 2026-12-02 19:21:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:21:36Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 803

@@ -20,39 +20,797 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later
+    /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept.
+    load_missed: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the
+    /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`.
+    estimated_size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `admit_cap(cap)`: stops further `StorePipeline`
+    /// additions so the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
+    /// Build/settings stamp written next to `runtime.plib` when a fresh library is first flushed.
+    stamp: String,
+    /// True when `runtime.stamp` should be written on the next successful flush (fresh library
+    /// or upgrade from a library with no stamp file yet).
+    write_stamp: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
-pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    let Some(ready) = super::warm_library::take_ready() else { return Ok(()) };
-    let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
-        .ok_or("Pipeline library: runtime driver identity is unavailable")?;
-    if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
-    let open = |bytes| NativeLibrary::open_shared(device, bytes);
-    let graphics = ready.graphics.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
-    let compute = ready.compute.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
+/// Within this distance of `admit_cap(Runtime::cap)`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+/// Conservative per-entry overhead above `GetCachedBlob()` + UTF-16 name to cover root signature,
+/// input layout, and pipeline-desc subobjects serialized by D3D12.
+const ENTRY_OVERHEAD: u64 = 64 << 10;
+/// Safety buffer below `cap` where admission stops (for real caps >= 16 MiB), so minor D3D12
+/// directory/metadata growth on the final admitted store cannot push `flush_runtime_on` over `cap`.
+const CAP_ADMIT_HEADROOM: u64 = 2 << 20;
+
+fn admit_cap(cap: u64) -> u64 {
+    if cap >= (16 << 20) { cap.saturating_sub(CAP_ADMIT_HEADROOM) } else { cap }
+}
+
+fn runtime_stamp() -> String {
+    format!(
+        "{}:{:016x}:{:016x}",
+        env!("XCL_PIPELINE_LAYOUT_ID"),
+        crate::gpu::recomp::pso::translation_cache_identity(),
+        super::warm_settings_key(),
+    )
+}
+
+fn stamp_path(path: &std::path::Path) -> std::path::PathBuf {
+    path.with_extension("stamp")
+}
+
+fn should_reset_full_runtime(existing_len: u64, cap: u64, saved_stamp: Option<&str>, current_stamp: &str) -> bool {
+    existing_len >= admit_cap(cap) && saved_stamp.map(str::trim) != Some(current_stamp)
+}
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let current_stamp = runtime_stamp();
+    let saved_stamp = std::fs::read_to_string(stamp_path(&path)).ok();
+    let bytes = bytes.filter(|b| {
+        if b.len() as u64 > cap {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            return false;
+        }
+        if should_reset_full_runtime(b.len() as u64, cap, saved_stamp.as_deref(), &current_stamp) {
+            crate::xlog_info!(
+                "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB and contains entries from an older build or settings; starting it fresh",
+                path.display()
+            );
+            return false;
+        }
+        true
+    });
+    let mut started_fresh = bytes.is_none();
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            started_fresh = true;
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let initial_size = library.serialized_size();
+    let full = initial_size >= admit_cap(cap);
+    let write_stamp = started_fresh || saved_stamp.is_none();
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        load_missed: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        estimated_size: initial_size.into(),
+        full: full.into(),
+        stamp: current_stamp,
+        write_stamp: write_stamp.into(),
+    })
+}
+
+fn check_library_support(supported: bool, has_prepared: bool, cache_only: bool) -> std::result::Result<bool, String> {
+    if supported {
+        return Ok(true);
     }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
-        crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+    if cache_only && has_prepared {
+        return Err("Pipeline library: the device does not support pipeline libraries".into());
+    }
+    crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+    Ok(false)
+}
+
+fn check_activation_driver(
+    ready_driver: u64,
+    runtime_driver: Option<u64>,
+    has_prepared: bool,
+    cache_only: bool,
+) -> std::result::Result<bool, String> {
+    if runtime_driver == Some(ready_driver) {
+        return Ok(true);
+    }
+    let reason = if runtime_driver.is_none() {
+        "Pipeline library: runtime driver identity is unavailable"
+    } else {
+        "Pipeline library: runtime adapter or driver differs from the prepared cache"
+    };
+    if cache_only && has_prepared {
+        return Err(reason.into());
+    }
+    if has_prepared {
+        crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib");
+    }
+    Ok(false)
+}
+
+fn open_active_for_device(
+    device: &ID3D12Device,
+    ready: super::warm_library::Ready,
+    runtime_driver: Option<u64>,
+    cache_only: bool,
+) -> 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 !check_library_support(NativeLibrary::supported(device), has_prepared, cache_only)? {
+        return Ok(None);
+    }
+    let open = |bytes| NativeLibrary::open_shared(device, bytes);
+    let graphics = if use_prepared {
+        ready.graphics.map(open).transpose()
+            .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?
+    } else {
+        None
+    };
+    let compute = if use_prepared {
+        ready.compute.map(open).transpose()
+            .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?
+    } else {
+        None
+    };
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    Ok(Some(Active { graphics, compute, runtime, names, handed: Default::default() }))
+}
+
+pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
+    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
+    let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device);
+    let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1");
+    let Some(active) = open_active_for_device(device, ready, runtime_driver, cache_only)? else {
+        return Ok(());
+    };
+    start_counting();
+    let has_any_prepared = active.graphics.is_some() || active.compute.is_some();
+    let has_runtime = active.runtime.is_some();
+    if ACTIVE.set(active).is_ok() {
+        if has_any_prepared {
+            crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+        } else if has_runtime {
+            crate::xlog_info!("Pipeline library: activated runtime library for lazy runtime loading");
+        }
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+static PERIODIC_FLUSH_TID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
+            PERIODIC_FLUSH_TID.store(tid, std::sync::atomic::Ordering::Release);
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                since += 1;
+                if since >= flush_every() {
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {
+        runtime.mark_full(current);
+        state.disabled = true;
+        crate::xlog_warn!(
+            "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",
+            runtime.path.display(), current, runtime.cap
+        );
+        return false;
+    }
+    let bytes = match serialize_runtime(runtime) {
+        Ok(b) => b,
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display());
+            }
+            return false;
+        }
+    };
+    if bytes.len() as u64 > runtime.cap {
+        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",
+            runtime.path.display(), bytes.len(), runtime.cap
+        );
+        return false;
+    }
+    match write(&runtime.path, &bytes) {
+        Ok(()) => {
+            state.consecutive_failures = 0;
+            runtime.size.store(bytes.len() as u64, Ordering::Relaxed);
+            if runtime.write_stamp.swap(false, Ordering::AcqRel) {
+                let _ = write_atomic(&stamp_path(&runtime.path), runtime.stamp.as_bytes());
+            }
+            crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})",
+                bytes.len(), runtime.path.display());
+            true
+        }
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display());
+            }
+            false
+        }
+    }
+}
+
+/// Writes `runtime.plib` again when pipelines were added to it since it was last written.
+pub(crate) fn flush_runtime() {
+    let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return };
+    flush_runtime_on(runtime, write_atomic);
+}
+
+/// Runs `f` on a helper thread up to `timeout`. Returns `None` if it finished (or could not
+/// spawn), or `Some(tid)` with the helper's OS thread ID when it is still running at timeout.
+fn run_with_timeout(name: &str, timeout: std::time::Duration, f: impl FnOnce() + Send + 'static) -> Option<u32> {
+    let (tid_tx, tid_rx) = std::sync::mpsc::sync_channel(1);
+    let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1);
+    if std::thread::Builder::new().name(name.into()).spawn(move || {
+        let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
+        let _ = tid_tx.send(tid);
+        f();
+        let _ = done_tx.send(());
+    }).is_err() {
+        return None;
+    }
+    let deadline = std::time::Instant::now() + timeout;
+    let tid = tid_rx.recv_timeout(timeout).unwrap_or(0);
+    let remaining = deadline.saturating_duration_since(std::time::Instant::now());
+    match done_rx.recv_timeout(remaining) {
+        Ok(()) => None,
+        Err(_) => Some(tid),
+    }
+}
+
+/// Bounded `flush_runtime` for title shutdown (`end_title`, `WM_CLOSE`): returns `[0, 0]` when
+/// nothing is pending/in-flight or the flush finishes within `timeout`. On timeout, returns the OS
+/// thread IDs of the active flush threads so `end_title` can exclude them from thread suspension
+/// (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() {
+        if state.disabled || runtime.added.load(std::sync::atomic::Ordering::Acquire) == 0 {
+            return [0, 0];
+        }
+    }
+    let Some(end_tid) = run_with_timeout("xcl-plib-end-flush", timeout, move || {
+        flush_runtime_on(runtime, write_atomic);
+    }) else {
+        return [0, 0];
+    };
+    crate::xlog_warn!(
+        "Pipeline library: shutdown flush of {} did not finish within {} ms; continuing shutdown",
+        runtime.path.display(), timeout.as_millis()
+    );
+    [end_tid, PERIODIC_FLUSH_TID.load(std::sync::atomic::Ordering::Acquire)]
+}
+
+fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> {
+    unsafe { crate::hle::d3d12x::real::pso_cached_blob_size(pipeline.as_raw()) }
+}
+
+fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> {
+    let blob = cached_blob_size(pipeline)?;
+    let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2);
+    Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD))
+}
+
+impl Runtime {
+    fn mark_full(&self, bytes: u64) {
+        if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) {
+            crate::xlog_info!(
+                "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions",
+                self.path.display(), bytes, self.cap
+            );
+        }
+    }
+
+    /// Reserves `est` bytes on the lock-free read path only while the cumulative estimate stays at
+    /// least `NEAR_CAP_MARGIN` below `admit_cap(cap)`. Large pipelines or concurrent bursts that
+    /// cross that threshold fall through to `store_lock.write()` + exact `serialized_size()`.
+    fn try_reserve_fast(&self, est: u64) -> bool {
+        use std::sync::atomic::Ordering;
+        let fast_limit = admit_cap(self.cap).saturating_sub(NEAR_CAP_MARGIN);
+        if est > fast_limit { return false; }
+        let mut cur = self.estimated_size.load(Ordering::Acquire);
+        loop {
+            let Some(next) = cur.checked_add(est) else { return false };
+            if next > fast_limit { return false; }
+            match self.estimated_size.compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire) {
+                Ok(_) => return true,
+                Err(actual) => cur = actual,
+            }
+        }
+    }
+
+    fn can_store_locked(&self, est: u64) -> bool {
+        use std::sync::atomic::Ordering;
+        if self.full.load(Ordering::Acquire) { return false; }
+        let admit = admit_cap(self.cap);
+        let current = self.library.serialized_size();
+        self.estimated_size.store(current, Ordering::Release);
+        if current >= admit {
+            self.mark_full(current);
+            return false;
+        }
+        if current.saturating_add(est) > admit {
+            if est <= NEAR_CAP_MARGIN {
+                self.mark_full(current);
+            }
+            return false;
+        }
+        true
+    }
+}
+
+enum StoreOutcome {
+    /// Pipeline is present and usable in `runtime.library` (newly stored or verified existing).
+    Usable,
+    /// `E_INVALIDARG` on a name whose `Load*` failed in this run: existing entry is unusable
+    /// and cannot be replaced in-place, so stop retrying without marking it handed out.
+    UnusableExisting,
+    /// Transient store error (e.g. `E_OUTOFMEMORY`): leave out of `known` so a later call can retry.
+    TransientError,
+}
+
+fn record_store_result(runtime: &Runtime, name: &str, result: Result<()>) -> StoreOutcome {
+    match result {
+        Ok(()) => {
+            runtime.added.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
+            runtime.load_missed.lock().unwrap().remove(name);
+            StoreOutcome::Usable
+        }
+        Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => {
+            if runtime.load_missed.lock().unwrap().contains(name) {
+                crate::xlog_warn!(
+                    "Pipeline library: {name} already exists in {} but failed to load; not marking usable",
+                    runtime.path.display()
+                );
+                StoreOutcome::UnusableExisting
+            } else {
+                StoreOutcome::Usable
+            }
+        }
+        Err(e) => {
+            crate::xlog_warn!("Pipeline library: keeping {name}: {e}");
+            StoreOutcome::TransientError
+        }
+    }
+}
+
+fn read_cached_blob(pipeline: &ID3D12PipelineState) -> Option<Vec<u8>> {
+    // Use the adoption-aware helper because the first hand-out of a COM object from a pipeline
+    // library may have been adopted (swapping its vtable pointer to XCL's console ext class).
+    unsafe { crate::hle::d3d12x::real::read_pso_cached_blob(pipeline.as_raw()) }
+}
+
+impl Active {
+    fn with_name(
+        &self,
+        name: &str,
+        kind: super::pipeline_stats::Kind,
+        f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>,
+        prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>,
+    ) -> Option<Loaded> {
+        use super::pipeline_stats::{library, Source};
+        let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len();
+        let _same_name = self.names[slot].lock().unwrap();
+        let already_handed = self.handed.lock().unwrap().contains(name);
+        let (found, source) = if let Some(found) = prepared(self).and_then(|lib| f(lib).ok()) {
+            (found, Source::Prepared)
+        } else {
+            let runtime = self.runtime.as_ref()?;
+            match f(&runtime.library) {
+                Ok(found) => (found, Source::Runtime),
+                Err(_) => {
+                    runtime.load_missed.lock().unwrap().insert(name.into());
+                    return None;
+                }
+            }
+        };
+        if let Some(runtime) = &self.runtime {
+            runtime.load_missed.lock().unwrap().remove(name);
+            runtime.known.lock().unwrap().insert(name.into());
+        }
+        if already_handed {
+            // A library loads a name as the same COM object each time, and XCL keys what it knows
+            // of a pipeline by its object (a dispatch chain by its first piece: a second chain
+            // with that piece replaced the first, and the replaced one's release deadlocked on the
+            // chain table). Hand out its cached blob instead so the caller creates a distinct COM
+            // object without recompiling in the driver, even for small shaders below the RAM blob
+            // cache threshold.
+            return read_cached_blob(&found).map(Loaded::Blob);
+        }
+        library(kind, source);
+        self.handed.lock().unwrap().insert(name.into());
+        Some(Loaded::Pipeline(found))
+    }
+
+    fn apply_store_outcome(&self, runtime: &Runtime, name: &str, outcome: StoreOutcome) {
+        match outcome {
+            StoreOutcome::Usable => {
+                runtime.known.lock().unwrap().insert(name.into());
+                // (a load may give back the very object stored: this one is out already)
+                self.handed.lock().unwrap().insert(name.into());
+            }
+            StoreOutcome::UnusableExisting => {
+                runtime.known.lock().unwrap().insert(name.into());
+            }
+            StoreOutcome::TransientError => {}
+        }
+    }
+
+    /// A pipeline built at runtime, kept in `runtime.plib` (one found in a library is not kept again).
+    fn store_runtime(&self, name: &str, pipeline: &ID3D12PipelineState) {
+        use std::sync::atomic::Ordering;
+        let Some(runtime) = self.runtime.as_ref() else { return };
+        if name.is_empty() || runtime.full.load(Ordering::Acquire) { return }
+        let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len();
+        let _same_name = self.names[slot].lock().unwrap();
+        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 };
+        // Reserve while holding `store_lock.read()` so a concurrent `store_lock.write()` holder
+        // can never reset `estimated_size` while an unstored fast-path reservation is in flight.
+        let outcome = {
+            let read_guard = runtime.store_lock.read().unwrap();
+            if runtime.full.load(Ordering::Acquire) { return }
+            if runtime.try_reserve_fast(est) {
+                record_store_result(runtime, name, runtime.library.store(name, pipeline))
+            } else {
+                drop(read_guard);
+                let _write_guard = runtime.store_lock.write().unwrap();
+                if !runtime.can_store_locked(est) { return }
+                let outcome = record_store_result(runtime, name, runtime.library.store(name, pipeline));
+                let after = runtime.library.serialized_size();
+                runtime.estimated_size.store(after, Ordering::Release);
+                if matches!(outcome, StoreOutcome::Usable) && after >= admit_cap(runtime.cap) {
+                    runtime.mark_full(after);
+                }
+                outcome
+            }
+        };
+        self.apply_store_outcome(runtime, name, outcome);
+    }
+}
+
+fn with_name(
+    name: &str,
+    kind: super::pipeline_stats::Kind,
+    f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>,
+    prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>,
+) -> Option<Loaded> {
+    ACTIVE.get()?.with_name(name, kind, f, prepared)
+}
+
+fn store_runtime(name: &str, pipeline: &ID3D12PipelineState) {
+    if let Some(active) = ACTIVE.get() { active.store_runtime(name, pipeline); }
+}
+
+/// One build of a pipeline at a time while the title runs (`one_build`).
+struct OneBuildFlights {
+    building: std::sync::Mutex<Option<std::collections::HashMap<String, (std::thread::ThreadId, u64)>>>,
+    next_id: std::sync::atomic::AtomicU64,
+    built: std::sync::Condvar,
+}
+
+impl OneBuildFlights {
+    const fn new() -> Self {
+        Self {
+            building: std::sync::Mutex::new(None),
+            next_id: std::sync::atomic::AtomicU64::new(0),
+            built: std::sync::Condvar::new(),
+        }
+    }
+
+    fn enter(&self, name: &str, wait: std::time::Duration) -> OneBuildGuard<'_> {
+        let until = std::time::Instant::now() + wait;
+        let mut building = self.building.lock().unwrap();
+        while building.as_ref().is_some_and(|b| b.contains_key(name)) {
+            let left = until.saturating_duration_since(std::time::Instant::now());
+            if left.is_zero() {
+                crate::xlog_info!("Pipeline library: still waiting for another build of {name} after {} s; building it here too", wait.as_secs());
+                return OneBuildGuard { flights: self, flight: None };
+            }
+            building = self.built.wait_timeout(building, left).unwrap().0;
+        }
+        let id = self.next_id.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
+        building.get_or_insert_with(Default::default).insert(name.to_owned(), (std::thread::current().id(), id));
+        OneBuildGuard { flights: self, flight: Some((name.to_owned(), id)) }
+    }
+
+    /// Releases any in-flight build(s) owned by the current thread so a worker parked at the
+    /// compile gate does not stall an ungated title thread waiting on the same pipeline name.
+    fn release_current_thread(&self) {
+        let me = std::thread::current().id();
+        let mut building = self.building.lock().unwrap();
+        let Some(map) = building.as_mut() else { return };
+        let before = map.len();
+        map.retain(|_, (tid, _)| *tid != me);
+        if map.len() != before {
+            self.built.notify_all();
+        }
+    }
+}
+
+static FLIGHTS: OneBuildFlights = OneBuildFlights::new();
+
+/// While held, no other thread builds the pipeline of this name.
+pub(crate) struct OneBuildGuard<'a> {
+    flights: &'a OneBuildFlights,
+    flight: Option<(String, u64)>,
+}
+
+pub(crate) type OneBuild = OneBuildGuard<'static>;
+
+impl Drop for OneBuildGuard<'_> {
+    fn drop(&mut self) {
+        let Some((name, id)) = self.flight.take() else { return };
+        let mut removed = false;
+        if let Some(building) = self.flights.building.lock().unwrap().as_mut() {
+            if building.get(&name).is_some_and(|&(_, cur)| cur == id) {
+                building.remove(&name);
+                removed = true;
+            }
+        }
+        if removed {
+            self.flights.built.notify_all();
+        }
+    }
+}
+
+/// Releases any `one_build` flight owned by the current thread when it parks in the compile gate.
+pub(crate) fn release_one_build_on_park() {
+    FLIGHTS.release_current_thread();
+}
+
+fn should_use_one_build(name: &str, has_runtime: bool, runtime_full: bool) -> bool {
+    !name.is_empty() && has_runtime && !runtime_full
+}
+
+/// Up to `XCL_ONE_BUILD_WAIT_S` (60) for another thread's build of this name to end: that one is
+/// 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 {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4774712903 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4774712903). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:21:36Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 803 ~~~~diff @@ -20,39 +20,797 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later + /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept. + load_missed: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the + /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`. + estimated_size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `admit_cap(cap)`: stops further `StorePipeline` + /// additions so the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, + /// Build/settings stamp written next to `runtime.plib` when a fresh library is first flushed. + stamp: String, + /// True when `runtime.stamp` should be written on the next successful flush (fresh library + /// or upgrade from a library with no stamp file yet). + write_stamp: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); -pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - let Some(ready) = super::warm_library::take_ready() else { return Ok(()) }; - let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) - .ok_or("Pipeline library: runtime driver identity is unavailable")?; - if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } - let open = |bytes| NativeLibrary::open_shared(device, bytes); - let graphics = ready.graphics.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; - let compute = ready.compute.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; +/// Within this distance of `admit_cap(Runtime::cap)`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +/// Conservative per-entry overhead above `GetCachedBlob()` + UTF-16 name to cover root signature, +/// input layout, and pipeline-desc subobjects serialized by D3D12. +const ENTRY_OVERHEAD: u64 = 64 << 10; +/// Safety buffer below `cap` where admission stops (for real caps >= 16 MiB), so minor D3D12 +/// directory/metadata growth on the final admitted store cannot push `flush_runtime_on` over `cap`. +const CAP_ADMIT_HEADROOM: u64 = 2 << 20; + +fn admit_cap(cap: u64) -> u64 { + if cap >= (16 << 20) { cap.saturating_sub(CAP_ADMIT_HEADROOM) } else { cap } +} + +fn runtime_stamp() -> String { + format!( + "{}:{:016x}:{:016x}", + env!("XCL_PIPELINE_LAYOUT_ID"), + crate::gpu::recomp::pso::translation_cache_identity(), + super::warm_settings_key(), + ) +} + +fn stamp_path(path: &std::path::Path) -> std::path::PathBuf { + path.with_extension("stamp") +} + +fn should_reset_full_runtime(existing_len: u64, cap: u64, saved_stamp: Option<&str>, current_stamp: &str) -> bool { + existing_len >= admit_cap(cap) && saved_stamp.map(str::trim) != Some(current_stamp) +} + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let current_stamp = runtime_stamp(); + let saved_stamp = std::fs::read_to_string(stamp_path(&path)).ok(); + let bytes = bytes.filter(|b| { + if b.len() as u64 > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return false; + } + if should_reset_full_runtime(b.len() as u64, cap, saved_stamp.as_deref(), &current_stamp) { + crate::xlog_info!( + "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB and contains entries from an older build or settings; starting it fresh", + path.display() + ); + return false; + } + true + }); + let mut started_fresh = bytes.is_none(); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + started_fresh = true; + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let initial_size = library.serialized_size(); + let full = initial_size >= admit_cap(cap); + let write_stamp = started_fresh || saved_stamp.is_none(); + Some(Runtime { + library, + path, + cap, + known: Default::default(), + load_missed: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + estimated_size: initial_size.into(), + full: full.into(), + stamp: current_stamp, + write_stamp: write_stamp.into(), + }) +} + +fn check_library_support(supported: bool, has_prepared: bool, cache_only: bool) -> std::result::Result<bool, String> { + if supported { + return Ok(true); } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { - crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); + if cache_only && has_prepared { + return Err("Pipeline library: the device does not support pipeline libraries".into()); + } + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + Ok(false) +} + +fn check_activation_driver( + ready_driver: u64, + runtime_driver: Option<u64>, + has_prepared: bool, + cache_only: bool, +) -> std::result::Result<bool, String> { + if runtime_driver == Some(ready_driver) { + return Ok(true); + } + let reason = if runtime_driver.is_none() { + "Pipeline library: runtime driver identity is unavailable" + } else { + "Pipeline library: runtime adapter or driver differs from the prepared cache" + }; + if cache_only && has_prepared { + return Err(reason.into()); + } + if has_prepared { + crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib"); + } + Ok(false) +} + +fn open_active_for_device( + device: &ID3D12Device, + ready: super::warm_library::Ready, + runtime_driver: Option<u64>, + cache_only: bool, +) -> 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 !check_library_support(NativeLibrary::supported(device), has_prepared, cache_only)? { + return Ok(None); + } + let open = |bytes| NativeLibrary::open_shared(device, bytes); + let graphics = if use_prepared { + ready.graphics.map(open).transpose() + .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))? + } else { + None + }; + let compute = if use_prepared { + ready.compute.map(open).transpose() + .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))? + } else { + None + }; + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + Ok(Some(Active { graphics, compute, runtime, names, handed: Default::default() })) +} + +pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { + 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; + let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device); + let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1"); + let Some(active) = open_active_for_device(device, ready, runtime_driver, cache_only)? else { + return Ok(()); + }; + start_counting(); + let has_any_prepared = active.graphics.is_some() || active.compute.is_some(); + let has_runtime = active.runtime.is_some(); + if ACTIVE.set(active).is_ok() { + if has_any_prepared { + crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); + } else if has_runtime { + crate::xlog_info!("Pipeline library: activated runtime library for lazy runtime loading"); + } } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +static PERIODIC_FLUSH_TID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + PERIODIC_FLUSH_TID.store(tid, std::sync::atomic::Ordering::Release); + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + since += 1; + if since >= flush_every() { + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { + runtime.mark_full(current); + state.disabled = true; + crate::xlog_warn!( + "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library", + runtime.path.display(), current, runtime.cap + ); + return false; + } + let bytes = match serialize_runtime(runtime) { + Ok(b) => b, + Err(e) => { + state.consecutive_failures += 1; + if state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display()); + } + return false; + } + }; + if bytes.len() as u64 > runtime.cap { + 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", + runtime.path.display(), bytes.len(), runtime.cap + ); + return false; + } + match write(&runtime.path, &bytes) { + Ok(()) => { + state.consecutive_failures = 0; + runtime.size.store(bytes.len() as u64, Ordering::Relaxed); + if runtime.write_stamp.swap(false, Ordering::AcqRel) { + let _ = write_atomic(&stamp_path(&runtime.path), runtime.stamp.as_bytes()); + } + crate::xlog_info!("Pipeline library: kept {added} more pipelines built at runtime ({} bytes in {})", + bytes.len(), runtime.path.display()); + true + } + Err(e) => { + state.consecutive_failures += 1; + if is_permanent_write_error(&e) || state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempt(s): {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: writing {}: {e}", runtime.path.display()); + } + false + } + } +} + +/// Writes `runtime.plib` again when pipelines were added to it since it was last written. +pub(crate) fn flush_runtime() { + let Some(runtime) = ACTIVE.get().and_then(|a| a.runtime.as_ref()) else { return }; + flush_runtime_on(runtime, write_atomic); +} + +/// Runs `f` on a helper thread up to `timeout`. Returns `None` if it finished (or could not +/// spawn), or `Some(tid)` with the helper's OS thread ID when it is still running at timeout. +fn run_with_timeout(name: &str, timeout: std::time::Duration, f: impl FnOnce() + Send + 'static) -> Option<u32> { + let (tid_tx, tid_rx) = std::sync::mpsc::sync_channel(1); + let (done_tx, done_rx) = std::sync::mpsc::sync_channel(1); + if std::thread::Builder::new().name(name.into()).spawn(move || { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let _ = tid_tx.send(tid); + f(); + let _ = done_tx.send(()); + }).is_err() { + return None; + } + let deadline = std::time::Instant::now() + timeout; + let tid = tid_rx.recv_timeout(timeout).unwrap_or(0); + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); + match done_rx.recv_timeout(remaining) { + Ok(()) => None, + Err(_) => Some(tid), + } +} + +/// Bounded `flush_runtime` for title shutdown (`end_title`, `WM_CLOSE`): returns `[0, 0]` when +/// nothing is pending/in-flight or the flush finishes within `timeout`. On timeout, returns the OS +/// thread IDs of the active flush threads so `end_title` can exclude them from thread suspension +/// (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() { + if state.disabled || runtime.added.load(std::sync::atomic::Ordering::Acquire) == 0 { + return [0, 0]; + } + } + let Some(end_tid) = run_with_timeout("xcl-plib-end-flush", timeout, move || { + flush_runtime_on(runtime, write_atomic); + }) else { + return [0, 0]; + }; + crate::xlog_warn!( + "Pipeline library: shutdown flush of {} did not finish within {} ms; continuing shutdown", + runtime.path.display(), timeout.as_millis() + ); + [end_tid, PERIODIC_FLUSH_TID.load(std::sync::atomic::Ordering::Acquire)] +} + +fn cached_blob_size(pipeline: &ID3D12PipelineState) -> Option<u64> { + unsafe { crate::hle::d3d12x::real::pso_cached_blob_size(pipeline.as_raw()) } +} + +fn estimated_store_bytes(name: &str, pipeline: &ID3D12PipelineState) -> Option<u64> { + let blob = cached_blob_size(pipeline)?; + let name_bytes = (name.encode_utf16().count() as u64 + 1).saturating_mul(2); + Some(blob.saturating_add(name_bytes).saturating_add(ENTRY_OVERHEAD)) +} + +impl Runtime { + fn mark_full(&self, bytes: u64) { + if !self.full.swap(true, std::sync::atomic::Ordering::AcqRel) { + crate::xlog_info!( + "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB ({} / {} bytes); keeping stored pipelines and stopping further additions", + self.path.display(), bytes, self.cap + ); + } + } + + /// Reserves `est` bytes on the lock-free read path only while the cumulative estimate stays at + /// least `NEAR_CAP_MARGIN` below `admit_cap(cap)`. Large pipelines or concurrent bursts that + /// cross that threshold fall through to `store_lock.write()` + exact `serialized_size()`. + fn try_reserve_fast(&self, est: u64) -> bool { + use std::sync::atomic::Ordering; + let fast_limit = admit_cap(self.cap).saturating_sub(NEAR_CAP_MARGIN); + if est > fast_limit { return false; } + let mut cur = self.estimated_size.load(Ordering::Acquire); + loop { + let Some(next) = cur.checked_add(est) else { return false }; + if next > fast_limit { return false; } + match self.estimated_size.compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return true, + Err(actual) => cur = actual, + } + } + } + + fn can_store_locked(&self, est: u64) -> bool { + use std::sync::atomic::Ordering; + if self.full.load(Ordering::Acquire) { return false; } + let admit = admit_cap(self.cap); + let current = self.library.serialized_size(); + self.estimated_size.store(current, Ordering::Release); + if current >= admit { + self.mark_full(current); + return false; + } + if current.saturating_add(est) > admit { + if est <= NEAR_CAP_MARGIN { + self.mark_full(current); + } + return false; + } + true + } +} + +enum StoreOutcome { + /// Pipeline is present and usable in `runtime.library` (newly stored or verified existing). + Usable, + /// `E_INVALIDARG` on a name whose `Load*` failed in this run: existing entry is unusable + /// and cannot be replaced in-place, so stop retrying without marking it handed out. + UnusableExisting, + /// Transient store error (e.g. `E_OUTOFMEMORY`): leave out of `known` so a later call can retry. + TransientError, +} + +fn record_store_result(runtime: &Runtime, name: &str, result: Result<()>) -> StoreOutcome { + match result { + Ok(()) => { + runtime.added.fetch_add(1, std::sync::atomic::Ordering::AcqRel); + runtime.load_missed.lock().unwrap().remove(name); + StoreOutcome::Usable + } + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => { + if runtime.load_missed.lock().unwrap().contains(name) { + crate::xlog_warn!( + "Pipeline library: {name} already exists in {} but failed to load; not marking usable", + runtime.path.display() + ); + StoreOutcome::UnusableExisting + } else { + StoreOutcome::Usable + } + } + Err(e) => { + crate::xlog_warn!("Pipeline library: keeping {name}: {e}"); + StoreOutcome::TransientError + } + } +} + +fn read_cached_blob(pipeline: &ID3D12PipelineState) -> Option<Vec<u8>> { + // Use the adoption-aware helper because the first hand-out of a COM object from a pipeline + // library may have been adopted (swapping its vtable pointer to XCL's console ext class). + unsafe { crate::hle::d3d12x::real::read_pso_cached_blob(pipeline.as_raw()) } +} + +impl Active { + fn with_name( + &self, + name: &str, + kind: super::pipeline_stats::Kind, + f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>, + prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>, + ) -> Option<Loaded> { + use super::pipeline_stats::{library, Source}; + let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len(); + let _same_name = self.names[slot].lock().unwrap(); + let already_handed = self.handed.lock().unwrap().contains(name); + let (found, source) = if let Some(found) = prepared(self).and_then(|lib| f(lib).ok()) { + (found, Source::Prepared) + } else { + let runtime = self.runtime.as_ref()?; + match f(&runtime.library) { + Ok(found) => (found, Source::Runtime), + Err(_) => { + runtime.load_missed.lock().unwrap().insert(name.into()); + return None; + } + } + }; + if let Some(runtime) = &self.runtime { + runtime.load_missed.lock().unwrap().remove(name); + runtime.known.lock().unwrap().insert(name.into()); + } + if already_handed { + // A library loads a name as the same COM object each time, and XCL keys what it knows + // of a pipeline by its object (a dispatch chain by its first piece: a second chain + // with that piece replaced the first, and the replaced one's release deadlocked on the + // chain table). Hand out its cached blob instead so the caller creates a distinct COM + // object without recompiling in the driver, even for small shaders below the RAM blob + // cache threshold. + return read_cached_blob(&found).map(Loaded::Blob); + } + library(kind, source); + self.handed.lock().unwrap().insert(name.into()); + Some(Loaded::Pipeline(found)) + } + + fn apply_store_outcome(&self, runtime: &Runtime, name: &str, outcome: StoreOutcome) { + match outcome { + StoreOutcome::Usable => { + runtime.known.lock().unwrap().insert(name.into()); + // (a load may give back the very object stored: this one is out already) + self.handed.lock().unwrap().insert(name.into()); + } + StoreOutcome::UnusableExisting => { + runtime.known.lock().unwrap().insert(name.into()); + } + StoreOutcome::TransientError => {} + } + } + + /// A pipeline built at runtime, kept in `runtime.plib` (one found in a library is not kept again). + fn store_runtime(&self, name: &str, pipeline: &ID3D12PipelineState) { + use std::sync::atomic::Ordering; + let Some(runtime) = self.runtime.as_ref() else { return }; + if name.is_empty() || runtime.full.load(Ordering::Acquire) { return } + let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % self.names.len(); + let _same_name = self.names[slot].lock().unwrap(); + 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 }; + // Reserve while holding `store_lock.read()` so a concurrent `store_lock.write()` holder + // can never reset `estimated_size` while an unstored fast-path reservation is in flight. + let outcome = { + let read_guard = runtime.store_lock.read().unwrap(); + if runtime.full.load(Ordering::Acquire) { return } + if runtime.try_reserve_fast(est) { + record_store_result(runtime, name, runtime.library.store(name, pipeline)) + } else { + drop(read_guard); + let _write_guard = runtime.store_lock.write().unwrap(); + if !runtime.can_store_locked(est) { return } + let outcome = record_store_result(runtime, name, runtime.library.store(name, pipeline)); + let after = runtime.library.serialized_size(); + runtime.estimated_size.store(after, Ordering::Release); + if matches!(outcome, StoreOutcome::Usable) && after >= admit_cap(runtime.cap) { + runtime.mark_full(after); + } + outcome + } + }; + self.apply_store_outcome(runtime, name, outcome); + } +} + +fn with_name( + name: &str, + kind: super::pipeline_stats::Kind, + f: impl Fn(&NativeLibrary) -> windows::core::Result<ID3D12PipelineState>, + prepared: impl FnOnce(&Active) -> Option<&NativeLibrary>, +) -> Option<Loaded> { + ACTIVE.get()?.with_name(name, kind, f, prepared) +} + +fn store_runtime(name: &str, pipeline: &ID3D12PipelineState) { + if let Some(active) = ACTIVE.get() { active.store_runtime(name, pipeline); } +} + +/// One build of a pipeline at a time while the title runs (`one_build`). +struct OneBuildFlights { + building: std::sync::Mutex<Option<std::collections::HashMap<String, (std::thread::ThreadId, u64)>>>, + next_id: std::sync::atomic::AtomicU64, + built: std::sync::Condvar, +} + +impl OneBuildFlights { + const fn new() -> Self { + Self { + building: std::sync::Mutex::new(None), + next_id: std::sync::atomic::AtomicU64::new(0), + built: std::sync::Condvar::new(), + } + } + + fn enter(&self, name: &str, wait: std::time::Duration) -> OneBuildGuard<'_> { + let until = std::time::Instant::now() + wait; + let mut building = self.building.lock().unwrap(); + while building.as_ref().is_some_and(|b| b.contains_key(name)) { + let left = until.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + crate::xlog_info!("Pipeline library: still waiting for another build of {name} after {} s; building it here too", wait.as_secs()); + return OneBuildGuard { flights: self, flight: None }; + } + building = self.built.wait_timeout(building, left).unwrap().0; + } + let id = self.next_id.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + building.get_or_insert_with(Default::default).insert(name.to_owned(), (std::thread::current().id(), id)); + OneBuildGuard { flights: self, flight: Some((name.to_owned(), id)) } + } + + /// Releases any in-flight build(s) owned by the current thread so a worker parked at the + /// compile gate does not stall an ungated title thread waiting on the same pipeline name. + fn release_current_thread(&self) { + let me = std::thread::current().id(); + let mut building = self.building.lock().unwrap(); + let Some(map) = building.as_mut() else { return }; + let before = map.len(); + map.retain(|_, (tid, _)| *tid != me); + if map.len() != before { + self.built.notify_all(); + } + } +} + +static FLIGHTS: OneBuildFlights = OneBuildFlights::new(); + +/// While held, no other thread builds the pipeline of this name. +pub(crate) struct OneBuildGuard<'a> { + flights: &'a OneBuildFlights, + flight: Option<(String, u64)>, +} + +pub(crate) type OneBuild = OneBuildGuard<'static>; + +impl Drop for OneBuildGuard<'_> { + fn drop(&mut self) { + let Some((name, id)) = self.flight.take() else { return }; + let mut removed = false; + if let Some(building) = self.flights.building.lock().unwrap().as_mut() { + if building.get(&name).is_some_and(|&(_, cur)| cur == id) { + building.remove(&name); + removed = true; + } + } + if removed { + self.flights.built.notify_all(); + } + } +} + +/// Releases any `one_build` flight owned by the current thread when it parks in the compile gate. +pub(crate) fn release_one_build_on_park() { + FLIGHTS.release_current_thread(); +} + +fn should_use_one_build(name: &str, has_runtime: bool, runtime_full: bool) -> bool { + !name.is_empty() && has_runtime && !runtime_full +} + +/// Up to `XCL_ONE_BUILD_WAIT_S` (60) for another thread's build of this name to end: that one is +/// 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 { ~~~~ --- **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.
bmjask commented 2026-12-02 19:21:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T19:21:36Z.

Review: COMMENTED


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.

<!-- greyfinch-sync:ivall/xcl:review:6157337295 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#pullrequestreview-6157337295). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T19:21:36Z. **Review:** COMMENTED --- 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._
Kalmarv commented 2026-12-02 20:04:42 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T20:04:42Z.


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.
<!-- greyfinch-sync:ivall/xcl:comment:7357175129 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7357175129). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T20:04:42Z. --- 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 commented 2026-12-02 20:16:43 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T20:16:43Z.

Review: COMMENTED


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.

<!-- greyfinch-sync:ivall/xcl:review:6158208501 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#pullrequestreview-6158208501). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T20:16:43Z. **Review:** COMMENTED --- 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._
bmjask commented 2026-12-02 20:16:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T20:16:44Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 1031

@@ -230,6 +1024,10 @@ impl NativeLibrary {
         unsafe { self.library.LoadPipeline(&HSTRING::from(name), desc) }
     }
 
+    pub(crate) fn serialized_size(&self) -> u64 {
+        unsafe { self.library.GetSerializedSize() as u64 }
+    }
+
     pub(crate) fn serialize(&self) -> Result<Vec<u8>> {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775419182 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4775419182). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T20:16:44Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 1031 ~~~~diff @@ -230,6 +1024,10 @@ impl NativeLibrary { unsafe { self.library.LoadPipeline(&HSTRING::from(name), desc) } } + pub(crate) fn serialized_size(&self) -> u64 { + unsafe { self.library.GetSerializedSize() as u64 } + } + pub(crate) fn serialize(&self) -> Result<Vec<u8>> { ~~~~ --- **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.
bmjask commented 2026-12-02 20:16:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T20:16:44Z.

Code review location: crates/xcl/src/shaders/pipeline_library.rs; line 454

@@ -20,39 +20,825 @@ struct Previous {
 
 static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None);
 
+/// Result of looking up a named pipeline in the active libraries.
+pub(crate) enum Loaded {
+    /// First hand-out of this name's COM object in this process.
+    Pipeline(ID3D12PipelineState),
+    /// This name's COM object was already handed out; its driver blob lets the caller create a
+    /// distinct COM object without recompiling in the driver.
+    Blob(Vec<u8>),
+}
+
 struct Active {
     graphics: Option<NativeLibrary>,
     compute: Option<NativeLibrary>,
+    runtime: Option<Runtime>,
     names: [std::sync::Mutex<()>; 64],
+    /// Names whose pipeline a library handed out (or stored at runtime) in this process.
+    handed: std::sync::Mutex<std::collections::HashSet<String>>,
+}
+
+#[derive(Default)]
+struct FlushState {
+    consecutive_failures: u32,
+    disabled: bool,
+}
+
+const MAX_FLUSH_FAILURES: u32 = 3;
+
+/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under
+/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`),
+/// and serves what no prepared library has: pipelines no recorded recipe described, and those
+/// whose translation changed since the last preparation.
+struct Runtime {
+    library: NativeLibrary,
+    path: std::path::PathBuf,
+    cap: u64,
+    known: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later
+    /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept.
+    load_missed: std::sync::Mutex<std::collections::HashSet<String>>,
+    /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits
+    /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks
+    /// pipeline loads (`with_name`).
+    flush_lock: std::sync::Mutex<FlushState>,
+    /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly
+    /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across
+    /// disk I/O.
+    store_lock: std::sync::RwLock<()>,
+    added: std::sync::atomic::AtomicUsize,
+    /// Bytes last read or written: a larger library is written less often (`flush_every`).
+    size: std::sync::atomic::AtomicU64,
+    /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the
+    /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`.
+    estimated_size: std::sync::atomic::AtomicU64,
+    /// Latched once `runtime.plib` reaches `admit_cap(cap)`: stops further `StorePipeline`
+    /// additions so the saved library stays `<= cap` and reloads cleanly on the next launch.
+    full: std::sync::atomic::AtomicBool,
+    /// Build/settings stamp written next to `runtime.plib` when a fresh library is first flushed.
+    stamp: String,
+    /// True when `runtime.stamp` should be written on the next successful flush (fresh library
+    /// or upgrade from a library with no stamp file yet).
+    write_stamp: std::sync::atomic::AtomicBool,
 }
 
 static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new();
 
-pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
-    let Some(ready) = super::warm_library::take_ready() else { return Ok(()) };
-    let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)
-        .ok_or("Pipeline library: runtime driver identity is unavailable")?;
-    if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) }
-    if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) }
-    let open = |bytes| NativeLibrary::open_shared(device, bytes);
-    let graphics = ready.graphics.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?;
-    let compute = ready.compute.map(open).transpose()
-        .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?;
-    if let Some((path, bytes)) = ready.migration {
-        write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?;
+/// Within this distance of `admit_cap(Runtime::cap)`, `store_runtime` serializes additions under
+/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`.
+const NEAR_CAP_MARGIN: u64 = 16 << 20;
+/// Conservative per-entry overhead above `GetCachedBlob()` + UTF-16 name to cover root signature,
+/// input layout, and pipeline-desc subobjects serialized by D3D12.
+const ENTRY_OVERHEAD: u64 = 64 << 10;
+/// Safety buffer below `cap` where admission stops (for real caps >= 16 MiB), so minor D3D12
+/// directory/metadata growth on the final admitted store cannot push `flush_runtime_on` over `cap`.
+const CAP_ADMIT_HEADROOM: u64 = 2 << 20;
+
+fn admit_cap(cap: u64) -> u64 {
+    if cap >= (16 << 20) { cap.saturating_sub(CAP_ADMIT_HEADROOM) } else { cap }
+}
+
+fn runtime_stamp() -> String {
+    format!(
+        "{}:{:016x}:{:016x}",
+        env!("XCL_PIPELINE_LAYOUT_ID"),
+        crate::gpu::recomp::pso::translation_cache_identity(),
+        super::warm_settings_key(),
+    )
+}
+
+fn stamp_path(path: &std::path::Path) -> std::path::PathBuf {
+    path.with_extension("stamp")
+}
+
+fn should_reset_full_runtime(existing_len: u64, cap: u64, saved_stamp: Option<&str>, current_stamp: &str) -> bool {
+    existing_len >= admit_cap(cap) && saved_stamp.map(str::trim) != Some(current_stamp)
+}
+
+fn needs_stamp_write(started_fresh: bool, saved_stamp: Option<&str>, current_stamp: &str) -> bool {
+    started_fresh || saved_stamp.map(str::trim) != Some(current_stamp)
+}
+
+/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds
+/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the
+/// saved library stays reusable across launches; lowering the cap below an existing file resets
+/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily
+/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size.
+fn runtime_cap() -> u64 {
+    parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref())
+}
+
+fn parse_runtime_cap(raw: Option<&str>) -> u64 {
+    raw.and_then(|v| v.trim().parse::<u64>().ok())
+        .unwrap_or(2048)
+        .saturating_mul(1 << 20)
+}
+
+enum ReadCapped {
+    Bytes(std::sync::Arc<[u8]>),
+    OverCap,
+    Skip,
+}
+
+fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped {
+    use std::io::Read;
+    if cap == 0 { return ReadCapped::Skip; }
+    let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip };
+    let mut bytes = Vec::new();
+    if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; }
+    let limit = cap.saturating_add(1);
+    if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; }
+    if bytes.is_empty() { return ReadCapped::Skip; }
+    if bytes.len() as u64 > cap { return ReadCapped::OverCap; }
+    ReadCapped::Bytes(bytes.into())
+}
+
+pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> {
+    if cap == 0 { return None; }
+    let file = std::fs::File::open(path).ok()?;
+    let meta = file.metadata().ok()?;
+    if !meta.is_file() { return None; }
+    let len = meta.len();
+    if len == 0 { return None; }
+    if len > cap {
+        crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+        return None;
+    }
+    match read_capped(file, len, cap) {
+        ReadCapped::Bytes(bytes) => Some(bytes),
+        ReadCapped::OverCap => {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            None
+        }
+        ReadCapped::Skip => None,
+    }
+}
+
+pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> {
+    read_runtime_file_capped(path, runtime_cap())
+}
+
+/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush.
+fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) {
+    let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return };
+    let prefix = format!("{stem}.tmp");
+    let Ok(entries) = std::fs::read_dir(parent) else { return };
+    let my_pid = std::process::id();
+    for entry in entries.flatten() {
+        let name = entry.file_name();
+        let Some(name) = name.to_str() else { continue };
+        let Some(rest) = name.strip_prefix(&prefix) else { continue };
+        let live_other = rest.split_once('-')
+            .and_then(|(pid, _)| pid.parse::<u32>().ok())
+            .is_some_and(|pid| pid != my_pid && is_running(pid));
+        if !live_other {
+            let _ = std::fs::remove_file(entry.path());
+        }
+    }
+}
+
+fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> {
+    cleanup_stale_runtime_temps(&path, crate::state::process_is_running);
+    let cap = runtime_cap();
+    if cap == 0 {
+        crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)");
+        return None;
+    }
+    let current_stamp = runtime_stamp();
+    let saved_stamp = std::fs::read_to_string(stamp_path(&path)).ok();
+    let bytes = bytes.filter(|b| {
+        if b.len() as u64 > cap {
+            crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display());
+            return false;
+        }
+        if should_reset_full_runtime(b.len() as u64, cap, saved_stamp.as_deref(), &current_stamp) {
+            crate::xlog_info!(
+                "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB and contains entries from an older build or settings; starting it fresh",
+                path.display()
+            );
+            return false;
+        }
+        true
+    });
+    let mut started_fresh = bytes.is_none();
+    let size = bytes.as_ref().map_or(0, |b| b.len() as u64);
+    let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) {
+        Some(Ok(library)) => library,
+        Some(Err(e)) => {
+            // (one of another driver: D3D12 opens a library only with the driver that made it)
+            crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display());
+            started_fresh = true;
+            NativeLibrary::empty(device).ok()?
+        }
+        None => NativeLibrary::empty(device).ok()?,
+    };
+    let initial_size = library.serialized_size();
+    let full = initial_size >= admit_cap(cap);
+    let write_stamp = needs_stamp_write(started_fresh, saved_stamp.as_deref(), &current_stamp);
+    Some(Runtime {
+        library,
+        path,
+        cap,
+        known: Default::default(),
+        load_missed: Default::default(),
+        flush_lock: Default::default(),
+        store_lock: Default::default(),
+        added: Default::default(),
+        size: size.into(),
+        estimated_size: initial_size.into(),
+        full: full.into(),
+        stamp: current_stamp,
+        write_stamp: write_stamp.into(),
+    })
+}
+
+fn check_library_support(supported: bool, has_prepared: bool, cache_only: bool) -> std::result::Result<bool, String> {
+    if supported {
+        return Ok(true);
+    }
+    if cache_only && has_prepared {
+        return Err("Pipeline library: the device does not support pipeline libraries".into());
+    }
+    crate::xlog_info!("Pipeline library: the device does not support pipeline libraries");
+    Ok(false)
+}
+
+fn check_activation_driver(
+    ready_driver: u64,
+    runtime_driver: Option<u64>,
+    has_prepared: bool,
+    cache_only: bool,
+) -> std::result::Result<bool, String> {
+    if runtime_driver == Some(ready_driver) {
+        return Ok(true);
+    }
+    let reason = if runtime_driver.is_none() {
+        "Pipeline library: runtime driver identity is unavailable"
+    } else {
+        "Pipeline library: runtime adapter or driver differs from the prepared cache"
+    };
+    if cache_only && has_prepared {
+        return Err(reason.into());
+    }
+    if has_prepared {
+        crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib");
     }
-    if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() {
-        crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+    Ok(false)
+}
+
+fn open_active_for_device(
+    device: &ID3D12Device,
+    ready: super::warm_library::Ready,
+    runtime_driver: Option<u64>,
+    cache_only: bool,
+) -> 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 !check_library_support(NativeLibrary::supported(device), has_prepared, cache_only)? {
+        return Ok(None);
+    }
+    let open = |bytes| NativeLibrary::open_shared(device, bytes);
+    let graphics = if use_prepared {
+        ready.graphics.map(open).transpose()
+            .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?
+    } else {
+        None
+    };
+    let compute = if use_prepared {
+        ready.compute.map(open).transpose()
+            .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?
+    } else {
+        None
+    };
+    let runtime = open_runtime(device, ready.runtime_path, ready.runtime);
+    let names = std::array::from_fn(|_| std::sync::Mutex::new(()));
+    Ok(Some(Active { graphics, compute, runtime, names, handed: Default::default() }))
+}
+
+pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> {
+    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;
+        let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?;
+        let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows())
+            .join(super::warm_library::RUNTIME);
+        Some(super::warm_library::Ready {
+            graphics: None,
+            compute: None,
+            runtime: read_runtime_file(&path),
+            runtime_path: path,
+            driver,
+        })
+    });
+    let Some(ready) = ready else { return Ok(()) };
+    let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device);
+    let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1");
+    let Some(active) = open_active_for_device(device, ready, runtime_driver, cache_only)? else {
+        return Ok(());
+    };
+    start_counting();
+    let has_any_prepared = active.graphics.is_some() || active.compute.is_some();
+    let has_runtime = active.runtime.is_some();
+    if ACTIVE.set(active).is_ok() {
+        if has_any_prepared {
+            crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading");
+        } else if has_runtime {
+            crate::xlog_info!("Pipeline library: activated runtime library for lazy runtime loading");
+        }
     }
     Ok(())
 }
 
-fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> {
-    let active = ACTIVE.get()?;
-    let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len();
-    let _same_name = active.names[slot].lock().unwrap();
-    f(active)?.ok()
+static PERIODIC_FLUSH_TID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+static SHUTTING_DOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+
+/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the
+/// runtime library is written when it grew, and the counts are logged when they changed.
+fn start_counting() {
+    static STARTED: std::sync::Once = std::sync::Once::new();
+    STARTED.call_once(|| {
+        super::pipeline_stats::arm();
+        let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| {
+            let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
+            PERIODIC_FLUSH_TID.store(tid, std::sync::atomic::Ordering::Release);
+            let mut since = 0;
+            loop {
+                std::thread::sleep(std::time::Duration::from_secs(30));
+                if SHUTTING_DOWN.load(std::sync::atomic::Ordering::Acquire) {
+                    return;
+                }
+                since += 1;
+                if since >= flush_every() {
+                    if SHUTTING_DOWN.load(std::sync::atomic::Ordering::Acquire) {
+                        return;
+                    }
+                    flush_runtime();
+                    since = 0;
+                }
+                if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); }
+            }
+        });
+    });
+}
+
+/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time.
+fn flush_every() -> u64 {
+    let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed));
+    1 + (size >> 28)
+}
+
+fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> {
+    // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline
+    // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small).
+    // Retry without blocking stores first, and only pause stores if they keep racing.
+    for _ in 0..3 {
+        match runtime.library.serialize() {
+            Ok(bytes) => return Ok(bytes),
+            Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue,
+            Err(e) => return Err(e),
+        }
+    }
+    let _pause_stores = runtime.store_lock.write().unwrap();
+    runtime.library.serialize()
+}
+
+fn is_permanent_write_error(e: &std::io::Error) -> bool {
+    const ERROR_WRITE_PROTECT: i32 = 19;
+    e.raw_os_error() == Some(ERROR_WRITE_PROTECT)
+}
+
+fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool {
+    use std::sync::atomic::Ordering;
+    let mut state = runtime.flush_lock.lock().unwrap();
+    if state.disabled { return false }
+    let added = runtime.added.swap(0, Ordering::AcqRel);
+    if added == 0 { return false }
+    let current = runtime.library.serialized_size();
+    if current > runtime.cap {
+        runtime.mark_full(current);
+        state.disabled = true;
+        crate::xlog_warn!(
+            "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library",
+            runtime.path.display(), current, runtime.cap
+        );
+        return false;
+    }
+    let bytes = match serialize_runtime(runtime) {
+        Ok(b) => b,
+        Err(e) => {
+            state.consecutive_failures += 1;
+            if state.consecutive_failures >= MAX_FLUSH_FAILURES {
+                state.disabled = true;
+                crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}",
+                    runtime.path.display(), state.consecutive_failures);
+            } else {
+                runtime.added.fetch_add(added, Ordering::AcqRel);
+                crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display());
+            }
+            return false;
+        }
+    };
+    if bytes.len() as u64 > runtime.cap {
+        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",
+            runtime.path.display(), bytes.len(), runtime.cap
+        );
+        return false;
+    }
+    match write(&runtime.path, &bytes) {
+        Ok(()) => {
+            state.consecutive_failures = 0;
+            runtime.size.store(bytes.len() as u64, Ordering::Relaxed);
+            if runtime.write_stamp.swap(false, Ordering::AcqRel) {

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775419196 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4775419196). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T20:16:44Z. **Code review location:** `crates/xcl/src/shaders/pipeline_library.rs`; line 454 ~~~~diff @@ -20,39 +20,825 @@ struct Previous { static BUILD: std::sync::Mutex<Option<Builder>> = std::sync::Mutex::new(None); +/// Result of looking up a named pipeline in the active libraries. +pub(crate) enum Loaded { + /// First hand-out of this name's COM object in this process. + Pipeline(ID3D12PipelineState), + /// This name's COM object was already handed out; its driver blob lets the caller create a + /// distinct COM object without recompiling in the driver. + Blob(Vec<u8>), +} + struct Active { graphics: Option<NativeLibrary>, compute: Option<NativeLibrary>, + runtime: Option<Runtime>, names: [std::sync::Mutex<()>; 64], + /// Names whose pipeline a library handed out (or stored at runtime) in this process. + handed: std::sync::Mutex<std::collections::HashSet<String>>, +} + +#[derive(Default)] +struct FlushState { + consecutive_failures: u32, + disabled: bool, +} + +const MAX_FLUSH_FAILURES: u32 = 3; + +/// `runtime.plib`: every pipeline the title built while it ran, kept for its next runs under +/// XCL's per-title data folder. It is written again while new ones are added (`flush_runtime`), +/// and serves what no prepared library has: pipelines no recorded recipe described, and those +/// whose translation changed since the last preparation. +struct Runtime { + library: NativeLibrary, + path: std::path::PathBuf, + cap: u64, + known: std::sync::Mutex<std::collections::HashSet<String>>, + /// Names whose `Load*` from this runtime library failed in this run: if `StorePipeline` later + /// returns `E_INVALIDARG`, the existing entry is unusable rather than cleanly kept. + load_missed: std::sync::Mutex<std::collections::HashSet<String>>, + /// Held end-to-end across `added.swap(0)` + `serialize` + `write_atomic` so shutdown waits + /// for any in-flight write and older snapshots cannot overwrite newer ones. Never blocks + /// pipeline loads (`with_name`). + flush_lock: std::sync::Mutex<FlushState>, + /// Read-locked by `store_runtime`; write-locked near `cap` or if `Serialize` repeatedly + /// races with concurrent `StorePipeline` calls. Never taken by `with_name` or held across + /// disk I/O. + store_lock: std::sync::RwLock<()>, + added: std::sync::atomic::AtomicUsize, + /// Bytes last read or written: a larger library is written less often (`flush_every`). + size: std::sync::atomic::AtomicU64, + /// Conservative running byte estimate used by `try_reserve_fast` so concurrent stores on the + /// read-lock path cannot collectively push `library` past `cap - NEAR_CAP_MARGIN`. + estimated_size: std::sync::atomic::AtomicU64, + /// Latched once `runtime.plib` reaches `admit_cap(cap)`: stops further `StorePipeline` + /// additions so the saved library stays `<= cap` and reloads cleanly on the next launch. + full: std::sync::atomic::AtomicBool, + /// Build/settings stamp written next to `runtime.plib` when a fresh library is first flushed. + stamp: String, + /// True when `runtime.stamp` should be written on the next successful flush (fresh library + /// or upgrade from a library with no stamp file yet). + write_stamp: std::sync::atomic::AtomicBool, } static ACTIVE: std::sync::OnceLock<Active> = std::sync::OnceLock::new(); -pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { - let Some(ready) = super::warm_library::take_ready() else { return Ok(()) }; - let driver = crate::hle::d3d12x::real::preparation_driver_identity(device) - .ok_or("Pipeline library: runtime driver identity is unavailable")?; - if driver != ready.driver { return Err("Pipeline library: runtime adapter or driver differs from the prepared cache".into()) } - if !NativeLibrary::supported(device) { return Err("Pipeline library: runtime device does not support pipeline libraries".into()) } - let open = |bytes| NativeLibrary::open_shared(device, bytes); - let graphics = ready.graphics.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))?; - let compute = ready.compute.map(open).transpose() - .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))?; - if let Some((path, bytes)) = ready.migration { - write_atomic(&path, &bytes).map_err(|e| format!("Pipeline library: writing migrated receipt: {e}"))?; +/// Within this distance of `admit_cap(Runtime::cap)`, `store_runtime` serializes additions under +/// `store_lock.write()` and checks each pipeline's estimated size before calling `StorePipeline`. +const NEAR_CAP_MARGIN: u64 = 16 << 20; +/// Conservative per-entry overhead above `GetCachedBlob()` + UTF-16 name to cover root signature, +/// input layout, and pipeline-desc subobjects serialized by D3D12. +const ENTRY_OVERHEAD: u64 = 64 << 10; +/// Safety buffer below `cap` where admission stops (for real caps >= 16 MiB), so minor D3D12 +/// directory/metadata growth on the final admitted store cannot push `flush_runtime_on` over `cap`. +const CAP_ADMIT_HEADROOM: u64 = 2 << 20; + +fn admit_cap(cap: u64) -> u64 { + if cap >= (16 << 20) { cap.saturating_sub(CAP_ADMIT_HEADROOM) } else { cap } +} + +fn runtime_stamp() -> String { + format!( + "{}:{:016x}:{:016x}", + env!("XCL_PIPELINE_LAYOUT_ID"), + crate::gpu::recomp::pso::translation_cache_identity(), + super::warm_settings_key(), + ) +} + +fn stamp_path(path: &std::path::Path) -> std::path::PathBuf { + path.with_extension("stamp") +} + +fn should_reset_full_runtime(existing_len: u64, cap: u64, saved_stamp: Option<&str>, current_stamp: &str) -> bool { + existing_len >= admit_cap(cap) && saved_stamp.map(str::trim) != Some(current_stamp) +} + +fn needs_stamp_write(started_fresh: bool, saved_stamp: Option<&str>, current_stamp: &str) -> bool { + started_fresh || saved_stamp.map(str::trim) != Some(current_stamp) +} + +/// `XCL_RUNTIME_LIBRARY_MB` (2048 MiB default; `0` disables `runtime.plib`): bounds +/// `runtime.plib` on both store/save and load. Once full, further runtime stores stop so the +/// saved library stays reusable across launches; lowering the cap below an existing file resets +/// it on the next launch. D3D12 retains the opened bytes in RAM and each flush temporarily +/// allocates a serialized copy, so commit overhead is roughly 1-2x the file size. +fn runtime_cap() -> u64 { + parse_runtime_cap(std::env::var("XCL_RUNTIME_LIBRARY_MB").ok().as_deref()) +} + +fn parse_runtime_cap(raw: Option<&str>) -> u64 { + raw.and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(2048) + .saturating_mul(1 << 20) +} + +enum ReadCapped { + Bytes(std::sync::Arc<[u8]>), + OverCap, + Skip, +} + +fn read_capped(reader: impl std::io::Read, expected: u64, cap: u64) -> ReadCapped { + use std::io::Read; + if cap == 0 { return ReadCapped::Skip; } + let Ok(reserve) = usize::try_from(expected.min(cap).saturating_add(1)) else { return ReadCapped::Skip }; + let mut bytes = Vec::new(); + if bytes.try_reserve_exact(reserve).is_err() { return ReadCapped::Skip; } + let limit = cap.saturating_add(1); + if reader.take(limit).read_to_end(&mut bytes).is_err() { return ReadCapped::Skip; } + if bytes.is_empty() { return ReadCapped::Skip; } + if bytes.len() as u64 > cap { return ReadCapped::OverCap; } + ReadCapped::Bytes(bytes.into()) +} + +pub(super) fn read_runtime_file_capped(path: &std::path::Path, cap: u64) -> Option<std::sync::Arc<[u8]>> { + if cap == 0 { return None; } + let file = std::fs::File::open(path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() { return None; } + let len = meta.len(); + if len == 0 { return None; } + if len > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return None; + } + match read_capped(file, len, cap) { + ReadCapped::Bytes(bytes) => Some(bytes), + ReadCapped::OverCap => { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + None + } + ReadCapped::Skip => None, + } +} + +pub(super) fn read_runtime_file(path: &std::path::Path) -> Option<std::sync::Arc<[u8]>> { + read_runtime_file_capped(path, runtime_cap()) +} + +/// Remove orphaned `<stem>.tmp<pid>-<n>` files left behind by a killed or crashed flush. +fn cleanup_stale_runtime_temps(path: &std::path::Path, is_running: impl Fn(u32) -> bool) { + let (Some(parent), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else { return }; + let prefix = format!("{stem}.tmp"); + let Ok(entries) = std::fs::read_dir(parent) else { return }; + let my_pid = std::process::id(); + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + let Some(rest) = name.strip_prefix(&prefix) else { continue }; + let live_other = rest.split_once('-') + .and_then(|(pid, _)| pid.parse::<u32>().ok()) + .is_some_and(|pid| pid != my_pid && is_running(pid)); + if !live_other { + let _ = std::fs::remove_file(entry.path()); + } + } +} + +fn open_runtime(device: &ID3D12Device, path: std::path::PathBuf, bytes: Option<std::sync::Arc<[u8]>>) -> Option<Runtime> { + cleanup_stale_runtime_temps(&path, crate::state::process_is_running); + let cap = runtime_cap(); + if cap == 0 { + crate::xlog_info!("Pipeline library: runtime library disabled (XCL_RUNTIME_LIBRARY_MB=0)"); + return None; + } + let current_stamp = runtime_stamp(); + let saved_stamp = std::fs::read_to_string(stamp_path(&path)).ok(); + let bytes = bytes.filter(|b| { + if b.len() as u64 > cap { + crate::xlog_info!("Pipeline library: {} is over XCL_RUNTIME_LIBRARY_MB; starting it again", path.display()); + return false; + } + if should_reset_full_runtime(b.len() as u64, cap, saved_stamp.as_deref(), &current_stamp) { + crate::xlog_info!( + "Pipeline library: {} reached XCL_RUNTIME_LIBRARY_MB and contains entries from an older build or settings; starting it fresh", + path.display() + ); + return false; + } + true + }); + let mut started_fresh = bytes.is_none(); + let size = bytes.as_ref().map_or(0, |b| b.len() as u64); + let library = match bytes.map(|b| NativeLibrary::open_shared(device, b)) { + Some(Ok(library)) => library, + Some(Err(e)) => { + // (one of another driver: D3D12 opens a library only with the driver that made it) + crate::xlog_info!("Pipeline library: {} not reusable ({e}); starting it again", path.display()); + started_fresh = true; + NativeLibrary::empty(device).ok()? + } + None => NativeLibrary::empty(device).ok()?, + }; + let initial_size = library.serialized_size(); + let full = initial_size >= admit_cap(cap); + let write_stamp = needs_stamp_write(started_fresh, saved_stamp.as_deref(), &current_stamp); + Some(Runtime { + library, + path, + cap, + known: Default::default(), + load_missed: Default::default(), + flush_lock: Default::default(), + store_lock: Default::default(), + added: Default::default(), + size: size.into(), + estimated_size: initial_size.into(), + full: full.into(), + stamp: current_stamp, + write_stamp: write_stamp.into(), + }) +} + +fn check_library_support(supported: bool, has_prepared: bool, cache_only: bool) -> std::result::Result<bool, String> { + if supported { + return Ok(true); + } + if cache_only && has_prepared { + return Err("Pipeline library: the device does not support pipeline libraries".into()); + } + crate::xlog_info!("Pipeline library: the device does not support pipeline libraries"); + Ok(false) +} + +fn check_activation_driver( + ready_driver: u64, + runtime_driver: Option<u64>, + has_prepared: bool, + cache_only: bool, +) -> std::result::Result<bool, String> { + if runtime_driver == Some(ready_driver) { + return Ok(true); + } + let reason = if runtime_driver.is_none() { + "Pipeline library: runtime driver identity is unavailable" + } else { + "Pipeline library: runtime adapter or driver differs from the prepared cache" + }; + if cache_only && has_prepared { + return Err(reason.into()); + } + if has_prepared { + crate::xlog_warn!("{reason}; skipping prepared pipeline libraries and continuing with runtime.plib"); } - if ACTIVE.set(Active { graphics, compute, names: std::array::from_fn(|_| std::sync::Mutex::new(())) }).is_ok() { - crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); + Ok(false) +} + +fn open_active_for_device( + device: &ID3D12Device, + ready: super::warm_library::Ready, + runtime_driver: Option<u64>, + cache_only: bool, +) -> 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 !check_library_support(NativeLibrary::supported(device), has_prepared, cache_only)? { + return Ok(None); + } + let open = |bytes| NativeLibrary::open_shared(device, bytes); + let graphics = if use_prepared { + ready.graphics.map(open).transpose() + .map_err(|e| format!("Pipeline library: runtime graphics activation failed ({e})"))? + } else { + None + }; + let compute = if use_prepared { + ready.compute.map(open).transpose() + .map_err(|e| format!("Pipeline library: runtime compute activation failed ({e})"))? + } else { + None + }; + let runtime = open_runtime(device, ready.runtime_path, ready.runtime); + let names = std::array::from_fn(|_| std::sync::Mutex::new(())); + Ok(Some(Active { graphics, compute, runtime, names, handed: Default::default() })) +} + +pub(crate) fn activate(device: &ID3D12Device) -> std::result::Result<(), String> { + 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; + let driver = crate::hle::d3d12x::real::preparation_driver_identity(device)?; + let path = super::warm_library::runtime_directory(data_dir, super::warm_library::runtime_windows()) + .join(super::warm_library::RUNTIME); + Some(super::warm_library::Ready { + graphics: None, + compute: None, + runtime: read_runtime_file(&path), + runtime_path: path, + driver, + }) + }); + let Some(ready) = ready else { return Ok(()) }; + let runtime_driver = crate::hle::d3d12x::real::preparation_driver_identity(device); + let cache_only = std::env::var("XCL_PREPARE_CACHE_ONLY").is_ok_and(|v| v.trim() == "1"); + let Some(active) = open_active_for_device(device, ready, runtime_driver, cache_only)? else { + return Ok(()); + }; + start_counting(); + let has_any_prepared = active.graphics.is_some() || active.compute.is_some(); + let has_runtime = active.runtime.is_some(); + if ACTIVE.set(active).is_ok() { + if has_any_prepared { + crate::xlog_info!("Pipeline library: activated prepared PSOs for lazy runtime loading"); + } else if has_runtime { + crate::xlog_info!("Pipeline library: activated runtime library for lazy runtime loading"); + } } Ok(()) } -fn with_name<T>(name: &str, f: impl FnOnce(&Active) -> Option<windows::core::Result<T>>) -> Option<T> { - let active = ACTIVE.get()?; - let slot = crate::gpu::shader::fnv64(name.as_bytes()) as usize % active.names.len(); - let _same_name = active.names[slot].lock().unwrap(); - f(active)?.ok() +static PERIODIC_FLUSH_TID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); +static SHUTTING_DOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// The title's pipelines are counted from here on (`pipeline_stats`), and every 30 s the +/// runtime library is written when it grew, and the counts are logged when they changed. +fn start_counting() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + super::pipeline_stats::arm(); + let _ = std::thread::Builder::new().name("xcl-pipeline-library".into()).spawn(|| { + let tid = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + PERIODIC_FLUSH_TID.store(tid, std::sync::atomic::Ordering::Release); + let mut since = 0; + loop { + std::thread::sleep(std::time::Duration::from_secs(30)); + if SHUTTING_DOWN.load(std::sync::atomic::Ordering::Acquire) { + return; + } + since += 1; + if since >= flush_every() { + if SHUTTING_DOWN.load(std::sync::atomic::Ordering::Acquire) { + return; + } + flush_runtime(); + since = 0; + } + if let Some(line) = super::pipeline_stats::summary() { crate::xlog_info!("{line}"); } + } + }); + }); +} + +/// In 30 s periods: once more for each 256 MB of `runtime.plib`, which is serialized whole each time. +fn flush_every() -> u64 { + let size = ACTIVE.get().and_then(|a| a.runtime.as_ref()).map_or(0, |r| r.size.load(std::sync::atomic::Ordering::Relaxed)); + 1 + (size >> 28) +} + +fn serialize_runtime(runtime: &Runtime) -> Result<Vec<u8>> { + // D3D12 synchronizes Serialize with concurrent Load* calls; a concurrent StorePipeline + // between GetSerializedSize and Serialize can return E_INVALIDARG (buffer too small). + // Retry without blocking stores first, and only pause stores if they keep racing. + for _ in 0..3 { + match runtime.library.serialize() { + Ok(bytes) => return Ok(bytes), + Err(e) if e.code() == windows::Win32::Foundation::E_INVALIDARG => continue, + Err(e) => return Err(e), + } + } + let _pause_stores = runtime.store_lock.write().unwrap(); + runtime.library.serialize() +} + +fn is_permanent_write_error(e: &std::io::Error) -> bool { + const ERROR_WRITE_PROTECT: i32 = 19; + e.raw_os_error() == Some(ERROR_WRITE_PROTECT) +} + +fn flush_runtime_on(runtime: &Runtime, write: impl FnOnce(&std::path::Path, &[u8]) -> std::io::Result<()>) -> bool { + use std::sync::atomic::Ordering; + let mut state = runtime.flush_lock.lock().unwrap(); + if state.disabled { return false } + let added = runtime.added.swap(0, Ordering::AcqRel); + if added == 0 { return false } + let current = runtime.library.serialized_size(); + if current > runtime.cap { + runtime.mark_full(current); + state.disabled = true; + crate::xlog_warn!( + "Pipeline library: {} would exceed XCL_RUNTIME_LIBRARY_MB ({} > {} bytes); keeping the previous on-disk library", + runtime.path.display(), current, runtime.cap + ); + return false; + } + let bytes = match serialize_runtime(runtime) { + Ok(b) => b, + Err(e) => { + state.consecutive_failures += 1; + if state.consecutive_failures >= MAX_FLUSH_FAILURES { + state.disabled = true; + crate::xlog_warn!("Pipeline library: stopping runtime library writes to {} after {} failed attempts: {e}", + runtime.path.display(), state.consecutive_failures); + } else { + runtime.added.fetch_add(added, Ordering::AcqRel); + crate::xlog_warn!("Pipeline library: serializing {}: {e}", runtime.path.display()); + } + return false; + } + }; + if bytes.len() as u64 > runtime.cap { + 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", + runtime.path.display(), bytes.len(), runtime.cap + ); + return false; + } + match write(&runtime.path, &bytes) { + Ok(()) => { + state.consecutive_failures = 0; + runtime.size.store(bytes.len() as u64, Ordering::Relaxed); + if runtime.write_stamp.swap(false, Ordering::AcqRel) { ~~~~ --- **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.
bmjask commented 2026-12-02 20:16:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T20:16:44Z.

Code review location: crates/xcl/src/hle/d3d12x/real.rs; line 8274

@@ -8171,7 +8271,8 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const
     let gkey = (disk_key.0, disk_key.1, rs as usize);
     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));

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775419208 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4775419208). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T20:16:44Z. **Code review location:** `crates/xcl/src/hle/d3d12x/real.rs`; line 8274 ~~~~diff @@ -8171,7 +8271,8 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let gkey = (disk_key.0, disk_key.1, rs as usize); 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)); ~~~~ --- **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.
bmjask commented 2026-12-02 20:16:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T20:16:44Z.

Code review location: crates/xcl/src/hle/d3d12x/real.rs; line 9692

@@ -9567,6 +9686,27 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu:
             }
         }
     }
+    // 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(

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4775419220 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#discussion_r4775419220). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T20:16:44Z. **Code review location:** `crates/xcl/src/hle/d3d12x/real.rs`; line 9692 ~~~~diff @@ -9567,6 +9686,27 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: } } } + // 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( ~~~~ --- **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.
Kalmarv commented 2026-12-02 20:58:24 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Kalmarv on 2026-12-02T20:58:24Z.


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.
<!-- greyfinch-sync:ivall/xcl:comment:7358604459 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7358604459). Originally posted by [Kalmarv](https://github.com/Kalmarv) on 2026-12-02T20:58:24Z. --- 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.
jsalzy commented 2026-12-02 23:48:35 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by jsalzy on 2026-12-02T23:48:35Z.


merge-check claim
head: 5894838c8b

<!-- greyfinch-sync:ivall/xcl:comment:7362451366 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7362451366). Originally posted by [jsalzy](https://github.com/jsalzy) on 2026-12-02T23:48:35Z. --- merge-check claim head: 5894838c8b5897d7243048eab1987159eea246c6
jsalzy commented 2026-12-02 23:57:56 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by jsalzy on 2026-12-02T23:57:56Z.


merge-check
base: 078358a
head: 5894838
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3034 passed, 0 failed, 52 ignored; SKIPPED: 25 (22 no wave64 on this GPU; 2 no heap windows (opt-in XCL_HEAP_WINDOWS=1); 1 driver cache cannot be disabled without Windows Developer Mode); failing: none
title run: not run
review: read real.rs, launcher.rs, present.rs, state.rs, gpu/recomp/pso.rs, build.rs and pipeline_library.rs's runtime path (activate, store, flush, cap, one_build, temp cleanup); warm_library.rs and pso_corpus.rs read for their publish and file handling, not line by line. No defect found in those. build.rs only drops the two legacy cache IDs (-5 lines). store cannot fail at run time (no build active -> store_runtime), so finish_two_pass's E_INVALIDARG returns apply only while a library is being prepared, as on main. one_build waits up to 60 s (XCL_ONE_BUILD_WAIT_S) for another thread's build of the same pipeline, is released when its holder parks in the compile gate, and is off once the runtime library is full; enter_two_pass_compute_one_build drops the mesh compile slot before waiting (tested). File writes and deletes stay in XCL's own folders: runtime.plib now lives in the per-title data folder, cleanup_stale_runtime_temps removes only runtime.tmp- files of processes no longer running, publish removes its own .plib.pending files, and the tests use %TEMP%. end_title and window close flush with a 5 s budget and keep the flush threads unsuspended. The new pipeline-library tests ran and passed (none skipped); no new compiler warnings. No duplicate: no other PR adds a runtime library, its cap or single-flight builds; #3158 and #3467 (both open) edit the same code and may conflict with it.
performance: on by default: every run reads runtime.plib (up to XCL_RUNTIME_LIBRARY_MB, 2048 MiB) into memory and keeps it, and while it grows it is serialized whole and rewritten every 30 s plus one more 30 s per 256 MB (throny's runs reached ~1.1 GB in 900 s), which costs commit and disk writes on machines near their commit limit, against fewer driver rebuilds (690 s of builds in the description's 240 s run). Exit and window close can take up to 5 s longer for the last flush. Not measured here.
verdict: safe to merge
hardware / tool and model: RTX 4070 SUPER 12 GB (621.24 / 32.0.16.2124), Ryzen 7 7800X3D, 32 GB, Windows 11 Pro 25H2 26200.9974, Rust 1.100.0, debug / Claude app (Claude Opus 5.5): merge, build and suite run on this PC with git and cargo only; diff review by Claude Opus 5.5.

<!-- greyfinch-sync:ivall/xcl:comment:7362638764 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7362638764). Originally posted by [jsalzy](https://github.com/jsalzy) on 2026-12-02T23:57:56Z. --- merge-check base: 078358a head: 5894838 merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3034 passed, 0 failed, 52 ignored; SKIPPED: 25 (22 no wave64 on this GPU; 2 no heap windows (opt-in XCL_HEAP_WINDOWS=1); 1 driver cache cannot be disabled without Windows Developer Mode); failing: none title run: not run review: read real.rs, launcher.rs, present.rs, state.rs, gpu/recomp/pso.rs, build.rs and pipeline_library.rs's runtime path (activate, store, flush, cap, one_build, temp cleanup); warm_library.rs and pso_corpus.rs read for their publish and file handling, not line by line. No defect found in those. build.rs only drops the two legacy cache IDs (-5 lines). store cannot fail at run time (no build active -> store_runtime), so finish_two_pass's E_INVALIDARG returns apply only while a library is being prepared, as on main. one_build waits up to 60 s (XCL_ONE_BUILD_WAIT_S) for another thread's build of the same pipeline, is released when its holder parks in the compile gate, and is off once the runtime library is full; enter_two_pass_compute_one_build drops the mesh compile slot before waiting (tested). File writes and deletes stay in XCL's own folders: runtime.plib now lives in the per-title data folder, cleanup_stale_runtime_temps removes only runtime.tmp<pid>-<n> files of processes no longer running, publish removes its own .plib.pending files, and the tests use %TEMP%. end_title and window close flush with a 5 s budget and keep the flush threads unsuspended. The new pipeline-library tests ran and passed (none skipped); no new compiler warnings. No duplicate: no other PR adds a runtime library, its cap or single-flight builds; #3158 and #3467 (both open) edit the same code and may conflict with it. performance: on by default: every run reads runtime.plib (up to XCL_RUNTIME_LIBRARY_MB, 2048 MiB) into memory and keeps it, and while it grows it is serialized whole and rewritten every 30 s plus one more 30 s per 256 MB (throny's runs reached ~1.1 GB in 900 s), which costs commit and disk writes on machines near their commit limit, against fewer driver rebuilds (690 s of builds in the description's 240 s run). Exit and window close can take up to 5 s longer for the last flush. Not measured here. verdict: safe to merge hardware / tool and model: RTX 4070 SUPER 12 GB (621.24 / 32.0.16.2124), Ryzen 7 7800X3D, 32 GB, Windows 11 Pro 25H2 26200.9974, Rust 1.100.0, debug / Claude app (Claude Opus 5.5): merge, build and suite run on this PC with git and cargo only; diff review by Claude Opus 5.5.
Foniass commented 2026-12-03 04:22:16 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T04:22:16Z.


merge-check
base: 078358a058
head: 5894838c8b
merge: clean
build: ok
tests: 3034 passed, 0 failed, 52 ignored; 28 skipped, the same as on main
review: 4 medium, 1 nit (below)
performance: 60 s smoke run: 1669 → 1672 frames (100 % of main), peak commit 17577 → 18436 MB, no device removal, no crash
title run: retail title on the RTX 5070 Ti (driver 621.14), into the world by scripted presses: 228 s there, 0 device removals, 0 crashes, 3.3 presents/s; run with XCL_SKIP_CS=95cc13288a27a96e (the NVIDIA hang at the end of loading, #3541) and NVIDIA's 2048 MB shader heap (#2590)
verdict: safe to merge: no blocking finding (the points below are medium or nits), the suite passes and the smoke run is clean
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5


In short: Keeps prepared pipeline libraries per memory layout with separate graphics and compute freshness. It also adds runtime.plib in XCL's per-title data folder, which keeps every pipeline built at runtime, with one build per name at a time, pipeline objects handed out once and reused through their cached blob, a 2048 MiB cap, and a Pipelines: stats line. By reading, the earlier blocking points are fixed (no writes into the game folder, ordered flushes and temp cleanup, one_build reuse, loads not blocked by serialization), and nothing in the code blocks it. What is left is the default-on memory cost and the size.

Medium

  1. Default-on memory cost up to the 2 GiB cap. runtime.plib is now active for every title (activate ~376); its bytes stay in RAM for the whole process, and each flush makes a full serialized copy. Entries from older builds are dropped only once the file reaches the cap and less than half of it is current (should_reset_full_runtime ~164), and every translator change renames all pipelines. After a few XCL updates a title can carry up to ~2 GiB of stale entries and ~4 GiB of extra commit. Measured only in 60 s runs (+275 MB peak in the PR's own pair). Consider a lower default cap, or resetting when most bytes come from older builds whatever the size.
  2. Size well over the limit. One commit of +3240/-509 (~3,750 lines, ~1,300 of them tests). The description gives a reason, but the settings-key additions (XCL_RDNA_FLOAT and the others), the removal of the v1/v2 receipt migration, and pipeline_stats with XCL_PIPELINE_MEASURE each stand on their own, and CONTRIBUTING puts diagnostics in their own PR.
  3. Timing-sensitive tests. pipeline_library.rs tests assert wall-clock bounds (< 140 ms ~2300, < 200 ms ~2341, < 500 ms ~2162, < 1 s ~2131) around 20-80 ms sleeps. With --test-threads=4 on a loaded machine they can fail spuriously. Widen the margins, or assert ordering rather than elapsed time.
  4. Fallback corpus identity reads the whole corpus at launch. corpus_identity (warm_library.rs ~138-180) reads graphics.bin and every compute file into one buffer, then copies that buffer four times to hash it, on every launch whose staged corpus has no identity file. For a large corpus that is a memory spike of several copies and a slow start; hash the files as a stream instead.

Nit

  1. Stores can briefly hold up loads. store_runtime holds the per-name slot lock while it waits for store_lock.write(), which serialize_runtime takes after three E_INVALIDARG retries (~460). Loads of names in the same slot then wait for a whole serialize, although the field comment says loads are never blocked.
Checked and fine
  • Earlier finding fixed: runtime.plib lives under XCL_DATA_ROOT or %LOCALAPPDATA%\XCL<title>\pipeline-libraries, not in the game folder, and the README says so
  • Earlier finding fixed: flush_lock is held across added.swap, serialize and write_atomic, so a shutdown flush waits for a periodic flush in progress (bounded to 5 s), and stale runtime.tmp files of dead processes are removed at start
  • Earlier finding fixed: a thread woken in one_build gets Loaded::Blob from the pipeline object already handed out and builds from it without recompiling, CachedWhole probes skip one_build, and with_name, store_runtime, one_build and flush now have tests
  • Earlier finding fixed: with_name no longer takes the flush lock, so serialization does not block loads except in the rare store_lock fallback above
  • Earlier finding fixed: kind_of maps "graphics stream" labels to Kind::Stream, matching the runtime-library hits
  • Lock order is consistent: names[slot], then handed/known/load_missed briefly, then store_lock, and flush_lock is never taken while store_lock is held, so there is no cycle
  • A normal-priority caller that takes over a low-priority holder's build cannot be undone by the old holder: drop and mark_stored check the build id and thread
  • end_title keeps the periodic flusher and any end-flush thread still running unsuspended, so a suspended thread cannot hold the heap or the D3D12 lock during drain_gpu
  • Merges cleanly onto main and with the other four PRs
How this was tested
  • Merged onto main 078358a0, then cargo build --workspace and cargo test --workspace --no-fail-fast -- --test-threads=4.
  • The skipped GPU tests are those this card can't run (no wave64 on NVIDIA, no D3D12 debug layer, and similar).
  • scripts/smoke.ps1: 60 s of a retail title on main 078358a0 and on this merge; presents per 2 s at the end: 60 60 60.
  • Title run: the release build of this merge launched the retail title with XCL_RUN_SECONDS=300 and scripted A presses counted from the first frame (XCL_PRESS_BASE=frame, #3712) into the world from an existing save; time in the world is counted from the first in-world draw call to the end of the run.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7367565177 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7367565177). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-03T04:22:16Z. --- merge-check base: 078358a058f7ba5d16690dba8dc4e55d2c88ae0a head: 5894838c8b5897d7243048eab1987159eea246c6 merge: clean build: ok tests: 3034 passed, 0 failed, 52 ignored; 28 skipped, the same as on main review: 4 medium, 1 nit (below) performance: 60 s smoke run: 1669 → 1672 frames (100 % of main), peak commit 17577 → 18436 MB, no device removal, no crash title run: retail title on the RTX 5070 Ti (driver 621.14), into the world by scripted presses: 228 s there, 0 device removals, 0 crashes, 3.3 presents/s; run with `XCL_SKIP_CS=95cc13288a27a96e` (the NVIDIA hang at the end of loading, #3541) and NVIDIA's 2048 MB shader heap (#2590) verdict: safe to merge: no blocking finding (the points below are medium or nits), the suite passes and the smoke run is clean hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5 --- **In short:** Keeps prepared pipeline libraries per memory layout with separate graphics and compute freshness. It also adds runtime.plib in XCL's per-title data folder, which keeps every pipeline built at runtime, with one build per name at a time, pipeline objects handed out once and reused through their cached blob, a 2048 MiB cap, and a Pipelines: stats line. By reading, the earlier blocking points are fixed (no writes into the game folder, ordered flushes and temp cleanup, one_build reuse, loads not blocked by serialization), and nothing in the code blocks it. What is left is the default-on memory cost and the size. #### Medium 1. **Default-on memory cost up to the 2 GiB cap.** runtime.plib is now active for every title (activate ~376); its bytes stay in RAM for the whole process, and each flush makes a full serialized copy. Entries from older builds are dropped only once the file reaches the cap and less than half of it is current (should_reset_full_runtime ~164), and every translator change renames all pipelines. After a few XCL updates a title can carry up to ~2 GiB of stale entries and ~4 GiB of extra commit. Measured only in 60 s runs (+275 MB peak in the PR's own pair). Consider a lower default cap, or resetting when most bytes come from older builds whatever the size. 2. **Size well over the limit.** One commit of +3240/-509 (~3,750 lines, ~1,300 of them tests). The description gives a reason, but the settings-key additions (XCL_RDNA_FLOAT and the others), the removal of the v1/v2 receipt migration, and pipeline_stats with XCL_PIPELINE_MEASURE each stand on their own, and CONTRIBUTING puts diagnostics in their own PR. 3. **Timing-sensitive tests.** pipeline_library.rs tests assert wall-clock bounds (< 140 ms ~2300, < 200 ms ~2341, < 500 ms ~2162, < 1 s ~2131) around 20-80 ms sleeps. With --test-threads=4 on a loaded machine they can fail spuriously. Widen the margins, or assert ordering rather than elapsed time. 4. **Fallback corpus identity reads the whole corpus at launch.** corpus_identity (warm_library.rs ~138-180) reads graphics.bin and every compute file into one buffer, then copies that buffer four times to hash it, on every launch whose staged corpus has no identity file. For a large corpus that is a memory spike of several copies and a slow start; hash the files as a stream instead. #### Nit 5. **Stores can briefly hold up loads.** store_runtime holds the per-name slot lock while it waits for store_lock.write(), which serialize_runtime takes after three E_INVALIDARG retries (~460). Loads of names in the same slot then wait for a whole serialize, although the field comment says loads are never blocked. <details><summary>Checked and fine</summary> - Earlier finding fixed: runtime.plib lives under XCL_DATA_ROOT or %LOCALAPPDATA%\XCL\<title>\pipeline-libraries, not in the game folder, and the README says so - Earlier finding fixed: flush_lock is held across added.swap, serialize and write_atomic, so a shutdown flush waits for a periodic flush in progress (bounded to 5 s), and stale runtime.tmp files of dead processes are removed at start - Earlier finding fixed: a thread woken in one_build gets Loaded::Blob from the pipeline object already handed out and builds from it without recompiling, CachedWhole probes skip one_build, and with_name, store_runtime, one_build and flush now have tests - Earlier finding fixed: with_name no longer takes the flush lock, so serialization does not block loads except in the rare store_lock fallback above - Earlier finding fixed: kind_of maps "graphics stream" labels to Kind::Stream, matching the runtime-library hits - Lock order is consistent: names[slot], then handed/known/load_missed briefly, then store_lock, and flush_lock is never taken while store_lock is held, so there is no cycle - A normal-priority caller that takes over a low-priority holder's build cannot be undone by the old holder: drop and mark_stored check the build id and thread - end_title keeps the periodic flusher and any end-flush thread still running unsuspended, so a suspended thread cannot hold the heap or the D3D12 lock during drain_gpu - Merges cleanly onto main and with the other four PRs </details> <details><summary>How this was tested</summary> - Merged onto main `078358a0`, then `cargo build --workspace` and `cargo test --workspace --no-fail-fast -- --test-threads=4`. - The skipped GPU tests are those this card can't run (no wave64 on NVIDIA, no D3D12 debug layer, and similar). - `scripts/smoke.ps1`: 60 s of a retail title on main `078358a0` and on this merge; presents per 2 s at the end: 60 60 60. - Title run: the release build of this merge launched the retail title with `XCL_RUN_SECONDS=300` and scripted A presses counted from the first frame (`XCL_PRESS_BASE=frame`, #3712) into the world from an existing save; time in the world is counted from the first in-world draw call to the end of the run. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
throny commented 2026-12-03 06:23:38 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by throny on 2026-12-03T06:23:38Z.


Merge check: safe (head 5894838c8, merged onto main 16c2fd082)

  • RTX 4080 (driver 621.40), i9-12900K, Windows 11 26300, release build

  • cargo test --workspace -- --test-threads=4: 3040 passed, 0 failed, 56 ignored; 25 SKIPPED lines, no test binary ended abnormally

  • retail title, 300 s world run: reached the world, no device removal, no crash, first frame 10.17 s, 2.90 presents/s (main 2.88 on the run before), 0 Aftermath dumps

  • diff scanned; build.rs only drops the two legacy id constants

  • warm second start (same build, libraries from the first run): activated the runtime library, no device removal, no crash, first frame 8.22 s (cold 10.17 s), 2.88 presents/s, 0 Aftermath dumps; the runtime library was about 1.19 GB at its save after 160 s

Not tested: AMD/Intel cards; a start that hits the size cap.

AI use: Claude Code (Claude Opus 5.5) ran the checks and wrote this comment.

<!-- greyfinch-sync:ivall/xcl:comment:7369783560 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3633#issuecomment-7369783560). Originally posted by [throny](https://github.com/throny) on 2026-12-03T06:23:38Z. --- **Merge check: safe** (head 5894838c8, merged onto main 16c2fd082) - RTX 4080 (driver 621.40), i9-12900K, Windows 11 26300, release build - `cargo test --workspace -- --test-threads=4`: 3040 passed, 0 failed, 56 ignored; 25 SKIPPED lines, no test binary ended abnormally - retail title, 300 s world run: reached the world, no device removal, no crash, first frame 10.17 s, 2.90 presents/s (main 2.88 on the run before), 0 Aftermath dumps - diff scanned; build.rs only drops the two legacy id constants - warm second start (same build, libraries from the first run): activated the runtime library, no device removal, no crash, first frame 8.22 s (cold 10.17 s), 2.88 presents/s, 0 Aftermath dumps; the runtime library was about 1.19 GB at its save after 160 s Not tested: AMD/Intel cards; a start that hits the size cap. AI use: Claude Code (Claude Opus 5.5) ran the checks and wrote this comment.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3633:upstream-pr/3633'
git switch 'upstream-pr/3633'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3633'
git switch 'upstream-pr/3633'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3633'
git switch 'upstream-pr/3633'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3633'
git switch 'main'
git merge --squash 'upstream-pr/3633'
git switch 'main'
git merge --ff-only 'upstream-pr/3633'
git switch 'main'
git merge 'upstream-pr/3633'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
xcl-dev/xcl!3633
No description provided.