vulkan: keep MoltenVK device-address buffers alive through queued work #721

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

@⁠carbonimax on GitHub · 2026-09-19 20:23 UTC · original
carbonimax:codex/moltenvk-bda-lifetime → main · +475 −147 · 6 files · 3 commits · closed without merging

MoltenVK can lose the device with Metal Invalid Resource (code 9) when Kyty retires a device-address buffer after its last actual use. MoltenVK declares all live addressable buffers when encoding BDA shaders, so later queued command buffers can still reference the retired Metal resource even when their shaders never access that buffer.

On MoltenVK only, wait for the latest submitted scheduler tick in the deferred buffer-deletion callback before destroying the cached buffer. Other drivers retain the existing retirement behavior. This is a conservative driver workaround: it can drain queued work during deletion batches and reduce CPU/GPU overlap.

Scope

  • Detect MoltenVK through driver properties; no change to descriptor policy.
  • Add an opt-in host GPU reproducer with separate output regions and strict success/device-loss verdicts.
  • Independent of #715 and the remaining live-checkout WIP. Based on current main (f100f78); adapted from local commit 6b31300.
  • The repository formatting hook also reformatted touched source files.

Validation

On the isolated PR sources: compiler syntax checks for the modified translation units and successful compilation of the standalone reproducer. The safe GPU mode was rerun on Apple M4 Pro with the local MoltenVK 1.4.3 fork.

Previously reviewed evidence from the live checkout:

  • Corrected standalone reproducer: five successful safe-mode runs and five deliberate hazard reproductions, each with successful wait followed by VK_ERROR_DEVICE_LOST and Metal code 9.
  • Same-binary game A/B with argument buffers disabled: 5/20 failures without the workaround versus 0/20 with it.
  • Final binary: 0/8 failures with argument buffers and 0/8 without.
  • Shader CFG, PerVertex GPU and descriptor-policy tests passed there.

Game trials stopped at the first PerVertex draw, beyond the two known early crash sites. These are bounded stability checks on a checkout with other WIP, not visual or gameplay validation of this isolated PR. The black screen remains unresolved. The observed queue-drain cost is a known tradeoff; retaining implicitly referenced resources in MoltenVK would be preferable.

Reproducer

cmake --build <build-dir> --target device_address_lifetime_gpu_tests
SDL_VULKAN_LIBRARY=/path/to/libMoltenVK.dylib <build-dir>/device_address_lifetime_gpu_tests
# Opt-in negative control; intentionally triggers device loss on the affected driver:
SDL_VULKAN_LIBRARY=/path/to/libMoltenVK.dylib <build-dir>/device_address_lifetime_gpu_tests --expect-driver-hazard

The harness loads MoltenVK with dlopen and is not part of default CI. In hazard mode, exit 0 requires exactly device loss after successful completion of the buffer's sole user; a failed initial wait is inconclusive, not a successful reproduction.

Completion boundary

This workaround waits for Vulkan timeline visibility. It addresses MoltenVK keeping implicit references to otherwise unused live device-address buffers in later queued work; it does not prove Metal command-buffer completion. A separately reproduced Metal API validation window between timeline visibility and command-buffer completion remains outside this PR. No submission-fence protocol change is included here.

Main update validation (2026-10-01)

Updated against main 44798085. The GPU reproducer is Apple-only and checks portability enumeration and device-enumeration failures. Local build and host checks are recorded separately from the historical GPU evidence; no new GPU run was performed during this update.

**@⁠carbonimax** on GitHub · 2026-09-19 20:23 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721) `carbonimax:codex/moltenvk-bda-lifetime` → `main` · +475 −147 · 6 files · 3 commits · closed without merging MoltenVK can lose the device with Metal `Invalid Resource` (code 9) when Kyty retires a device-address buffer after its last actual use. MoltenVK declares all live addressable buffers when encoding BDA shaders, so later queued command buffers can still reference the retired Metal resource even when their shaders never access that buffer. On MoltenVK only, wait for the latest submitted scheduler tick in the deferred buffer-deletion callback before destroying the cached buffer. Other drivers retain the existing retirement behavior. This is a conservative driver workaround: it can drain queued work during deletion batches and reduce CPU/GPU overlap. ## Scope - Detect MoltenVK through driver properties; no change to descriptor policy. - Add an opt-in host GPU reproducer with separate output regions and strict success/device-loss verdicts. - Independent of #715 and the remaining live-checkout WIP. Based on current `main` (`f100f78`); adapted from local commit `6b31300`. - The repository formatting hook also reformatted touched source files. ## Validation On the isolated PR sources: compiler syntax checks for the modified translation units and successful compilation of the standalone reproducer. The safe GPU mode was rerun on Apple M4 Pro with the local MoltenVK 1.4.3 fork. Previously reviewed evidence from the live checkout: - Corrected standalone reproducer: five successful safe-mode runs and five deliberate hazard reproductions, each with successful wait followed by `VK_ERROR_DEVICE_LOST` and Metal code 9. - Same-binary game A/B with argument buffers disabled: 5/20 failures without the workaround versus 0/20 with it. - Final binary: 0/8 failures with argument buffers and 0/8 without. - Shader CFG, PerVertex GPU and descriptor-policy tests passed there. Game trials stopped at the first PerVertex draw, beyond the two known early crash sites. These are bounded stability checks on a checkout with other WIP, not visual or gameplay validation of this isolated PR. The black screen remains unresolved. The observed queue-drain cost is a known tradeoff; retaining implicitly referenced resources in MoltenVK would be preferable. ## Reproducer ```sh cmake --build <build-dir> --target device_address_lifetime_gpu_tests SDL_VULKAN_LIBRARY=/path/to/libMoltenVK.dylib <build-dir>/device_address_lifetime_gpu_tests # Opt-in negative control; intentionally triggers device loss on the affected driver: SDL_VULKAN_LIBRARY=/path/to/libMoltenVK.dylib <build-dir>/device_address_lifetime_gpu_tests --expect-driver-hazard ``` The harness loads MoltenVK with `dlopen` and is not part of default CI. In hazard mode, exit 0 requires exactly device loss after successful completion of the buffer's sole user; a failed initial wait is inconclusive, not a successful reproduction. ### Completion boundary This workaround waits for Vulkan timeline visibility. It addresses MoltenVK keeping implicit references to otherwise unused live device-address buffers in later queued work; it does not prove Metal command-buffer completion. A separately reproduced Metal API validation window between timeline visibility and command-buffer completion remains outside this PR. No submission-fence protocol change is included here. ### Main update validation (2026-10-01) Updated against main 44798085. The GPU reproducer is Apple-only and checks portability enumeration and device-enumeration failures. Local build and host checks are recorded separately from the historical GPU evidence; no new GPU run was performed during this update.
MoltenVK declares all live device-address buffers to Metal when encoding a BDA
shader. Destroying one after its last guest use can invalidate later queued
command buffers that declared it without accessing it, causing DeviceLost.
Wait for the latest submitted scheduler tick before deleting cached buffers on
MoltenVK; retain the existing retirement behavior for other drivers. This can
drain the queue during buffer deletion batches until the driver retains these
resources itself.

Add an opt-in GPU reproducer with independent destination regions and strict
wait/device-loss verdicts. Reviewed evidence: 5/5 safe runs and 5/5 hazard
reproductions; the game A/B had 5/20 failures without the workaround and 0/20
with it, followed by 0/16 failures on the final binary. Game runs stop at the
first PerVertex draw; correct visual output is not established.

Validation: reviewed GPU logs and shader/policy suites; isolated committed
sources pass syntax compilation without unrelated WIP changes.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apply the repository's pinned clang-format 22.1.3 hook to the source files modified by this pull request.

