graphics: evict and retry when an image cannot be allocated #1271

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

@⁠msfvn on GitHub · 2026-10-09 02:25 UTC · original
msfvn:evict-on-image-oom → main · +72 −9 · 4 files · 2 commits · closed without merging

Problem

When device memory is full, Image's constructor exits with failed to create image. The texture cache collector runs between submissions and only frees images older than a number of GC ticks, so when the working set grows quickly (scene transitions) it cannot free memory in time. On 4-6 GB GPUs this ends the game:

  • Astro Bot (PPSA21567), RTX 3050 Laptop 4 GB: exits at the intro's ship scene, ~227 s after boot, on current main (with the community non-RT patch) with failed to create image.
  • The same error is reported with RTX 4050 6 GB in #596, #648 and #768.

Change

  • Image records the allocation failure (allocation_failed) instead of exiting.
  • TextureCache::InsertImage then calls EvictForAllocation() and retries, up to three times:
    • it evicts up to 256 MiB of images that are not bound or targeted by the draw being prepared, not used in the last two GC ticks, and not the image the caller keeps using across the insert (ResolveDepthOverlap, ExpandImage and AssociateStencil pass theirs as keep);
    • GPU-written images are downloaded before eviction, including tiled ones (which the regular collector never evicts), limited to 32 MiB of downloads per pass so they fit the 64 MiB download buffer;
    • it calls CommandScheduler::Finish() so their deferred destruction runs and the memory is returned before the retry. The caller holds m_lock; none of the scheduler's deferred operations take it.
  • If nothing can be evicted, or after three attempts, it exits with the same message as before.

Testing

