gpu: compile recorded shader programs ahead of their first draw #1311

Closed
github-bot wants to merge 8 commits from gh-pr/1311/head into gh-pr/1311/base
Owner

@⁠NeySlim on GitHub · 2026-10-09 15:27 UTC · original
NeySlim:perf/shader-cache-ahead → main · +1782 −72 · 10 files · 8 commits · closed without merging

Problem

Kyty translates each new guest shader to SPIR-V on the GPU command thread when a draw or dispatch first uses it, and none of this work survives the run. In God of War Ragnarök (PPSA08332), a new game compiles about 1,900 shader programs in its first 12 minutes. Even in a second run of the same build, with the driver caches warm, the GPU command thread still spends 30 s on them (TranslateProgram 25.1 s, CompileProgram 5.1 s), in stalls of up to 1.6 s per frame in gameplay. The Vulkan pipeline cache only covers the driver part.

Change

  • Every program the shader cache compiles is recorded with the inputs that determine it: stage, guest code (and the back half of fused stages), user data count, stage input info, resource specialization and push data offset. Only programs that compiled are recorded. A SWAPPC program is not recorded: it links guest functions read from memory at the draw, which a record does not hold, so the draw compiles it as before (a worker also refuses such a record).
  • The records are saved to _PipelineCache/<title>.shaders.bin at exit and at most every 60 s while new programs appear, through a uniquely named temporary file and an atomic rename (concurrent instances never mix their data), with a checksum per record (a damaged tail is dropped). The file is tied to the device and driver, and to KYTY_GRAPHICS_CACHE_VERSION: a hash of the sources under src/graphics (paths and contents), the compiler identity and the build type, computed by generate_version.cmake at each build into the generated kytyShaderCacheVersion.h, because the recorded inputs are derived by code across the graphics tree. Since the key comes from the sources, this cache also works in builds from a modified tree. The Vulkan pipeline cache key is left as it is on main.
  • At start the records are loaded but not compiled. When the game maps a shader (AgcCreateShader), its recorded programs are queued to worker threads (a quarter of the hardware threads, 1 to 8). A worker translates, emits the SPIR-V and creates the shader module from the recorded inputs, with the same compile options as the command thread.
  • When the command thread first needs a program key, it adopts the finished job, waits for a running one, or compiles a queued one itself, so it never waits behind other jobs. Without a job it compiles as before. The existing lookup then decides whether a program matches the draw (same key, same specialization, same push data offset): a draw never uses a missing or different program, and nothing is skipped.

Test

  • ShaderCacheFileFormat: round trip, other signature, truncated record, damaged record.
  • ShaderCachePersistence: a first cache compiles a compute program with a buffer specialization and saves it; a second cache reloads the record, compiles it on a worker when the shader is mapped, and its lookup adopts it without compiling (same program info, pipeline created); a record still pending is compiled once by the caller; a file with another signature is ignored.
  • ShaderCacheGraphicsPrograms: the same for a vertex and a pixel program of one draw.
  • ShaderCacheRecordPadding: equal fields give identical records whatever the padding bytes of the input info and the resource specialization hold (records are written field by field).
  • ShaderCacheConcurrentWaiters: a recorded program that the lookup thread compiles itself is in flight until it ends, and a concurrent waiter wakes only after it; a lookup from a second thread is refused (ShaderCacheLookupThread).
  • ShaderCacheRecordPadding also checks that the queue of an async compute program (read by GETREG) survives the record with the same program key.
  • ShaderCacheSwappcRecord: a recorded SWAPPC program is not compiled ahead from its own code.
  • ShaderCachePersistence also checks that a second cache created and destroyed meanwhile does not remove the first cache's shader map observer.

They run with --pipeline-cache-only (ctest pipeline_cache) and in the full run, and are skipped in non-Release builds. They fail without the adoption ("the lookup compiled the program again") and without the recording ("the recorded program was not reloaded").

Validation

Linux, Ryzen AI Max+ 395, Radeon 8060S, Mesa RADV 26.2.3. God of War Ragnarök, new game, two runs in a row per build, Mesa disk cache emptied before the first run of each build, GPU clock forced high. The second runs compare as follows (T0: gameplay reached; the runs do not reach exactly the same content):

Second run, same build before with this PR
Compile time on the GPU command thread, whole run 42.8 s 10.9 s
of which translation and SPIR-V 30.2 s (1,842 programs) 2.5 s (28 new programs)
Cutscene T0+10..140 s: compile per frame 1.3 ms 0.01 ms
Cutscene: stalls over 50 ms, longest frame, fps 17, 317 ms, 16.6 0, 94 ms, 17.9
Gameplay T0+200..420 s: compile per frame 3.9 ms 0.2 ms
Gameplay: stalls over 50 ms, longest stall, longest frame, fps 44, 1.6 s, 2.6 s, 16.5 5, 0.24 s, 0.44 s, 17.3

The 1,927 recorded programs are compiled on the workers while the game boots: 42 s of CPU time on one thread (measured offline), 16 s of it captured on the workers before the first gameplay frame of a third run. In that third run, with the GPU clock governor left alone, the clock stayed between 2.1 and 2.3 GHz (10th percentile and median) through the cutscene and gameplay; in an earlier profile of a run without this cache on the same machine, compilation bursts had held it at 600 MHz for up to 80 s.

The measured builds also kept the Vulkan pipeline cache across rebuilds (a separate change, not part of this PR); within a second run of the same build that makes no difference, the driver cache is warm in both columns.

First runs are unchanged: with empty driver caches the command thread spends 184 to 191 s compiling, 157 s of it in the driver.

  • shader_recompiler_compute_tests, one case per process: same results as origin/main (627 of 637 cases pass on both; the same 10 fail on this RADV setup).
  • ctest pipeline_cache, resource_tracking and resource_materialization pass.

Not tested on Windows or macOS. The workers use std::jthread and a std::condition_variable like the existing GPU threads; the cache file is replaced with std::filesystem::rename, which replaces an existing file on Windows too, and Kyty opens files with delete sharing on Windows.

#988 stores the recompiler output (plans and SPIR-V) on disk. This PR stores only the inputs and compiles them again with the running build, so a record is only used when it gives the program key of the draw, like a program compiled earlier in the same run.

AI use

I used Claude Code (AI agent) to profile the compilation, design and write the change and the tests, and run the measurements and tests above on my machine. I reviewed the diff and the results; the agent then separated this change from the pipeline cache one and ran the tests above again.

**@⁠NeySlim** on GitHub · 2026-10-09 15:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311) `NeySlim:perf/shader-cache-ahead` → `main` · +1782 −72 · 10 files · 8 commits · closed without merging ## Problem Kyty translates each new guest shader to SPIR-V on the GPU command thread when a draw or dispatch first uses it, and none of this work survives the run. In God of War Ragnarök (PPSA08332), a new game compiles about 1,900 shader programs in its first 12 minutes. Even in a second run of the same build, with the driver caches warm, the GPU command thread still spends 30 s on them (`TranslateProgram` 25.1 s, `CompileProgram` 5.1 s), in stalls of up to 1.6 s per frame in gameplay. The Vulkan pipeline cache only covers the driver part. ## Change - Every program the shader cache compiles is recorded with the inputs that determine it: stage, guest code (and the back half of fused stages), user data count, stage input info, resource specialization and push data offset. Only programs that compiled are recorded. A SWAPPC program is not recorded: it links guest functions read from memory at the draw, which a record does not hold, so the draw compiles it as before (a worker also refuses such a record). - The records are saved to `_PipelineCache/<title>.shaders.bin` at exit and at most every 60 s while new programs appear, through a uniquely named temporary file and an atomic rename (concurrent instances never mix their data), with a checksum per record (a damaged tail is dropped). The file is tied to the device and driver, and to `KYTY_GRAPHICS_CACHE_VERSION`: a hash of the sources under `src/graphics` (paths and contents), the compiler identity and the build type, computed by `generate_version.cmake` at each build into the generated `kytyShaderCacheVersion.h`, because the recorded inputs are derived by code across the graphics tree. Since the key comes from the sources, this cache also works in builds from a modified tree. The Vulkan pipeline cache key is left as it is on main. - At start the records are loaded but not compiled. When the game maps a shader (`AgcCreateShader`), its recorded programs are queued to worker threads (a quarter of the hardware threads, 1 to 8). A worker translates, emits the SPIR-V and creates the shader module from the recorded inputs, with the same compile options as the command thread. - When the command thread first needs a program key, it adopts the finished job, waits for a running one, or compiles a queued one itself, so it never waits behind other jobs. Without a job it compiles as before. The existing lookup then decides whether a program matches the draw (same key, same specialization, same push data offset): a draw never uses a missing or different program, and nothing is skipped. ## Test - `ShaderCacheFileFormat`: round trip, other signature, truncated record, damaged record. - `ShaderCachePersistence`: a first cache compiles a compute program with a buffer specialization and saves it; a second cache reloads the record, compiles it on a worker when the shader is mapped, and its lookup adopts it without compiling (same program info, pipeline created); a record still pending is compiled once by the caller; a file with another signature is ignored. - `ShaderCacheGraphicsPrograms`: the same for a vertex and a pixel program of one draw. - `ShaderCacheRecordPadding`: equal fields give identical records whatever the padding bytes of the input info and the resource specialization hold (records are written field by field). - `ShaderCacheConcurrentWaiters`: a recorded program that the lookup thread compiles itself is in flight until it ends, and a concurrent waiter wakes only after it; a lookup from a second thread is refused (`ShaderCacheLookupThread`). - `ShaderCacheRecordPadding` also checks that the queue of an async compute program (read by GETREG) survives the record with the same program key. - `ShaderCacheSwappcRecord`: a recorded SWAPPC program is not compiled ahead from its own code. - `ShaderCachePersistence` also checks that a second cache created and destroyed meanwhile does not remove the first cache's shader map observer. They run with `--pipeline-cache-only` (ctest `pipeline_cache`) and in the full run, and are skipped in non-Release builds. They fail without the adoption ("the lookup compiled the program again") and without the recording ("the recorded program was not reloaded"). ## Validation Linux, Ryzen AI Max+ 395, Radeon 8060S, Mesa RADV 26.2.3. God of War Ragnarök, new game, two runs in a row per build, Mesa disk cache emptied before the first run of each build, GPU clock forced high. The second runs compare as follows (T0: gameplay reached; the runs do not reach exactly the same content): | Second run, same build | before | with this PR | |---|---|---| | Compile time on the GPU command thread, whole run | 42.8 s | 10.9 s | | of which translation and SPIR-V | 30.2 s (1,842 programs) | 2.5 s (28 new programs) | | Cutscene T0+10..140 s: compile per frame | 1.3 ms | 0.01 ms | | Cutscene: stalls over 50 ms, longest frame, fps | 17, 317 ms, 16.6 | 0, 94 ms, 17.9 | | Gameplay T0+200..420 s: compile per frame | 3.9 ms | 0.2 ms | | Gameplay: stalls over 50 ms, longest stall, longest frame, fps | 44, 1.6 s, 2.6 s, 16.5 | 5, 0.24 s, 0.44 s, 17.3 | The 1,927 recorded programs are compiled on the workers while the game boots: 42 s of CPU time on one thread (measured offline), 16 s of it captured on the workers before the first gameplay frame of a third run. In that third run, with the GPU clock governor left alone, the clock stayed between 2.1 and 2.3 GHz (10th percentile and median) through the cutscene and gameplay; in an earlier profile of a run without this cache on the same machine, compilation bursts had held it at 600 MHz for up to 80 s. The measured builds also kept the Vulkan pipeline cache across rebuilds (a separate change, not part of this PR); within a second run of the same build that makes no difference, the driver cache is warm in both columns. First runs are unchanged: with empty driver caches the command thread spends 184 to 191 s compiling, 157 s of it in the driver. - `shader_recompiler_compute_tests`, one case per process: same results as `origin/main` (627 of 637 cases pass on both; the same 10 fail on this RADV setup). - ctest `pipeline_cache`, `resource_tracking` and `resource_materialization` pass. Not tested on Windows or macOS. The workers use `std::jthread` and a `std::condition_variable` like the existing GPU threads; the cache file is replaced with `std::filesystem::rename`, which replaces an existing file on Windows too, and Kyty opens files with delete sharing on Windows. ## Related #988 stores the recompiler output (plans and SPIR-V) on disk. This PR stores only the inputs and compiles them again with the running build, so a record is only used when it gives the program key of the draw, like a program compiled earlier in the same run. ## AI use I used Claude Code (AI agent) to profile the compilation, design and write the change and the tests, and run the measurements and tests above on my machine. I reviewed the diff and the results; the agent then separated this change from the pipeline cache one and ran the tests above again.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:52:32 +00:00
github-bot closed this pull request 2026-11-26 09:52:32 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 15:30 UTC · original · edited 2026-10-21 23:04 UTC

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

  • Last reviewed commit: 5447e4da636a0f05819be084aa340b126ee08bd1
  • Latest commit, not reviewed: 467687cbb8

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d4e48d0c-c935-4586-abce-6027b57b4580
📥 Commits