Assisted-by: OpenAI GPT-6.1 Sol
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:30:45 +00:00
github-bot closed this pull request 2026-11-26 09:30:45 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:32 UTC · original · edited 2026-10-13 22:44 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.

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: a438dcde-8ba6-43c7-8aca-a88c0fc5087d
📥 Commits

Reviewing files that changed from the base of the PR and between ae2a9df10e3d46c2be95c1eae8d1b5f960535bc2 and cc9ffcd1f6570b2dc52bb40f7f0ef94f6fb9df47.

📒 Files selected for processing (3)
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/presentation/window/vulkanWindow.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/graphics/host_gpu/renderer/cache/bufferCache.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

Walkthrough

The change detects MoltenVK and records whether device-address buffer destruction must wait for queued work. When that policy is enabled, deferred buffer deletion waits through the preceding scheduler tick. An Apple-only, excluded GPU test target exercises normal and expected-hazard outcomes.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🟡 Moderate · up to cc9ff

MoltenVK can still release a buffer before Metal has finished using it, leaving a reported validation window that can disrupt GPU work. Resolve this lifetime gap before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 0dcfb

The workaround conservatively extends GPU buffer lifetimes on MoltenVK. No new guest-facing capability or privilege expansion was identified in the inspected paths. Remaining uncertainty concerns concurrent access and failure cleanup, rather than a verified security vulnerability.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The directly evidenced scope is host-owned cached buffers and graphics-queue work in a process using MoltenVK. Non-MoltenVK drivers do not enable the added wait. No broader privilege or cross-service exposure was established.

Trust Boundaries and Controls

  • inferred — In the inspected descriptor path, guest addresses resolve through cache ownership lookup rather than supplying cache-internal BufferIds directly. Unregistration removes the old buffer from lookup before destruction. A host accessor can accept an existing BufferId, but concurrent reuse of a stale ID was not demonstrated or fully excluded.

Resilience and Maintainability Implications

  • observed — Normal shutdown stops and joins guest work, then drains scheduler callbacks before buffer-cache member destruction. Scheduler shutdown submits an outstanding command, waits for queue completion and drains deferred operations. Repeated buffer deletion is guarded by the deleted-buffer state. These are counterevidence to ordinary shutdown-owner loss and duplicate-erasure concerns, not proof of device-recovery safety.
Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check Passed The description clearly explains the MoltenVK-specific buffer-lifetime workaround, the reproducer, scope, validation, and known limitations.
Title check Passed The title clearly and concisely identifies the main change: keeping MoltenVK device-address buffers alive through queued work.
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.

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-09-19 20:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#issuecomment-5745087518) · edited 2026-10-13 22:44 UTC <!-- 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/721?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. > > 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**: `a438dcde-8ba6-43c7-8aca-a88c0fc5087d` </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> Reviewing files that changed from the base of the PR and between ae2a9df10e3d46c2be95c1eae8d1b5f960535bc2 and cc9ffcd1f6570b2dc52bb40f7f0ef94f6fb9df47. </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing (3)</strong></summary> <dl> <dd> * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/presentation/window/vulkanWindow.cpp` </dd> </dl> </details> <details> <summary><strong>🚧 Files skipped from review as they are similar to previous changes (1)</strong></summary> <dl> <dd> * src/graphics/host_gpu/renderer/cache/bufferCache.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> ## Walkthrough The change detects MoltenVK and records whether device-address buffer destruction must wait for queued work. When that policy is enabled, deferred buffer deletion waits through the preceding scheduler tick. An Apple-only, excluded GPU test target exercises normal and expected-hazard outcomes. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"cc9ffcd1f6570b2dc52bb40f7f0ef94f6fb9df47" --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong>🟡 Moderate</strong> · up to <code>cc9ff</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `cc9ff` --> <!-- final_review_risk_coverage:{"sourceCommitId":"cc9ffcd1f6570b2dc52bb40f7f0ef94f6fb9df47","coveredCommitId":"cc9ffcd1f6570b2dc52bb40f7f0ef94f6fb9df47","kind":"reviewed"} --> MoltenVK can still release a buffer before Metal has finished using it, leaving a reported validation window that can disrupt GPU work. Resolve this lifetime gap before merging. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- architecture_review_start --> <details> <summary><strong>Security Architecture Review</strong></summary> <dl> <dd> **Security architecture risk:** _🔵 Low_ · up to `0dcfb` The workaround conservatively extends GPU buffer lifetimes on MoltenVK. No new guest-facing capability or privilege expansion was identified in the inspected paths. Remaining uncertainty concerns concurrent access and failure cleanup, rather than a verified security vulnerability. **Retained concerns** No architecture-level concerns identified. <details> <summary><h4><strong>Security review details</strong></h4></summary> <dl> <dd> **Security Blast Radius** - _inferred_ — The directly evidenced scope is host-owned cached buffers and graphics-queue work in a process using MoltenVK. Non-MoltenVK drivers do not enable the added wait. No broader privilege or cross-service exposure was established. **Trust Boundaries and Controls** - _inferred_ — In the inspected descriptor path, guest addresses resolve through cache ownership lookup rather than supplying cache-internal BufferIds directly. Unregistration removes the old buffer from lookup before destruction. A host accessor can accept an existing BufferId, but concurrent reuse of a stale ID was not demonstrated or fully excluded. **Resilience and Maintainability Implications** - _observed_ — Normal shutdown stops and joins guest work, then drains scheduler callbacks before buffer-cache member destruction. Scheduler shutdown submits an outstanding command, waits for queue completion and drains deferred operations. Repeated buffer deletion is guarded by the deleted-buffer state. These are counterevidence to ordinary shutdown-owner loss and duplicate-erasure concerns, not proof of device-recovery safety. </dd> </dl> </details> </dd> </dl> </details> <!-- architecture_review_end --> <!-- 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-v1.svg" width="14" height="17" align="middle" alt="Passed" title="Passed"></picture></sup> 4 | <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v1.svg" width="14" height="17" align="middle" alt="Failed" title="Failed"></picture></sup> 1</strong></summary> <dl> <dd> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :---------------- | :----------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Warning](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg) | Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 5 files. | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong>✅ Passed checks (4 passed)</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------- | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description clearly explains the MoltenVK-specific buffer-lifetime workaround, the reproducer, scope, validation, and known limitations. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely identifies the main change: keeping MoltenVK device-address buffers alive through queued work. | | 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. | </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=721)! 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

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:32 UTC · original · edited 2026-10-01 17:29 UTC
On CMakeLists.txt line 384 (outdated):

@@ -375,6 +375,14 @@ endfunction()
 
 add_kyty_full_emulator_test(shader_cfg_tests "${KYTY_TESTS_DIR}/shaderCfgTests.cpp")
 
+# Keeps device-address buffers alive until queued MoltenVK work completes (the game lost the device
+# otherwise). Needs a real Vulkan driver through SDL_VULKAN_LIBRARY, so it stays opt-in.
+add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL
+	"${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp"
+)
+target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers})
+target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers)

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '360,400p' CMakeLists.txt
sed -n '1,35p' tests/DeviceAddressLifetimeGpuTests.cpp
rg -n -i 'WIN32|APPLE|UNIX|dlfcn|device_address_lifetime_gpu_tests|MoltenVK' CMakeLists.txt cmake tests src | head -240

Repository: KytyPS5/KytyPS5

Length of output: 20535


🏁 Script executed:

sed -n '1,120p' CMakeLists.txt
sed -n '330,390p' CMakeLists.txt
sed -n '150,185p' tests/DeviceAddressLifetimeGpuTests.cpp
rg -n -C 4 'dlopen|dlsym|dlclose|LoadLibrary|GetProcAddress|DeviceAddressLifetimeGpuTests|device_address_lifetime_gpu_tests|SDL_VULKAN_LIBRARY' CMakeLists.txt tests src graphics 2>/dev/null | head -240

Repository: KytyPS5/KytyPS5

Length of output: 23147


Restrict the target to Apple platforms.

The project supports Windows, but this target is unguarded. Its source includes POSIX-only <dlfcn.h> and calls dlopen and dlsym. When SDL_VULKAN_LIBRARY is unset, it also attempts to load libMoltenVK.dylib. An explicit Windows build can therefore fail. No portable loader is used by this target.

Proposed CMake change
-add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL
-	"${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp"
-)
-target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers})
-target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers)
+if(APPLE)
+	add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL
+		"${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp"
+	)
+	target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers})
+	target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers)
+endif()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

if(APPLE)
	add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL
		"${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp"
	)
	target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers})
	target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers)
endif()

✅ Confirmed as addressed by @⁠carbonimax

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#discussion_r4054618115) · edited 2026-10-01 17:29 UTC On `CMakeLists.txt` line 384 (outdated): ```diff @@ -375,6 +375,14 @@ endfunction() add_kyty_full_emulator_test(shader_cfg_tests "${KYTY_TESTS_DIR}/shaderCfgTests.cpp") +# Keeps device-address buffers alive until queued MoltenVK work completes (the game lost the device +# otherwise). Needs a real Vulkan driver through SDL_VULKAN_LIBRARY, so it stays opt-in. +add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL + "${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp" +) +target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers}) +target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers) ``` _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '360,400p' CMakeLists.txt sed -n '1,35p' tests/DeviceAddressLifetimeGpuTests.cpp rg -n -i 'WIN32|APPLE|UNIX|dlfcn|device_address_lifetime_gpu_tests|MoltenVK' CMakeLists.txt cmake tests src | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 20535 --- 🏁 Script executed: ```bash sed -n '1,120p' CMakeLists.txt sed -n '330,390p' CMakeLists.txt sed -n '150,185p' tests/DeviceAddressLifetimeGpuTests.cpp rg -n -C 4 'dlopen|dlsym|dlclose|LoadLibrary|GetProcAddress|DeviceAddressLifetimeGpuTests|device_address_lifetime_gpu_tests|SDL_VULKAN_LIBRARY' CMakeLists.txt tests src graphics 2>/dev/null | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 23147 --- </details> **Restrict the target to Apple platforms.** The project supports Windows, but this target is unguarded. Its source includes POSIX-only `<dlfcn.h>` and calls `dlopen` and `dlsym`. When `SDL_VULKAN_LIBRARY` is unset, it also attempts to load `libMoltenVK.dylib`. An explicit Windows build can therefore fail. No portable loader is used by this target. <details> <summary>Proposed CMake change</summary> ```diff -add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL - "${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp" -) -target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers}) -target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers) +if(APPLE) + add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL + "${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp" + ) + target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers}) + target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers) +endif() ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion if(APPLE) add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL "${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp" ) target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers}) target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers) endif() ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:tapir --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:47d6997787034216bce48278 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠carbonimax <!-- This is an auto-generated comment by CodeRabbit -->
@ -0,0 +194,4 @@
Check(vkEnumeratePhysicalDevices(instance, &n, devices.data()), "vkEnumeratePhysicalDevices");
if (n == 0 || devices[0] == VK_NULL_HANDLE) { std::printf("No Vulkan physical device; inconclusive\n"); return 2; }
VkPhysicalDevice phys = devices[0];
vkGetPhysicalDeviceMemoryProperties(phys, &g_mp);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:32 UTC · original · edited 2026-10-01 17:32 UTC

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '150,195p' tests/DeviceAddressLifetimeGpuTests.cpp
sed -n '900,1085p' src/graphics/presentation/window/vulkanWindow.cpp
rg -n -C4 'PORTABILITY_ENUMERATION|ENUMERATE_PORTABILITY|vkEnumeratePhysicalDevices|vkCreateInstance' src tests CMakeLists.txt

Repository: KytyPS5/KytyPS5

Length of output: 19201


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- test file includes and setup ---'
sed -n '1,145p' tests/DeviceAddressLifetimeGpuTests.cpp
printf '%s\n' '--- test body context ---'
sed -n '145,215p' tests/DeviceAddressLifetimeGpuTests.cpp
printf '%s\n' '--- references and build/test gating ---'
rg -n -C5 'DeviceAddressLifetimeGpuTests|expect-driver-hazard|libMoltenVK|SDL_VULKAN_LIBRARY|add_test|APPLE|Darwin' CMakeLists.txt cmake tests src .github 2>/dev/null | head -240

Repository: KytyPS5/KytyPS5

Length of output: 31878


Enable portability enumeration and validate the physical-device result.

On supported MoltenVK runs, enable VK_KHR_portability_enumeration and VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR, using the same extension-availability condition as production. Without them, some MoltenVK versions can report zero physical devices. The current code ignores the enumeration result and can pass an unwritten phys to vkGetPhysicalDeviceMemoryProperties. Initialize phys, check the result, and reject zero devices before using the handle.

✅ Confirmed as addressed by @⁠carbonimax

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#discussion_r4054618122) · edited 2026-10-01 17:32 UTC _🩺 Stability & Availability_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '150,195p' tests/DeviceAddressLifetimeGpuTests.cpp sed -n '900,1085p' src/graphics/presentation/window/vulkanWindow.cpp rg -n -C4 'PORTABILITY_ENUMERATION|ENUMERATE_PORTABILITY|vkEnumeratePhysicalDevices|vkCreateInstance' src tests CMakeLists.txt ``` Repository: KytyPS5/KytyPS5 Length of output: 19201 --- 🏁 Script executed: ```bash #!/bin/bash set -eu printf '%s\n' '--- test file includes and setup ---' sed -n '1,145p' tests/DeviceAddressLifetimeGpuTests.cpp printf '%s\n' '--- test body context ---' sed -n '145,215p' tests/DeviceAddressLifetimeGpuTests.cpp printf '%s\n' '--- references and build/test gating ---' rg -n -C5 'DeviceAddressLifetimeGpuTests|expect-driver-hazard|libMoltenVK|SDL_VULKAN_LIBRARY|add_test|APPLE|Darwin' CMakeLists.txt cmake tests src .github 2>/dev/null | head -240 ``` Repository: KytyPS5/KytyPS5 Length of output: 31878 --- </details> **Enable portability enumeration and validate the physical-device result.** On supported MoltenVK runs, enable `VK_KHR_portability_enumeration` and `VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR`, using the same extension-availability condition as production. Without them, some MoltenVK versions can report zero physical devices. The current code ignores the enumeration result and can pass an unwritten `phys` to `vkGetPhysicalDeviceMemoryProperties`. Initialize `phys`, check the result, and reject zero devices before using the handle. <!-- fingerprinting:phantom:medusa:tapir --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:8454ace471c2745444b19aef --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠carbonimax <!-- This is an auto-generated comment by CodeRabbit -->
@ -0,0 +281,4 @@
return early ? 2 : 1;
}
vkResetCommandPool(g_dev, pool, 0);
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-19 20:32 UTC · original · edited 2026-10-01 17:31 UTC

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '200,272p' tests/DeviceAddressLifetimeGpuTests.cpp
rg -n -C5 'cmds|lifetime|vkCmdBindPipeline|vkCmdPushConstants|vkQueueSubmit|vkWaitSemaphores|vkDestroyBuffer|vkFreeMemory|expect-driver-hazard' tests/DeviceAddressLifetimeGpuTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 10832