Linux, RTX 3050 Laptop 4 GB, 7.5 GB RAM, Astro Bot with the community non-RT patch, scripted input through the intro, 420 s runs on current main:

  • main: exits at 227 s with failed to create image: extent=2048x2048x1 format=146.
  • main + this change (together with #1269, #1270 and the other open memory changes): runs the full 420 s with correct rendering. While the ship-interior scene does not fit in VRAM, images are evicted and recreated and the frame rate drops to about 1 fps; slow, but no longer fatal.

AI involvement: written with Claude Code (AI assistant) at my request and reviewed by a C++ developer I know; tested on my machine (RTX 3050 Laptop 4 GB, CachyOS) as described above, including playing Astro Bot on this build. Happy to adjust anything you point out.

**@⁠msfvn** on GitHub · 2026-10-09 02:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1271) `msfvn:evict-on-image-oom` → `main` · +72 −9 · 4 files · 2 commits · closed without merging ### Problem When device memory is full, `Image`'s constructor exits with `failed to create image`. The texture cache collector runs between submissions and only frees images older than a number of GC ticks, so when the working set grows quickly (scene transitions) it cannot free memory in time. On 4-6 GB GPUs this ends the game: - Astro Bot (PPSA21567), RTX 3050 Laptop 4 GB: exits at the intro's ship scene, ~227 s after boot, on current `main` (with the community non-RT patch) with `failed to create image`. - The same error is reported with RTX 4050 6 GB in #596, #648 and #768. ### Change - `Image` records the allocation failure (`allocation_failed`) instead of exiting. - `TextureCache::InsertImage` then calls `EvictForAllocation()` and retries, up to three times: - it evicts up to 256 MiB of images that are not bound or targeted by the draw being prepared, not used in the last two GC ticks, and not the image the caller keeps using across the insert (`ResolveDepthOverlap`, `ExpandImage` and `AssociateStencil` pass theirs as `keep`); - GPU-written images are downloaded before eviction, including tiled ones (which the regular collector never evicts), limited to 32 MiB of downloads per pass so they fit the 64 MiB download buffer; - it calls `CommandScheduler::Finish()` so their deferred destruction runs and the memory is returned before the retry. The caller holds `m_lock`; none of the scheduler's deferred operations take it. - If nothing can be evicted, or after three attempts, it exits with the same message as before. ### Testing Linux, RTX 3050 Laptop 4 GB, 7.5 GB RAM, Astro Bot with the community non-RT patch, scripted input through the intro, 420 s runs on current `main`: - `main`: exits at 227 s with `failed to create image: extent=2048x2048x1 format=146`. - `main` + this change (together with #1269, #1270 and the other open memory changes): runs the full 420 s with correct rendering. While the ship-interior scene does not fit in VRAM, images are evicted and recreated and the frame rate drops to about 1 fps; slow, but no longer fatal. **AI involvement:** written with Claude Code (AI assistant) at my request and reviewed by a C++ developer I know; tested on my machine (RTX 3050 Laptop 4 GB, CachyOS) as described above, including playing Astro Bot on this build. Happy to adjust anything you point out.
When device memory is full, image creation exits with "failed to create
image". The collector runs between submissions and frees images older than
a few frames, so it cannot keep up when the working set grows quickly; on
4-6 GB GPUs this ends the game at scene transitions (Astro Bot on a 4 GB
RTX 3050 Laptop at the intro's ship scene; reports with RTX 4050 6 GB in

Report the failure from the image constructor instead, and let
InsertImage evict up to 256 MiB of images the current draw has not
touched (downloading GPU-written ones first, within the download buffer),
finish the GPU work so their deferred destruction frees the memory, and
retry. It still exits if nothing can be evicted or after three attempts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ResolveDepthOverlap, ExpandImage and AssociateStencil keep using an
existing image after InsertImage returns, and RefreshImage /
RefreshCopySource do not touch the LRU, so that image could be picked by
EvictForAllocation and erased by Finish() before the caller copies from
it. Pass it to InsertImage as an image to keep, and also skip images bound
or targeted by the draw being prepared.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:50:48 +00:00
github-bot closed this pull request 2026-11-26 09:50:48 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 02:27 UTC · original · edited 2026-10-11 02:07 UTC

Review in Change Stack →

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: 4adb503c-93e4-4f58-8c3a-da9561f4f658


📥 Commits

Reviewing files that changed from the base of the PR and between 6715e56ac0c3f5b9fa280f396217e74f92a0fc05 and e21bdcc3d2.



📒 Files selected for processing (2)
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h


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

Walkthrough

Image records failed image allocation instead of terminating. TextureCache::InsertImage removes failed entries and retries allocation after attempting to evict eligible cached images. The cache preserves specified images during eviction. Eviction requires an active scheduler and at least two GC ticks. It applies limits to selected image memory and GPU-modified image downloads.

Suggested reviewers: nmzik



Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🟡 Moderate · up to e21bd

Under image-memory pressure, an overlapping-image operation can use an image after eviction. Protect the merged candidate during retry before merging.

Pre-merge checks | Passed 4 | Failed 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 13.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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.
Title check Passed The title clearly and concisely describes the main change: evicting cached images and retrying allocation when image creation fails.
Description check Passed The description directly explains the allocation failure problem, the eviction and retry behavior, safety conditions, and test results.

  • Autopilot · 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 02:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1271#issuecomment-6073020238) · edited 2026-10-11 02:07 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/1271?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 --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary><strong>ℹ️ Recent review info</strong></summary> <dl> <dd> <dl> <dd> <details> <summary><strong>⚙️ Run configuration</strong></summary> <dl> <dd> <dl> <dd> - **Configuration used**: Repository: KytyPS5/KytyPS5/.coderabbit.yaml - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `4adb503c-93e4-4f58-8c3a-da9561f4f658` <hr> </dd> </dl> <hr> </dd> </dl> </details> <details> <summary><strong>📥 Commits</strong></summary> <dl> <dd> <dl> <dd> Reviewing files that changed from the base of the PR and between 6715e56ac0c3f5b9fa280f396217e74f92a0fc05 and e21bdcc3d289c2e338d384d512f5da42746ed8fc. <hr> </dd> </dl> <hr> </dd> </dl> </details> <details> <summary><strong>📒 Files selected for processing (2)</strong></summary> <dl> <dd> <dl> <dd> * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` <hr> </dd> </dl> <hr> </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. <hr> </dd> </dl> <hr> </dd> </dl> </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> <details> <summary><strong>📝 Walkthrough</strong></summary> <dl> <dd> ## Walkthrough `Image` records failed image allocation instead of terminating. `TextureCache::InsertImage` removes failed entries and retries allocation after attempting to evict eligible cached images. The cache preserves specified images during eviction. Eviction requires an active scheduler and at least two GC ticks. It applies limits to selected image memory and GPU-modified image downloads. **Suggested reviewers:** `nmzik` <hr> </dd> </dl> </details> <hr> </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"e21bdcc3d289c2e338d384d512f5da42746ed8fc" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** **🟡 Moderate** · up to `e21bd` <!-- final_review_risk_coverage:{"sourceCommitId":"e21bdcc3d289c2e338d384d512f5da42746ed8fc","coveredCommitId":"e21bdcc3d289c2e338d384d512f5da42746ed8fc","kind":"reviewed"} --> Under image-memory pressure, an overlapping-image operation can use an image after eviction. Protect the merged candidate during retry before merging. <!-- final_review_risk_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 13.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 4 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 | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------- | | 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. | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely describes the main change: evicting cached images and retrying allocation when image creation fails. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the allocation failure problem, the eviction and retry behavior, safety conditions, and test results. | </dd> </dl> </details> <hr> </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">Autopilot</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=1271)! 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) <hr> </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -1925,0 +1979,4 @@
return false;
}
m_scheduler.Finish();
return true;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 02:27 UTC · original · edited 2026-10-11 02:05 UTC

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Eviction can free images that the code calling InsertImage still uses.