Reviewing files that changed from the base of the PR and between 508fe10cb61cf0bc2eceeb14dd70f6bbac2fd596 and 5447e4da636a0f05819be084aa340b126ee08bd1.

📒 Files selected for processing: 3
  • CMakeLists.txt
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • tests/ShaderRecompilerComputeTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

📝 Walkthrough

The change adds a versioned, persistent shader-recipe cache alongside the Vulkan driver cache. It records compiled shader programs, queues cached recipes after shader mapping, and supports background compilation and program adoption. The cache format validates signatures, record hashes, and payload data. Build configuration generates a graphics cache version, and tests cover cache parsing, persistence, and background compilation.

Suggested reviewers: jeanpaul87

Priority: ➖ Normal

Change: Feature

Merge Risk: ⚪ Minimal · up to 5447e

This change adds a persistent shader cache that compiles recorded programs in the background before their first draw. No concrete merge-blocking defect remains in the reviewed changes, and the reported cache and GPU test results match main.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 12.82% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 78 functions across 6 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description clearly explains the persistent shader-program recording, background compilation, cache behavior, tests, and measured performance impact.
Title check Passed The title accurately and concisely identifies the main change: compiling recorded shader programs before their first draw.
Full details: Docstring Coverage

Explanation

Docstring coverage is 12.82% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 78 functions across 6 files. (2 skipped: 1 unsupported, 1 too large.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 15:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#issuecomment-6084014246) · edited 2026-10-21 23:04 UTC <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1311?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > - Last reviewed commit: 5447e4da636a0f05819be084aa340b126ee08bd1 > - Latest commit, not reviewed: 467687cbb8c41f458db86a9a7215d2744d233e8d > > Use the following commands to manage reviews: > - `@coderabbitai resume` to resume automatic reviews. > - `@coderabbitai review` to trigger a single review. > > Use the checkboxes below for quick actions: > - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> ▶️ Resume reviews > - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review <!-- end of auto-generated comment: review paused by coderabbit.ai --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `d4e48d0c-c935-4586-abce-6027b57b4580` </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between 508fe10cb61cf0bc2eceeb14dd70f6bbac2fd596 and 5447e4da636a0f05819be084aa340b126ee08bd1. </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing: 3</strong></summary> <dl> <dd> * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </dd> </dl> </details> <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> The change adds a versioned, persistent shader-recipe cache alongside the Vulkan driver cache. It records compiled shader programs, queues cached recipes after shader mapping, and supports background compilation and program adoption. The cache format validates signatures, record hashes, and payload data. Build configuration generates a graphics cache version, and tests cover cache parsing, persistence, and background compilation. **Suggested reviewers:** `jeanpaul87` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"5447e4da636a0f05819be084aa340b126ee08bd1" --> **Change:** Feature <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>⚪ Minimal</strong> · up to <code>5447e</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **⚪ Minimal** · up to `5447e` --> <!-- final_review_risk_coverage:{"sourceCommitId":"5447e4da636a0f05819be084aa340b126ee08bd1","coveredCommitId":"5447e4da636a0f05819be084aa340b126ee08bd1","kind":"reviewed"} --> This change adds a persistent shader cache that compiles recorded programs in the background before their first draw. No concrete merge-blocking defect remains in the reviewed changes, and the reported cache and GPU test results match main. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-inconclusive-14-v2.svg" width="14" height="14" align="middle" alt="Inconclusive" title="Inconclusive"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 inconclusive</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | Docstring coverage is 12.82% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 78 functions across 6 files. (2 skipped: … | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------- | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description clearly explains the persistent shader-program recording, background compilation, cache behavior, tests, and measured performance impact. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title accurately and concisely identifies the main change: compiling recorded shader programs before their first draw. | </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 12.82% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 78 functions across 6 files. (2 skipped: 1 unsupported, 1 too large.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1311)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠jeanpaul87 on GitHub · 2026-10-09 15:46 UTC · original · edited 2026-10-09 15:48 UTC
On src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp line 613 (outdated):

@@ -398,28 +454,375 @@ struct PipelineCache::ProgramCache {
 		return permutation.handle;
 	}
 
+	// Moves the background result for `key` into the cache. Without one, marks the key so that a
+	// later prefetch does not compile it a second time.
+	ProgramMap::iterator Adopt(const ProgramKey& key) {
+		std::optional<SourceEntry> result;
+		{
+			std::unique_lock lock(job_mutex);
+			auto [iter, inserted] = jobs.try_emplace(key);
+			auto& job             = iter->second;
+			if (inserted) {
+				job.state = Job::State::Taken;
+				return programs.end();
+			}
+			switch (job.state) {
+				case Job::State::Taken: return programs.end();
+				case Job::State::Running: {
+					const auto begin = std::chrono::steady_clock::now();
+					WaitForJob(lock, job);
+					stats.waited++;
+					stats.waited_us +=
+					    static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(
+					                              std::chrono::steady_clock::now() - begin)
+					                              .count());
+					result = std::move(job.result);
+					break;
+				}
+				case Job::State::Done: result = std::move(job.result); break;
+				case Job::State::Dormant:
+				case Job::State::Queued:
+					// Not started yet: compiling here is faster than waiting behind other jobs.
+					std::erase(queue, &job);
+					job.state = Job::State::Running;
+					lock.unlock();
+					result = CompileJob(job.recipes);
+					lock.lock();
+					stats.compiled += result ? result->permutations.size() : 0;
+					break;
+			}
+			job.state = Job::State::Taken;
+			job.result.reset();
+			job.recipes = {};
+		}
+		if (!result) {
+			return programs.end();
+		}
+		for (auto& permutation: result->permutations) {
+			permutation.handle.id = ++next_shader_id;
+		}
+		return programs.emplace(key, std::move(*result)).first;
+	}
+
+	void WaitForJob(std::unique_lock<std::mutex>& lock, const Job& job) {
+		job_done.wait(lock, [&job] { return job.state == Job::State::Done; });
+	}
+
+	template <typename InputInfo>
+	Permutation CompileRecipe(const ShaderCacheRecipe&                           recipe,
+	                          std::optional<ShaderRecompiler::IR::ResourcePlan>& plan) const {
+		InputInfo input_info;
+		std::memcpy(&input_info, recipe.input.data(), sizeof(input_info));
+		// Translation reads the user data count, not the values.
+		const std::vector<uint32_t> user_data(recipe.user_data_count, 0u);
+		const auto options    = MakeOptions(recipe.hash, user_data, recipe.back_code, input_info);
+		const auto stage_name = GetStageNames(recipe.stage).name;
+		DumpShaderOriginal(stage_name, recipe.hash, recipe.code);
+		auto translated = ShaderRecompiler::TranslateProgram(recipe.code, options);
+		if (!plan) {
+			plan.emplace(ShaderRecompiler::IR::ExtractResourcePlan(translated.program));
+		}
+		return CompilePermutation(stage_name, options, std::move(translated), recipe.specialization,
+		                          recipe.push_data_start);
+	}
+
+	// Compiles every recipe of one source key; safe on any thread.
+	std::optional<SourceEntry> CompileJob(const ShaderCacheRecipes& recipes) const {
+		std::optional<ShaderRecompiler::IR::ResourcePlan> plan;
+		std::vector<Permutation>                          permutations;
+		for (const auto& recipe: recipes) {
+			switch (recipe->stage) {
+				case ShaderType::Pixel:
+					permutations.push_back(CompileRecipe<ShaderPixelInputInfo>(*recipe, plan));
+					break;
+				case ShaderType::Compute:
+					permutations.push_back(CompileRecipe<ShaderComputeInputInfo>(*recipe, plan));
+					break;
+				default:
+					permutations.push_back(CompileRecipe<ShaderVertexInputInfo>(*recipe, plan));
+					break;
+			}
+		}
+		if (!plan) {
+			return std::nullopt;
+		}
+		std::optional<SourceEntry> entry;
+		entry.emplace(std::move(*plan));
+		entry->permutations = std::move(permutations);
+		return entry;
+	}
+
+	// The key a recipe compiles to, or nothing for input that this build cannot use.
+	static std::optional<ProgramKey> RecipeKey(const ShaderCacheRecipe& recipe) {
+		ProgramKey key {
+		    .stage           = recipe.stage,
+		    .hash            = recipe.hash,
+		    .user_data_count = recipe.user_data_count,
+		    .code_size       = static_cast<uint32_t>(recipe.code.size()),
+		};
+		if (recipe.input.size() != ShaderCacheInputSize(recipe.stage)) {
+			return std::nullopt;
+		}
+		switch (recipe.stage) {
+			case ShaderType::Pixel: {
+				ShaderPixelInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				if (info.input_num > std::size(info.interpolator_settings)) {
+					return std::nullopt;
+				}
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+			case ShaderType::Compute: {
+				ShaderComputeInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+			default: {
+				ShaderVertexInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				if (info.logical_stage != recipe.stage || info.resources_num < 0 ||
+				    info.resources_num > ShaderVertexInputInfo::RES_MAX) {
+					return std::nullopt;
+				}
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+		}
+		return key;
+	}
+
+	template <typename InputInfo>
+	void Record(const ShaderParams& params, const InputInfo& input_info,
+	            const ShaderRecompiler::IR::ResourceSpecialization& specialization,
+	            uint32_t                                            push_data_start) {
+		if (cache_path.empty()) {
+			return;
+		}
+		auto recipe             = std::make_shared<ShaderCacheRecipe>();
+		recipe->stage           = GetStage(input_info);
+		recipe->user_data_count = params.user_data_count;
+		recipe->push_data_start = push_data_start;
+		recipe->hash            = params.hash;
+		recipe->code.assign(params.code.begin(), params.code.end());
+		recipe->back_code.assign(params.back_code.begin(), params.back_code.end());
+		auto input  = input_info;
+		input.stage = {};
+		recipe->input.resize(sizeof(input));
+		std::memcpy(recipe->input.data(), &input, sizeof(input));

Could copying the whole struct here accidentally include uninitialized padding bytes? I'm wondering if that might cause the hash to change for identical inputs. Should we zero it out with memset before copying the data?

**@⁠jeanpaul87** on GitHub · 2026-10-09 15:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4231929575) · edited 2026-10-09 15:48 UTC On `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` line 613 (outdated): ```diff @@ -398,28 +454,375 @@ struct PipelineCache::ProgramCache { return permutation.handle; } + // Moves the background result for `key` into the cache. Without one, marks the key so that a + // later prefetch does not compile it a second time. + ProgramMap::iterator Adopt(const ProgramKey& key) { + std::optional<SourceEntry> result; + { + std::unique_lock lock(job_mutex); + auto [iter, inserted] = jobs.try_emplace(key); + auto& job = iter->second; + if (inserted) { + job.state = Job::State::Taken; + return programs.end(); + } + switch (job.state) { + case Job::State::Taken: return programs.end(); + case Job::State::Running: { + const auto begin = std::chrono::steady_clock::now(); + WaitForJob(lock, job); + stats.waited++; + stats.waited_us += + static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>( + std::chrono::steady_clock::now() - begin) + .count()); + result = std::move(job.result); + break; + } + case Job::State::Done: result = std::move(job.result); break; + case Job::State::Dormant: + case Job::State::Queued: + // Not started yet: compiling here is faster than waiting behind other jobs. + std::erase(queue, &job); + job.state = Job::State::Running; + lock.unlock(); + result = CompileJob(job.recipes); + lock.lock(); + stats.compiled += result ? result->permutations.size() : 0; + break; + } + job.state = Job::State::Taken; + job.result.reset(); + job.recipes = {}; + } + if (!result) { + return programs.end(); + } + for (auto& permutation: result->permutations) { + permutation.handle.id = ++next_shader_id; + } + return programs.emplace(key, std::move(*result)).first; + } + + void WaitForJob(std::unique_lock<std::mutex>& lock, const Job& job) { + job_done.wait(lock, [&job] { return job.state == Job::State::Done; }); + } + + template <typename InputInfo> + Permutation CompileRecipe(const ShaderCacheRecipe& recipe, + std::optional<ShaderRecompiler::IR::ResourcePlan>& plan) const { + InputInfo input_info; + std::memcpy(&input_info, recipe.input.data(), sizeof(input_info)); + // Translation reads the user data count, not the values. + const std::vector<uint32_t> user_data(recipe.user_data_count, 0u); + const auto options = MakeOptions(recipe.hash, user_data, recipe.back_code, input_info); + const auto stage_name = GetStageNames(recipe.stage).name; + DumpShaderOriginal(stage_name, recipe.hash, recipe.code); + auto translated = ShaderRecompiler::TranslateProgram(recipe.code, options); + if (!plan) { + plan.emplace(ShaderRecompiler::IR::ExtractResourcePlan(translated.program)); + } + return CompilePermutation(stage_name, options, std::move(translated), recipe.specialization, + recipe.push_data_start); + } + + // Compiles every recipe of one source key; safe on any thread. + std::optional<SourceEntry> CompileJob(const ShaderCacheRecipes& recipes) const { + std::optional<ShaderRecompiler::IR::ResourcePlan> plan; + std::vector<Permutation> permutations; + for (const auto& recipe: recipes) { + switch (recipe->stage) { + case ShaderType::Pixel: + permutations.push_back(CompileRecipe<ShaderPixelInputInfo>(*recipe, plan)); + break; + case ShaderType::Compute: + permutations.push_back(CompileRecipe<ShaderComputeInputInfo>(*recipe, plan)); + break; + default: + permutations.push_back(CompileRecipe<ShaderVertexInputInfo>(*recipe, plan)); + break; + } + } + if (!plan) { + return std::nullopt; + } + std::optional<SourceEntry> entry; + entry.emplace(std::move(*plan)); + entry->permutations = std::move(permutations); + return entry; + } + + // The key a recipe compiles to, or nothing for input that this build cannot use. + static std::optional<ProgramKey> RecipeKey(const ShaderCacheRecipe& recipe) { + ProgramKey key { + .stage = recipe.stage, + .hash = recipe.hash, + .user_data_count = recipe.user_data_count, + .code_size = static_cast<uint32_t>(recipe.code.size()), + }; + if (recipe.input.size() != ShaderCacheInputSize(recipe.stage)) { + return std::nullopt; + } + switch (recipe.stage) { + case ShaderType::Pixel: { + ShaderPixelInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + if (info.input_num > std::size(info.interpolator_settings)) { + return std::nullopt; + } + BuildStageStaticKey(info, key.static_state); + break; + } + case ShaderType::Compute: { + ShaderComputeInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + BuildStageStaticKey(info, key.static_state); + break; + } + default: { + ShaderVertexInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + if (info.logical_stage != recipe.stage || info.resources_num < 0 || + info.resources_num > ShaderVertexInputInfo::RES_MAX) { + return std::nullopt; + } + BuildStageStaticKey(info, key.static_state); + break; + } + } + return key; + } + + template <typename InputInfo> + void Record(const ShaderParams& params, const InputInfo& input_info, + const ShaderRecompiler::IR::ResourceSpecialization& specialization, + uint32_t push_data_start) { + if (cache_path.empty()) { + return; + } + auto recipe = std::make_shared<ShaderCacheRecipe>(); + recipe->stage = GetStage(input_info); + recipe->user_data_count = params.user_data_count; + recipe->push_data_start = push_data_start; + recipe->hash = params.hash; + recipe->code.assign(params.code.begin(), params.code.end()); + recipe->back_code.assign(params.back_code.begin(), params.back_code.end()); + auto input = input_info; + input.stage = {}; + recipe->input.resize(sizeof(input)); + std::memcpy(recipe->input.data(), &input, sizeof(input)); ``` Could copying the whole struct here accidentally include uninitialized padding bytes? I'm wondering if that might cause the hash to change for identical inputs. Should we zero it out with memset before copying the data?
Author
Owner

@⁠jeanpaul87 on GitHub · 2026-10-09 15:47 UTC · original
On src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp line 760 (outdated):

@@ -398,28 +454,375 @@ struct PipelineCache::ProgramCache {
 		return permutation.handle;
 	}
 
+	// Moves the background result for `key` into the cache. Without one, marks the key so that a
+	// later prefetch does not compile it a second time.
+	ProgramMap::iterator Adopt(const ProgramKey& key) {
+		std::optional<SourceEntry> result;
+		{
+			std::unique_lock lock(job_mutex);
+			auto [iter, inserted] = jobs.try_emplace(key);
+			auto& job             = iter->second;
+			if (inserted) {
+				job.state = Job::State::Taken;
+				return programs.end();
+			}
+			switch (job.state) {
+				case Job::State::Taken: return programs.end();
+				case Job::State::Running: {
+					const auto begin = std::chrono::steady_clock::now();
+					WaitForJob(lock, job);
+					stats.waited++;
+					stats.waited_us +=
+					    static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(
+					                              std::chrono::steady_clock::now() - begin)
+					                              .count());
+					result = std::move(job.result);
+					break;
+				}
+				case Job::State::Done: result = std::move(job.result); break;
+				case Job::State::Dormant:
+				case Job::State::Queued:
+					// Not started yet: compiling here is faster than waiting behind other jobs.
+					std::erase(queue, &job);
+					job.state = Job::State::Running;
+					lock.unlock();
+					result = CompileJob(job.recipes);
+					lock.lock();
+					stats.compiled += result ? result->permutations.size() : 0;
+					break;
+			}
+			job.state = Job::State::Taken;
+			job.result.reset();
+			job.recipes = {};
+		}
+		if (!result) {
+			return programs.end();
+		}
+		for (auto& permutation: result->permutations) {
+			permutation.handle.id = ++next_shader_id;
+		}
+		return programs.emplace(key, std::move(*result)).first;
+	}
+
+	void WaitForJob(std::unique_lock<std::mutex>& lock, const Job& job) {
+		job_done.wait(lock, [&job] { return job.state == Job::State::Done; });
+	}
+
+	template <typename InputInfo>
+	Permutation CompileRecipe(const ShaderCacheRecipe&                           recipe,
+	                          std::optional<ShaderRecompiler::IR::ResourcePlan>& plan) const {
+		InputInfo input_info;
+		std::memcpy(&input_info, recipe.input.data(), sizeof(input_info));
+		// Translation reads the user data count, not the values.
+		const std::vector<uint32_t> user_data(recipe.user_data_count, 0u);
+		const auto options    = MakeOptions(recipe.hash, user_data, recipe.back_code, input_info);
+		const auto stage_name = GetStageNames(recipe.stage).name;
+		DumpShaderOriginal(stage_name, recipe.hash, recipe.code);
+		auto translated = ShaderRecompiler::TranslateProgram(recipe.code, options);
+		if (!plan) {
+			plan.emplace(ShaderRecompiler::IR::ExtractResourcePlan(translated.program));
+		}
+		return CompilePermutation(stage_name, options, std::move(translated), recipe.specialization,
+		                          recipe.push_data_start);
+	}
+
+	// Compiles every recipe of one source key; safe on any thread.
+	std::optional<SourceEntry> CompileJob(const ShaderCacheRecipes& recipes) const {
+		std::optional<ShaderRecompiler::IR::ResourcePlan> plan;
+		std::vector<Permutation>                          permutations;
+		for (const auto& recipe: recipes) {
+			switch (recipe->stage) {
+				case ShaderType::Pixel:
+					permutations.push_back(CompileRecipe<ShaderPixelInputInfo>(*recipe, plan));
+					break;
+				case ShaderType::Compute:
+					permutations.push_back(CompileRecipe<ShaderComputeInputInfo>(*recipe, plan));
+					break;
+				default:
+					permutations.push_back(CompileRecipe<ShaderVertexInputInfo>(*recipe, plan));
+					break;
+			}
+		}
+		if (!plan) {
+			return std::nullopt;
+		}
+		std::optional<SourceEntry> entry;
+		entry.emplace(std::move(*plan));
+		entry->permutations = std::move(permutations);
+		return entry;
+	}
+
+	// The key a recipe compiles to, or nothing for input that this build cannot use.
+	static std::optional<ProgramKey> RecipeKey(const ShaderCacheRecipe& recipe) {
+		ProgramKey key {
+		    .stage           = recipe.stage,
+		    .hash            = recipe.hash,
+		    .user_data_count = recipe.user_data_count,
+		    .code_size       = static_cast<uint32_t>(recipe.code.size()),
+		};
+		if (recipe.input.size() != ShaderCacheInputSize(recipe.stage)) {
+			return std::nullopt;
+		}
+		switch (recipe.stage) {
+			case ShaderType::Pixel: {
+				ShaderPixelInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				if (info.input_num > std::size(info.interpolator_settings)) {
+					return std::nullopt;
+				}
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+			case ShaderType::Compute: {
+				ShaderComputeInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+			default: {
+				ShaderVertexInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				if (info.logical_stage != recipe.stage || info.resources_num < 0 ||
+				    info.resources_num > ShaderVertexInputInfo::RES_MAX) {
+					return std::nullopt;
+				}
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+		}
+		return key;
+	}
+
+	template <typename InputInfo>
+	void Record(const ShaderParams& params, const InputInfo& input_info,
+	            const ShaderRecompiler::IR::ResourceSpecialization& specialization,
+	            uint32_t                                            push_data_start) {
+		if (cache_path.empty()) {
+			return;
+		}
+		auto recipe             = std::make_shared<ShaderCacheRecipe>();
+		recipe->stage           = GetStage(input_info);
+		recipe->user_data_count = params.user_data_count;
+		recipe->push_data_start = push_data_start;
+		recipe->hash            = params.hash;
+		recipe->code.assign(params.code.begin(), params.code.end());
+		recipe->back_code.assign(params.back_code.begin(), params.back_code.end());
+		auto input  = input_info;
+		input.stage = {};
+		recipe->input.resize(sizeof(input));
+		std::memcpy(recipe->input.data(), &input, sizeof(input));
+		recipe->specialization = specialization;
+		std::lock_guard lock(job_mutex);
+		recipes.push_back(std::move(recipe));
+		dirty = true;
+		if (std::chrono::steady_clock::now() - last_save > PeriodicSaveInterval) {
+			last_save      = std::chrono::steady_clock::now();
+			save_requested = true;
+			StartWorkers();
+			job_ready.notify_one();
+		}
+	}
+
+	void Load(const std::filesystem::path& path, std::string signature) {
+		cache_path      = path;
+		cache_signature = std::move(signature);
+		std::vector<uint8_t> data;
+		ShaderCacheRecipes   loaded;
+		size_t               parsed    = 0;
+		const auto           path_text = Common::PathToString(path);
+		if (ReadShaderCacheFile(path, data) &&
+		    !ParseShaderCache(data, cache_signature, loaded, &parsed)) {
+			PipelineCacheLog(
+			    "Shader cache: invalidating {} (graphics code, device or driver changed)",
+			    path_text);
+		}
+		{
+			std::lock_guard lock(job_mutex);
+			for (auto& recipe: loaded) {
+				auto key = RecipeKey(*recipe);
+				if (!key) {
+					continue;
+				}
+				auto& job     = jobs[std::move(*key)];
+				auto& trigger = triggers[XXH3_64bits(recipe->code.data(),
+				                                     recipe->code.size() * sizeof(uint32_t))];
+				if (std::ranges::find(trigger, &job) == trigger.end()) {
+					trigger.push_back(&job);
+				}
+				job.recipes.push_back(recipe);
+				recipes.push_back(std::move(recipe));
+			}
+			// The next save drops a damaged tail, unusable records or a stale file.
+			dirty     = parsed != data.size() || recipes.size() != loaded.size();
+			last_save = std::chrono::steady_clock::now();
+			PipelineCacheLog("Shader cache: {} recorded programs in {} sources from {}",
+			                 recipes.size(), jobs.size(), path_text);
+		}
+		ShaderSetMapObserver(
+		    [](void* user, uint64_t hash) {
+			    static_cast<ProgramCache*>(user)->OnShaderMapped(hash);
+		    },
+		    this);
+	}
+
+	// The game loaded a shader: compile its recorded programs before the first draw needs them.
+	void OnShaderMapped(uint64_t hash) {
+		std::lock_guard lock(job_mutex);
+		const auto      trigger = triggers.find(hash);
+		if (trigger == triggers.end()) {
+			return;
+		}
+		for (auto* job: trigger->second) {
+			if (job->state == Job::State::Dormant) {
+				job->state = Job::State::Queued;
+				queue.push_back(job);
+			}
+		}
+		triggers.erase(trigger);
+		StartWorkers();
+		job_ready.notify_all();
+	}
+
+	// Called with job_mutex held.
+	void StartWorkers() {
+		if (!workers.empty()) {
+			return;
+		}
+		const auto count = std::clamp(std::thread::hardware_concurrency() / 4u, 1u, 8u);
+		for (uint32_t i = 0; i < count; i++) {
+			workers.emplace_back([this](std::stop_token stop) { WorkerLoop(stop); });
+		}
+	}
+
+	void WorkerLoop(const std::stop_token& stop) {
+		std::unique_lock lock(job_mutex);
+		for (;;) {
+			job_ready.wait(lock, [this, &stop] {
+				return stop.stop_requested() || !queue.empty() || save_requested;
+			});
+			if (stop.stop_requested()) {
+				return;
+			}
+			if (save_requested) {
+				save_requested = false;
+				lock.unlock();
+				SaveRecipes();
+				lock.lock();
+				continue;
+			}
+			auto* job = queue.front();
+			queue.pop_front();
+			job->state = Job::State::Running;
+			running++;
+			lock.unlock();
+			auto result = CompileJob(job->recipes);
+			lock.lock();
+			stats.compiled_ahead += result ? result->permutations.size() : 0;
+			job->result = std::move(result);
+			job->state  = Job::State::Done;
+			running--;
+			job_done.notify_all();
+		}
+	}
+
+	void SaveRecipes() {
+		std::lock_guard    save_lock(save_mutex);
+		ShaderCacheRecipes snapshot;
+		{
+			std::lock_guard lock(job_mutex);
+			if (!dirty || cache_path.empty()) {
+				return;
+			}
+			snapshot = recipes;
+			dirty    = false;
+		}
+		const auto data = SerializeShaderCache(cache_signature, snapshot);
+		if (!WriteShaderCacheFile(cache_path, data)) {
+			std::lock_guard lock(job_mutex);
+			dirty = true;
+			PipelineCacheLog("Shader cache: failed to write {}", Common::PathToString(cache_path));
+			return;
+		}
+		PipelineCacheLog("Shader cache: saved {} recorded programs ({} bytes) to {}",
+		                 snapshot.size(), data.size(), Common::PathToString(cache_path));
+	}
+
+	void WaitForBackgroundCompilation() {
+		std::unique_lock lock(job_mutex);
+		job_done.wait(lock, [this] { return queue.empty() && running == 0; });
+	}
+
 	explicit ProgramCache(vk::Device device): device(device) {
 		lookup_key.static_state.reserve(MaxStaticKeyWords);
 	}
 	~ProgramCache() {
-		for (const auto& [key, entry]: programs) {
-			(void)key;
+		if (!cache_path.empty()) {
+			ShaderSetMapObserver(nullptr, nullptr);

If we have two ProgramCache instances alive at the same time (like in the tests), won't destroying one accidentally clear the observer for the other? Should we maybe check if this instance actually owns the observer before setting it to null?

**@⁠jeanpaul87** on GitHub · 2026-10-09 15:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4231940382) On `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` line 760 (outdated): ```diff @@ -398,28 +454,375 @@ struct PipelineCache::ProgramCache { return permutation.handle; } + // Moves the background result for `key` into the cache. Without one, marks the key so that a + // later prefetch does not compile it a second time. + ProgramMap::iterator Adopt(const ProgramKey& key) { + std::optional<SourceEntry> result; + { + std::unique_lock lock(job_mutex); + auto [iter, inserted] = jobs.try_emplace(key); + auto& job = iter->second; + if (inserted) { + job.state = Job::State::Taken; + return programs.end(); + } + switch (job.state) { + case Job::State::Taken: return programs.end(); + case Job::State::Running: { + const auto begin = std::chrono::steady_clock::now(); + WaitForJob(lock, job); + stats.waited++; + stats.waited_us += + static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>( + std::chrono::steady_clock::now() - begin) + .count()); + result = std::move(job.result); + break; + } + case Job::State::Done: result = std::move(job.result); break; + case Job::State::Dormant: + case Job::State::Queued: + // Not started yet: compiling here is faster than waiting behind other jobs. + std::erase(queue, &job); + job.state = Job::State::Running; + lock.unlock(); + result = CompileJob(job.recipes); + lock.lock(); + stats.compiled += result ? result->permutations.size() : 0; + break; + } + job.state = Job::State::Taken; + job.result.reset(); + job.recipes = {}; + } + if (!result) { + return programs.end(); + } + for (auto& permutation: result->permutations) { + permutation.handle.id = ++next_shader_id; + } + return programs.emplace(key, std::move(*result)).first; + } + + void WaitForJob(std::unique_lock<std::mutex>& lock, const Job& job) { + job_done.wait(lock, [&job] { return job.state == Job::State::Done; }); + } + + template <typename InputInfo> + Permutation CompileRecipe(const ShaderCacheRecipe& recipe, + std::optional<ShaderRecompiler::IR::ResourcePlan>& plan) const { + InputInfo input_info; + std::memcpy(&input_info, recipe.input.data(), sizeof(input_info)); + // Translation reads the user data count, not the values. + const std::vector<uint32_t> user_data(recipe.user_data_count, 0u); + const auto options = MakeOptions(recipe.hash, user_data, recipe.back_code, input_info); + const auto stage_name = GetStageNames(recipe.stage).name; + DumpShaderOriginal(stage_name, recipe.hash, recipe.code); + auto translated = ShaderRecompiler::TranslateProgram(recipe.code, options); + if (!plan) { + plan.emplace(ShaderRecompiler::IR::ExtractResourcePlan(translated.program)); + } + return CompilePermutation(stage_name, options, std::move(translated), recipe.specialization, + recipe.push_data_start); + } + + // Compiles every recipe of one source key; safe on any thread. + std::optional<SourceEntry> CompileJob(const ShaderCacheRecipes& recipes) const { + std::optional<ShaderRecompiler::IR::ResourcePlan> plan; + std::vector<Permutation> permutations; + for (const auto& recipe: recipes) { + switch (recipe->stage) { + case ShaderType::Pixel: + permutations.push_back(CompileRecipe<ShaderPixelInputInfo>(*recipe, plan)); + break; + case ShaderType::Compute: + permutations.push_back(CompileRecipe<ShaderComputeInputInfo>(*recipe, plan)); + break; + default: + permutations.push_back(CompileRecipe<ShaderVertexInputInfo>(*recipe, plan)); + break; + } + } + if (!plan) { + return std::nullopt; + } + std::optional<SourceEntry> entry; + entry.emplace(std::move(*plan)); + entry->permutations = std::move(permutations); + return entry; + } + + // The key a recipe compiles to, or nothing for input that this build cannot use. + static std::optional<ProgramKey> RecipeKey(const ShaderCacheRecipe& recipe) { + ProgramKey key { + .stage = recipe.stage, + .hash = recipe.hash, + .user_data_count = recipe.user_data_count, + .code_size = static_cast<uint32_t>(recipe.code.size()), + }; + if (recipe.input.size() != ShaderCacheInputSize(recipe.stage)) { + return std::nullopt; + } + switch (recipe.stage) { + case ShaderType::Pixel: { + ShaderPixelInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + if (info.input_num > std::size(info.interpolator_settings)) { + return std::nullopt; + } + BuildStageStaticKey(info, key.static_state); + break; + } + case ShaderType::Compute: { + ShaderComputeInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + BuildStageStaticKey(info, key.static_state); + break; + } + default: { + ShaderVertexInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + if (info.logical_stage != recipe.stage || info.resources_num < 0 || + info.resources_num > ShaderVertexInputInfo::RES_MAX) { + return std::nullopt; + } + BuildStageStaticKey(info, key.static_state); + break; + } + } + return key; + } + + template <typename InputInfo> + void Record(const ShaderParams& params, const InputInfo& input_info, + const ShaderRecompiler::IR::ResourceSpecialization& specialization, + uint32_t push_data_start) { + if (cache_path.empty()) { + return; + } + auto recipe = std::make_shared<ShaderCacheRecipe>(); + recipe->stage = GetStage(input_info); + recipe->user_data_count = params.user_data_count; + recipe->push_data_start = push_data_start; + recipe->hash = params.hash; + recipe->code.assign(params.code.begin(), params.code.end()); + recipe->back_code.assign(params.back_code.begin(), params.back_code.end()); + auto input = input_info; + input.stage = {}; + recipe->input.resize(sizeof(input)); + std::memcpy(recipe->input.data(), &input, sizeof(input)); + recipe->specialization = specialization; + std::lock_guard lock(job_mutex); + recipes.push_back(std::move(recipe)); + dirty = true; + if (std::chrono::steady_clock::now() - last_save > PeriodicSaveInterval) { + last_save = std::chrono::steady_clock::now(); + save_requested = true; + StartWorkers(); + job_ready.notify_one(); + } + } + + void Load(const std::filesystem::path& path, std::string signature) { + cache_path = path; + cache_signature = std::move(signature); + std::vector<uint8_t> data; + ShaderCacheRecipes loaded; + size_t parsed = 0; + const auto path_text = Common::PathToString(path); + if (ReadShaderCacheFile(path, data) && + !ParseShaderCache(data, cache_signature, loaded, &parsed)) { + PipelineCacheLog( + "Shader cache: invalidating {} (graphics code, device or driver changed)", + path_text); + } + { + std::lock_guard lock(job_mutex); + for (auto& recipe: loaded) { + auto key = RecipeKey(*recipe); + if (!key) { + continue; + } + auto& job = jobs[std::move(*key)]; + auto& trigger = triggers[XXH3_64bits(recipe->code.data(), + recipe->code.size() * sizeof(uint32_t))]; + if (std::ranges::find(trigger, &job) == trigger.end()) { + trigger.push_back(&job); + } + job.recipes.push_back(recipe); + recipes.push_back(std::move(recipe)); + } + // The next save drops a damaged tail, unusable records or a stale file. + dirty = parsed != data.size() || recipes.size() != loaded.size(); + last_save = std::chrono::steady_clock::now(); + PipelineCacheLog("Shader cache: {} recorded programs in {} sources from {}", + recipes.size(), jobs.size(), path_text); + } + ShaderSetMapObserver( + [](void* user, uint64_t hash) { + static_cast<ProgramCache*>(user)->OnShaderMapped(hash); + }, + this); + } + + // The game loaded a shader: compile its recorded programs before the first draw needs them. + void OnShaderMapped(uint64_t hash) { + std::lock_guard lock(job_mutex); + const auto trigger = triggers.find(hash); + if (trigger == triggers.end()) { + return; + } + for (auto* job: trigger->second) { + if (job->state == Job::State::Dormant) { + job->state = Job::State::Queued; + queue.push_back(job); + } + } + triggers.erase(trigger); + StartWorkers(); + job_ready.notify_all(); + } + + // Called with job_mutex held. + void StartWorkers() { + if (!workers.empty()) { + return; + } + const auto count = std::clamp(std::thread::hardware_concurrency() / 4u, 1u, 8u); + for (uint32_t i = 0; i < count; i++) { + workers.emplace_back([this](std::stop_token stop) { WorkerLoop(stop); }); + } + } + + void WorkerLoop(const std::stop_token& stop) { + std::unique_lock lock(job_mutex); + for (;;) { + job_ready.wait(lock, [this, &stop] { + return stop.stop_requested() || !queue.empty() || save_requested; + }); + if (stop.stop_requested()) { + return; + } + if (save_requested) { + save_requested = false; + lock.unlock(); + SaveRecipes(); + lock.lock(); + continue; + } + auto* job = queue.front(); + queue.pop_front(); + job->state = Job::State::Running; + running++; + lock.unlock(); + auto result = CompileJob(job->recipes); + lock.lock(); + stats.compiled_ahead += result ? result->permutations.size() : 0; + job->result = std::move(result); + job->state = Job::State::Done; + running--; + job_done.notify_all(); + } + } + + void SaveRecipes() { + std::lock_guard save_lock(save_mutex); + ShaderCacheRecipes snapshot; + { + std::lock_guard lock(job_mutex); + if (!dirty || cache_path.empty()) { + return; + } + snapshot = recipes; + dirty = false; + } + const auto data = SerializeShaderCache(cache_signature, snapshot); + if (!WriteShaderCacheFile(cache_path, data)) { + std::lock_guard lock(job_mutex); + dirty = true; + PipelineCacheLog("Shader cache: failed to write {}", Common::PathToString(cache_path)); + return; + } + PipelineCacheLog("Shader cache: saved {} recorded programs ({} bytes) to {}", + snapshot.size(), data.size(), Common::PathToString(cache_path)); + } + + void WaitForBackgroundCompilation() { + std::unique_lock lock(job_mutex); + job_done.wait(lock, [this] { return queue.empty() && running == 0; }); + } + explicit ProgramCache(vk::Device device): device(device) { lookup_key.static_state.reserve(MaxStaticKeyWords); } ~ProgramCache() { - for (const auto& [key, entry]: programs) { - (void)key; + if (!cache_path.empty()) { + ShaderSetMapObserver(nullptr, nullptr); ``` If we have two ProgramCache instances alive at the same time (like in the tests), won't destroying one accidentally clear the observer for the other? Should we maybe check if this instance actually owns the observer before setting it to null?
Author
Owner

@⁠jeanpaul87 on GitHub · 2026-10-09 15:48 UTC · original · approved these changes

**@⁠jeanpaul87** on GitHub · 2026-10-09 15:48 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#pullrequestreview-5472281265) · **approved these changes**
@ -349,3 +436,3 @@
lookup_key.code_size = static_cast<uint32_t>(params.code.size());
BuildStageStaticKey(input_info, lookup_key.static_state);
auto entry = programs.find(lookup_key);
auto entry = programs.find(lookup_key);
Author
Owner

@⁠jeanpaul87 on GitHub · 2026-10-09 15:52 UTC · original

I noticed we read from and write to the programs map (.find() in Get and .emplace() in Adopt) without holding any mutex. Since standard unordered_map isn't thread-safe, if multiple GPU threads call this at the same time, won't this corrupt the map and crash the emulator? Should we add a dedicated lock around programs?

**@⁠jeanpaul87** on GitHub · 2026-10-09 15:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4231986563) I noticed we read from and write to the programs map (.find() in Get and .emplace() in Adopt) without holding any mutex. Since standard unordered_map isn't thread-safe, if multiple GPU threads call this at the same time, won't this corrupt the map and crash the emulator? Should we add a dedicated lock around programs?
@ -483,0 +584,4 @@
lock.unlock();
result = CompileJob(job.recipes, hook);
lock.lock();
stats.compiled += result ? result->permutations.size() : 0;
Author
Owner

@⁠jeanpaul87 on GitHub · 2026-10-09 15:52 UTC · original

If a thread steals a queued job to compile it directly here, it breaks out of the switch and immediately sets the state to Taken. Since it completely skips setting the state to Done and never calls job_done.notify_all(), won't any other threads currently stuck in WaitForJob sleep forever and cause a deadlock?

**@⁠jeanpaul87** on GitHub · 2026-10-09 15:52 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4231990666) If a thread steals a queued job to compile it directly here, it breaks out of the switch and immediately sets the state to Taken. Since it completely skips setting the state to Done and never calls job_done.notify_all(), won't any other threads currently stuck in WaitForJob sleep forever and cause a deadlock?
Author
Owner

@⁠jeanpaul87 on GitHub · 2026-10-09 15:53 UTC · original · requested changes

**@⁠jeanpaul87** on GitHub · 2026-10-09 15:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#pullrequestreview-5472347131) · **requested changes**
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 16:25 UTC · original
On src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp line 613 (outdated):

@@ -398,28 +454,375 @@ struct PipelineCache::ProgramCache {
 		return permutation.handle;
 	}
 
+	// Moves the background result for `key` into the cache. Without one, marks the key so that a
+	// later prefetch does not compile it a second time.
+	ProgramMap::iterator Adopt(const ProgramKey& key) {
+		std::optional<SourceEntry> result;
+		{
+			std::unique_lock lock(job_mutex);
+			auto [iter, inserted] = jobs.try_emplace(key);
+			auto& job             = iter->second;
+			if (inserted) {
+				job.state = Job::State::Taken;
+				return programs.end();
+			}
+			switch (job.state) {
+				case Job::State::Taken: return programs.end();
+				case Job::State::Running: {
+					const auto begin = std::chrono::steady_clock::now();
+					WaitForJob(lock, job);
+					stats.waited++;
+					stats.waited_us +=
+					    static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(
+					                              std::chrono::steady_clock::now() - begin)
+					                              .count());
+					result = std::move(job.result);
+					break;
+				}
+				case Job::State::Done: result = std::move(job.result); break;
+				case Job::State::Dormant:
+				case Job::State::Queued:
+					// Not started yet: compiling here is faster than waiting behind other jobs.
+					std::erase(queue, &job);
+					job.state = Job::State::Running;
+					lock.unlock();
+					result = CompileJob(job.recipes);
+					lock.lock();
+					stats.compiled += result ? result->permutations.size() : 0;
+					break;
+			}
+			job.state = Job::State::Taken;
+			job.result.reset();
+			job.recipes = {};
+		}
+		if (!result) {
+			return programs.end();
+		}
+		for (auto& permutation: result->permutations) {
+			permutation.handle.id = ++next_shader_id;
+		}
+		return programs.emplace(key, std::move(*result)).first;
+	}
+
+	void WaitForJob(std::unique_lock<std::mutex>& lock, const Job& job) {
+		job_done.wait(lock, [&job] { return job.state == Job::State::Done; });
+	}
+
+	template <typename InputInfo>
+	Permutation CompileRecipe(const ShaderCacheRecipe&                           recipe,
+	                          std::optional<ShaderRecompiler::IR::ResourcePlan>& plan) const {
+		InputInfo input_info;
+		std::memcpy(&input_info, recipe.input.data(), sizeof(input_info));
+		// Translation reads the user data count, not the values.
+		const std::vector<uint32_t> user_data(recipe.user_data_count, 0u);
+		const auto options    = MakeOptions(recipe.hash, user_data, recipe.back_code, input_info);
+		const auto stage_name = GetStageNames(recipe.stage).name;
+		DumpShaderOriginal(stage_name, recipe.hash, recipe.code);
+		auto translated = ShaderRecompiler::TranslateProgram(recipe.code, options);
+		if (!plan) {
+			plan.emplace(ShaderRecompiler::IR::ExtractResourcePlan(translated.program));
+		}
+		return CompilePermutation(stage_name, options, std::move(translated), recipe.specialization,
+		                          recipe.push_data_start);
+	}
+
+	// Compiles every recipe of one source key; safe on any thread.
+	std::optional<SourceEntry> CompileJob(const ShaderCacheRecipes& recipes) const {
+		std::optional<ShaderRecompiler::IR::ResourcePlan> plan;
+		std::vector<Permutation>                          permutations;
+		for (const auto& recipe: recipes) {
+			switch (recipe->stage) {
+				case ShaderType::Pixel:
+					permutations.push_back(CompileRecipe<ShaderPixelInputInfo>(*recipe, plan));
+					break;
+				case ShaderType::Compute:
+					permutations.push_back(CompileRecipe<ShaderComputeInputInfo>(*recipe, plan));
+					break;
+				default:
+					permutations.push_back(CompileRecipe<ShaderVertexInputInfo>(*recipe, plan));
+					break;
+			}
+		}
+		if (!plan) {
+			return std::nullopt;
+		}
+		std::optional<SourceEntry> entry;
+		entry.emplace(std::move(*plan));
+		entry->permutations = std::move(permutations);
+		return entry;
+	}
+
+	// The key a recipe compiles to, or nothing for input that this build cannot use.
+	static std::optional<ProgramKey> RecipeKey(const ShaderCacheRecipe& recipe) {
+		ProgramKey key {
+		    .stage           = recipe.stage,
+		    .hash            = recipe.hash,
+		    .user_data_count = recipe.user_data_count,
+		    .code_size       = static_cast<uint32_t>(recipe.code.size()),
+		};
+		if (recipe.input.size() != ShaderCacheInputSize(recipe.stage)) {
+			return std::nullopt;
+		}
+		switch (recipe.stage) {
+			case ShaderType::Pixel: {
+				ShaderPixelInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				if (info.input_num > std::size(info.interpolator_settings)) {
+					return std::nullopt;
+				}
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+			case ShaderType::Compute: {
+				ShaderComputeInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+			default: {
+				ShaderVertexInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				if (info.logical_stage != recipe.stage || info.resources_num < 0 ||
+				    info.resources_num > ShaderVertexInputInfo::RES_MAX) {
+					return std::nullopt;
+				}
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+		}
+		return key;
+	}
+
+	template <typename InputInfo>
+	void Record(const ShaderParams& params, const InputInfo& input_info,
+	            const ShaderRecompiler::IR::ResourceSpecialization& specialization,
+	            uint32_t                                            push_data_start) {
+		if (cache_path.empty()) {
+			return;
+		}
+		auto recipe             = std::make_shared<ShaderCacheRecipe>();
+		recipe->stage           = GetStage(input_info);
+		recipe->user_data_count = params.user_data_count;
+		recipe->push_data_start = push_data_start;
+		recipe->hash            = params.hash;
+		recipe->code.assign(params.code.begin(), params.code.end());
+		recipe->back_code.assign(params.back_code.begin(), params.back_code.end());
+		auto input  = input_info;
+		input.stage = {};
+		recipe->input.resize(sizeof(input));
+		std::memcpy(recipe->input.data(), &input, sizeof(input));

Thanks, good catch. The program key itself was built from the fields (BuildStageStaticKey), not from these bytes, but the padding did reach the file and the per-record checksum: identical inputs could give different bytes, and leftover stack data was written to disk. Fixed in e1e1997c04: the stage input info and the resource specialization are now written field by field (bools as one byte, enums as their underlying type), so no padding or runtime pointers are stored, and decoding rejects a size mismatch or an invalid bool. The new ShaderCacheRecordPadding test builds each structure over memory filled with two different patterns and checks that the records are identical; it fails with the old memcpy.

**@⁠NeySlim** on GitHub · 2026-10-09 16:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4232279529) On `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` line 613 (outdated): ```diff @@ -398,28 +454,375 @@ struct PipelineCache::ProgramCache { return permutation.handle; } + // Moves the background result for `key` into the cache. Without one, marks the key so that a + // later prefetch does not compile it a second time. + ProgramMap::iterator Adopt(const ProgramKey& key) { + std::optional<SourceEntry> result; + { + std::unique_lock lock(job_mutex); + auto [iter, inserted] = jobs.try_emplace(key); + auto& job = iter->second; + if (inserted) { + job.state = Job::State::Taken; + return programs.end(); + } + switch (job.state) { + case Job::State::Taken: return programs.end(); + case Job::State::Running: { + const auto begin = std::chrono::steady_clock::now(); + WaitForJob(lock, job); + stats.waited++; + stats.waited_us += + static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>( + std::chrono::steady_clock::now() - begin) + .count()); + result = std::move(job.result); + break; + } + case Job::State::Done: result = std::move(job.result); break; + case Job::State::Dormant: + case Job::State::Queued: + // Not started yet: compiling here is faster than waiting behind other jobs. + std::erase(queue, &job); + job.state = Job::State::Running; + lock.unlock(); + result = CompileJob(job.recipes); + lock.lock(); + stats.compiled += result ? result->permutations.size() : 0; + break; + } + job.state = Job::State::Taken; + job.result.reset(); + job.recipes = {}; + } + if (!result) { + return programs.end(); + } + for (auto& permutation: result->permutations) { + permutation.handle.id = ++next_shader_id; + } + return programs.emplace(key, std::move(*result)).first; + } + + void WaitForJob(std::unique_lock<std::mutex>& lock, const Job& job) { + job_done.wait(lock, [&job] { return job.state == Job::State::Done; }); + } + + template <typename InputInfo> + Permutation CompileRecipe(const ShaderCacheRecipe& recipe, + std::optional<ShaderRecompiler::IR::ResourcePlan>& plan) const { + InputInfo input_info; + std::memcpy(&input_info, recipe.input.data(), sizeof(input_info)); + // Translation reads the user data count, not the values. + const std::vector<uint32_t> user_data(recipe.user_data_count, 0u); + const auto options = MakeOptions(recipe.hash, user_data, recipe.back_code, input_info); + const auto stage_name = GetStageNames(recipe.stage).name; + DumpShaderOriginal(stage_name, recipe.hash, recipe.code); + auto translated = ShaderRecompiler::TranslateProgram(recipe.code, options); + if (!plan) { + plan.emplace(ShaderRecompiler::IR::ExtractResourcePlan(translated.program)); + } + return CompilePermutation(stage_name, options, std::move(translated), recipe.specialization, + recipe.push_data_start); + } + + // Compiles every recipe of one source key; safe on any thread. + std::optional<SourceEntry> CompileJob(const ShaderCacheRecipes& recipes) const { + std::optional<ShaderRecompiler::IR::ResourcePlan> plan; + std::vector<Permutation> permutations; + for (const auto& recipe: recipes) { + switch (recipe->stage) { + case ShaderType::Pixel: + permutations.push_back(CompileRecipe<ShaderPixelInputInfo>(*recipe, plan)); + break; + case ShaderType::Compute: + permutations.push_back(CompileRecipe<ShaderComputeInputInfo>(*recipe, plan)); + break; + default: + permutations.push_back(CompileRecipe<ShaderVertexInputInfo>(*recipe, plan)); + break; + } + } + if (!plan) { + return std::nullopt; + } + std::optional<SourceEntry> entry; + entry.emplace(std::move(*plan)); + entry->permutations = std::move(permutations); + return entry; + } + + // The key a recipe compiles to, or nothing for input that this build cannot use. + static std::optional<ProgramKey> RecipeKey(const ShaderCacheRecipe& recipe) { + ProgramKey key { + .stage = recipe.stage, + .hash = recipe.hash, + .user_data_count = recipe.user_data_count, + .code_size = static_cast<uint32_t>(recipe.code.size()), + }; + if (recipe.input.size() != ShaderCacheInputSize(recipe.stage)) { + return std::nullopt; + } + switch (recipe.stage) { + case ShaderType::Pixel: { + ShaderPixelInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + if (info.input_num > std::size(info.interpolator_settings)) { + return std::nullopt; + } + BuildStageStaticKey(info, key.static_state); + break; + } + case ShaderType::Compute: { + ShaderComputeInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + BuildStageStaticKey(info, key.static_state); + break; + } + default: { + ShaderVertexInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + if (info.logical_stage != recipe.stage || info.resources_num < 0 || + info.resources_num > ShaderVertexInputInfo::RES_MAX) { + return std::nullopt; + } + BuildStageStaticKey(info, key.static_state); + break; + } + } + return key; + } + + template <typename InputInfo> + void Record(const ShaderParams& params, const InputInfo& input_info, + const ShaderRecompiler::IR::ResourceSpecialization& specialization, + uint32_t push_data_start) { + if (cache_path.empty()) { + return; + } + auto recipe = std::make_shared<ShaderCacheRecipe>(); + recipe->stage = GetStage(input_info); + recipe->user_data_count = params.user_data_count; + recipe->push_data_start = push_data_start; + recipe->hash = params.hash; + recipe->code.assign(params.code.begin(), params.code.end()); + recipe->back_code.assign(params.back_code.begin(), params.back_code.end()); + auto input = input_info; + input.stage = {}; + recipe->input.resize(sizeof(input)); + std::memcpy(recipe->input.data(), &input, sizeof(input)); ``` Thanks, good catch. The program key itself was built from the fields (`BuildStageStaticKey`), not from these bytes, but the padding did reach the file and the per-record checksum: identical inputs could give different bytes, and leftover stack data was written to disk. Fixed in e1e1997c04: the stage input info and the resource specialization are now written field by field (bools as one byte, enums as their underlying type), so no padding or runtime pointers are stored, and decoding rejects a size mismatch or an invalid bool. The new `ShaderCacheRecordPadding` test builds each structure over memory filled with two different patterns and checks that the records are identical; it fails with the old `memcpy`.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 16:25 UTC · original
On src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp line 760 (outdated):

@@ -398,28 +454,375 @@ struct PipelineCache::ProgramCache {
 		return permutation.handle;
 	}
 
+	// Moves the background result for `key` into the cache. Without one, marks the key so that a
+	// later prefetch does not compile it a second time.
+	ProgramMap::iterator Adopt(const ProgramKey& key) {
+		std::optional<SourceEntry> result;
+		{
+			std::unique_lock lock(job_mutex);
+			auto [iter, inserted] = jobs.try_emplace(key);
+			auto& job             = iter->second;
+			if (inserted) {
+				job.state = Job::State::Taken;
+				return programs.end();
+			}
+			switch (job.state) {
+				case Job::State::Taken: return programs.end();
+				case Job::State::Running: {
+					const auto begin = std::chrono::steady_clock::now();
+					WaitForJob(lock, job);
+					stats.waited++;
+					stats.waited_us +=
+					    static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(
+					                              std::chrono::steady_clock::now() - begin)
+					                              .count());
+					result = std::move(job.result);
+					break;
+				}
+				case Job::State::Done: result = std::move(job.result); break;
+				case Job::State::Dormant:
+				case Job::State::Queued:
+					// Not started yet: compiling here is faster than waiting behind other jobs.
+					std::erase(queue, &job);
+					job.state = Job::State::Running;
+					lock.unlock();
+					result = CompileJob(job.recipes);
+					lock.lock();
+					stats.compiled += result ? result->permutations.size() : 0;
+					break;
+			}
+			job.state = Job::State::Taken;
+			job.result.reset();
+			job.recipes = {};
+		}
+		if (!result) {
+			return programs.end();
+		}
+		for (auto& permutation: result->permutations) {
+			permutation.handle.id = ++next_shader_id;
+		}
+		return programs.emplace(key, std::move(*result)).first;
+	}
+
+	void WaitForJob(std::unique_lock<std::mutex>& lock, const Job& job) {
+		job_done.wait(lock, [&job] { return job.state == Job::State::Done; });
+	}
+
+	template <typename InputInfo>
+	Permutation CompileRecipe(const ShaderCacheRecipe&                           recipe,
+	                          std::optional<ShaderRecompiler::IR::ResourcePlan>& plan) const {
+		InputInfo input_info;
+		std::memcpy(&input_info, recipe.input.data(), sizeof(input_info));
+		// Translation reads the user data count, not the values.
+		const std::vector<uint32_t> user_data(recipe.user_data_count, 0u);
+		const auto options    = MakeOptions(recipe.hash, user_data, recipe.back_code, input_info);
+		const auto stage_name = GetStageNames(recipe.stage).name;
+		DumpShaderOriginal(stage_name, recipe.hash, recipe.code);
+		auto translated = ShaderRecompiler::TranslateProgram(recipe.code, options);
+		if (!plan) {
+			plan.emplace(ShaderRecompiler::IR::ExtractResourcePlan(translated.program));
+		}
+		return CompilePermutation(stage_name, options, std::move(translated), recipe.specialization,
+		                          recipe.push_data_start);
+	}
+
+	// Compiles every recipe of one source key; safe on any thread.
+	std::optional<SourceEntry> CompileJob(const ShaderCacheRecipes& recipes) const {
+		std::optional<ShaderRecompiler::IR::ResourcePlan> plan;
+		std::vector<Permutation>                          permutations;
+		for (const auto& recipe: recipes) {
+			switch (recipe->stage) {
+				case ShaderType::Pixel:
+					permutations.push_back(CompileRecipe<ShaderPixelInputInfo>(*recipe, plan));
+					break;
+				case ShaderType::Compute:
+					permutations.push_back(CompileRecipe<ShaderComputeInputInfo>(*recipe, plan));
+					break;
+				default:
+					permutations.push_back(CompileRecipe<ShaderVertexInputInfo>(*recipe, plan));
+					break;
+			}
+		}
+		if (!plan) {
+			return std::nullopt;
+		}
+		std::optional<SourceEntry> entry;
+		entry.emplace(std::move(*plan));
+		entry->permutations = std::move(permutations);
+		return entry;
+	}
+
+	// The key a recipe compiles to, or nothing for input that this build cannot use.
+	static std::optional<ProgramKey> RecipeKey(const ShaderCacheRecipe& recipe) {
+		ProgramKey key {
+		    .stage           = recipe.stage,
+		    .hash            = recipe.hash,
+		    .user_data_count = recipe.user_data_count,
+		    .code_size       = static_cast<uint32_t>(recipe.code.size()),
+		};
+		if (recipe.input.size() != ShaderCacheInputSize(recipe.stage)) {
+			return std::nullopt;
+		}
+		switch (recipe.stage) {
+			case ShaderType::Pixel: {
+				ShaderPixelInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				if (info.input_num > std::size(info.interpolator_settings)) {
+					return std::nullopt;
+				}
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+			case ShaderType::Compute: {
+				ShaderComputeInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+			default: {
+				ShaderVertexInputInfo info;
+				std::memcpy(&info, recipe.input.data(), sizeof(info));
+				if (info.logical_stage != recipe.stage || info.resources_num < 0 ||
+				    info.resources_num > ShaderVertexInputInfo::RES_MAX) {
+					return std::nullopt;
+				}
+				BuildStageStaticKey(info, key.static_state);
+				break;
+			}
+		}
+		return key;
+	}
+
+	template <typename InputInfo>
+	void Record(const ShaderParams& params, const InputInfo& input_info,
+	            const ShaderRecompiler::IR::ResourceSpecialization& specialization,
+	            uint32_t                                            push_data_start) {
+		if (cache_path.empty()) {
+			return;
+		}
+		auto recipe             = std::make_shared<ShaderCacheRecipe>();
+		recipe->stage           = GetStage(input_info);
+		recipe->user_data_count = params.user_data_count;
+		recipe->push_data_start = push_data_start;
+		recipe->hash            = params.hash;
+		recipe->code.assign(params.code.begin(), params.code.end());
+		recipe->back_code.assign(params.back_code.begin(), params.back_code.end());
+		auto input  = input_info;
+		input.stage = {};
+		recipe->input.resize(sizeof(input));
+		std::memcpy(recipe->input.data(), &input, sizeof(input));
+		recipe->specialization = specialization;
+		std::lock_guard lock(job_mutex);
+		recipes.push_back(std::move(recipe));
+		dirty = true;
+		if (std::chrono::steady_clock::now() - last_save > PeriodicSaveInterval) {
+			last_save      = std::chrono::steady_clock::now();
+			save_requested = true;
+			StartWorkers();
+			job_ready.notify_one();
+		}
+	}
+
+	void Load(const std::filesystem::path& path, std::string signature) {
+		cache_path      = path;
+		cache_signature = std::move(signature);
+		std::vector<uint8_t> data;
+		ShaderCacheRecipes   loaded;
+		size_t               parsed    = 0;
+		const auto           path_text = Common::PathToString(path);
+		if (ReadShaderCacheFile(path, data) &&
+		    !ParseShaderCache(data, cache_signature, loaded, &parsed)) {
+			PipelineCacheLog(
+			    "Shader cache: invalidating {} (graphics code, device or driver changed)",
+			    path_text);
+		}
+		{
+			std::lock_guard lock(job_mutex);
+			for (auto& recipe: loaded) {
+				auto key = RecipeKey(*recipe);
+				if (!key) {
+					continue;
+				}
+				auto& job     = jobs[std::move(*key)];
+				auto& trigger = triggers[XXH3_64bits(recipe->code.data(),
+				                                     recipe->code.size() * sizeof(uint32_t))];
+				if (std::ranges::find(trigger, &job) == trigger.end()) {
+					trigger.push_back(&job);
+				}
+				job.recipes.push_back(recipe);
+				recipes.push_back(std::move(recipe));
+			}
+			// The next save drops a damaged tail, unusable records or a stale file.
+			dirty     = parsed != data.size() || recipes.size() != loaded.size();
+			last_save = std::chrono::steady_clock::now();
+			PipelineCacheLog("Shader cache: {} recorded programs in {} sources from {}",
+			                 recipes.size(), jobs.size(), path_text);
+		}
+		ShaderSetMapObserver(
+		    [](void* user, uint64_t hash) {
+			    static_cast<ProgramCache*>(user)->OnShaderMapped(hash);
+		    },
+		    this);
+	}
+
+	// The game loaded a shader: compile its recorded programs before the first draw needs them.
+	void OnShaderMapped(uint64_t hash) {
+		std::lock_guard lock(job_mutex);
+		const auto      trigger = triggers.find(hash);
+		if (trigger == triggers.end()) {
+			return;
+		}
+		for (auto* job: trigger->second) {
+			if (job->state == Job::State::Dormant) {
+				job->state = Job::State::Queued;
+				queue.push_back(job);
+			}
+		}
+		triggers.erase(trigger);
+		StartWorkers();
+		job_ready.notify_all();
+	}
+
+	// Called with job_mutex held.
+	void StartWorkers() {
+		if (!workers.empty()) {
+			return;
+		}
+		const auto count = std::clamp(std::thread::hardware_concurrency() / 4u, 1u, 8u);
+		for (uint32_t i = 0; i < count; i++) {
+			workers.emplace_back([this](std::stop_token stop) { WorkerLoop(stop); });
+		}
+	}
+
+	void WorkerLoop(const std::stop_token& stop) {
+		std::unique_lock lock(job_mutex);
+		for (;;) {
+			job_ready.wait(lock, [this, &stop] {
+				return stop.stop_requested() || !queue.empty() || save_requested;
+			});
+			if (stop.stop_requested()) {
+				return;
+			}
+			if (save_requested) {
+				save_requested = false;
+				lock.unlock();
+				SaveRecipes();
+				lock.lock();
+				continue;
+			}
+			auto* job = queue.front();
+			queue.pop_front();
+			job->state = Job::State::Running;
+			running++;
+			lock.unlock();
+			auto result = CompileJob(job->recipes);
+			lock.lock();
+			stats.compiled_ahead += result ? result->permutations.size() : 0;
+			job->result = std::move(result);
+			job->state  = Job::State::Done;
+			running--;
+			job_done.notify_all();
+		}
+	}
+
+	void SaveRecipes() {
+		std::lock_guard    save_lock(save_mutex);
+		ShaderCacheRecipes snapshot;
+		{
+			std::lock_guard lock(job_mutex);
+			if (!dirty || cache_path.empty()) {
+				return;
+			}
+			snapshot = recipes;
+			dirty    = false;
+		}
+		const auto data = SerializeShaderCache(cache_signature, snapshot);
+		if (!WriteShaderCacheFile(cache_path, data)) {
+			std::lock_guard lock(job_mutex);
+			dirty = true;
+			PipelineCacheLog("Shader cache: failed to write {}", Common::PathToString(cache_path));
+			return;
+		}
+		PipelineCacheLog("Shader cache: saved {} recorded programs ({} bytes) to {}",
+		                 snapshot.size(), data.size(), Common::PathToString(cache_path));
+	}
+
+	void WaitForBackgroundCompilation() {
+		std::unique_lock lock(job_mutex);
+		job_done.wait(lock, [this] { return queue.empty() && running == 0; });
+	}
+
 	explicit ProgramCache(vk::Device device): device(device) {
 		lookup_key.static_state.reserve(MaxStaticKeyWords);
 	}
 	~ProgramCache() {
-		for (const auto& [key, entry]: programs) {
-			(void)key;
+		if (!cache_path.empty()) {
+			ShaderSetMapObserver(nullptr, nullptr);

Thanks, you're right, and a compare-and-clear alone would not have been enough: the second cache's Load also replaced the first cache's observer. Fixed in e1e1997c04: the shader map now keeps a list of observers; each cache adds itself in Load and removes only its own entry in its destructor (under the observer mutex, so a running notification ends first). ShaderCachePersistence now creates and destroys a second cache while the first one is alive, then maps the shader and checks that the first cache still compiles its recorded program; this fails with the single observer.

**@⁠NeySlim** on GitHub · 2026-10-09 16:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4232279767) On `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` line 760 (outdated): ```diff @@ -398,28 +454,375 @@ struct PipelineCache::ProgramCache { return permutation.handle; } + // Moves the background result for `key` into the cache. Without one, marks the key so that a + // later prefetch does not compile it a second time. + ProgramMap::iterator Adopt(const ProgramKey& key) { + std::optional<SourceEntry> result; + { + std::unique_lock lock(job_mutex); + auto [iter, inserted] = jobs.try_emplace(key); + auto& job = iter->second; + if (inserted) { + job.state = Job::State::Taken; + return programs.end(); + } + switch (job.state) { + case Job::State::Taken: return programs.end(); + case Job::State::Running: { + const auto begin = std::chrono::steady_clock::now(); + WaitForJob(lock, job); + stats.waited++; + stats.waited_us += + static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>( + std::chrono::steady_clock::now() - begin) + .count()); + result = std::move(job.result); + break; + } + case Job::State::Done: result = std::move(job.result); break; + case Job::State::Dormant: + case Job::State::Queued: + // Not started yet: compiling here is faster than waiting behind other jobs. + std::erase(queue, &job); + job.state = Job::State::Running; + lock.unlock(); + result = CompileJob(job.recipes); + lock.lock(); + stats.compiled += result ? result->permutations.size() : 0; + break; + } + job.state = Job::State::Taken; + job.result.reset(); + job.recipes = {}; + } + if (!result) { + return programs.end(); + } + for (auto& permutation: result->permutations) { + permutation.handle.id = ++next_shader_id; + } + return programs.emplace(key, std::move(*result)).first; + } + + void WaitForJob(std::unique_lock<std::mutex>& lock, const Job& job) { + job_done.wait(lock, [&job] { return job.state == Job::State::Done; }); + } + + template <typename InputInfo> + Permutation CompileRecipe(const ShaderCacheRecipe& recipe, + std::optional<ShaderRecompiler::IR::ResourcePlan>& plan) const { + InputInfo input_info; + std::memcpy(&input_info, recipe.input.data(), sizeof(input_info)); + // Translation reads the user data count, not the values. + const std::vector<uint32_t> user_data(recipe.user_data_count, 0u); + const auto options = MakeOptions(recipe.hash, user_data, recipe.back_code, input_info); + const auto stage_name = GetStageNames(recipe.stage).name; + DumpShaderOriginal(stage_name, recipe.hash, recipe.code); + auto translated = ShaderRecompiler::TranslateProgram(recipe.code, options); + if (!plan) { + plan.emplace(ShaderRecompiler::IR::ExtractResourcePlan(translated.program)); + } + return CompilePermutation(stage_name, options, std::move(translated), recipe.specialization, + recipe.push_data_start); + } + + // Compiles every recipe of one source key; safe on any thread. + std::optional<SourceEntry> CompileJob(const ShaderCacheRecipes& recipes) const { + std::optional<ShaderRecompiler::IR::ResourcePlan> plan; + std::vector<Permutation> permutations; + for (const auto& recipe: recipes) { + switch (recipe->stage) { + case ShaderType::Pixel: + permutations.push_back(CompileRecipe<ShaderPixelInputInfo>(*recipe, plan)); + break; + case ShaderType::Compute: + permutations.push_back(CompileRecipe<ShaderComputeInputInfo>(*recipe, plan)); + break; + default: + permutations.push_back(CompileRecipe<ShaderVertexInputInfo>(*recipe, plan)); + break; + } + } + if (!plan) { + return std::nullopt; + } + std::optional<SourceEntry> entry; + entry.emplace(std::move(*plan)); + entry->permutations = std::move(permutations); + return entry; + } + + // The key a recipe compiles to, or nothing for input that this build cannot use. + static std::optional<ProgramKey> RecipeKey(const ShaderCacheRecipe& recipe) { + ProgramKey key { + .stage = recipe.stage, + .hash = recipe.hash, + .user_data_count = recipe.user_data_count, + .code_size = static_cast<uint32_t>(recipe.code.size()), + }; + if (recipe.input.size() != ShaderCacheInputSize(recipe.stage)) { + return std::nullopt; + } + switch (recipe.stage) { + case ShaderType::Pixel: { + ShaderPixelInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + if (info.input_num > std::size(info.interpolator_settings)) { + return std::nullopt; + } + BuildStageStaticKey(info, key.static_state); + break; + } + case ShaderType::Compute: { + ShaderComputeInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + BuildStageStaticKey(info, key.static_state); + break; + } + default: { + ShaderVertexInputInfo info; + std::memcpy(&info, recipe.input.data(), sizeof(info)); + if (info.logical_stage != recipe.stage || info.resources_num < 0 || + info.resources_num > ShaderVertexInputInfo::RES_MAX) { + return std::nullopt; + } + BuildStageStaticKey(info, key.static_state); + break; + } + } + return key; + } + + template <typename InputInfo> + void Record(const ShaderParams& params, const InputInfo& input_info, + const ShaderRecompiler::IR::ResourceSpecialization& specialization, + uint32_t push_data_start) { + if (cache_path.empty()) { + return; + } + auto recipe = std::make_shared<ShaderCacheRecipe>(); + recipe->stage = GetStage(input_info); + recipe->user_data_count = params.user_data_count; + recipe->push_data_start = push_data_start; + recipe->hash = params.hash; + recipe->code.assign(params.code.begin(), params.code.end()); + recipe->back_code.assign(params.back_code.begin(), params.back_code.end()); + auto input = input_info; + input.stage = {}; + recipe->input.resize(sizeof(input)); + std::memcpy(recipe->input.data(), &input, sizeof(input)); + recipe->specialization = specialization; + std::lock_guard lock(job_mutex); + recipes.push_back(std::move(recipe)); + dirty = true; + if (std::chrono::steady_clock::now() - last_save > PeriodicSaveInterval) { + last_save = std::chrono::steady_clock::now(); + save_requested = true; + StartWorkers(); + job_ready.notify_one(); + } + } + + void Load(const std::filesystem::path& path, std::string signature) { + cache_path = path; + cache_signature = std::move(signature); + std::vector<uint8_t> data; + ShaderCacheRecipes loaded; + size_t parsed = 0; + const auto path_text = Common::PathToString(path); + if (ReadShaderCacheFile(path, data) && + !ParseShaderCache(data, cache_signature, loaded, &parsed)) { + PipelineCacheLog( + "Shader cache: invalidating {} (graphics code, device or driver changed)", + path_text); + } + { + std::lock_guard lock(job_mutex); + for (auto& recipe: loaded) { + auto key = RecipeKey(*recipe); + if (!key) { + continue; + } + auto& job = jobs[std::move(*key)]; + auto& trigger = triggers[XXH3_64bits(recipe->code.data(), + recipe->code.size() * sizeof(uint32_t))]; + if (std::ranges::find(trigger, &job) == trigger.end()) { + trigger.push_back(&job); + } + job.recipes.push_back(recipe); + recipes.push_back(std::move(recipe)); + } + // The next save drops a damaged tail, unusable records or a stale file. + dirty = parsed != data.size() || recipes.size() != loaded.size(); + last_save = std::chrono::steady_clock::now(); + PipelineCacheLog("Shader cache: {} recorded programs in {} sources from {}", + recipes.size(), jobs.size(), path_text); + } + ShaderSetMapObserver( + [](void* user, uint64_t hash) { + static_cast<ProgramCache*>(user)->OnShaderMapped(hash); + }, + this); + } + + // The game loaded a shader: compile its recorded programs before the first draw needs them. + void OnShaderMapped(uint64_t hash) { + std::lock_guard lock(job_mutex); + const auto trigger = triggers.find(hash); + if (trigger == triggers.end()) { + return; + } + for (auto* job: trigger->second) { + if (job->state == Job::State::Dormant) { + job->state = Job::State::Queued; + queue.push_back(job); + } + } + triggers.erase(trigger); + StartWorkers(); + job_ready.notify_all(); + } + + // Called with job_mutex held. + void StartWorkers() { + if (!workers.empty()) { + return; + } + const auto count = std::clamp(std::thread::hardware_concurrency() / 4u, 1u, 8u); + for (uint32_t i = 0; i < count; i++) { + workers.emplace_back([this](std::stop_token stop) { WorkerLoop(stop); }); + } + } + + void WorkerLoop(const std::stop_token& stop) { + std::unique_lock lock(job_mutex); + for (;;) { + job_ready.wait(lock, [this, &stop] { + return stop.stop_requested() || !queue.empty() || save_requested; + }); + if (stop.stop_requested()) { + return; + } + if (save_requested) { + save_requested = false; + lock.unlock(); + SaveRecipes(); + lock.lock(); + continue; + } + auto* job = queue.front(); + queue.pop_front(); + job->state = Job::State::Running; + running++; + lock.unlock(); + auto result = CompileJob(job->recipes); + lock.lock(); + stats.compiled_ahead += result ? result->permutations.size() : 0; + job->result = std::move(result); + job->state = Job::State::Done; + running--; + job_done.notify_all(); + } + } + + void SaveRecipes() { + std::lock_guard save_lock(save_mutex); + ShaderCacheRecipes snapshot; + { + std::lock_guard lock(job_mutex); + if (!dirty || cache_path.empty()) { + return; + } + snapshot = recipes; + dirty = false; + } + const auto data = SerializeShaderCache(cache_signature, snapshot); + if (!WriteShaderCacheFile(cache_path, data)) { + std::lock_guard lock(job_mutex); + dirty = true; + PipelineCacheLog("Shader cache: failed to write {}", Common::PathToString(cache_path)); + return; + } + PipelineCacheLog("Shader cache: saved {} recorded programs ({} bytes) to {}", + snapshot.size(), data.size(), Common::PathToString(cache_path)); + } + + void WaitForBackgroundCompilation() { + std::unique_lock lock(job_mutex); + job_done.wait(lock, [this] { return queue.empty() && running == 0; }); + } + explicit ProgramCache(vk::Device device): device(device) { lookup_key.static_state.reserve(MaxStaticKeyWords); } ~ProgramCache() { - for (const auto& [key, entry]: programs) { - (void)key; + if (!cache_path.empty()) { + ShaderSetMapObserver(nullptr, nullptr); ``` Thanks, you're right, and a compare-and-clear alone would not have been enough: the second cache's `Load` also replaced the first cache's observer. Fixed in e1e1997c04: the shader map now keeps a list of observers; each cache adds itself in `Load` and removes only its own entry in its destructor (under the observer mutex, so a running notification ends first). `ShaderCachePersistence` now creates and destroys a second cache while the first one is alive, then maps the shader and checks that the first cache still compiles its recorded program; this fails with the single observer.
@ -349,3 +436,3 @@
lookup_key.code_size = static_cast<uint32_t>(params.code.size());
BuildStageStaticKey(input_info, lookup_key.static_state);
auto entry = programs.find(lookup_key);
auto entry = programs.find(lookup_key);
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 16:25 UTC · original

Thanks for checking this. Get and Adopt only run on the thread that looks programs up, the GPU thread: GuestGpu::ThreadRun processes the graphics queue and all compute queues on that one thread, and GetGraphicsPrograms/GetComputeProgram are only called from RenderExecutor there. That was already the contract on main (programs and the lookup_key scratch member had no lock before this PR). The workers never touch programs: they only read recipes and store job results under job_mutex, and the lookup thread moves a result into programs itself. To make this explicit, e1e1997c04 adds a check: the first thread that looks up a program owns the cache, and a lookup from any other thread exits with an error (tested by ShaderCacheLookupThread).

**@⁠NeySlim** on GitHub · 2026-10-09 16:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4232280006) Thanks for checking this. `Get` and `Adopt` only run on the thread that looks programs up, the GPU thread: `GuestGpu::ThreadRun` processes the graphics queue and all compute queues on that one thread, and `GetGraphicsPrograms`/`GetComputeProgram` are only called from `RenderExecutor` there. That was already the contract on main (`programs` and the `lookup_key` scratch member had no lock before this PR). The workers never touch `programs`: they only read recipes and store job results under `job_mutex`, and the lookup thread moves a result into `programs` itself. To make this explicit, e1e1997c04 adds a check: the first thread that looks up a program owns the cache, and a lookup from any other thread exits with an error (tested by `ShaderCacheLookupThread`).
@ -483,0 +584,4 @@
lock.unlock();
result = CompileJob(job.recipes, hook);
lock.lock();
stats.compiled += result ? result->permutations.size() : 0;
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 16:25 UTC · original

Thanks, good point. With a single lookup thread, no other thread can wait in WaitForJob on a job that this thread took, but the state handling was still inconsistent: the taken job was not counted as running, so WaitForBackgroundCompilation could return while it was still compiling. Fixed in e1e1997c04: a job compiled by the lookup thread now goes through Running and Done like a worker job (running count, job_done.notify_all()) before it is adopted (Taken); WaitForJob wakes on any state other than Running; at shutdown, jobs that never started go back to Dormant and waiters are woken. The new ShaderCacheConcurrentWaiters test holds that compilation in a hook (semaphores, no sleeps), checks that it is in flight, and checks that a concurrent WaitForBackgroundCompilation returns only after it ended; it fails without the change.

**@⁠NeySlim** on GitHub · 2026-10-09 16:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4232280273) Thanks, good point. With a single lookup thread, no other thread can wait in `WaitForJob` on a job that this thread took, but the state handling was still inconsistent: the taken job was not counted as running, so `WaitForBackgroundCompilation` could return while it was still compiling. Fixed in e1e1997c04: a job compiled by the lookup thread now goes through Running and Done like a worker job (running count, `job_done.notify_all()`) before it is adopted (Taken); `WaitForJob` wakes on any state other than Running; at shutdown, jobs that never started go back to Dormant and waiters are woken. The new `ShaderCacheConcurrentWaiters` test holds that compilation in a hook (semaphores, no sleeps), checks that it is in flight, and checks that a concurrent `WaitForBackgroundCompilation` returns only after it ended; it fails without the change.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 16:26 UTC · original

@⁠jeanpaul87 thanks a lot for the review! All four points are addressed in e1e1997c04, with a test for each (details in the threads). Could you take another look when you have time?

**@⁠NeySlim** on GitHub · 2026-10-09 16:26 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#issuecomment-6084932067) @⁠jeanpaul87 thanks a lot for the review! All four points are addressed in e1e1997c04, with a test for each (details in the threads). Could you take another look when you have time?
@ -43537,0 +43908,4 @@
seen_by_waiter = cache.GetProgramStats().compiled;
});
waiting.acquire();
release.release();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 16:32 UTC · original · edited 2026-10-09 16:49 UTC

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -eu
file='tests/ShaderRecompilerComputeTests.cpp'
printf '%s\n' '--- test block ---'
nl -ba "$file" | sed -n '37315,37365p'
printf '%s\n' '--- WaitForBackgroundCompilation references ---'
rg -n -F -- 'WaitForBackgroundCompilation' --glob '*.{cpp,h,hpp}' .
printf '%s\n' '--- declarations/definitions near matches ---'
rg -n -F -- 'void WaitForBackgroundCompilation' --glob '*.{cpp,h,hpp}' . || true

Repository: KytyPS5/KytyPS5

Length of output: 3478


🏁 Script executed:

set -eu
file='src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp'
printf '%s\n' '--- background wait implementation ---'
nl -ba "$file" | sed -n '735,805p'
printf '%s\n' '--- public forwarding wrapper ---'
nl -ba "$file" | sed -n '1015,1040p'
printf '%s\n' '--- compile hook and relevant job methods ---'
rg -n -F --glob '*.{cpp,h,hpp}' -e 'SetRecordedCompileHook' -e 'recorded_compile_hook' -e 'WaitForBackgroundCompilation' src tests || true
printf '%s\n' '--- header declarations ---'
nl -ba src/graphics/host_gpu/renderer/pipeline/pipelineCache.h | sed -n '95,140p'

Repository: KytyPS5/KytyPS5

Length of output: 7496


Synchronize with the actual background wait before releasing compilation.

The proposed waiter_started signal would still occur before cache.WaitForBackgroundCompilation(). The waiter can be descheduled after that signal, so !waiter_returned.try_acquire() can pass before the waiter reaches job_done.wait. Add a test-only synchronization point around the actual blocking wait. Release compilation only after that point confirms that the waiter is blocked, then join both threads and check the final count.

✅ Confirmed as addressed by @⁠NeySlim

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 16:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4232336004) · edited 2026-10-09 16:49 UTC **🎯 Functional Correctness** | **🟡 Minor** | **⚡ Quick win** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash set -eu file='tests/ShaderRecompilerComputeTests.cpp' printf '%s\n' '--- test block ---' nl -ba "$file" | sed -n '37315,37365p' printf '%s\n' '--- WaitForBackgroundCompilation references ---' rg -n -F -- 'WaitForBackgroundCompilation' --glob '*.{cpp,h,hpp}' . printf '%s\n' '--- declarations/definitions near matches ---' rg -n -F -- 'void WaitForBackgroundCompilation' --glob '*.{cpp,h,hpp}' . || true ``` Repository: KytyPS5/KytyPS5 Length of output: 3478 --- 🏁 Script executed: ```bash set -eu file='src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp' printf '%s\n' '--- background wait implementation ---' nl -ba "$file" | sed -n '735,805p' printf '%s\n' '--- public forwarding wrapper ---' nl -ba "$file" | sed -n '1015,1040p' printf '%s\n' '--- compile hook and relevant job methods ---' rg -n -F --glob '*.{cpp,h,hpp}' -e 'SetRecordedCompileHook' -e 'recorded_compile_hook' -e 'WaitForBackgroundCompilation' src tests || true printf '%s\n' '--- header declarations ---' nl -ba src/graphics/host_gpu/renderer/pipeline/pipelineCache.h | sed -n '95,140p' ``` Repository: KytyPS5/KytyPS5 Length of output: 7496 --- </details> **Synchronize with the actual background wait before releasing compilation.** The proposed `waiter_started` signal would still occur before `cache.WaitForBackgroundCompilation()`. The waiter can be descheduled after that signal, so `!waiter_returned.try_acquire()` can pass before the waiter reaches `job_done.wait`. Add a test-only synchronization point around the actual blocking wait. Release compilation only after that point confirms that the waiter is blocked, then join both threads and check the final count. <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:4d33fff86555529b22e32bd0 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠NeySlim <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 16:32 UTC · original · reviewed

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: bf18b76f-6b80-4d86-a014-83d1e834e36c
📥 Commits

Reviewing files that changed from the base of the PR and between 4972f8e048cbf2bf0d7d9ba8563b474e68458ec9 and e1e1997c04ff437963f2757e43ffe821bccff27e.

📒 Files selected for processing (7)
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp
  • src/graphics/host_gpu/renderer/pipeline/pipelineCache.h
  • src/graphics/host_gpu/renderer/pipeline/shaderCacheFile.cpp
  • src/graphics/host_gpu/renderer/pipeline/shaderCacheFile.h
  • src/graphics/shader/shader.cpp
  • src/graphics/shader/shader.h
  • tests/ShaderRecompilerComputeTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 16:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#pullrequestreview-5472759479) · **reviewed** **Actionable comments posted: 1** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `bf18b76f-6b80-4d86-a014-83d1e834e36c` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 4972f8e048cbf2bf0d7d9ba8563b474e68458ec9 and e1e1997c04ff437963f2757e43ffe821bccff27e. </details> <details> <summary>📒 Files selected for processing (7)</summary> * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.cpp` * `src/graphics/host_gpu/renderer/pipeline/pipelineCache.h` * `src/graphics/host_gpu/renderer/pipeline/shaderCacheFile.cpp` * `src/graphics/host_gpu/renderer/pipeline/shaderCacheFile.h` * `src/graphics/shader/shader.cpp` * `src/graphics/shader/shader.h` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=b1dd38a8-5216-4d76-86fd-b700800e23fc attempt=fd3bab87-6084-435d-af29-a162d4ec0b15 batch=1/1 -->
@ -43537,0 +43908,4 @@
seen_by_waiter = cache.GetProgramStats().compiled;
});
waiting.acquire();
release.release();
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 16:49 UTC · original

Good point, thanks. Fixed in 37d846135d: PipelineCache::SetBackgroundWaitHook adds a test-only hook that WaitForBackgroundCompilation calls under job_mutex right before job_done.wait, telling whether it is about to block (nothing runs when the hook is unset). The test releases the compilation only after this hook has run, so the compilation can end only once the waiter is blocked in the wait, and it checks that the waiter did block. With the old handling of a job taken by the lookup thread, the test now fails at "waiter blocked".

**@⁠NeySlim** on GitHub · 2026-10-09 16:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4232472336) Good point, thanks. Fixed in 37d846135d: `PipelineCache::SetBackgroundWaitHook` adds a test-only hook that `WaitForBackgroundCompilation` calls under `job_mutex` right before `job_done.wait`, telling whether it is about to block (nothing runs when the hook is unset). The test releases the compilation only after this hook has run, so the compilation can end only once the waiter is blocked in the wait, and it checks that the waiter did block. With the old handling of a job taken by the lookup thread, the test now fails at "waiter blocked".
@ -43537,0 +43908,4 @@
seen_by_waiter = cache.GetProgramStats().compiled;
});
waiting.acquire();
release.release();
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 16:49 UTC · original