Make every hazard-mode submission use x.address. The current source selection makes only cbs[0] access x. Hazard mode waits for first, which is the signal value for cbs[0], before destroying x. The remaining submissions use src.address, so no submitted command buffer can access x after destruction. Use x.address for every recorded command buffer and remove the now-unused src allocation.

Suggested fix
-	Mem src = MakeBuffer(region), dst = MakeBuffer(region * VkDeviceSize(queued + 1));
+	Mem dst = MakeBuffer(region * VkDeviceSize(queued + 1));
...
-		Mem x = MakeBuffer(count * 4);  // only command buffer 0 reads it
+		Mem x = MakeBuffer(count * 4);  // every command buffer reads it
...
-			struct { uint64_t s, d; uint32_t it, n; } push {i == 0 ? x.address : src.address, dst.address + region * i, 256u, count};
+			struct { uint64_t s, d; uint32_t it, n; } push {x.address, dst.address + region * i, 256u, count};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	const uint32_t count = 1u << 20;
	// Each command buffer writes its own destination region, so the only hazard left is the lifetime of x.
	const VkDeviceSize region = VkDeviceSize {count} * 4;
	Mem dst = MakeBuffer(region * VkDeviceSize(queued + 1));
	uint64_t value = 0;
		for (int t = 0; t < trials; ++t) {
		Mem x = MakeBuffer(count * 4);  // every command buffer reads it
		std::vector<VkCommandBuffer> cbs(queued + 1);
		VkCommandBufferAllocateInfo ai {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
		ai.commandPool = pool; ai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; ai.commandBufferCount = uint32_t(cbs.size());
		Check(vkAllocateCommandBuffers(g_dev, &ai, cbs.data()), "vkAllocateCommandBuffers");
		for (size_t i = 0; i < cbs.size(); ++i) {
			VkCommandBufferBeginInfo bi {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
			bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
			Check(vkBeginCommandBuffer(cbs[i], &bi), "vkBeginCommandBuffer");
			struct { uint64_t s, d; uint32_t it, n; } push {x.address, dst.address + region * i, 256u, count};
			vkCmdBindPipeline(cbs[i], VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
			vkCmdPushConstants(cbs[i], layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push);
			vkCmdDispatch(cbs[i], count / 64, 1, 1);
			Check(vkEndCommandBuffer(cbs[i]), "vkEndCommandBuffer");
		}
		const uint64_t first = value + 1;
		for (size_t i = 0; i < cbs.size(); ++i) {
			const uint64_t signal = ++value;
			VkTimelineSemaphoreSubmitInfo ts {VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO};
			ts.signalSemaphoreValueCount = 1; ts.pSignalSemaphoreValues = &signal;
			VkSubmitInfo sub {VK_STRUCTURE_TYPE_SUBMIT_INFO}; sub.pNext = &ts;
			sub.commandBufferCount = 1; sub.pCommandBuffers = &cbs[i];
			sub.signalSemaphoreCount = 1; sub.pSignalSemaphores = &timeline;
			Check(vkQueueSubmit(queue, 1, &sub, VK_NULL_HANDLE), "vkQueueSubmit");
		}
		VkSemaphoreWaitInfo wi {VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; wi.semaphoreCount = 1; wi.pSemaphores = &timeline;
		const uint64_t wait_value = early ? first : value;  // early: only the command buffer that used x
		wi.pValues = &wait_value;
		const VkResult w = vkWaitSemaphores(g_dev, &wi, 10000000000ull);
		if (w != VK_SUCCESS) {
			// x may still be in use: destroying it would test nothing.
			std::printf("trial %d mode=%s wait=%d: inconclusive, x kept alive\n", t, early ? "early" : "late", w);
			return 2;
		}
		vkDestroyBuffer(g_dev, x.buffer, nullptr);
		vkFreeMemory(g_dev, x.memory, nullptr);
		const VkResult idle = vkQueueWaitIdle(queue);
		std::printf("trial %d mode=%s wait=%d idle=%d\n", t, early ? "early" : "late", w, idle);
		if (early && idle == VK_ERROR_DEVICE_LOST) {
			std::printf("DeviceAddressLifetimeGpuTests: driver hazard reproduced\n");
			return 0;
		}
		if (idle != VK_SUCCESS) {
			std::printf("DeviceAddressLifetimeGpuTests: %s (idle=%d)\n", early ? "unexpected error" : "FAILED", idle);
			return early ? 2 : 1;
		}
		vkResetCommandPool(g_dev, pool, 0);
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#discussion_r4054618123) · edited 2026-10-01 17:31 UTC _🎯 Functional Correctness_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '200,272p' tests/DeviceAddressLifetimeGpuTests.cpp rg -n -C5 'cmds|lifetime|vkCmdBindPipeline|vkCmdPushConstants|vkQueueSubmit|vkWaitSemaphores|vkDestroyBuffer|vkFreeMemory|expect-driver-hazard' tests/DeviceAddressLifetimeGpuTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 10832 --- </details> **Make every hazard-mode submission use `x.address`.** The current source selection makes only `cbs[0]` access `x`. Hazard mode waits for `first`, which is the signal value for `cbs[0]`, before destroying `x`. The remaining submissions use `src.address`, so no submitted command buffer can access `x` after destruction. Use `x.address` for every recorded command buffer and remove the now-unused `src` allocation. <details><summary>Suggested fix</summary> ```diff - Mem src = MakeBuffer(region), dst = MakeBuffer(region * VkDeviceSize(queued + 1)); + Mem dst = MakeBuffer(region * VkDeviceSize(queued + 1)); ... - Mem x = MakeBuffer(count * 4); // only command buffer 0 reads it + Mem x = MakeBuffer(count * 4); // every command buffer reads it ... - struct { uint64_t s, d; uint32_t it, n; } push {i == 0 ? x.address : src.address, dst.address + region * i, 256u, count}; + struct { uint64_t s, d; uint32_t it, n; } push {x.address, dst.address + region * i, 256u, count}; ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const uint32_t count = 1u << 20; // Each command buffer writes its own destination region, so the only hazard left is the lifetime of x. const VkDeviceSize region = VkDeviceSize {count} * 4; Mem dst = MakeBuffer(region * VkDeviceSize(queued + 1)); uint64_t value = 0; for (int t = 0; t < trials; ++t) { Mem x = MakeBuffer(count * 4); // every command buffer reads it std::vector<VkCommandBuffer> cbs(queued + 1); VkCommandBufferAllocateInfo ai {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; ai.commandPool = pool; ai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; ai.commandBufferCount = uint32_t(cbs.size()); Check(vkAllocateCommandBuffers(g_dev, &ai, cbs.data()), "vkAllocateCommandBuffers"); for (size_t i = 0; i < cbs.size(); ++i) { VkCommandBufferBeginInfo bi {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; Check(vkBeginCommandBuffer(cbs[i], &bi), "vkBeginCommandBuffer"); struct { uint64_t s, d; uint32_t it, n; } push {x.address, dst.address + region * i, 256u, count}; vkCmdBindPipeline(cbs[i], VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); vkCmdPushConstants(cbs[i], layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); vkCmdDispatch(cbs[i], count / 64, 1, 1); Check(vkEndCommandBuffer(cbs[i]), "vkEndCommandBuffer"); } const uint64_t first = value + 1; for (size_t i = 0; i < cbs.size(); ++i) { const uint64_t signal = ++value; VkTimelineSemaphoreSubmitInfo ts {VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; ts.signalSemaphoreValueCount = 1; ts.pSignalSemaphoreValues = &signal; VkSubmitInfo sub {VK_STRUCTURE_TYPE_SUBMIT_INFO}; sub.pNext = &ts; sub.commandBufferCount = 1; sub.pCommandBuffers = &cbs[i]; sub.signalSemaphoreCount = 1; sub.pSignalSemaphores = &timeline; Check(vkQueueSubmit(queue, 1, &sub, VK_NULL_HANDLE), "vkQueueSubmit"); } VkSemaphoreWaitInfo wi {VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; wi.semaphoreCount = 1; wi.pSemaphores = &timeline; const uint64_t wait_value = early ? first : value; // early: only the command buffer that used x wi.pValues = &wait_value; const VkResult w = vkWaitSemaphores(g_dev, &wi, 10000000000ull); if (w != VK_SUCCESS) { // x may still be in use: destroying it would test nothing. std::printf("trial %d mode=%s wait=%d: inconclusive, x kept alive\n", t, early ? "early" : "late", w); return 2; } vkDestroyBuffer(g_dev, x.buffer, nullptr); vkFreeMemory(g_dev, x.memory, nullptr); const VkResult idle = vkQueueWaitIdle(queue); std::printf("trial %d mode=%s wait=%d idle=%d\n", t, early ? "early" : "late", w, idle); if (early && idle == VK_ERROR_DEVICE_LOST) { std::printf("DeviceAddressLifetimeGpuTests: driver hazard reproduced\n"); return 0; } if (idle != VK_SUCCESS) { std::printf("DeviceAddressLifetimeGpuTests: %s (idle=%d)\n", early ? "unexpected error" : "FAILED", idle); return early ? 2 : 1; } vkResetCommandPool(g_dev, pool, 0); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:tapir --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:fedf07778440d4a1a0b42697 --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

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

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: aed55a9a-95ce-471a-b559-5e3f5ece0142

📥 Commits

Reviewing files that changed from the base of the PR and between f100f785da and b7399078130b602e160efd9760b7685112876f35.

📒 Files selected for processing (6)
  • CMakeLists.txt
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/vulkanCommon.h
  • src/graphics/presentation/window/vulkanWindow.cpp
  • tests/DeviceAddressLifetimeGpuTests.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-19 20:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#pullrequestreview-5257549524) · **reviewed** **Actionable comments posted: 3** --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `aed55a9a-95ce-471a-b559-5e3f5ece0142` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between f100f785dafa108bbf5b40ea8e425e08236f981a and b7399078130b602e160efd9760b7685112876f35. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `CMakeLists.txt` * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/vulkanCommon.h` * `src/graphics/presentation/window/vulkanWindow.cpp` * `tests/DeviceAddressLifetimeGpuTests.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠carbonimax on GitHub · 2026-10-01 17:16 UTC · original
On CMakeLists.txt line 384 (outdated):

@@ -375,6 +375,14 @@ endfunction()
 
 add_kyty_full_emulator_test(shader_cfg_tests "${KYTY_TESTS_DIR}/shaderCfgTests.cpp")
 
+# Keeps device-address buffers alive until queued MoltenVK work completes (the game lost the device
+# otherwise). Needs a real Vulkan driver through SDL_VULKAN_LIBRARY, so it stays opt-in.
+add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL
+	"${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp"
+)
+target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers})
+target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers)

Fixed in the updated branch: device_address_lifetime_gpu_tests is now created only inside if(APPLE). The production buffer-retirement policy remains selected by the Vulkan driver ID.

**@⁠carbonimax** on GitHub · 2026-10-01 17:16 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#discussion_r4158321679) On `CMakeLists.txt` line 384 (outdated): ```diff @@ -375,6 +375,14 @@ endfunction() add_kyty_full_emulator_test(shader_cfg_tests "${KYTY_TESTS_DIR}/shaderCfgTests.cpp") +# Keeps device-address buffers alive until queued MoltenVK work completes (the game lost the device +# otherwise). Needs a real Vulkan driver through SDL_VULKAN_LIBRARY, so it stays opt-in. +add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL + "${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp" +) +target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers}) +target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers) ``` Fixed in the updated branch: device_address_lifetime_gpu_tests is now created only inside if(APPLE). The production buffer-retirement policy remains selected by the Vulkan driver ID.
@ -0,0 +281,4 @@
return early ? 2 : 1;
}
vkResetCommandPool(g_dev, pool, 0);
}
Author
Owner