EvictForAllocation runs inside InsertImage. Several callers keep a live source image around that call:

  • ResolveDepthOverlap (Line 756) keeps cached / cached_id. After the insert, it reads cached and passes cached_id to CopyImage.
  • ExpandImage (Line 908) keeps source_id. After the insert, it uses source_id with CopyImage and CopyImageMip.
  • FindImage (Line 1326) keeps nothing alive, so it is not affected.

The victim filter accepts any registered image whose LRU tick is below m_gc_tick - 2. RefreshCopySource and RefreshImage do not call TouchImage, so an old copy source stays in the victim range.

Here is the failure sequence when a victim is freed:

  1. FreeImage clears GpuModified.
  2. DeleteImage defers m_slot_images.erase.
  3. m_scheduler.Finish() runs that deferred erase right away.
  4. The caller then reads a freed slot through cached or source_id.

The result is a use-after-free. The caller also copies from a source image whose native contents were destroyed. If the download was skipped, the GPU-written data is lost.

Exclude the in-flight source images from eviction. One fix: touch the source with TouchImage before calling InsertImage in ResolveDepthOverlap and ExpandImage. A more robust fix: pass a set of protected ImageIds into EvictForAllocation and skip them in the ForEachItemBelow callback.

Proposed minimal fix
 	RefreshCopySource(source_id);
+	TouchImage(m_slot_images[source_id]);
 	const auto expanded_id = InsertImage(info);

In ResolveDepthOverlap, add TouchImage(cached); before InsertImage(info). Also take the cached reference again after the call.

✅ Addressed in commit 6715e56