@NeySlim, thanks for fixing this. Calling the hook under job_mutex before job_done.wait closes the scheduling gap. The "waiter blocked" check also tests the failure case identified in this finding.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 16:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#discussion_r4232476124) `@NeySlim`, thanks for fixing this. Calling the hook under `job_mutex` before `job_done.wait` closes the scheduling gap. The `"waiter blocked"` check also tests the failure case identified in this finding. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=A%20test%20signal%20before%20a%20thread%20starts%20waiting%20isn%E2%80%99t%20enough%E2%80%94it%20could%20be%20descheduled.%20%40coderabbitai%E2%80%99s%20fix%20synchronizes%20at%20the%20actual%20wait%2C%20making%20the%20race%20test%20deterministic%20and%20catching%20regressions.%20Give%20it%20a%20try!%20%F0%9F%A7%AA&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1311%23discussion_r4232336004)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠NeySlim on GitHub · 2026-10-09 19:03 UTC · original

Rebased on main after the SWAPPC linking (1818aae5, 3e9f88bf), the GETREG queue fields (bb5edbd4) and the inline sampler planning (8c813865). I checked every input these add to program translation against the record (new commit b73560ff):

  • async_compute (GETREG queue fields) is a new compute input field. It is part of the program key, but the field-by-field record missed it: a recorded async program would have been compiled on a worker as graphics compute. It is now recorded; ShaderCacheRecordPadding checks it survives with the same key.
  • A SWAPPC program links guest functions read from memory at the draw (RefreshShaderSource), which the record does not hold. Such programs are no longer recorded, and a worker refuses a recorded one instead of translating its code alone; the draw compiles it as before. New test ShaderCacheSwappcRecord.
  • Inline sampler candidates and the other planning changes (973809cd, 5b68a26c, 3b1a9470, 488c0aca) are derived from the guest code and the resource specialization, both already recorded.