@⁠carbonimax on GitHub · 2026-10-01 17:17 UTC · original

The later submissions intentionally use src.address rather than x.address. The only explicit shader use of x is submission 0, whose timeline value is waited before destruction. The regression reproduces MoltenVK declaring an otherwise unused live BDA buffer in later command buffers, so those commands must not explicitly use x: doing that would instead create an application use-after-free and invalidate the driver-hazard reproducer. Each later command has a distinct destination region to avoid an unrelated write race. The test also retains the default queue-retirement variant. This PR waits for timeline visibility and does not claim to close the separate Metal API validation window before command-buffer completion.

**@⁠carbonimax** on GitHub · 2026-10-01 17:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#discussion_r4158327718) The later submissions intentionally use src.address rather than x.address. The only explicit shader use of x is submission 0, whose timeline value is waited before destruction. The regression reproduces MoltenVK declaring an otherwise unused live BDA buffer in later command buffers, so those commands must not explicitly use x: doing that would instead create an application use-after-free and invalidate the driver-hazard reproducer. Each later command has a distinct destination region to avoid an unrelated write race. The test also retains the default queue-retirement variant. This PR waits for timeline visibility and does not claim to close the separate Metal API validation window before command-buffer completion.
@ -0,0 +194,4 @@
Check(vkEnumeratePhysicalDevices(instance, &n, devices.data()), "vkEnumeratePhysicalDevices");
if (n == 0 || devices[0] == VK_NULL_HANDLE) { std::printf("No Vulkan physical device; inconclusive\n"); return 2; }
VkPhysicalDevice phys = devices[0];
vkGetPhysicalDeviceMemoryProperties(phys, &g_mp);
Author
Owner

@⁠carbonimax on GitHub · 2026-10-01 17:17 UTC · original

Fixed in the updated branch: the test enumerates instance extensions and enables VK_KHR_portability_enumeration plus its instance flag only when available. Both physical-device enumeration calls are checked; the handles are initialized to VK_NULL_HANDLE, and an empty device list exits as inconclusive rather than reading an uninitialized handle.

**@⁠carbonimax** on GitHub · 2026-10-01 17:17 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#discussion_r4158328633) Fixed in the updated branch: the test enumerates instance extensions and enables VK_KHR_portability_enumeration plus its instance flag only when available. Both physical-device enumeration calls are checked; the handles are initialized to VK_NULL_HANDLE, and an empty device list exits as inconclusive rather than reading an uninitialized handle.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-01 17:29 UTC · original
On CMakeLists.txt line 384 (outdated):

@@ -375,6 +375,14 @@ endfunction()
 
 add_kyty_full_emulator_test(shader_cfg_tests "${KYTY_TESTS_DIR}/shaderCfgTests.cpp")
 
+# Keeps device-address buffers alive until queued MoltenVK work completes (the game lost the device
+# otherwise). Needs a real Vulkan driver through SDL_VULKAN_LIBRARY, so it stays opt-in.
+add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL
+	"${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp"
+)
+target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers})
+target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers)

@carbonimax, thanks for the fix and clarification. The supplied CMakeLists.txt places device_address_lifetime_gpu_tests inside if(APPLE), which addresses this finding. The production buffer-retirement policy remains selected by the Vulkan driver ID.