**@⁠coderabbitai[bot]** on GitHub · 2026-10-09 02:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1271#discussion_r4226055065) · edited 2026-10-11 02:05 UTC **🩺 Stability & Availability** | **🟠 Major** | **⚡ Quick win** **Eviction can free images that the code calling `InsertImage` still uses.** `EvictForAllocation` runs inside `InsertImage`. Several callers keep a live source image around that call: - `ResolveDepthOverlap` (Line 756) keeps `cached` / `cached_id`. After the insert, it reads `cached` and passes `cached_id` to `CopyImage`. - `ExpandImage` (Line 908) keeps `source_id`. After the insert, it uses `source_id` with `CopyImage` and `CopyImageMip`. - `FindImage` (Line 1326) keeps nothing alive, so it is not affected. The victim filter accepts any registered image whose LRU tick is below `m_gc_tick - 2`. `RefreshCopySource` and `RefreshImage` do not call `TouchImage`, so an old copy source stays in the victim range. Here is the failure sequence when a victim is freed: 1. `FreeImage` clears `GpuModified`. 2. `DeleteImage` defers `m_slot_images.erase`. 3. `m_scheduler.Finish()` runs that deferred erase right away. 4. The caller then reads a freed slot through `cached` or `source_id`. The result is a use-after-free. The caller also copies from a source image whose native contents were destroyed. If the download was skipped, the GPU-written data is lost. Exclude the in-flight source images from eviction. One fix: touch the source with `TouchImage` before calling `InsertImage` in `ResolveDepthOverlap` and `ExpandImage`. A more robust fix: pass a set of protected `ImageId`s into `EvictForAllocation` and skip them in the `ForEachItemBelow` callback. <details> <summary>Proposed minimal fix</summary> ```diff RefreshCopySource(source_id); + TouchImage(m_slot_images[source_id]); const auto expanded_id = InsertImage(info); ``` In `ResolveDepthOverlap`, add `TouchImage(cached);` before `InsertImage(info)`. Also take the `cached` reference again after the call. </details> <!-- fingerprinting:phantom:medusa:pangolin --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:2291600dcdac113b1b934a4c --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Addressed in commit 6715e56
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-09 02:27 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: ed96da72-46b9-42ec-804e-30c098144c01
📥 Commits

Reviewing files that changed from the base of the PR and between 7b9997baea and c60ebe1ec71c855e2d439a40c7e2aaa5719cf038.