Mutation checks redone (adoption, recording, async field, SWAPPC guard, stolen job, waiter hook, lookup thread, observer scope): each fails or hangs its test. pipeline_cache, resource_tracking, resource_materialization pass; GPU suite one case per process: 602 of 612 on both this branch and main. Body updated.

**@⁠NeySlim** on GitHub · 2026-10-09 19:03 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#issuecomment-6087413234) Rebased on main after the SWAPPC linking (1818aae5, 3e9f88bf), the GETREG queue fields (bb5edbd4) and the inline sampler planning (8c813865). I checked every input these add to program translation against the record (new commit b73560ff): - `async_compute` (GETREG queue fields) is a new compute input field. It is part of the program key, but the field-by-field record missed it: a recorded async program would have been compiled on a worker as graphics compute. It is now recorded; `ShaderCacheRecordPadding` checks it survives with the same key. - A SWAPPC program links guest functions read from memory at the draw (`RefreshShaderSource`), which the record does not hold. Such programs are no longer recorded, and a worker refuses a recorded one instead of translating its code alone; the draw compiles it as before. New test `ShaderCacheSwappcRecord`. - Inline sampler candidates and the other planning changes (973809cd, 5b68a26c, 3b1a9470, 488c0aca) are derived from the guest code and the resource specialization, both already recorded. Mutation checks redone (adoption, recording, async field, SWAPPC guard, stolen job, waiter hook, lookup thread, observer scope): each fails or hangs its test. `pipeline_cache`, `resource_tracking`, `resource_materialization` pass; GPU suite one case per process: 602 of 612 on both this branch and main. Body updated.
Author
Owner

@⁠NeySlim on GitHub · 2026-10-13 22:35 UTC · original

Rebased on main. Programs compiled ahead now take maintenance8_enabled from the device like the draw path (460a196f), so recorded shaders with dynamic sample offsets get the same SPIR-V and validation. GPU suite unchanged vs main (627/637, same 10 failures here).

**@⁠NeySlim** on GitHub · 2026-10-13 22:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1311#issuecomment-6156669160) Rebased on main. Programs compiled ahead now take maintenance8_enabled from the device like the draw path (460a196f), so recorded shaders with dynamic sample offsets get the same SPIR-V and validation. GPU suite unchanged vs main (627/637, same 10 failures here).

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.