✏️ Learnings added
Learnt from: carbonimax
Repo: KytyPS5/KytyPS5 PR: 721
File: CMakeLists.txt:0-0
Timestamp: 2026-10-01T17:29:35.432Z
Learning: In KytyPS5/KytyPS5, the standalone device_address_lifetime_gpu_tests target in CMakeLists.txt is Apple-only. This platform restriction is separate from the production device-address buffer-retirement policy, which is selected by the Vulkan driver ID rather than the host platform.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


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-01 17:29 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#discussion_r4158434952) On `CMakeLists.txt` line 384 (outdated): ```diff @@ -375,6 +375,14 @@ endfunction() add_kyty_full_emulator_test(shader_cfg_tests "${KYTY_TESTS_DIR}/shaderCfgTests.cpp") +# Keeps device-address buffers alive until queued MoltenVK work completes (the game lost the device +# otherwise). Needs a real Vulkan driver through SDL_VULKAN_LIBRARY, so it stays opt-in. +add_executable(device_address_lifetime_gpu_tests EXCLUDE_FROM_ALL + "${KYTY_TESTS_DIR}/DeviceAddressLifetimeGpuTests.cpp" +) +target_include_directories(device_address_lifetime_gpu_tests PRIVATE ${inc_headers}) +target_link_libraries(device_address_lifetime_gpu_tests Vulkan::Headers) ``` `@carbonimax`, thanks for the fix and clarification. The supplied `CMakeLists.txt` places `device_address_lifetime_gpu_tests` inside `if(APPLE)`, which addresses this finding. The production buffer-retirement policy remains selected by the Vulkan driver ID. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: carbonimax Repo: KytyPS5/KytyPS5 PR: 721 File: CMakeLists.txt:0-0 Timestamp: 2026-10-01T17:29:35.432Z Learning: In KytyPS5/KytyPS5, the standalone device_address_lifetime_gpu_tests target in CMakeLists.txt is Apple-only. This platform restriction is separate from the production device-address buffer-retirement policy, which is selected by the Vulkan driver ID rather than the host platform. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> --- <!-- 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=Guarding%20the%20GPU%20test%20target%20with%20%60if(APPLE)%60%20avoids%20Windows%20build%20failures%20from%20POSIX-only%20%60dlfcn.h%60%20and%20MoltenVK%20loading.%20Try%20CodeRabbit%20for%20actionable%20reviews%20like%20this!%20%40coderabbitai&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F721%23discussion_r4054618115)? 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 -->
@ -0,0 +281,4 @@
return early ? 2 : 1;
}
vkResetCommandPool(g_dev, pool, 0);
}
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-01 17:31 UTC · original

@carbonimax, thanks for the clarification. My suggested change was incorrect, and I withdraw the finding.

Only submission 0 should explicitly read x.address. Waiting for its timeline value before destroying x isolates the MoltenVK hazard: later command buffers declare the live BDA buffer without explicitly accessing it. Making every submission read x.address would introduce an application use-after-free and invalidate the reproducer.

The distinct destination regions avoid an unrelated write race. The default mode retains the queue-retirement variant. Neither mode establishes that timeline visibility closes the separate Metal API validation window before command-buffer completion.


✏️ Learnings added
Learnt from: carbonimax
Repo: KytyPS5/KytyPS5 PR: 721
File: tests/DeviceAddressLifetimeGpuTests.cpp:231-284
Timestamp: 2026-10-01T17:31:39.005Z
Learning: In KytyPS5/KytyPS5, tests/DeviceAddressLifetimeGpuTests.cpp is a C++ Vulkan reproducer for MoltenVK declaring otherwise unused live buffer-device-address resources in later command buffers. Only submission 0 explicitly reads x.address; later submissions must read src.address. Hazard mode waits for submission 0's timeline value before destroying x. Making later submissions explicitly read x would introduce an application use-after-free and invalidate the driver-hazard reproducer. Separate destination regions prevent unrelated write races. Timeline visibility must not be equated with closing the separate Metal API validation window before command-buffer completion.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-01 17:31 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#discussion_r4158452366) `@carbonimax`, thanks for the clarification. My suggested change was incorrect, and I withdraw the finding. Only submission 0 should explicitly read `x.address`. Waiting for its timeline value before destroying `x` isolates the MoltenVK hazard: later command buffers declare the live BDA buffer without explicitly accessing it. Making every submission read `x.address` would introduce an application use-after-free and invalidate the reproducer. The distinct destination regions avoid an unrelated write race. The default mode retains the queue-retirement variant. Neither mode establishes that timeline visibility closes the separate Metal API validation window before command-buffer completion. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: carbonimax Repo: KytyPS5/KytyPS5 PR: 721 File: tests/DeviceAddressLifetimeGpuTests.cpp:231-284 Timestamp: 2026-10-01T17:31:39.005Z Learning: In KytyPS5/KytyPS5, tests/DeviceAddressLifetimeGpuTests.cpp is a C++ Vulkan reproducer for MoltenVK declaring otherwise unused live buffer-device-address resources in later command buffers. Only submission 0 explicitly reads x.address; later submissions must read src.address. Hazard mode waits for submission 0's timeline value before destroying x. Making later submissions explicitly read x would introduce an application use-after-free and invalidate the driver-hazard reproducer. Separate destination regions prevent unrelated write races. Timeline visibility must not be equated with closing the separate Metal API validation window before command-buffer completion. ``` > Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings). </details> ✅ Review thread resolved. _You are interacting with an AI system._ <!-- This is an auto-generated reply by CodeRabbit -->
@ -0,0 +194,4 @@
Check(vkEnumeratePhysicalDevices(instance, &n, devices.data()), "vkEnumeratePhysicalDevices");
if (n == 0 || devices[0] == VK_NULL_HANDLE) { std::printf("No Vulkan physical device; inconclusive\n"); return 2; }
VkPhysicalDevice phys = devices[0];
vkGetPhysicalDeviceMemoryProperties(phys, &g_mp);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-01 17:32 UTC · original

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu
ast-grep outline tests/DeviceAddressLifetimeGpuTests.cpp --match main --view expanded
sed -n '155,230p' tests/DeviceAddressLifetimeGpuTests.cpp

Length of output: 5733


@carbonimax, verified in the updated code. The test enables the portability extension and instance flag only when available. Both physical-device enumeration calls are checked. Device handles start as VK_NULL_HANDLE, and empty or null results exit with code 2 before use. This addresses the 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-01 17:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#discussion_r4158460066) <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ```shell #!/bin/bash set -eu ast-grep outline tests/DeviceAddressLifetimeGpuTests.cpp --match main --view expanded sed -n '155,230p' tests/DeviceAddressLifetimeGpuTests.cpp ``` Length of output: 5733 --- </details> `@carbonimax`, verified in the updated code. The test enables the portability extension and instance flag only when available. Both physical-device enumeration calls are checked. Device handles start as `VK_NULL_HANDLE`, and empty or null results exit with code 2 before use. This addresses the 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=MoltenVK%20tests%20can%20miss%20devices%20without%20portability%20enumeration.%20%40coderabbitai%20caught%20the%20fix%3A%20enable%20it%20when%20available%20and%20validate%20device%20results%20before%20using%20handles.%20Try%20it!%20%F0%9F%A9%BA%E2%9A%A1&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F721%23discussion_r4054618122)? 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 -->
@ -155,0 +158,4 @@
m_scheduler.GetMasterSemaphore().Wait(m_scheduler.CurrentTick() - 1);
}
m_slot_buffers.erase(id);
});
Author
Owner

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