📒 Files selected for processing (4)
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • src/graphics/host_gpu/renderer/image/image.cpp
  • src/graphics/host_gpu/renderer/image/image.h

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 02:27 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1271#pullrequestreview-5465049208) · **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**: `ed96da72-46b9-42ec-804e-30c098144c01` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 7b9997baea0d385e9e8fc2bd3abeb02110bc4148 and c60ebe1ec71c855e2d439a40c7e2aaa5719cf038. </details> <details> <summary>📒 Files selected for processing (4)</summary> * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` * `src/graphics/host_gpu/renderer/image/image.cpp` * `src/graphics/host_gpu/renderer/image/image.h` </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=acfda5c9-d74b-4123-83d8-29ddb55427c2 attempt=72123cb7-26f1-4e73-8461-9bfcc394f5aa batch=1/1 -->
@ -1925,0 +1950,4 @@
m_lru_cache.ForEachItemBelow(m_gc_tick - 2, [&](ImageId id) {
const auto* image = m_slot_images.try_get(id);
if (image == nullptr || !image->registered || image->depth_id || id == keep ||
image->binding.is_bound || image->binding.is_target) {
Author
Owner

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

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

Protect the merged image during allocation retry.

When FindImage processes multiple overlapping candidates, ResolveOverlap can receive m_slot_images[result].info as requested. If that call reaches ExpandImage, InsertImage protects source_id but not result. An allocation failure can therefore evict result; Finish() completes its deferred erasure before the retry reads requested again. This leaves the retry with a dangling ImageInfo reference. Pass all live candidate IDs to eviction, including result, rather than excluding only keep.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-11 01:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1271#discussion_r4239838803) **🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift** **Protect the merged image during allocation retry.** When `FindImage` processes multiple overlapping candidates, `ResolveOverlap` can receive `m_slot_images[result].info` as `requested`. If that call reaches `ExpandImage`, `InsertImage` protects `source_id` but not `result`. An allocation failure can therefore evict `result`; `Finish()` completes its deferred erasure before the retry reads `requested` again. This leaves the retry with a dangling `ImageInfo` reference. Pass all live candidate IDs to eviction, including `result`, rather than excluding only `keep`. <!-- fingerprinting:phantom:poseidon:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:6dc6c99772ba3173263aacc9 --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 01:19 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: fb5e3547-8485-4523-9560-559c3baeaa5e
📥 Commits

Reviewing files that changed from the base of the PR and between c60ebe1ec71c855e2d439a40c7e2aaa5719cf038 and 6715e56ac0c3f5b9fa280f396217e74f92a0fc05.

📒 Files selected for processing (2)
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h

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-11 01:19 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1271#pullrequestreview-5481464447) · **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**: `fb5e3547-8485-4523-9560-559c3baeaa5e` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between c60ebe1ec71c855e2d439a40c7e2aaa5719cf038 and 6715e56ac0c3f5b9fa280f396217e74f92a0fc05. </details> <details> <summary>📒 Files selected for processing (2)</summary> * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` </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=ade2b553-b51e-49cd-9106-8981a78735b5 attempt=e1d31590-3283-49b1-af77-4d03be6293cd batch=1/1 -->
@ -1925,0 +1979,4 @@
return false;
}
m_scheduler.Finish();
return true;
Author
Owner

@⁠msfvn on GitHub · 2026-10-11 02:00 UTC · original

Good catch, fixed in e21bdcc3. InsertImage now takes the image the caller keeps using (ResolveDepthOverlap passes cached_id, ExpandImage passes source_id, and AssociateStencil passes depth_id, which had the same issue), and EvictForAllocation skips it. It also skips images bound or targeted by the draw being prepared (binding.is_bound / is_target, reset per draw in ResetBindings). I also rebased onto current main to resolve the conflict with 5559cfcb.

**@⁠msfvn** on GitHub · 2026-10-11 02:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1271#discussion_r4239927076) Good catch, fixed in e21bdcc3. `InsertImage` now takes the image the caller keeps using (`ResolveDepthOverlap` passes `cached_id`, `ExpandImage` passes `source_id`, and `AssociateStencil` passes `depth_id`, which had the same issue), and `EvictForAllocation` skips it. It also skips images bound or targeted by the draw being prepared (`binding.is_bound` / `is_target`, reset per draw in `ResetBindings`). I also rebased onto current `main` to resolve the conflict with 5559cfcb.
@ -1925,0 +1979,4 @@
return false;
}
m_scheduler.Finish();
return true;
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-11 02:05 UTC · original

@msfvn Thanks for the fix and the clarification. The supplied code protects cached_id, source_id, and depth_id during allocation recovery. The victim filter also excludes bound and targeted images. This addresses the reported use-after-free.


✏️ Learnings added
Learnt from: msfvn
Repo: KytyPS5/KytyPS5 PR: 1271
File: src/graphics/host_gpu/renderer/cache/textureCache.cpp:1968-1982
Timestamp: 2026-10-11T02:05:12.482Z
Learning: In the C++ texture cache for KytyPS5, image.binding.is_bound and image.binding.is_target identify images bound or targeted by the draw being prepared. ResetBindings resets these flags per draw. In src/graphics/host_gpu/renderer/cache/textureCache.cpp, allocation-recovery eviction must exclude these images as well as images that the caller still uses.

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-11 02:05 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1271#discussion_r4239936783) `@msfvn` Thanks for the fix and the clarification. The supplied code protects `cached_id`, `source_id`, and `depth_id` during allocation recovery. The victim filter also excludes bound and targeted images. This addresses the reported use-after-free. --- <details> <summary>✏️ Learnings added</summary> ``` Learnt from: msfvn Repo: KytyPS5/KytyPS5 PR: 1271 File: src/graphics/host_gpu/renderer/cache/textureCache.cpp:1968-1982 Timestamp: 2026-10-11T02:05:12.482Z Learning: In the C++ texture cache for KytyPS5, image.binding.is_bound and image.binding.is_target identify images bound or targeted by the draw being prepared. ResetBindings resets these flags per draw. In src/graphics/host_gpu/renderer/cache/textureCache.cpp, allocation-recovery eviction must exclude these images as well as images that the caller still uses. ``` > 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=Prevent%20image%20use-after-free%3A%20protect%20in-flight%20sources%20and%20draw-bound%20targets%20from%20eviction.%20Try%20%40coderabbitai%20for%20reviews%20that%20catch%20subtle%20bugs!%20%F0%9F%9B%A1%EF%B8%8F&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F1271%23discussion_r4226055065)? 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

@⁠Nmzik on GitHub · 2026-10-21 18:47 UTC · original

This is a hack and uses RAM as fallback (performance will be low)

**@⁠Nmzik** on GitHub · 2026-10-21 18:47 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1271#issuecomment-6323846660) This is a hack and uses RAM as fallback (performance will be low)

Pull request closed

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