sed -n '115,155p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
rg -n 'CurrentTick\\(|NextTick\\(|Wait\\(|Signal\\(|DestroyBuffer|Erase|m_buffers' src/graphics/host_gpu/renderer src/graphics/host_gpu

Repository: KytyPS5/KytyPS5

Length of output: 1748


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- exact references ---'
for pat in 'CurrentTick(' 'DeferOperation(' 'GetMasterSemaphore' 'device_address_destruction_waits_for_queue' 'class MasterSemaphore' 'Wait(' 'Signal('; do
  printf '\n### %s\n' "$pat"
  rg -n -F -- "$pat" src || test "$?" -eq 1
done
printf '%s\n' '--- candidate scheduler/semaphore files ---'
rg --files src | rg -i '(scheduler|semaphore|sync|bufferCache|buffer_cache|graphics)' | head -200
printf '%s\n' '--- changed file surrounding declarations ---'
rg -n -F -- 'class BufferCache' src/graphics/host_gpu/renderer/cache/bufferCache.h src/graphics/host_gpu/renderer/cache/bufferCache.cpp || true

Repository: KytyPS5/KytyPS5

Length of output: 24495


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- exact references ---'
for pat in 'CurrentTick(' 'DeferOperation(' 'GetMasterSemaphore' 'device_address_destruction_waits_for_queue' 'Wait(' 'Signal('; do
  printf '\n### %s\n' "$pat"
  rg -n -F -- "$pat" src || test "$?" -eq 1
done
printf '%s\n' '--- candidate scheduler/semaphore files ---'
rg --files src | rg -i '(scheduler|semaphore|sync|bufferCache|buffer_cache|graphics)' | head -200
printf '%s\n' '--- changed file declarations ---'
rg -n -F -- 'class BufferCache' src/graphics/host_gpu/renderer/cache/bufferCache.h src/graphics/host_gpu/renderer/cache/bufferCache.cpp || true

Repository: KytyPS5/KytyPS5

Length of output: 24302


🏁 Script executed:

set -o pipefail
for spec in \
  'src/graphics/host_gpu/renderer/masterSemaphore.h:1,90' \
  'src/graphics/host_gpu/renderer/masterSemaphore.cpp:1,100' \
  'src/graphics/host_gpu/renderer/commandScheduler.cpp:110,145' \
  'src/graphics/host_gpu/renderer/commandScheduler.cpp:170,295' \
  'src/graphics/host_gpu/renderer/commandScheduler.cpp:330,370' \
  'src/graphics/presentation/window/vulkanWindow.cpp:950,990' \
  'src/graphics/host_gpu/renderer/cache/bufferCache.cpp:105,150' \
  'src/graphics/host_gpu/renderer/cache/bufferCache.cpp:200,235' \
  'src/graphics/host_gpu/renderer/cache/bufferCache.cpp:630,680'; do
  file=${spec%%:*}; range=${spec#*:}
  printf '\n--- %s:%s ---\n' "$file" "$range"
  nl -ba "$file" | sed -n "${range//,/-}p"
done

Repository: KytyPS5/KytyPS5

Length of output: 1234


🏁 Script executed:

set -o pipefail
read_block() {
  file=$1; start=$2; end=$3
  printf '\n--- %s:%s-%s ---\n' "$file" "$start" "$end"
  awk -v s="$start" -v e="$end" 'NR >= s && NR <= e { printf "%6d %s\n", NR, $0 }' "$file"
}
read_block src/graphics/host_gpu/renderer/masterSemaphore.h 1 90
read_block src/graphics/host_gpu/renderer/masterSemaphore.cpp 1 100
read_block src/graphics/host_gpu/renderer/commandScheduler.cpp 110 145
read_block src/graphics/host_gpu/renderer/commandScheduler.cpp 170 295
read_block src/graphics/host_gpu/renderer/commandScheduler.cpp 330 370
read_block src/graphics/presentation/window/vulkanWindow.cpp 950 990
read_block src/graphics/host_gpu/renderer/cache/bufferCache.cpp 105 150
read_block src/graphics/host_gpu/renderer/cache/bufferCache.cpp 200 235
read_block src/graphics/host_gpu/renderer/cache/bufferCache.cpp 630 680

Repository: KytyPS5/KytyPS5

Length of output: 20447


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- driver helper references ---'
rg -n -F -- 'DeviceAddressBufferDestructionWaitsForQueue' src
printf '%s\n' '--- helper definitions and surrounding declarations ---'
rg -n -F -- 'driverID' src/graphics/host_gpu src/graphics/presentation/window | head -80
printf '%s\n' '--- submit tail ---'
awk 'NR >= 340 && NR <= 390 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/renderer/commandScheduler.cpp
printf '%s\n' '--- buffer slot and owner definitions ---'
rg -n -F -- 'm_slot_buffers' src/graphics/host_gpu/renderer/cache/bufferCache.h src/graphics/host_gpu/renderer/cache/bufferCache.cpp
rg -n -F -- 'struct Buffer' src/graphics/host_gpu/renderer/cache/bufferCache.h
awk 'NR >= 1 && NR <= 110 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/renderer/cache/bufferCache.h

Repository: KytyPS5/KytyPS5

Length of output: 11229


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- driver helper ---'
awk 'NR >= 55 && NR <= 90 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/vulkanCommon.h
printf '%s\n' '--- buffer cache type declarations ---'
awk 'NR >= 103 && NR <= 145 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/renderer/cache/bufferCache.h
printf '%s\n' '--- Buffer aliases/declarations ---'
rg -n -F -- 'using Buffer' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer
rg -n -F -- 'class Buffer' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer
printf '%s\n' '--- stream buffer ownership and destruction ---'
rg -n -F -- '~StreamBuffer' src/graphics/host_gpu/renderer/cache/streamBuffer.h src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
awk 'NR >= 1 && NR <= 130 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/renderer/cache/streamBuffer.h

Repository: KytyPS5/KytyPS5

Length of output: 12282


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- Buffer destructor and resource destruction ---'
rg -n -F -- 'Buffer::~Buffer' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
rg -n -F -- 'destroyBuffer' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
rg -n -F -- 'vmaDestroyBuffer' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp
awk 'NR >= 130 && NR <= 210 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp

Repository: KytyPS5/KytyPS5

Length of output: 5029


Wait for Metal command-buffer completion before erasing the buffer.

On MoltenVK, the callback waits only for the Vulkan timeline value. That value can become visible while the submitted Metal command buffer still references the buffer. m_slot_buffers.erase(id) then invokes Buffer::~Buffer, which calls vmaDestroyBuffer. MoltenVK can abort the queued command buffer with Invalid Resource.

Use a completion-level fence or queue-completion wait before destroying the buffer. Do not use timeline visibility as the destruction guarantee.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 09:42 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#discussion_r4228773253) **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '115,155p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp rg -n 'CurrentTick\\(|NextTick\\(|Wait\\(|Signal\\(|DestroyBuffer|Erase|m_buffers' src/graphics/host_gpu/renderer src/graphics/host_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 1748 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- exact references ---' for pat in 'CurrentTick(' 'DeferOperation(' 'GetMasterSemaphore' 'device_address_destruction_waits_for_queue' 'class MasterSemaphore' 'Wait(' 'Signal('; do printf '\n### %s\n' "$pat" rg -n -F -- "$pat" src || test "$?" -eq 1 done printf '%s\n' '--- candidate scheduler/semaphore files ---' rg --files src | rg -i '(scheduler|semaphore|sync|bufferCache|buffer_cache|graphics)' | head -200 printf '%s\n' '--- changed file surrounding declarations ---' rg -n -F -- 'class BufferCache' src/graphics/host_gpu/renderer/cache/bufferCache.h src/graphics/host_gpu/renderer/cache/bufferCache.cpp || true ``` Repository: KytyPS5/KytyPS5 Length of output: 24495 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- exact references ---' for pat in 'CurrentTick(' 'DeferOperation(' 'GetMasterSemaphore' 'device_address_destruction_waits_for_queue' 'Wait(' 'Signal('; do printf '\n### %s\n' "$pat" rg -n -F -- "$pat" src || test "$?" -eq 1 done printf '%s\n' '--- candidate scheduler/semaphore files ---' rg --files src | rg -i '(scheduler|semaphore|sync|bufferCache|buffer_cache|graphics)' | head -200 printf '%s\n' '--- changed file declarations ---' rg -n -F -- 'class BufferCache' src/graphics/host_gpu/renderer/cache/bufferCache.h src/graphics/host_gpu/renderer/cache/bufferCache.cpp || true ``` Repository: KytyPS5/KytyPS5 Length of output: 24302 --- 🏁 Script executed: ```bash set -o pipefail for spec in \ 'src/graphics/host_gpu/renderer/masterSemaphore.h:1,90' \ 'src/graphics/host_gpu/renderer/masterSemaphore.cpp:1,100' \ 'src/graphics/host_gpu/renderer/commandScheduler.cpp:110,145' \ 'src/graphics/host_gpu/renderer/commandScheduler.cpp:170,295' \ 'src/graphics/host_gpu/renderer/commandScheduler.cpp:330,370' \ 'src/graphics/presentation/window/vulkanWindow.cpp:950,990' \ 'src/graphics/host_gpu/renderer/cache/bufferCache.cpp:105,150' \ 'src/graphics/host_gpu/renderer/cache/bufferCache.cpp:200,235' \ 'src/graphics/host_gpu/renderer/cache/bufferCache.cpp:630,680'; do file=${spec%%:*}; range=${spec#*:} printf '\n--- %s:%s ---\n' "$file" "$range" nl -ba "$file" | sed -n "${range//,/-}p" done ``` Repository: KytyPS5/KytyPS5 Length of output: 1234 --- 🏁 Script executed: ```bash set -o pipefail read_block() { file=$1; start=$2; end=$3 printf '\n--- %s:%s-%s ---\n' "$file" "$start" "$end" awk -v s="$start" -v e="$end" 'NR >= s && NR <= e { printf "%6d %s\n", NR, $0 }' "$file" } read_block src/graphics/host_gpu/renderer/masterSemaphore.h 1 90 read_block src/graphics/host_gpu/renderer/masterSemaphore.cpp 1 100 read_block src/graphics/host_gpu/renderer/commandScheduler.cpp 110 145 read_block src/graphics/host_gpu/renderer/commandScheduler.cpp 170 295 read_block src/graphics/host_gpu/renderer/commandScheduler.cpp 330 370 read_block src/graphics/presentation/window/vulkanWindow.cpp 950 990 read_block src/graphics/host_gpu/renderer/cache/bufferCache.cpp 105 150 read_block src/graphics/host_gpu/renderer/cache/bufferCache.cpp 200 235 read_block src/graphics/host_gpu/renderer/cache/bufferCache.cpp 630 680 ``` Repository: KytyPS5/KytyPS5 Length of output: 20447 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- driver helper references ---' rg -n -F -- 'DeviceAddressBufferDestructionWaitsForQueue' src printf '%s\n' '--- helper definitions and surrounding declarations ---' rg -n -F -- 'driverID' src/graphics/host_gpu src/graphics/presentation/window | head -80 printf '%s\n' '--- submit tail ---' awk 'NR >= 340 && NR <= 390 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/renderer/commandScheduler.cpp printf '%s\n' '--- buffer slot and owner definitions ---' rg -n -F -- 'm_slot_buffers' src/graphics/host_gpu/renderer/cache/bufferCache.h src/graphics/host_gpu/renderer/cache/bufferCache.cpp rg -n -F -- 'struct Buffer' src/graphics/host_gpu/renderer/cache/bufferCache.h awk 'NR >= 1 && NR <= 110 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/renderer/cache/bufferCache.h ``` Repository: KytyPS5/KytyPS5 Length of output: 11229 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- driver helper ---' awk 'NR >= 55 && NR <= 90 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/vulkanCommon.h printf '%s\n' '--- buffer cache type declarations ---' awk 'NR >= 103 && NR <= 145 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/renderer/cache/bufferCache.h printf '%s\n' '--- Buffer aliases/declarations ---' rg -n -F -- 'using Buffer' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer rg -n -F -- 'class Buffer' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer printf '%s\n' '--- stream buffer ownership and destruction ---' rg -n -F -- '~StreamBuffer' src/graphics/host_gpu/renderer/cache/streamBuffer.h src/graphics/host_gpu/renderer/cache/streamBuffer.cpp awk 'NR >= 1 && NR <= 130 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/renderer/cache/streamBuffer.h ``` Repository: KytyPS5/KytyPS5 Length of output: 12282 --- 🏁 Script executed: ```bash set -o pipefail printf '%s\n' '--- Buffer destructor and resource destruction ---' rg -n -F -- 'Buffer::~Buffer' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp rg -n -F -- 'destroyBuffer' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp rg -n -F -- 'vmaDestroyBuffer' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp awk 'NR >= 130 && NR <= 210 { printf "%6d %s\n", NR, $0 }' src/graphics/host_gpu/renderer/cache/streamBuffer.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 5029 --- </details> **Wait for Metal command-buffer completion before erasing the buffer.** On MoltenVK, the callback waits only for the Vulkan timeline value. That value can become visible while the submitted Metal command buffer still references the buffer. `m_slot_buffers.erase(id)` then invokes `Buffer::~Buffer`, which calls `vmaDestroyBuffer`. MoltenVK can abort the queued command buffer with `Invalid Resource`. Use a completion-level fence or queue-completion wait before destroying the buffer. Do not use timeline visibility as the destruction guarantee. <!-- fingerprinting:phantom:medusa:serval --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f24cc8865e9522933d272fdd --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 09:42 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: 25b7b3f2-14aa-4b21-aa8f-1cc219df4c23
📥 Commits

Reviewing files that changed from the base of the PR and between 0dcfb500a313fca904578b57ae945990c126eb74 and ae2a9df10e3d46c2be95c1eae8d1b5f960535bc2.

📒 Files selected for processing (5)
  • CMakeLists.txt
  • src/graphics/host_gpu/graphicContext.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/vulkanCommon.h
  • src/graphics/presentation/window/vulkanWindow.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/graphics/host_gpu/vulkanCommon.h

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

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 09:42 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/721#pullrequestreview-5468409857) · **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**: `25b7b3f2-14aa-4b21-aa8f-1cc219df4c23` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 0dcfb500a313fca904578b57ae945990c126eb74 and ae2a9df10e3d46c2be95c1eae8d1b5f960535bc2. </details> <details> <summary>📒 Files selected for processing (5)</summary> * `CMakeLists.txt` * `src/graphics/host_gpu/graphicContext.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/vulkanCommon.h` * `src/graphics/presentation/window/vulkanWindow.cpp` </details> <details> <summary>🚧 Files skipped from review as they are similar to previous changes (1)</summary> * src/graphics/host_gpu/vulkanCommon.h </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=307970f0-06c2-4527-bfba-143066985b29 attempt=26e2a5f0-c18e-4d33-a8e1-9d7b4394f75c batch=1/1 -->

Pull request closed

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