graphics: small formatted reads sync GPU-written images #2193

Open
github-bot wants to merge 12 commits from github-bot/gh-2193 into main AGit
Owner

@⁠Nawid3333 on GitHub · 2026-11-10 10:50 UTC · original
Nawid3333:fix/small-formatted-reads-sync-images → main · +274 −18 · 5 files · 12 commits · open

Cause

BufferCache::ObtainBuffer has a streaming shortcut for small reads: when a read is not written, is at most 16 KiB (CACHING_PAGESIZE), and its pages are CPU-modified but not GPU-modified, it copies guest memory into the stream buffer and returns. SynchronizeBufferFromImage, which copies a GPU-written image into the buffer for formatted reads (is_texel_buffer), only runs on the path after that shortcut.

Image GPU writes update the image's state but do not mark the buffer tracker's pages GPU-modified, and an image upload of a range that has no cache buffer and no GPU-modified buffer data uses staging memory without registering one. So a range whose image the GPU has written can still look CPU-modified and unregistered to the buffer cache. A formatted read of 16 KiB or less at that image then takes the shortcut and returns the stale guest bytes instead of the image's texels. Larger reads already go on to SynchronizeBufferFromImage.

The same happens to the source of CopyBuffer (guest DMA copies), which acquires its source with is_texel_buffer set: the copy's own image check keeps it off the CPU memcpy path, but the source acquisition can still stream stale bytes.

Change

ObtainBuffer now looks the image up once for every formatted read that is not written: TextureCache::FindImageFromRange with its default ensure_valid, which selects an image at the read address that passes SafeToDownload(). The shortcut is not taken when it finds one (except in the guarded case below), and the image id is passed to SynchronizeBufferFromImage, which rechecks the image and applies its transfer checks instead of repeating the lookup. Reads without an image, raw reads (while --sync-raw-image-buffers is off), and reads of images the CPU has written keep the shortcut.

When the image starts at the read address, the requested buffer range is extended to the image's end, so a small read at the base of a larger GPU-written image gets a buffer that holds the image, and the buffer is synchronized over that whole range, so the image's other pages do not stay CPU-modified behind the read. The range is not extended when a GPU-modified buffer page lies behind the read: InvalidateMemoryFromGPU only marks images that start at a written address, so such an image still looks current and its download would overwrite the newer buffer bytes; that read is handled as on main. A stencil record resolves through depth_id to its depth image, which can start at another address; then the range is not extended. An image has to start at the read address to be found, so a small read that starts inside a larger GPU-written image is not covered by this change.

#1246 (closed by its author) excluded all texel buffers from the shortcut (!is_texel_buffer) for buffer view alignment and lifetime reasons. That form would fix a read as large as its image, but not a small read at the base of a larger image, and it drops the shortcut for every small formatted read, including those with no image behind them.

Tests

shader_recompiler_compute_tests adds CheckSmallFormattedImageSync (selector --small-formatted-image-sync-only, ctest graphics_small_formatted_image_sync). It creates six single-mip R32Uint images (two of 16 KiB, four of 32 KiB), uploads known texels, marks them GPU-written and overwrites their guest memory with 0xdeadbeef. It checks its preconditions first (each of these images is safe to download and found at its address, its guest memory holds the overwritten value, and its range is unregistered, CPU-modified and not GPU-modified). Then it reads, comparing every word with the uploaded texels:

  • a 32 KiB image with a 32 KiB formatted ObtainBuffer read (control);
  • 16 KiB images with a 16 KiB formatted read and a 16 KiB CopyBuffer;
  • 32 KiB images with a 16 KiB formatted read and a 16 KiB CopyBuffer at their base;
  • a plain 16 KiB read of the second half of a 32 KiB image, after a formatted read of the whole image (control) and after a 16 KiB formatted read at its base;
  • a 32 KiB image whose second half is then obtained as a written buffer: after a 16 KiB formatted read at the image's base the second half must still hold the buffer's words;
  • the stencil plane of a GPU-written depth target that starts after its stencil plane, with a 4 KiB formatted read: the buffer must cover the read and not reach the depth image (this checks the buffer bounds, not stencil values).

8e5186fe9 (the first test, on main 782a85c62) fails with read word 0 expected 0x71000000, got 0xdeadbeef; copy word 0 expected 0x71000000, got 0xdeadbeef. 73b508622 (the 32 KiB cases, with the change as of 0b5f61e84) fails at partial formatted read and copy with the same read and copy mismatches, d55622cee (the stencil case, with the change as of 260a080e3) fails with a small stencil read grew its buffer to the depth image, and 2082a39bd (the reads behind a formatted read, with the change as of c56c4362a) fails at read behind a partial formatted read with word 0 expected 0x71001000, got 0xdeadbeef, and 5c090cac7 (the written second half, with the change as of ac49a8dec) fails at buffer write behind a partial formatted read with word 0 expected 0xdeadbeef, got 0x71001000. The head passes.

This was run on an RX 9070 XT (Windows 11, clang-cl). The test harness needs local changes to run on that GPU at all (#2038's robustness alignment change, attachment feedback loop dynamic state optional, a D24S8 to D32S8 swap at four places, and skipping VectorMinMaxF64CapturedAndEdges, which crashes the driver), and the full runs use a keep-going change. With those, the full suite fails the same 22 checks on main and with this change.

Costs

A small formatted read of a GPU-current image now obtains or creates a cache buffer and synchronizes it like reads over 16 KiB already do, instead of a stream buffer copy of guest memory. Every formatted read that is not written does one image lookup in ObtainBuffer (it walks the image entries of the 1 MiB page that holds the read address), and image synchronization reuses it; on main, reads that took the shortcut did no lookup and the others did one. A read at the base of a GPU-written image downloads all its levels on every such acquisition while the image stays safe to download, as a read of the whole image already does on main. The cache buffer registered over the image also means that a later CopyBuffer into that range no longer tries CopyToImage, which only runs for unregistered destinations.

CI on this head (78e7ab519): in the upstream run of this PR Windows and macOS passed, and Linux stopped while installing packages (Temporary failure resolving 'azure.archive.ubuntu.com'); in the fork CI run (run 43051447225) Windows and Linux passed, and its macOS job is running again because GitHub found no macOS runner for its earlier attempts.

In a game

No game is known to show this bug yet. To see what the change does in a game, Demon's Souls (PPSA01341) and Assassin's Creed Black Flag (PPSA28183) were booted without input on an RX 9070 XT with a build of this branch that counts the reads in ObtainBuffer: more than 65,000 and more than 131,000 formatted reads, and none of them found a GPU-written image at its address. So these boots never take the changed path: nothing is downloaded that main does not download, and their behaviour is the same as on main.

Written with Claude Code (AI): GLM and Codex pointed at this path in a review; Claude Code wrote the test and the change and ran them.

**@⁠Nawid3333** on GitHub · 2026-11-10 10:50 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193) `Nawid3333:fix/small-formatted-reads-sync-images` → `main` · +274 −18 · 5 files · 12 commits · open ## Cause `BufferCache::ObtainBuffer` has a streaming shortcut for small reads: when a read is not written, is at most 16 KiB (`CACHING_PAGESIZE`), and its pages are CPU-modified but not GPU-modified, it copies guest memory into the stream buffer and returns. `SynchronizeBufferFromImage`, which copies a GPU-written image into the buffer for formatted reads (`is_texel_buffer`), only runs on the path after that shortcut. Image GPU writes update the image's state but do not mark the buffer tracker's pages GPU-modified, and an image upload of a range that has no cache buffer and no GPU-modified buffer data uses staging memory without registering one. So a range whose image the GPU has written can still look CPU-modified and unregistered to the buffer cache. A formatted read of 16 KiB or less at that image then takes the shortcut and returns the stale guest bytes instead of the image's texels. Larger reads already go on to `SynchronizeBufferFromImage`. The same happens to the source of `CopyBuffer` (guest DMA copies), which acquires its source with `is_texel_buffer` set: the copy's own image check keeps it off the CPU memcpy path, but the source acquisition can still stream stale bytes. ## Change `ObtainBuffer` now looks the image up once for every formatted read that is not written: `TextureCache::FindImageFromRange` with its default `ensure_valid`, which selects an image at the read address that passes `SafeToDownload()`. The shortcut is not taken when it finds one (except in the guarded case below), and the image id is passed to `SynchronizeBufferFromImage`, which rechecks the image and applies its transfer checks instead of repeating the lookup. Reads without an image, raw reads (while `--sync-raw-image-buffers` is off), and reads of images the CPU has written keep the shortcut. When the image starts at the read address, the requested buffer range is extended to the image's end, so a small read at the base of a larger GPU-written image gets a buffer that holds the image, and the buffer is synchronized over that whole range, so the image's other pages do not stay CPU-modified behind the read. The range is not extended when a GPU-modified buffer page lies behind the read: `InvalidateMemoryFromGPU` only marks images that start at a written address, so such an image still looks current and its download would overwrite the newer buffer bytes; that read is handled as on main. A stencil record resolves through `depth_id` to its depth image, which can start at another address; then the range is not extended. An image has to start at the read address to be found, so a small read that starts inside a larger GPU-written image is not covered by this change. #1246 (closed by its author) excluded all texel buffers from the shortcut (`!is_texel_buffer`) for buffer view alignment and lifetime reasons. That form would fix a read as large as its image, but not a small read at the base of a larger image, and it drops the shortcut for every small formatted read, including those with no image behind them. ## Tests `shader_recompiler_compute_tests` adds `CheckSmallFormattedImageSync` (selector `--small-formatted-image-sync-only`, ctest `graphics_small_formatted_image_sync`). It creates six single-mip R32Uint images (two of 16 KiB, four of 32 KiB), uploads known texels, marks them GPU-written and overwrites their guest memory with 0xdeadbeef. It checks its preconditions first (each of these images is safe to download and found at its address, its guest memory holds the overwritten value, and its range is unregistered, CPU-modified and not GPU-modified). Then it reads, comparing every word with the uploaded texels: - a 32 KiB image with a 32 KiB formatted `ObtainBuffer` read (control); - 16 KiB images with a 16 KiB formatted read and a 16 KiB `CopyBuffer`; - 32 KiB images with a 16 KiB formatted read and a 16 KiB `CopyBuffer` at their base; - a plain 16 KiB read of the second half of a 32 KiB image, after a formatted read of the whole image (control) and after a 16 KiB formatted read at its base; - a 32 KiB image whose second half is then obtained as a written buffer: after a 16 KiB formatted read at the image's base the second half must still hold the buffer's words; - the stencil plane of a GPU-written depth target that starts after its stencil plane, with a 4 KiB formatted read: the buffer must cover the read and not reach the depth image (this checks the buffer bounds, not stencil values). 8e5186fe9 (the first test, on main 782a85c62) fails with `read word 0 expected 0x71000000, got 0xdeadbeef; copy word 0 expected 0x71000000, got 0xdeadbeef`. 73b508622 (the 32 KiB cases, with the change as of 0b5f61e84) fails at `partial formatted read and copy` with the same read and copy mismatches, d55622cee (the stencil case, with the change as of 260a080e3) fails with `a small stencil read grew its buffer to the depth image`, and 2082a39bd (the reads behind a formatted read, with the change as of c56c4362a) fails at `read behind a partial formatted read` with `word 0 expected 0x71001000, got 0xdeadbeef`, and 5c090cac7 (the written second half, with the change as of ac49a8dec) fails at `buffer write behind a partial formatted read` with `word 0 expected 0xdeadbeef, got 0x71001000`. The head passes. This was run on an RX 9070 XT (Windows 11, clang-cl). The test harness needs local changes to run on that GPU at all (#2038's robustness alignment change, attachment feedback loop dynamic state optional, a D24S8 to D32S8 swap at four places, and skipping `VectorMinMaxF64CapturedAndEdges`, which crashes the driver), and the full runs use a keep-going change. With those, the full suite fails the same 22 checks on main and with this change. ## Costs A small formatted read of a GPU-current image now obtains or creates a cache buffer and synchronizes it like reads over 16 KiB already do, instead of a stream buffer copy of guest memory. Every formatted read that is not written does one image lookup in `ObtainBuffer` (it walks the image entries of the 1 MiB page that holds the read address), and image synchronization reuses it; on main, reads that took the shortcut did no lookup and the others did one. A read at the base of a GPU-written image downloads all its levels on every such acquisition while the image stays safe to download, as a read of the whole image already does on main. The cache buffer registered over the image also means that a later `CopyBuffer` into that range no longer tries `CopyToImage`, which only runs for unregistered destinations. CI on this head (78e7ab519): in the upstream run of this PR Windows and macOS passed, and Linux stopped while installing packages (`Temporary failure resolving 'azure.archive.ubuntu.com'`); in the fork CI run ([run 43051447225](https://github.com/Nawid3333/KytyPS5/actions/runs/43051447225)) Windows and Linux passed, and its macOS job is running again because GitHub found no macOS runner for its earlier attempts. ## In a game No game is known to show this bug yet. To see what the change does in a game, Demon's Souls (PPSA01341) and Assassin's Creed Black Flag (PPSA28183) were booted without input on an RX 9070 XT with a build of this branch that counts the reads in `ObtainBuffer`: more than 65,000 and more than 131,000 formatted reads, and none of them found a GPU-written image at its address. So these boots never take the changed path: nothing is downloaded that main does not download, and their behaviour is the same as on main. Written with Claude Code (AI): GLM and Codex pointed at this path in a review; Claude Code wrote the test and the change and ran them.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A 16 KiB formatted read at the base of a 32 KiB GPU-written image, and a
16 KiB CopyBuffer from such an image, must return the image texels, not the
stale guest backing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A formatted read that starts at a GPU-written image now gets a cache buffer
that spans the whole image, so SynchronizeBufferFromImage can download
every level. Before, the buffer only spanned the read, and a read smaller
than the image's first level kept the stale guest bytes.

ObtainBuffer looks the image up once and passes it to
SynchronizeBufferFromImage, which no longer repeats the lookup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts in bufferCache.cpp and bufferCache.h: upstream's UploadCopies and
SynchronizeBda structure is kept; SynchronizeBuffer still takes the image to
sync from, and SynchronizeBufferFromImage takes the image id.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:16:43 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-10 11:00 UTC · original · edited 2026-11-23 17:15 UTC

Explain Change →

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
Walkthrough

BufferCache now resolves cached images for texel-buffer requests and passes the image ID through buffer synchronization. When an image starts at the requested address, buffer lookup can cover the image’s full data range. A new Vulkan test checks formatted-image reads and copies, including partial ranges and tail writes, and checks stencil-plane behavior. The test runs in the normal sequence or as a standalone CTest case.

Suggested reviewers: nmzik

Change: Bug fix

Merge Risk: Moderate · previous review 78e7a

This change fixes stale formatted reads for most GPU-written images. A formatted read at the base of a larger image can still return stale data when a later part of the image was written through a buffer. Small base reads can also trigger full-image downloads. Resolve or explicitly accept both before merging.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed

Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: synchronizing small formatted reads from GPU-written images.
Description check Passed The description directly explains the stale-read cause, implementation changes, tests, limitations, and validation results. It is fully related to the changeset.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 4 functions across 3 files. (1 skipped: 1 too large.)

Resolution

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

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-10 11:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#issuecomment-6765595424) · edited 2026-11-23 17:15 UTC <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/2193?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-buttons-v1/explain-change-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-buttons-v1/explain-change.svg" alt="Explain Change →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- This is an auto-generated comment: review paused by coderabbit.ai --> > [!NOTE] > ## Reviews paused > > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the `reviews.auto_review.auto_pause_after_reviewed_commits` setting. > > - Last reviewed commit: 78e7ab51940aca11e10648ee07e61c8d94eef7e2 > - Latest commit, not reviewed: 69783857bb0f4193cf5ddc40921226cc4d97193c > > 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 --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> <br> BufferCache now resolves cached images for texel-buffer requests and passes the image ID through buffer synchronization. When an image starts at the requested address, buffer lookup can cover the image’s full data range. A new Vulkan test checks formatted-image reads and copies, including partial ranges and tail writes, and checks stencil-plane behavior. The test runs in the normal sequence or as a standalone CTest case. **Suggested reviewers:** `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <!-- change_assessment_commit:"78e7ab51940aca11e10648ee07e61c8d94eef7e2" --> <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} --> **Change:** Bug fix <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-normal-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Moderate</strong> · previous review <code>78e7a</code></summary> <dl> <dd> <br> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🟡 Moderate** · up to `78e7a` --> <!-- final_review_risk_coverage:{"sourceCommitId":"78e7ab51940aca11e10648ee07e61c8d94eef7e2","coveredCommitId":"78e7ab51940aca11e10648ee07e61c8d94eef7e2","kind":"reviewed"} --> This change fixes stale formatted reads for most GPU-written images. A formatted read at the base of a larger image can still return stale data when a later part of the image was written through a buffer. Small base reads can also trigger full-image downloads. Resolve or explicitly accept both before merging. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-inconclusive-14-v2.svg" width="14" height="14" align="middle" alt="Inconclusive" title="Inconclusive"></picture></sup> 1</strong></summary> <dl> <dd> <br> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 inconclusive</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> <br> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title clearly and concisely describes the main change: synchronizing small formatted reads from GPU-written images. | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description directly explains the stale-read cause, implementation changes, tests, limitations, and validation results. It is fully related to the changeset. | | 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> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> <br> **Explanation** Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 4 functions across 3 files. (1 skipped: 1 too large.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=2193)! 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> <br> - [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> <!-- tips_end -->
Author
Owner

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Major · Allocate enough space to synchronize the image. · bufferCache.cpp:499-500

src/graphics/host_gpu/renderer/cache/bufferCache.cpp:499-500
Major · Functional Correctness · Heavy lift

Allocate enough space to synchronize the image.

For a 16 KiB read at the base of an uncached 32 KiB, single-mip GPU-written image, FindBuffer creates a 16 KiB buffer. SynchronizeBufferFromImage cannot fit the first mip and returns false, so the read still uses stale guest data. The new test reads the full 32 KiB image and misses this case. (raw.githubusercontent.com)

Size the cached buffer for the required image data, or support a partial image download.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 782a85c621 and 0b5f61e843.

Files selected for processing: 3

  • CMakeLists.txt
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-10 11:00 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#pullrequestreview-5840766300) · **reviewed** <!-- coderabbit-ai-generated:v1 --> > [!CAUTION] > Some comments are outside the diff and can’t be posted inline due to GitHub limitations. > > **⚠️ Outside diff range comments (1)** > > <details> > <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major</strong> · Allocate enough space to synchronize the image. · <code>bufferCache.cpp:499-500</code></summary><blockquote> > <dl> > <dd> > <br> > > `src/graphics/host_gpu/renderer/cache/bufferCache.cpp:499-500` > **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Functional Correctness** · **Heavy lift** > > **Allocate enough space to synchronize the image.** > > For a 16 KiB read at the base of an uncached 32 KiB, single-mip GPU-written image, `FindBuffer` creates a 16 KiB buffer. `SynchronizeBufferFromImage` cannot fit the first mip and returns false, so the read still uses stale guest data. The new test reads the full 32 KiB image and misses this case. ([raw.githubusercontent.com](https://raw.githubusercontent.com/KytyPS5/KytyPS5/0b5f61e843984a4e7178678e4bcfc78ae789d9bc/src/graphics/host_gpu/renderer/cache/textureCache.cpp)) > > Size the cached buffer for the required image data, or support a partial image download. > > <!-- cr-comment:v1:8f2e884f5b2d9356f9754d5d --> > > </dd> > </dl> > </blockquote></details> <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/782a85c621bd849762599a6a0e790596be119505/.coderabbit.yaml>) - **Commit**: [782a85c](<https://github.com/KytyPS5/KytyPS5/commit/782a85c621bd849762599a6a0e790596be119505>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `5b183802-907a-451f-aa60-400a1bab7175` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 782a85c621bd849762599a6a0e790596be119505 and 0b5f61e843984a4e7178678e4bcfc78ae789d9bc. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 3</summary> <dl> <dd> <br> * `CMakeLists.txt` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=0d96ce1e-cc6f-45c0-9484-991c68875661 attempt=cc3817b7-7801-4e4c-8d9e-334383ca8b63 batch=1/1 -->
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-10 14:49 UTC · original

The outside-diff point on bufferCache.cpp:499-500 was correct: a small formatted read at the base of a larger GPU-written image got a buffer too small for the image's first mip, so SynchronizeBufferFromImage returned false and the read kept the stale guest bytes.

Fixed in 260a080e3 and 3482789f0:

  • ObtainBuffer looks the image up once. When the image starts at the read address, the requested buffer range is extended to the image's end. The image id is passed to SynchronizeBufferFromImage, which no longer repeats the lookup.
  • A stencil record resolves through depth_id to its depth image, which can start at another address. Then the range is not extended.

Such a read downloads all image levels on every acquisition while the image stays safe to download, as a read of the whole image already does.

Tests:

  • 73b508622 adds a 16 KiB read and a 16 KiB copy at the bases of two 32 KiB GPU-written images. With the change as of 0b5f61e84 it fails at partial formatted read and copy with read word 0 expected 0x71000000, got 0xdeadbeef; copy word 0 expected 0x71000000, got 0xdeadbeef.
  • d55622cee adds a 4 KiB read at a stencil plane placed before its depth image and checks the buffer bounds. With the change as of 260a080e3 it fails with a small stencil read grew its buffer to the depth image.

Both pass on 3482789f0, and the full suite on our AMD test host has the same failures as before.

**@⁠Nawid3333** on GitHub · 2026-11-10 14:49 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#issuecomment-6770468914) The outside-diff point on `bufferCache.cpp:499-500` was correct: a small formatted read at the base of a larger GPU-written image got a buffer too small for the image's first mip, so `SynchronizeBufferFromImage` returned false and the read kept the stale guest bytes. Fixed in 260a080e3 and 3482789f0: - `ObtainBuffer` looks the image up once. When the image starts at the read address, the requested buffer range is extended to the image's end. The image id is passed to `SynchronizeBufferFromImage`, which no longer repeats the lookup. - A stencil record resolves through `depth_id` to its depth image, which can start at another address. Then the range is not extended. Such a read downloads all image levels on every acquisition while the image stays safe to download, as a read of the whole image already does. Tests: - 73b508622 adds a 16 KiB read and a 16 KiB copy at the bases of two 32 KiB GPU-written images. With the change as of 0b5f61e84 it fails at `partial formatted read and copy` with `read word 0 expected 0x71000000, got 0xdeadbeef; copy word 0 expected 0x71000000, got 0xdeadbeef`. - d55622cee adds a 4 KiB read at a stencil plane placed before its depth image and checks the buffer bounds. With the change as of 260a080e3 it fails with `a small stencil read grew its buffer to the depth image`. Both pass on 3482789f0, and the full suite on our AMD test host has the same failures as before.
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-11 13:40 UTC · original · edited 2026-11-11 15:55 UTC
On src/graphics/host_gpu/renderer/cache/bufferCache.cpp line 526 (outdated):

@@ -507,12 +510,20 @@ std::pair<Buffer*, uint64_t> BufferCache::ObtainBuffer(uint64_t vaddr, uint64_t
 		}
 	}
 
-	if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, size)) {
-		id = FindBuffer(vaddr, size);
+	auto end = vaddr + size;
+	if (image) {
+		std::scoped_lock lock {m_texture_cache.m_lock};
+		const auto&      range = m_texture_cache.m_slot_images[image].info.data;
+		if (range.address == vaddr) {
+			end = std::max(end, range.End());
+		}
+	}
+	if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, end - vaddr)) {
+		id = FindBuffer(vaddr, end - vaddr);
 	}
 	auto& buffer = m_slot_buffers[id];
 	TouchBuffer(buffer);
-	(void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer);
+	(void)SynchronizeBuffer(buffer, vaddr, size, is_written, image);

Major · Data Integrity & Integration · Heavy lift

Supported by static analysis

Script executed:

ast-grep outline src/graphics/host_gpu/renderer/cache/textureCache.cpp \
  --match 'DownloadImage|SynchronizeBufferFromImage' --view expanded

rg -n -C 8 '\bTextureCache::DownloadImage\s*\(' \
  src/graphics/host_gpu/renderer/cache/textureCache.cpp

rg -n -C 6 '\b(ForEachUploadRange|IsRegionCpuModified)\s*\(' src

Repository: KytyPS5/KytyPS5

Length of output: 11752


Script executed:

cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '400,535p'
cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1718,1805p'
cat -n src/graphics/host_gpu/memoryTracker.h | sed -n '1,130p'
cat -n src/graphics/host_gpu/memoryTracker.cpp | sed -n '1,125p'
rg -n -F -e 'FindImageFromRange(' -e 'IsSafeToDownload(' -e 'ForEachModifiedRange' -- src/graphics/host_gpu
git diff bc934ef03410b760fbf8e49db1d79485e7e5f887 c56c4362a3f638b23ecf94181138938ec714402c -- src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 26572


Script executed:

cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1320,1405p'
cat -n src/graphics/host_gpu/regionManager.h | sed -n '75,200p'
rg -n -F -e 'SafeToDownload' -e 'MarkRegionAsCpuModified' -e 'ObtainBuffer(' -- src/graphics/host_gpu/renderer src/graphics/host_gpu
cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '535,635p'
rg -n -F -e 'CpuModified' -e 'GpuModified' -- src/graphics/host_gpu/renderer/image src/graphics/host_gpu/renderer/cache/textureCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 21705


Script executed:

cat -n src/graphics/host_gpu/renderer/image/image.h | sed -n '80,135p'
rg -n -F -e 'RefreshImage(' -e 'MarkGpuModified(' -e 'MarkCpuDirty(' -e 'ClearCpuDirty(' -e 'ObtainBufferForImage(' -- src/graphics/host_gpu/renderer
cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '230,310p;1440,1515p'
cat -n src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '90,145p'
cat -n src/graphics/host_gpu/renderer/cache/bufferCache.h | sed -n '55,75p'
rg -n -F -e 'ForEachImageWithAddress(' -e 'TRACKER_PAGE_SIZE' -- src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/regionManager.h src/graphics/host_gpu/pageManager.h src/graphics/host_gpu

Repository: KytyPS5/KytyPS5

Length of output: 21821


Script executed:

cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '910,1005p;1120,1185p;1408,1440p'
cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '175,225p'
cat -n src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '680,720p;1100,1136p'
cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '265,325p;680,725p'
rg -n -F -e 'CheckSmallFormattedImageSync' -e 'MarkGpuWritten(' -- tests src/graphics/host_gpu/renderer

Repository: KytyPS5/KytyPS5

Length of output: 25150


Script executed:

cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1920,1975p'
cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '730,825p'
cat -n src/graphics/host_gpu/renderer/image/image.h | sed -n '50,82p'
cat -n tests/ShaderRecompilerComputeTests.cpp | sed -n '20149,20265p'
rg -n -F -e 'InvalidateMemoryFromGPU(' -e 'IsBufferModified()' -- src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.h

Repository: KytyPS5/KytyPS5

Length of output: 16709


Script executed:

cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1835,1875p'
cat -n tests/ShaderRecompilerComputeTests.cpp | sed -n '20260,20312p'
cat -n src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '109,138p'

Repository: KytyPS5/KytyPS5

Length of output: 6210


Script executed:

cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '50,80p'
cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1347,1383p'

Repository: KytyPS5/KytyPS5

Length of output: 3169


Preserve tracking for the full image transfer.

A small base read can download the full image while leaving later pages CPU-dirty. If a buffer write then invalidates the image, a larger base read can upload stale guest bytes over those pages. Preserve the downloaded data and its ownership across the full transferred range; clearing CPU-dirty bits alone would leave guest backing stale.

✅ Confirmed as addressed by @⁠Nawid3333

**@⁠coderabbitai[bot]** on GitHub · 2026-11-11 13:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4538589729) · edited 2026-11-11 15:55 UTC On `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` line 526 (outdated): ```diff @@ -507,12 +510,20 @@ std::pair<Buffer*, uint64_t> BufferCache::ObtainBuffer(uint64_t vaddr, uint64_t } } - if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, size)) { - id = FindBuffer(vaddr, size); + auto end = vaddr + size; + if (image) { + std::scoped_lock lock {m_texture_cache.m_lock}; + const auto& range = m_texture_cache.m_slot_images[image].info.data; + if (range.address == vaddr) { + end = std::max(end, range.End()); + } + } + if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, end - vaddr)) { + id = FindBuffer(vaddr, end - vaddr); } auto& buffer = m_slot_buffers[id]; TouchBuffer(buffer); - (void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer); + (void)SynchronizeBuffer(buffer, vaddr, size, is_written, image); ``` <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Heavy lift** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash ast-grep outline src/graphics/host_gpu/renderer/cache/textureCache.cpp \ --match 'DownloadImage|SynchronizeBufferFromImage' --view expanded rg -n -C 8 '\bTextureCache::DownloadImage\s*\(' \ src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -C 6 '\b(ForEachUploadRange|IsRegionCpuModified)\s*\(' src ``` Repository: KytyPS5/KytyPS5 Length of output: 11752 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '400,535p' cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1718,1805p' cat -n src/graphics/host_gpu/memoryTracker.h | sed -n '1,130p' cat -n src/graphics/host_gpu/memoryTracker.cpp | sed -n '1,125p' rg -n -F -e 'FindImageFromRange(' -e 'IsSafeToDownload(' -e 'ForEachModifiedRange' -- src/graphics/host_gpu git diff bc934ef03410b760fbf8e49db1d79485e7e5f887 c56c4362a3f638b23ecf94181138938ec714402c -- src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 26572 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1320,1405p' cat -n src/graphics/host_gpu/regionManager.h | sed -n '75,200p' rg -n -F -e 'SafeToDownload' -e 'MarkRegionAsCpuModified' -e 'ObtainBuffer(' -- src/graphics/host_gpu/renderer src/graphics/host_gpu cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '535,635p' rg -n -F -e 'CpuModified' -e 'GpuModified' -- src/graphics/host_gpu/renderer/image src/graphics/host_gpu/renderer/cache/textureCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 21705 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/image/image.h | sed -n '80,135p' rg -n -F -e 'RefreshImage(' -e 'MarkGpuModified(' -e 'MarkCpuDirty(' -e 'ClearCpuDirty(' -e 'ObtainBufferForImage(' -- src/graphics/host_gpu/renderer cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '230,310p;1440,1515p' cat -n src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '90,145p' cat -n src/graphics/host_gpu/renderer/cache/bufferCache.h | sed -n '55,75p' rg -n -F -e 'ForEachImageWithAddress(' -e 'TRACKER_PAGE_SIZE' -- src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/regionManager.h src/graphics/host_gpu/pageManager.h src/graphics/host_gpu ``` Repository: KytyPS5/KytyPS5 Length of output: 21821 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '910,1005p;1120,1185p;1408,1440p' cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '175,225p' cat -n src/graphics/host_gpu/renderer/renderDraw.cpp | sed -n '680,720p;1100,1136p' cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '265,325p;680,725p' rg -n -F -e 'CheckSmallFormattedImageSync' -e 'MarkGpuWritten(' -- tests src/graphics/host_gpu/renderer ``` Repository: KytyPS5/KytyPS5 Length of output: 25150 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1920,1975p' cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '730,825p' cat -n src/graphics/host_gpu/renderer/image/image.h | sed -n '50,82p' cat -n tests/ShaderRecompilerComputeTests.cpp | sed -n '20149,20265p' rg -n -F -e 'InvalidateMemoryFromGPU(' -e 'IsBufferModified()' -- src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.h ``` Repository: KytyPS5/KytyPS5 Length of output: 16709 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1835,1875p' cat -n tests/ShaderRecompilerComputeTests.cpp | sed -n '20260,20312p' cat -n src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '109,138p' ``` Repository: KytyPS5/KytyPS5 Length of output: 6210 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '50,80p' cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1347,1383p' ``` Repository: KytyPS5/KytyPS5 Length of output: 3169 --- </dd> </dl> </details> **Preserve tracking for the full image transfer.** A small base read can download the full image while leaving later pages CPU-dirty. If a buffer write then invalidates the image, a larger base read can upload stale guest bytes over those pages. Preserve the downloaded data and its ownership across the full transferred range; clearing CPU-dirty bits alone would leave guest backing stale. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:80b7751f1eda7c47f2a9adc1 --> <!-- This is an auto-generated reply by CodeRabbit --> ✅ Confirmed as addressed by @⁠Nawid3333 <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-11 13:40 UTC · original · reviewed

Actionable comments posted: 1

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 3482789f0e and c56c4362a3.

Files selected for processing: 4

  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-11 13:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#pullrequestreview-5859649716) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/bc934ef03410b760fbf8e49db1d79485e7e5f887/.coderabbit.yaml>) - **Commit**: [bc934ef](<https://github.com/KytyPS5/KytyPS5/commit/bc934ef03410b760fbf8e49db1d79485e7e5f887>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `2251195f-b680-4e9a-ad04-54b23b14aeec` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between 3482789f0e1afb797fc6d87aa1b5e1713e4bf1ea and c56c4362a3f638b23ecf94181138938ec714402c. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 4</summary> <dl> <dd> <br> * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=240ecddd-3039-4956-aece-69c4a762b281 attempt=a119786f-0f11-4f24-bd25-2e49f567c05c batch=1/1 -->
@ -515,3 +531,3 @@
auto& buffer = m_slot_buffers[id];
TouchBuffer(buffer);
(void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer);
(void)SynchronizeBuffer(buffer, vaddr, end - vaddr, is_written, image);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-11 14:33 UTC · original · edited 2026-11-11 15:34 UTC

Major · Performance & Scalability · Heavy lift

Avoid downloading the full image for every small read.

When a small read starts at a downloadable image’s base, each acquisition can download the entire image. For a 4096×4096 RGBA8 image, a four-byte read can cause a roughly 64 MiB transfer. Repeated bindings can substantially increase GPU traffic and reduce frame rate. Track whether the buffer already contains the current image data, or otherwise avoid redundant downloads.


Major · Data Integrity & Integration · Heavy lift

Supported by static analysis

Script executed:

#!/bin/bash
rg -n -C 4 'InvalidateMemoryFromGPU|m_gpu_modified_ranges\.Add|CopyBuffer\s*\(' src/graphics/host_gpu/renderer

Repository: KytyPS5/KytyPS5

Length of output: 7068


Script executed:

git diff bc934ef03410b760fbf8e49db1d79485e7e5f887 ac49a8dec0ab24ac19aa9e7412bcccb5aeec9ee2 -- src/graphics/host_gpu/renderer/cache/bufferCache.cpp
rg -n -F -e 'SynchronizeBufferFromImage' -e 'SynchronizeBuffer(' -e 'ObtainBuffer(' -e 'FindImage' -e 'InvalidateMemoryFromGPU' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/renderer/pipeline/descriptors.cpp
cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '350,645p'
cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1770,1905p'
cat -n src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '55,145p'

Repository: KytyPS5/KytyPS5

Length of output: 32251


Script executed:

cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1340,1415p;1710,1785p'
rg -n -F -e 'SafeToDownload' -e 'void TextureCache::DownloadImage' -e 'MarkBufferModified' -e 'ClearGpuModified' src/graphics/host_gpu/renderer
rg -n -F -e 'ForEachImageInRegion' src/graphics/host_gpu/renderer/cache/textureCache.h src/graphics/host_gpu/renderer/cache/textureCache.cpp

Repository: KytyPS5/KytyPS5

Length of output: 10061


Script executed:

cat -n src/graphics/host_gpu/renderer/image/image.h | sed -n '75,130p'
cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '130,205p'
rg -n -F -e 'ForEachUploadRange' -e 'IsRegionGpuModified' -e 'MarkGpuModified' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer/image
cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '250,300p;1900,1940p'
rg -n -F 'CheckSmallFormattedImageSync' tests src

Repository: KytyPS5/KytyPS5

Length of output: 11527


Script executed:

rg -n -F -e 'ForEachUploadRange' -e 'FindImageFromRange(' src/graphics/host_gpu
rg -n -F -e 'class MemoryTracker' -e 'struct MemoryTracker' src/graphics/host_gpu
cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '50,85p'
cat -n tests/ShaderRecompilerComputeTests.cpp | sed -n '20149,20380p'

Repository: KytyPS5/KytyPS5

Length of output: 16225


Script executed:

cat -n src/graphics/host_gpu/memoryTracker.h | sed -n '1,180p'
cat -n src/graphics/host_gpu/memoryTracker.cpp | sed -n '1,200p'
cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1470,1502p'

Repository: KytyPS5/KytyPS5

Length of output: 12117


Script executed:

rg -n -F -e 'ChangeState' -e 'UpdatePageWatchers' src/graphics/host_gpu/regionManager.h src/graphics/host_gpu/regionManager.cpp src/graphics/host_gpu/pageManager.h src/graphics/host_gpu/pageManager.cpp
cat -n src/graphics/host_gpu/regionManager.h | sed -n '70,230p'
cat -n src/graphics/host_gpu/regionManager.cpp | sed -n '1,220p'

Repository: KytyPS5/KytyPS5

Length of output: 6140


Script executed:

cat -n src/graphics/host_gpu/pageManager.cpp | sed -n '200,275p;288,305p'

Repository: KytyPS5/KytyPS5

Length of output: 4190


Preserve buffer writes before downloading the full image.

If a GPU buffer write starts inside an image, InvalidateMemoryFromGPU skips that image. A later formatted read at the image base can download the full image and overwrite the newer buffer bytes.

Preserve both the newer buffer bytes and the unaffected GPU image contents when resolving this overlap.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-11 14:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4539158307) · edited 2026-11-11 15:34 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Performance & Scalability** · **Heavy lift** **Avoid downloading the full image for every small read.** When a small read starts at a downloadable image’s base, each acquisition can download the entire image. For a 4096×4096 RGBA8 image, a four-byte read can cause a roughly 64 MiB transfer. Repeated bindings can substantially increase GPU traffic and reduce frame rate. Track whether the buffer already contains the current image data, or otherwise avoid redundant downloads. <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:a8e5f29b727189353d9e0a22 --> --- **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Heavy lift** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash #!/bin/bash rg -n -C 4 'InvalidateMemoryFromGPU|m_gpu_modified_ranges\.Add|CopyBuffer\s*\(' src/graphics/host_gpu/renderer ``` Repository: KytyPS5/KytyPS5 Length of output: 7068 --- Script executed: ```bash git diff bc934ef03410b760fbf8e49db1d79485e7e5f887 ac49a8dec0ab24ac19aa9e7412bcccb5aeec9ee2 -- src/graphics/host_gpu/renderer/cache/bufferCache.cpp rg -n -F -e 'SynchronizeBufferFromImage' -e 'SynchronizeBuffer(' -e 'ObtainBuffer(' -e 'FindImage' -e 'InvalidateMemoryFromGPU' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.cpp src/graphics/host_gpu/renderer/pipeline/descriptors.cpp cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '350,645p' cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1770,1905p' cat -n src/graphics/host_gpu/renderer/pipeline/descriptors.cpp | sed -n '55,145p' ``` Repository: KytyPS5/KytyPS5 Length of output: 32251 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1340,1415p;1710,1785p' rg -n -F -e 'SafeToDownload' -e 'void TextureCache::DownloadImage' -e 'MarkBufferModified' -e 'ClearGpuModified' src/graphics/host_gpu/renderer rg -n -F -e 'ForEachImageInRegion' src/graphics/host_gpu/renderer/cache/textureCache.h src/graphics/host_gpu/renderer/cache/textureCache.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 10061 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/image/image.h | sed -n '75,130p' cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '130,205p' rg -n -F -e 'ForEachUploadRange' -e 'IsRegionGpuModified' -e 'MarkGpuModified' src/graphics/host_gpu/renderer/cache src/graphics/host_gpu/renderer/image cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '250,300p;1900,1940p' rg -n -F 'CheckSmallFormattedImageSync' tests src ``` Repository: KytyPS5/KytyPS5 Length of output: 11527 --- Script executed: ```bash rg -n -F -e 'ForEachUploadRange' -e 'FindImageFromRange(' src/graphics/host_gpu rg -n -F -e 'class MemoryTracker' -e 'struct MemoryTracker' src/graphics/host_gpu cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '50,85p' cat -n tests/ShaderRecompilerComputeTests.cpp | sed -n '20149,20380p' ``` Repository: KytyPS5/KytyPS5 Length of output: 16225 --- Script executed: ```bash cat -n src/graphics/host_gpu/memoryTracker.h | sed -n '1,180p' cat -n src/graphics/host_gpu/memoryTracker.cpp | sed -n '1,200p' cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1470,1502p' ``` Repository: KytyPS5/KytyPS5 Length of output: 12117 --- Script executed: ```bash rg -n -F -e 'ChangeState' -e 'UpdatePageWatchers' src/graphics/host_gpu/regionManager.h src/graphics/host_gpu/regionManager.cpp src/graphics/host_gpu/pageManager.h src/graphics/host_gpu/pageManager.cpp cat -n src/graphics/host_gpu/regionManager.h | sed -n '70,230p' cat -n src/graphics/host_gpu/regionManager.cpp | sed -n '1,220p' ``` Repository: KytyPS5/KytyPS5 Length of output: 6140 --- Script executed: ```bash cat -n src/graphics/host_gpu/pageManager.cpp | sed -n '200,275p;288,305p' ``` Repository: KytyPS5/KytyPS5 Length of output: 4190 --- </dd> </dl> </details> **Preserve buffer writes before downloading the full image.** If a GPU buffer write starts inside an image, `InvalidateMemoryFromGPU` skips that image. A later formatted read at the image base can download the full image and overwrite the newer buffer bytes. Preserve both the newer buffer bytes and the unaffected GPU image contents when resolving this overlap. <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:2b2ab991bdd22f0ec7afcb37 --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-11 14:33 UTC · original · reviewed

Actionable comments posted: 2

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between c56c4362a3 and ac49a8dec0.

Files selected for processing: 2

  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-11 14:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#pullrequestreview-5860371735) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 2** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/bc934ef03410b760fbf8e49db1d79485e7e5f887/.coderabbit.yaml>) - **Commit**: [bc934ef](<https://github.com/KytyPS5/KytyPS5/commit/bc934ef03410b760fbf8e49db1d79485e7e5f887>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `7aafe1c6-e8fb-4808-8030-c6787b9ee38a` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between c56c4362a3f638b23ecf94181138938ec714402c and ac49a8dec0ab24ac19aa9e7412bcccb5aeec9ee2. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 2</summary> <dl> <dd> <br> * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=fe4c2f51-1073-46d3-97b6-222e146fc38a attempt=f755f7b8-a2c7-4a8f-9758-4e96c0a17286 batch=1/1 -->
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-11 14:35 UTC · original

Merged main (bc934ef) into the branch. The conflicts were in bufferCache.cpp and bufferCache.h with b510053 and 0ec2cd5: the merge keeps their UploadCopies and SynchronizeBda as they are, and SynchronizeBuffer still takes the image to sync from instead of is_texel_buffer.

Run again on the merge (RX 9070 XT, with the same local harness changes as in the description):

  • --small-formatted-image-sync-only passes.
  • The full shader_recompiler_compute_tests run, keep-going, has the same 22 failed checks as before the merge.
  • With main's src/ (bc934ef) under this branch's tests, SmallFormattedImageSync still fails: small formatted read and copy and partial formatted read and copy report read word 0 expected 0x71000000, got 0xdeadbeef; copy word 0 expected 0x71000000, got 0xdeadbeef, and the stencil check fails too. So main still has this bug after b510053 and 0ec2cd5.
**@⁠Nawid3333** on GitHub · 2026-11-11 14:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#issuecomment-6798672059) Merged main (bc934ef) into the branch. The conflicts were in `bufferCache.cpp` and `bufferCache.h` with b510053 and 0ec2cd5: the merge keeps their `UploadCopies` and `SynchronizeBda` as they are, and `SynchronizeBuffer` still takes the image to sync from instead of `is_texel_buffer`. Run again on the merge (RX 9070 XT, with the same local harness changes as in the description): - `--small-formatted-image-sync-only` passes. - The full `shader_recompiler_compute_tests` run, keep-going, has the same 22 failed checks as before the merge. - With main's `src/` (bc934ef) under this branch's tests, `SmallFormattedImageSync` still fails: `small formatted read and copy` and `partial formatted read and copy` report `read word 0 expected 0x71000000, got 0xdeadbeef; copy word 0 expected 0x71000000, got 0xdeadbeef`, and the stencil check fails too. So main still has this bug after b510053 and 0ec2cd5.
@ -515,3 +531,3 @@
auto& buffer = m_slot_buffers[id];
TouchBuffer(buffer);
(void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer);
(void)SynchronizeBuffer(buffer, vaddr, end - vaddr, is_written, image);
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-11 15:25 UTC · original

A buffer write inside the image. Right, and for a small read this was new with this PR: in the case the new check builds, main's small read takes the streaming shortcut and touches no cache buffer. 78e7ab5: ObtainBuffer extends the range to the image's end only when no GPU-modified buffer page lies behind the read; otherwise the read is handled as on main (range not extended, streaming shortcut allowed). 5c090ca adds the check: a 32 KiB GPU-written image, its second half obtained as a written buffer and reported with InvalidateMemoryFromGPU, then a 16 KiB formatted read at the base; the second half must still hold the buffer's words. On ac49a8d it fails with buffer write behind a partial formatted read: word 0 expected 0xdeadbeef, got 0x71001000; with 78e7ab5 it passes, and the full shader_recompiler_compute_tests run has the same 22 failed checks as before (RX 9070 XT).

What stays as on main: a read that covers the whole image still downloads it over such a write, because InvalidateMemoryFromGPU only marks images that start at the written address (image.info.data.address != address returns early). Changing that changes when images are refreshed from buffer writes in every game, so it is not part of this PR.

Download on every acquisition. SynchronizeBufferFromImage on main downloads the image on each call while it is safe to download; nothing records that the buffer already holds the image's data. A small read at the base now costs what a read of the whole image costs on main, as named under Costs. A record of that kind would have to be dropped by every image write, buffer write and CPU write in the range and would serve whole reads too, so it is a separate change. Counted in two games (boots of Demon's Souls and Assassin's Creed Black Flag, no input, a build of this branch with counters in ObtainBuffer): more than 65,000 and more than 131,000 formatted reads, none of which found a GPU-written image, so no download was added there.

**@⁠Nawid3333** on GitHub · 2026-11-11 15:25 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4539758396) **A buffer write inside the image.** Right, and for a small read this was new with this PR: in the case the new check builds, main's small read takes the streaming shortcut and touches no cache buffer. 78e7ab5: `ObtainBuffer` extends the range to the image's end only when no GPU-modified buffer page lies behind the read; otherwise the read is handled as on main (range not extended, streaming shortcut allowed). 5c090ca adds the check: a 32 KiB GPU-written image, its second half obtained as a written buffer and reported with `InvalidateMemoryFromGPU`, then a 16 KiB formatted read at the base; the second half must still hold the buffer's words. On ac49a8d it fails with `buffer write behind a partial formatted read: word 0 expected 0xdeadbeef, got 0x71001000`; with 78e7ab5 it passes, and the full `shader_recompiler_compute_tests` run has the same 22 failed checks as before (RX 9070 XT). What stays as on main: a read that covers the whole image still downloads it over such a write, because `InvalidateMemoryFromGPU` only marks images that start at the written address (`image.info.data.address != address` returns early). Changing that changes when images are refreshed from buffer writes in every game, so it is not part of this PR. **Download on every acquisition.** `SynchronizeBufferFromImage` on main downloads the image on each call while it is safe to download; nothing records that the buffer already holds the image's data. A small read at the base now costs what a read of the whole image costs on main, as named under Costs. A record of that kind would have to be dropped by every image write, buffer write and CPU write in the range and would serve whole reads too, so it is a separate change. Counted in two games (boots of Demon's Souls and Assassin's Creed Black Flag, no input, a build of this branch with counters in `ObtainBuffer`): more than 65,000 and more than 131,000 formatted reads, none of which found a GPU-written image, so no download was added there.
@ -486,3 +502,3 @@
if (!is_written && size <= CACHING_PAGESIZE &&
!m_memory_tracker.IsRegionGpuModified(vaddr, size) &&
m_memory_tracker.IsRegionCpuModified(vaddr, size)) {
m_memory_tracker.IsRegionCpuModified(vaddr, size) && (!image || written_past_read)) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-11 15:30 UTC · original · edited 2026-11-11 15:53 UTC

Major · Data Integrity & Integration · Heavy lift

Supported by static analysis

Script executed:

rg -n -C 12 'TextureCache::InvalidateMemoryFromGPU|Image::SafeToDownload' src/graphics/host_gpu/renderer/cache/textureCache.cpp
rg -n -C 10 'CheckSmallFormattedImageSync|tail|deadbeef' tests/ShaderRecompilerComputeTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 41898


Script executed:

git diff bc934ef03410b760fbf8e49db1d79485e7e5f887 78e7ab51940aca11e10648ee07e61c8d94eef7e2 -- src/graphics/host_gpu/renderer/cache/bufferCache.cpp
cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '420,575p'
rg -n -F -e 'SafeToDownload' -e 'FindImage' -e 'SynchronizeBufferFromImage' -e 'IsRegionGpuModified' src/graphics/host_gpu/renderer/cache/{bufferCache.cpp,textureCache.cpp,textureCache.h,image.cpp,image.h,memoryTracker.cpp,memoryTracker.h} 2>/dev/null
rg -n -F -e 'CheckSmallFormattedImageSync' -e 'written_tail_image' tests/ShaderRecompilerComputeTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 15440


Script executed:

cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1340,1385p;1735,1790p;1857,1866p'
cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '48,66p'
cat -n tests/ShaderRecompilerComputeTests.cpp | sed -n '20149,20345p'
rg -n -F -e 'SafeToDownload()' -e 'ForEachUploadRange' -e 'IsRegionCpuModified' -e 'IsRegionGpuModified' src/graphics/host_gpu/renderer

Repository: KytyPS5/KytyPS5

Length of output: 20100


Script executed:

cat -n src/graphics/host_gpu/renderer/image/image.h | sed -n '65,140p'
rg -n -F -e 'class MemoryTracker' -e 'ForEachUploadRange' -e 'MarkGpuWritten' -e 'ForEachImageWithAddress' src/graphics/host_gpu
cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '300,422p;600,650p'
cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '2000,2080p'

Repository: KytyPS5/KytyPS5

Length of output: 16200


Script executed:

cat -n src/graphics/host_gpu/memoryTracker.h | sed -n '1,190p'
cat -n src/graphics/host_gpu/memoryTracker.cpp | sed -n '1,230p'
cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '165,225p'
cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1460,1500p'

Repository: KytyPS5/KytyPS5

Length of output: 14792


Script executed:

rg -n -F -e 'TRACKER_PAGE_SIZE' -e 'ForEachModifiedRange' -e 'ChangeState' src/graphics/host_gpu/regionManager.h
cat -n src/graphics/host_gpu/regionManager.h | sed -n '1,245p'

Repository: KytyPS5/KytyPS5

Length of output: 6845


Script executed:

rg -n -F -e 'TRACKER_PAGE_SIZE' -e 'TRACKER_PAGE_BITS' src/graphics/host_gpu/regionDefinitions.h src/graphics/host_gpu/pageManager.h

Repository: KytyPS5/KytyPS5

Length of output: 384


Synchronize the image-backed prefix when the tail is GPU-modified.

A GPU-modified tail sets written_past_read, which allows the streaming shortcut to return stale guest bytes for the prefix. Synchronize the prefix while preserving the newer buffer tail. The tail regression currently discards the prefix result; check its contents too.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-11 15:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4539810641) · edited 2026-11-11 15:53 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major** · **Data Integrity & Integration** · **Heavy lift** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> <br> Script executed: ```bash rg -n -C 12 'TextureCache::InvalidateMemoryFromGPU|Image::SafeToDownload' src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -C 10 'CheckSmallFormattedImageSync|tail|deadbeef' tests/ShaderRecompilerComputeTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 41898 --- Script executed: ```bash git diff bc934ef03410b760fbf8e49db1d79485e7e5f887 78e7ab51940aca11e10648ee07e61c8d94eef7e2 -- src/graphics/host_gpu/renderer/cache/bufferCache.cpp cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '420,575p' rg -n -F -e 'SafeToDownload' -e 'FindImage' -e 'SynchronizeBufferFromImage' -e 'IsRegionGpuModified' src/graphics/host_gpu/renderer/cache/{bufferCache.cpp,textureCache.cpp,textureCache.h,image.cpp,image.h,memoryTracker.cpp,memoryTracker.h} 2>/dev/null rg -n -F -e 'CheckSmallFormattedImageSync' -e 'written_tail_image' tests/ShaderRecompilerComputeTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 15440 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1340,1385p;1735,1790p;1857,1866p' cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '48,66p' cat -n tests/ShaderRecompilerComputeTests.cpp | sed -n '20149,20345p' rg -n -F -e 'SafeToDownload()' -e 'ForEachUploadRange' -e 'IsRegionCpuModified' -e 'IsRegionGpuModified' src/graphics/host_gpu/renderer ``` Repository: KytyPS5/KytyPS5 Length of output: 20100 --- Script executed: ```bash cat -n src/graphics/host_gpu/renderer/image/image.h | sed -n '65,140p' rg -n -F -e 'class MemoryTracker' -e 'ForEachUploadRange' -e 'MarkGpuWritten' -e 'ForEachImageWithAddress' src/graphics/host_gpu cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '300,422p;600,650p' cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '2000,2080p' ``` Repository: KytyPS5/KytyPS5 Length of output: 16200 --- Script executed: ```bash cat -n src/graphics/host_gpu/memoryTracker.h | sed -n '1,190p' cat -n src/graphics/host_gpu/memoryTracker.cpp | sed -n '1,230p' cat -n src/graphics/host_gpu/renderer/cache/textureCache.h | sed -n '165,225p' cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1460,1500p' ``` Repository: KytyPS5/KytyPS5 Length of output: 14792 --- Script executed: ```bash rg -n -F -e 'TRACKER_PAGE_SIZE' -e 'ForEachModifiedRange' -e 'ChangeState' src/graphics/host_gpu/regionManager.h cat -n src/graphics/host_gpu/regionManager.h | sed -n '1,245p' ``` Repository: KytyPS5/KytyPS5 Length of output: 6845 --- Script executed: ```bash rg -n -F -e 'TRACKER_PAGE_SIZE' -e 'TRACKER_PAGE_BITS' src/graphics/host_gpu/regionDefinitions.h src/graphics/host_gpu/pageManager.h ``` Repository: KytyPS5/KytyPS5 Length of output: 384 --- </dd> </dl> </details> **Synchronize the image-backed prefix when the tail is GPU-modified.** A GPU-modified tail sets `written_past_read`, which allows the streaming shortcut to return stale guest bytes for the prefix. Synchronize the prefix while preserving the newer buffer tail. The tail regression currently discards the prefix result; check its contents too. <!-- fingerprinting:phantom:poseidon:wombat61 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:3970617393f264ad8f38bb3c --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-11 15:30 UTC · original · reviewed

Actionable comments posted: 1

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between ac49a8dec0 and 78e7ab5194.

Files selected for processing: 2

  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • tests/ShaderRecompilerComputeTests.cpp

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

**@⁠coderabbitai[bot]** on GitHub · 2026-11-11 15:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#pullrequestreview-5861188602) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 1** <h6> <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <br> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> <br> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/bc934ef03410b760fbf8e49db1d79485e7e5f887/.coderabbit.yaml>) - **Commit**: [bc934ef](<https://github.com/KytyPS5/KytyPS5/commit/bc934ef03410b760fbf8e49db1d79485e7e5f887>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `f023a490-643a-44f4-b1fa-4378631e4f77` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> <br> Reviewing files that changed from the base of the PR and between ac49a8dec0ab24ac19aa9e7412bcccb5aeec9ee2 and 78e7ab51940aca11e10648ee07e61c8d94eef7e2. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 2</summary> <dl> <dd> <br> * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. </dd> </dl> </details> </h6> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=216f8037-b8be-4fb3-b7f9-0787c2c87144 attempt=167aabf0-941e-44bb-8e3d-bd54951c9289 batch=1/1 -->
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-11 15:30 UTC · original
On src/graphics/host_gpu/renderer/cache/bufferCache.cpp line 526 (outdated):

@@ -507,12 +510,20 @@ std::pair<Buffer*, uint64_t> BufferCache::ObtainBuffer(uint64_t vaddr, uint64_t
 		}
 	}
 
-	if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, size)) {
-		id = FindBuffer(vaddr, size);
+	auto end = vaddr + size;
+	if (image) {
+		std::scoped_lock lock {m_texture_cache.m_lock};
+		const auto&      range = m_texture_cache.m_slot_images[image].info.data;
+		if (range.address == vaddr) {
+			end = std::max(end, range.End());
+		}
+	}
+	if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, end - vaddr)) {
+		id = FindBuffer(vaddr, end - vaddr);
 	}
 	auto& buffer = m_slot_buffers[id];
 	TouchBuffer(buffer);
-	(void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer);
+	(void)SynchronizeBuffer(buffer, vaddr, size, is_written, image);

Right. A formatted read at the base of a larger image got a buffer that spans the image and downloaded the whole image into it, but SynchronizeBuffer walked only the read's own range, so the image's other pages stayed CPU-modified in the tracker and a later read there returned the stale guest bytes.

ac49a8d: ObtainBuffer synchronizes the range it sized the buffer for (end - vaddr). The two differ only for a read with is_texel_buffer that is not written and starts at the base of a larger image it found. After such a read the tracker is now in the same state as after a read of the whole image on main: no CPU-modified page in the image's range. Guest memory itself is not written in either case; this PR does not change that.

2082a39 adds two checks to CheckSmallFormattedImageSync: a plain 16 KiB read of the second half of a 32 KiB image, once after a formatted read of the whole image (control) and once after a 16 KiB formatted read at its base. On c56c436 the second fails with read behind a partial formatted read: word 0 expected 0x71001000, got 0xdeadbeef; with ac49a8d both pass, and the full shader_recompiler_compute_tests run has the same 22 failed checks as before (RX 9070 XT, local harness changes as in the description).

**@⁠Nawid3333** on GitHub · 2026-11-11 15:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4539816125) On `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` line 526 (outdated): ```diff @@ -507,12 +510,20 @@ std::pair<Buffer*, uint64_t> BufferCache::ObtainBuffer(uint64_t vaddr, uint64_t } } - if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, size)) { - id = FindBuffer(vaddr, size); + auto end = vaddr + size; + if (image) { + std::scoped_lock lock {m_texture_cache.m_lock}; + const auto& range = m_texture_cache.m_slot_images[image].info.data; + if (range.address == vaddr) { + end = std::max(end, range.End()); + } + } + if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, end - vaddr)) { + id = FindBuffer(vaddr, end - vaddr); } auto& buffer = m_slot_buffers[id]; TouchBuffer(buffer); - (void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer); + (void)SynchronizeBuffer(buffer, vaddr, size, is_written, image); ``` Right. A formatted read at the base of a larger image got a buffer that spans the image and downloaded the whole image into it, but `SynchronizeBuffer` walked only the read's own range, so the image's other pages stayed CPU-modified in the tracker and a later read there returned the stale guest bytes. ac49a8d: `ObtainBuffer` synchronizes the range it sized the buffer for (`end - vaddr`). The two differ only for a read with `is_texel_buffer` that is not written and starts at the base of a larger image it found. After such a read the tracker is now in the same state as after a read of the whole image on main: no CPU-modified page in the image's range. Guest memory itself is not written in either case; this PR does not change that. 2082a39 adds two checks to `CheckSmallFormattedImageSync`: a plain 16 KiB read of the second half of a 32 KiB image, once after a formatted read of the whole image (control) and once after a 16 KiB formatted read at its base. On c56c436 the second fails with `read behind a partial formatted read: word 0 expected 0x71001000, got 0xdeadbeef`; with ac49a8d both pass, and the full `shader_recompiler_compute_tests` run has the same 22 failed checks as before (RX 9070 XT, local harness changes as in the description).
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-11 15:32 UTC · original
On src/graphics/host_gpu/renderer/cache/bufferCache.cpp line 526 (outdated):

@@ -507,12 +510,20 @@ std::pair<Buffer*, uint64_t> BufferCache::ObtainBuffer(uint64_t vaddr, uint64_t
 		}
 	}
 
-	if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, size)) {
-		id = FindBuffer(vaddr, size);
+	auto end = vaddr + size;
+	if (image) {
+		std::scoped_lock lock {m_texture_cache.m_lock};
+		const auto&      range = m_texture_cache.m_slot_images[image].info.data;
+		if (range.address == vaddr) {
+			end = std::max(end, range.End());
+		}
+	}
+	if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, end - vaddr)) {
+		id = FindBuffer(vaddr, end - vaddr);
 	}
 	auto& buffer = m_slot_buffers[id];
 	TouchBuffer(buffer);
-	(void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer);
+	(void)SynchronizeBuffer(buffer, vaddr, size, is_written, image);
Analysis chain

Script executed:

#!/bin/bash
set -u
echo '=== Current revision ==='
git rev-parse HEAD
echo '=== Source outlines ==='
ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --match 'SynchronizeBuffer|ObtainBuffer|RunGarbageCollector' --view expanded
ast-grep outline src/graphics/host_gpu/renderer/cache/textureCache.cpp --match 'SynchronizeBufferFromImage|DownloadImage|InvalidateMemoryFromGPU' --view expanded
ast-grep outline src/graphics/host_gpu/memoryTracker.h --match 'ForEachUploadRange' --view expanded
ast-grep outline tests/ShaderRecompilerComputeTests.cpp --match 'CheckSmallFormattedImageSync' --view expanded
echo '=== Relevant synchronization and tracker implementations ==='
rg -n -A75 -B3 'BufferCache::SynchronizeBufferFromImage\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp
rg -n -A80 -B3 'TextureCache::DownloadImage\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp
rg -n -A75 -B3 'ForEachUploadRange\s*\(' src/graphics/host_gpu/memoryTracker.h src/graphics/host_gpu/memoryTracker.cpp
rg -n -A60 -B3 'BufferCache::ObtainBuffer\s*\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
echo '=== Regression-test coverage ==='
rg -n -C8 'read behind a partial formatted read|read behind a full formatted read|CheckSmallFormattedImageSync|tail.write|tail write' tests/ShaderRecompilerComputeTests.cpp

Length of output: 22680


Script executed:

#!/bin/bash
echo '=== Formatted image synchronization regression ==='
cat -n tests/ShaderRecompilerComputeTests.cpp | sed -n '20149,20375p'
echo '=== Image invalidation ==='
cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1835,1895p'
echo '=== Image ownership and invalidation definitions ==='
ast-grep outline src/graphics/host_gpu/renderer/image/image.h --items all --match 'SafeToDownload|IsBufferModified|MarkGpuModified|MarkCpuDirty' --view expanded
rg -n -C8 'SafeToDownload\s*\(|IsBufferModified\s*\(|MarkGpuModified\s*\(|MarkCpuDirty\s*\(' src/graphics/host_gpu/renderer/image/image.h src/graphics/host_gpu/renderer/cache/textureCache.cpp
echo '=== Tracker dirty-range behavior ==='
ast-grep outline src/graphics/host_gpu/regionManager.h --items all --match 'ForEachModifiedRange|ChangeState' --view expanded
rg -n -A65 -B5 'ForEachModifiedRange\s*\(' src/graphics/host_gpu/regionManager.h

Length of output: 53618


@Nawid3333 Thanks. The expanded synchronization range addresses the CPU-dirty tail in the reported read test.

Verification is inconclusive for ownership after eviction. The buffer-write test writes the tail before the partial formatted read. It does not cover a write at the image base that invalidates the image after the read. The image download also does not mark the transferred bytes GPU-dirty.

Please test a partial formatted read, followed by a buffer write at the image base, buffer eviction, and a read of the untouched tail. Compare the result with the full-read control. I did not run the tests locally.


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

Thank you for using CodeRabbit!

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-11 15:32 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4539836615) On `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` line 526 (outdated): ```diff @@ -507,12 +510,20 @@ std::pair<Buffer*, uint64_t> BufferCache::ObtainBuffer(uint64_t vaddr, uint64_t } } - if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, size)) { - id = FindBuffer(vaddr, size); + auto end = vaddr + size; + if (image) { + std::scoped_lock lock {m_texture_cache.m_lock}; + const auto& range = m_texture_cache.m_slot_images[image].info.data; + if (range.address == vaddr) { + end = std::max(end, range.End()); + } + } + if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, end - vaddr)) { + id = FindBuffer(vaddr, end - vaddr); } auto& buffer = m_slot_buffers[id]; TouchBuffer(buffer); - (void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer); + (void)SynchronizeBuffer(buffer, vaddr, size, is_written, image); ``` <!-- coderabbit-ai-generated:v1 --> <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash set -u echo '=== Current revision ===' git rev-parse HEAD echo '=== Source outlines ===' ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --match 'SynchronizeBuffer|ObtainBuffer|RunGarbageCollector' --view expanded ast-grep outline src/graphics/host_gpu/renderer/cache/textureCache.cpp --match 'SynchronizeBufferFromImage|DownloadImage|InvalidateMemoryFromGPU' --view expanded ast-grep outline src/graphics/host_gpu/memoryTracker.h --match 'ForEachUploadRange' --view expanded ast-grep outline tests/ShaderRecompilerComputeTests.cpp --match 'CheckSmallFormattedImageSync' --view expanded echo '=== Relevant synchronization and tracker implementations ===' rg -n -A75 -B3 'BufferCache::SynchronizeBufferFromImage\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -A80 -B3 'TextureCache::DownloadImage\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -A75 -B3 'ForEachUploadRange\s*\(' src/graphics/host_gpu/memoryTracker.h src/graphics/host_gpu/memoryTracker.cpp rg -n -A60 -B3 'BufferCache::ObtainBuffer\s*\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp echo '=== Regression-test coverage ===' rg -n -C8 'read behind a partial formatted read|read behind a full formatted read|CheckSmallFormattedImageSync|tail.write|tail write' tests/ShaderRecompilerComputeTests.cpp ``` Length of output: 22680 --- Script executed: ```shell #!/bin/bash echo '=== Formatted image synchronization regression ===' cat -n tests/ShaderRecompilerComputeTests.cpp | sed -n '20149,20375p' echo '=== Image invalidation ===' cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1835,1895p' echo '=== Image ownership and invalidation definitions ===' ast-grep outline src/graphics/host_gpu/renderer/image/image.h --items all --match 'SafeToDownload|IsBufferModified|MarkGpuModified|MarkCpuDirty' --view expanded rg -n -C8 'SafeToDownload\s*\(|IsBufferModified\s*\(|MarkGpuModified\s*\(|MarkCpuDirty\s*\(' src/graphics/host_gpu/renderer/image/image.h src/graphics/host_gpu/renderer/cache/textureCache.cpp echo '=== Tracker dirty-range behavior ===' ast-grep outline src/graphics/host_gpu/regionManager.h --items all --match 'ForEachModifiedRange|ChangeState' --view expanded rg -n -A65 -B5 'ForEachModifiedRange\s*\(' src/graphics/host_gpu/regionManager.h ``` Length of output: 53618 --- </dd> </dl> </details> `@Nawid3333` Thanks. The expanded synchronization range addresses the CPU-dirty tail in the reported read test. **Verification is inconclusive for ownership after eviction.** The buffer-write test writes the tail *before* the partial formatted read. It does not cover a write at the image base that invalidates the image after the read. The image download also does not mark the transferred bytes GPU-dirty. Please test a partial formatted read, followed by a buffer write at the image base, buffer eviction, and a read of the untouched tail. Compare the result with the full-read control. I did not run the tests locally. --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=A%20small%20formatted%20read%20can%20transfer%20a%20whole%20image%2C%20leaving%20later%20pages%20marked%20CPU-dirty%20and%20risking%20stale%20data.%20%40coderabbitai%20caught%20the%20tracking%20gap%E2%80%94try%20it%20on%20your%20next%20PR%20%F0%9F%94%8D%E2%9C%85&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2193%23discussion_r4538589729)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
@ -515,3 +531,3 @@
auto& buffer = m_slot_buffers[id];
TouchBuffer(buffer);
(void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer);
(void)SynchronizeBuffer(buffer, vaddr, end - vaddr, is_written, image);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-11 15:35 UTC · original

Analysis chain

Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- Current revision ---'
git rev-parse HEAD
printf '%s\n' '--- Relevant source outlines ---'
ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --match 'ObtainBuffer|SynchronizeBuffer'
ast-grep outline src/graphics/host_gpu/renderer/cache/textureCache.cpp --match 'SynchronizeBufferFromImage|InvalidateMemoryFromGPU|FindImageFromRange'
ast-grep outline tests/ShaderRecompilerComputeTests.cpp --items all --match 'CheckSmallFormattedImageSync'
printf '%s\n' '--- Relevant code locations ---'
rg -n -C 4 'written_past_read|SynchronizeBufferFromImage\(|InvalidateMemoryFromGPU\(|buffer write behind a partial formatted read|CheckSmallFormattedImageSync' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.cpp tests/ShaderRecompilerComputeTests.cpp
printf '%s\n' '--- Image synchronization and invalidation ---'
python - <<'PY'
from pathlib import Path
p = Path("src/graphics/host_gpu/renderer/cache/textureCache.cpp")
lines = p.read_text().splitlines()
for name in ("BufferCache::SynchronizeBufferFromImage(", "TextureCache::InvalidateMemoryFromGPU("):
    for i, line in enumerate(lines):
        if name in line:
            print(f"\n--- {name} ---")
            for j in range(max(0, i-3), min(len(lines), i+65)):
                print(f"{j+1:6} {lines[j]}")
            break
p = Path("tests/ShaderRecompilerComputeTests.cpp")
lines = p.read_text().splitlines()
for i, line in enumerate(lines):
    if "buffer write behind a partial formatted read" in line:
        print("\n--- Buffer-write regression test ---")
        for j in range(max(0, i-80), min(len(lines), i+20)):
            print(f"{j+1:6} {lines[j]}")
        break
PY

Length of output: 35794


@Nawid3333 Thanks for the detailed analysis and the regression test. I checked the guard and test code. The guard avoids extending the range when it detects a GPU-modified tail, and the test checks that the tail is preserved. I did not run the GPU test.

The fallback retains limitations: the streaming path can return stale guest bytes for the base read, which the new tail check does not inspect. If streaming is unavailable and an existing buffer covers a downloadable image, synchronization can still overwrite the tail. I understand that broader overlap handling is outside this PR.

The reported game captures also support treating redundant-download tracking as separate work, though they do not measure workloads that encounter GPU-written images. Would you like follow-up issues for overlap handling and redundant downloads?


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

Thank you for using CodeRabbit!

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-11 15:35 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4539873597) <!-- coderabbit-ai-generated:v1 --> <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash set -u printf '%s\n' '--- Current revision ---' git rev-parse HEAD printf '%s\n' '--- Relevant source outlines ---' ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --match 'ObtainBuffer|SynchronizeBuffer' ast-grep outline src/graphics/host_gpu/renderer/cache/textureCache.cpp --match 'SynchronizeBufferFromImage|InvalidateMemoryFromGPU|FindImageFromRange' ast-grep outline tests/ShaderRecompilerComputeTests.cpp --items all --match 'CheckSmallFormattedImageSync' printf '%s\n' '--- Relevant code locations ---' rg -n -C 4 'written_past_read|SynchronizeBufferFromImage\(|InvalidateMemoryFromGPU\(|buffer write behind a partial formatted read|CheckSmallFormattedImageSync' src/graphics/host_gpu/renderer/cache/bufferCache.cpp src/graphics/host_gpu/renderer/cache/textureCache.cpp tests/ShaderRecompilerComputeTests.cpp printf '%s\n' '--- Image synchronization and invalidation ---' python - <<'PY' from pathlib import Path p = Path("src/graphics/host_gpu/renderer/cache/textureCache.cpp") lines = p.read_text().splitlines() for name in ("BufferCache::SynchronizeBufferFromImage(", "TextureCache::InvalidateMemoryFromGPU("): for i, line in enumerate(lines): if name in line: print(f"\n--- {name} ---") for j in range(max(0, i-3), min(len(lines), i+65)): print(f"{j+1:6} {lines[j]}") break p = Path("tests/ShaderRecompilerComputeTests.cpp") lines = p.read_text().splitlines() for i, line in enumerate(lines): if "buffer write behind a partial formatted read" in line: print("\n--- Buffer-write regression test ---") for j in range(max(0, i-80), min(len(lines), i+20)): print(f"{j+1:6} {lines[j]}") break PY ``` Length of output: 35794 --- </dd> </dl> </details> `@Nawid3333` Thanks for the detailed analysis and the regression test. I checked the guard and test code. The guard avoids extending the range when it detects a GPU-modified tail, and the test checks that the tail is preserved. I did not run the GPU test. The fallback retains limitations: the streaming path can return stale guest bytes for the base read, which the new tail check does not inspect. If streaming is unavailable and an existing buffer covers a downloadable image, synchronization can still overwrite the tail. I understand that broader overlap handling is outside this PR. The reported game captures also support treating redundant-download tracking as separate work, though they do not measure workloads that encounter GPU-written images. Would you like follow-up issues for overlap handling and redundant downloads? --- <!-- This is an auto-generated comment: tweet message by coderabbit.ai --> If you found this review helpful, would you consider giving us a shout-out on [X](https://twitter.com/intent/tweet?related=CodeRabbitAI&text=A%204-byte%20read%20can%20trigger%20a%2064%20MiB%20image%20download%2C%20while%20overlapping%20buffer%20writes%20risk%20being%20overwritten.%20%40coderabbitai%20catches%20performance%20and%20data-integrity%20pitfalls%E2%80%94try%20it%20on%20your%20next%20PR!%20%F0%9F%9A%80&url=https%3A%2F%2Fgithub.com%2FKytyPS5%2FKytyPS5%2Fpull%2F2193%23discussion_r4539158307)? Thank you for using CodeRabbit! <!-- end of auto-generated comment: tweet message by coderabbit.ai --> <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
@ -486,3 +502,3 @@
if (!is_written && size <= CACHING_PAGESIZE &&
!m_memory_tracker.IsRegionGpuModified(vaddr, size) &&
m_memory_tracker.IsRegionCpuModified(vaddr, size)) {
m_memory_tracker.IsRegionCpuModified(vaddr, size) && (!image || written_past_read)) {
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-11 15:53 UTC · original

In that case the read is handled as on main, stale prefix included: main's small read takes the same shortcut there. This PR leaves it at that on purpose, for two reasons:

  • The tracker cannot tell which data is newer. An image write marks no buffer page GPU-modified, so a GPU-modified page behind the read only says that a buffer write happened at some point, not that it came after the image's last write. Downloading the image first and putting the buffer bytes back on top would be wrong whenever the image was written later.
  • SynchronizeBufferFromImage cannot download part of a level: when mip 0 does not fit the buffer, copy_size stays 0 and it returns false. Syncing only the prefix would need a partial-level download in DownloadImage.

Both lead back to InvalidateMemoryFromGPU marking only images that start at the written address. Once a buffer write anywhere inside an image marks it, the image is no longer safe to download, FindImageFromRange skips it, and this case no longer exists. That is a separate change, because it decides when images are refreshed from buffer writes in every game.

The tail check leaves the prefix unchecked for the same reason: asserting the stale prefix would pin main's behaviour, and asserting the image's words would fail on main and on this PR alike.

**@⁠Nawid3333** on GitHub · 2026-11-11 15:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4540072247) In that case the read is handled as on main, stale prefix included: main's small read takes the same shortcut there. This PR leaves it at that on purpose, for two reasons: - The tracker cannot tell which data is newer. An image write marks no buffer page GPU-modified, so a GPU-modified page behind the read only says that a buffer write happened at some point, not that it came after the image's last write. Downloading the image first and putting the buffer bytes back on top would be wrong whenever the image was written later. - `SynchronizeBufferFromImage` cannot download part of a level: when mip 0 does not fit the buffer, `copy_size` stays 0 and it returns false. Syncing only the prefix would need a partial-level download in `DownloadImage`. Both lead back to `InvalidateMemoryFromGPU` marking only images that start at the written address. Once a buffer write anywhere inside an image marks it, the image is no longer safe to download, `FindImageFromRange` skips it, and this case no longer exists. That is a separate change, because it decides when images are refreshed from buffer writes in every game. The tail check leaves the prefix unchecked for the same reason: asserting the stale prefix would pin main's behaviour, and asserting the image's words would fail on main and on this PR alike.
Author
Owner

@⁠Nawid3333 on GitHub · 2026-11-11 15:54 UTC · original
On src/graphics/host_gpu/renderer/cache/bufferCache.cpp line 526 (outdated):

@@ -507,12 +510,20 @@ std::pair<Buffer*, uint64_t> BufferCache::ObtainBuffer(uint64_t vaddr, uint64_t
 		}
 	}
 
-	if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, size)) {
-		id = FindBuffer(vaddr, size);
+	auto end = vaddr + size;
+	if (image) {
+		std::scoped_lock lock {m_texture_cache.m_lock};
+		const auto&      range = m_texture_cache.m_slot_images[image].info.data;
+		if (range.address == vaddr) {
+			end = std::max(end, range.End());
+		}
+	}
+	if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, end - vaddr)) {
+		id = FindBuffer(vaddr, end - vaddr);
 	}
 	auto& buffer = m_slot_buffers[id];
 	TouchBuffer(buffer);
-	(void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer);
+	(void)SynchronizeBuffer(buffer, vaddr, size, is_written, image);

That sequence ends the same way after a partial read on this branch and after a whole-image read on main, from the code (not run): neither marks the downloaded bytes GPU-modified, and RunGarbageCollector deletes a buffer without GPU-modified pages after MarkRegionAsCpuModified, without saving it. The write at the image base then makes the image unsafe to download, so the next read of the tail uploads guest memory in both cases. A test of it would compare two equal outcomes, so I have not added one.

Making the cache own downloaded image bytes, so eviction writes them back, is a change for every image download, not one for this PR.

**@⁠Nawid3333** on GitHub · 2026-11-11 15:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4540082178) On `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` line 526 (outdated): ```diff @@ -507,12 +510,20 @@ std::pair<Buffer*, uint64_t> BufferCache::ObtainBuffer(uint64_t vaddr, uint64_t } } - if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, size)) { - id = FindBuffer(vaddr, size); + auto end = vaddr + size; + if (image) { + std::scoped_lock lock {m_texture_cache.m_lock}; + const auto& range = m_texture_cache.m_slot_images[image].info.data; + if (range.address == vaddr) { + end = std::max(end, range.End()); + } + } + if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, end - vaddr)) { + id = FindBuffer(vaddr, end - vaddr); } auto& buffer = m_slot_buffers[id]; TouchBuffer(buffer); - (void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer); + (void)SynchronizeBuffer(buffer, vaddr, size, is_written, image); ``` That sequence ends the same way after a partial read on this branch and after a whole-image read on main, from the code (not run): neither marks the downloaded bytes GPU-modified, and `RunGarbageCollector` deletes a buffer without GPU-modified pages after `MarkRegionAsCpuModified`, without saving it. The write at the image base then makes the image unsafe to download, so the next read of the tail uploads guest memory in both cases. A test of it would compare two equal outcomes, so I have not added one. Making the cache own downloaded image bytes, so eviction writes them back, is a change for every image download, not one for this PR.
@ -486,3 +502,3 @@
if (!is_written && size <= CACHING_PAGESIZE &&
!m_memory_tracker.IsRegionGpuModified(vaddr, size) &&
m_memory_tracker.IsRegionCpuModified(vaddr, size)) {
m_memory_tracker.IsRegionCpuModified(vaddr, size) && (!image || written_past_read)) {
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-11 15:54 UTC · original

Analysis chain

Script executed:

#!/bin/bash
set -u
printf '%s\n' '=== Current revision ==='
git rev-parse HEAD
printf '%s\n' '=== Relevant outlines ==='
ast-grep outline src/graphics/host_gpu/renderer/cache/textureCache.cpp --items all --match 'SynchronizeBufferFromImage|InvalidateMemoryFromGPU|FindImageFromRange|ForEachImageWithAddress' 2>&1
ast-grep outline src/graphics/host_gpu/renderer/image/image.h --items all --match 'SafeToDownload|MarkGpuWritten' 2>&1
printf '%s\n' '=== Image synchronization and invalidation ==='
rg -n -C 18 'BufferCache::SynchronizeBufferFromImage|TextureCache::InvalidateMemoryFromGPU|TextureCache::FindImageFromRange' src/graphics/host_gpu/renderer/cache/textureCache.cpp
rg -n -C 8 'SafeToDownload|MarkGpuWritten|ForEachImageWithAddress' src/graphics/host_gpu/renderer/image/image.h src/graphics/host_gpu/renderer/cache/textureCache.h
printf '%s\n' '=== Tail regression case ==='
rg -n -C 15 'written_tail_image' tests/ShaderRecompilerComputeTests.cpp
printf '%s\n' '=== Base ObtainBuffer ==='
git show bc934ef03410b760fbf8e49db1d79485e7e5f887:src/graphics/host_gpu/renderer/cache/bufferCache.cpp | awk '/std::pair<Buffer\*, uint64_t> BufferCache::ObtainBuffer\(/ {show=1} show {print} show && /^}/ {exit}'

Length of output: 19600


Script executed:

#!/bin/bash
printf '%s\n' '=== Complete image synchronization bounds ==='
cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1744,1805p'
printf '%s\n' '=== Image write tracking ==='
rg -n -C 12 'TextureCache::MarkGpuWritten\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp
printf '%s\n' '=== Buffer modification tracking definitions ==='
ast-grep outline src/graphics/host_gpu/memoryTracker.h --items all --match 'IsRegionGpuModified|MarkRegionAsGpuModified|ForEachUploadRange' 2>&1
rg -n -C 6 'IsRegionGpuModified\s*\(|MarkRegionAsGpuModified\s*\(' src/graphics/host_gpu/memoryTracker.h src/graphics/host_gpu/memoryTracker.cpp

Length of output: 8114


@Nawid3333 Thanks for the explanation. I withdraw my request for this PR.

The baseline permits the same streaming shortcut, and SynchronizeBufferFromImage cannot copy a partial mip level. My suggestion also assumed the buffer tail was newer than the image without establishing that order.

The stale-prefix case remains an existing limitation. Would you like me to open a follow-up issue for overlapping image invalidation and the stale read?

Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-11 15:54 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4540089310) <!-- coderabbit-ai-generated:v1 --> <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash set -u printf '%s\n' '=== Current revision ===' git rev-parse HEAD printf '%s\n' '=== Relevant outlines ===' ast-grep outline src/graphics/host_gpu/renderer/cache/textureCache.cpp --items all --match 'SynchronizeBufferFromImage|InvalidateMemoryFromGPU|FindImageFromRange|ForEachImageWithAddress' 2>&1 ast-grep outline src/graphics/host_gpu/renderer/image/image.h --items all --match 'SafeToDownload|MarkGpuWritten' 2>&1 printf '%s\n' '=== Image synchronization and invalidation ===' rg -n -C 18 'BufferCache::SynchronizeBufferFromImage|TextureCache::InvalidateMemoryFromGPU|TextureCache::FindImageFromRange' src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -C 8 'SafeToDownload|MarkGpuWritten|ForEachImageWithAddress' src/graphics/host_gpu/renderer/image/image.h src/graphics/host_gpu/renderer/cache/textureCache.h printf '%s\n' '=== Tail regression case ===' rg -n -C 15 'written_tail_image' tests/ShaderRecompilerComputeTests.cpp printf '%s\n' '=== Base ObtainBuffer ===' git show bc934ef03410b760fbf8e49db1d79485e7e5f887:src/graphics/host_gpu/renderer/cache/bufferCache.cpp | awk '/std::pair<Buffer\*, uint64_t> BufferCache::ObtainBuffer\(/ {show=1} show {print} show && /^}/ {exit}' ``` Length of output: 19600 --- Script executed: ```shell #!/bin/bash printf '%s\n' '=== Complete image synchronization bounds ===' cat -n src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1744,1805p' printf '%s\n' '=== Image write tracking ===' rg -n -C 12 'TextureCache::MarkGpuWritten\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp printf '%s\n' '=== Buffer modification tracking definitions ===' ast-grep outline src/graphics/host_gpu/memoryTracker.h --items all --match 'IsRegionGpuModified|MarkRegionAsGpuModified|ForEachUploadRange' 2>&1 rg -n -C 6 'IsRegionGpuModified\s*\(|MarkRegionAsGpuModified\s*\(' src/graphics/host_gpu/memoryTracker.h src/graphics/host_gpu/memoryTracker.cpp ``` Length of output: 8114 --- </dd> </dl> </details> `@Nawid3333` Thanks for the explanation. I withdraw my request for this PR. The baseline permits the same streaming shortcut, and `SynchronizeBufferFromImage` cannot copy a partial mip level. My suggestion also assumed the buffer tail was newer than the image without establishing that order. The stale-prefix case remains an existing limitation. Would you like me to open a follow-up issue for overlapping image invalidation and the stale read? <!-- <review_comment_withdrawn> --> Review thread resolved. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-11-11 15:55 UTC · original
On src/graphics/host_gpu/renderer/cache/bufferCache.cpp line 526 (outdated):

@@ -507,12 +510,20 @@ std::pair<Buffer*, uint64_t> BufferCache::ObtainBuffer(uint64_t vaddr, uint64_t
 		}
 	}
 
-	if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, size)) {
-		id = FindBuffer(vaddr, size);
+	auto end = vaddr + size;
+	if (image) {
+		std::scoped_lock lock {m_texture_cache.m_lock};
+		const auto&      range = m_texture_cache.m_slot_images[image].info.data;
+		if (range.address == vaddr) {
+			end = std::max(end, range.End());
+		}
+	}
+	if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, end - vaddr)) {
+		id = FindBuffer(vaddr, end - vaddr);
 	}
 	auto& buffer = m_slot_buffers[id];
 	TouchBuffer(buffer);
-	(void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer);
+	(void)SynchronizeBuffer(buffer, vaddr, size, is_written, image);
Analysis chain

Script executed:

#!/bin/bash
set -u
echo '=== Revision and relevant outlines ==='
git rev-parse HEAD
ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --match 'SynchronizeBuffer|ObtainBuffer|RunGarbageCollector' --view expanded
ast-grep outline src/graphics/host_gpu/renderer/cache/textureCache.cpp --match 'SynchronizeBufferFromImage|DownloadImage|InvalidateMemoryFromGPU' --view expanded
ast-grep outline src/graphics/host_gpu/memoryTracker.h --match 'ForEachUploadRange' --view expanded
echo '=== Current implementations ==='
rg -n -A35 -B2 'BufferCache::SynchronizeBufferFromImage\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp
rg -n -A65 -B2 'TextureCache::DownloadImage\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp
rg -n -A30 -B2 'TextureCache::InvalidateMemoryFromGPU\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp
rg -n -A45 -B2 'ForEachUploadRange\s*\(' src/graphics/host_gpu/memoryTracker.h
rg -n -A55 -B2 'BufferCache::ObtainBuffer\s*\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
rg -n -A60 -B2 'BufferCache::RunGarbageCollector\s*\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
echo '=== Baseline implementations on main ==='
git show bc934ef03410b760fbf8e49db1d79485e7e5f887:src/graphics/host_gpu/renderer/cache/bufferCache.cpp | rg -n -A55 -B2 'BufferCache::(ObtainBuffer|SynchronizeBuffer|RunGarbageCollector)\s*\('
git show bc934ef03410b760fbf8e49db1d79485e7e5f887:src/graphics/host_gpu/renderer/cache/textureCache.cpp | rg -n -A35 -B2 'BufferCache::SynchronizeBufferFromImage\s*\('
echo '=== Regression tests ==='
rg -n -C5 'read behind a partial formatted read|read behind a full formatted read' tests/ShaderRecompilerComputeTests.cpp

Length of output: 25876


Script executed:

#!/bin/bash
set -u
echo '=== Complete baseline image transfer ==='
git show bc934ef03410b760fbf8e49db1d79485e7e5f887:src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1744,1795p'
echo '=== Baseline upload and dirty tracking ==='
git show bc934ef03410b760fbf8e49db1d79485e7e5f887:src/graphics/host_gpu/memoryTracker.h | sed -n '65,93p'
echo '=== Current dirty-byte writeback ==='
ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --match 'DownloadBufferMemory' --view expanded
cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '155,180p;681,728p'
echo '=== Tail regression setup ==='
rg -n -C7 'part_tail|large_tail|written_tail' tests/ShaderRecompilerComputeTests.cpp

Length of output: 13238


@Nawid3333 You’re right. The image download on main at bc934ef also leaves the transferred bytes without GPU-dirty tracking. I withdraw my request for an eviction test in this PR.

One detail: if the base buffer write marks the buffer GPU-dirty, normal collection skips it. Aggressive collection writes back the tracked GPU-dirty bytes, but not the untouched image tail. That does not change the comparison with main.

The expanded synchronization range addresses the original CPU-dirty tail finding. I inspected the code and test, but did not run the test.

Would you like me to open a follow-up issue for image-download ownership and eviction?

Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-11-11 15:55 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/2193#discussion_r4540103650) On `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` line 526 (outdated): ```diff @@ -507,12 +510,20 @@ std::pair<Buffer*, uint64_t> BufferCache::ObtainBuffer(uint64_t vaddr, uint64_t } } - if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, size)) { - id = FindBuffer(vaddr, size); + auto end = vaddr + size; + if (image) { + std::scoped_lock lock {m_texture_cache.m_lock}; + const auto& range = m_texture_cache.m_slot_images[image].info.data; + if (range.address == vaddr) { + end = std::max(end, range.End()); + } + } + if (IsBufferInvalid(id) || !m_slot_buffers[id].IsInBounds(vaddr, end - vaddr)) { + id = FindBuffer(vaddr, end - vaddr); } auto& buffer = m_slot_buffers[id]; TouchBuffer(buffer); - (void)SynchronizeBuffer(buffer, vaddr, size, is_written, is_texel_buffer); + (void)SynchronizeBuffer(buffer, vaddr, size, is_written, image); ``` <!-- coderabbit-ai-generated:v1 --> <details> <summary>Analysis chain</summary> <dl> <dd> <br> Script executed: ```shell #!/bin/bash set -u echo '=== Revision and relevant outlines ===' git rev-parse HEAD ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --match 'SynchronizeBuffer|ObtainBuffer|RunGarbageCollector' --view expanded ast-grep outline src/graphics/host_gpu/renderer/cache/textureCache.cpp --match 'SynchronizeBufferFromImage|DownloadImage|InvalidateMemoryFromGPU' --view expanded ast-grep outline src/graphics/host_gpu/memoryTracker.h --match 'ForEachUploadRange' --view expanded echo '=== Current implementations ===' rg -n -A35 -B2 'BufferCache::SynchronizeBufferFromImage\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -A65 -B2 'TextureCache::DownloadImage\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -A30 -B2 'TextureCache::InvalidateMemoryFromGPU\s*\(' src/graphics/host_gpu/renderer/cache/textureCache.cpp rg -n -A45 -B2 'ForEachUploadRange\s*\(' src/graphics/host_gpu/memoryTracker.h rg -n -A55 -B2 'BufferCache::ObtainBuffer\s*\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp rg -n -A60 -B2 'BufferCache::RunGarbageCollector\s*\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp echo '=== Baseline implementations on main ===' git show bc934ef03410b760fbf8e49db1d79485e7e5f887:src/graphics/host_gpu/renderer/cache/bufferCache.cpp | rg -n -A55 -B2 'BufferCache::(ObtainBuffer|SynchronizeBuffer|RunGarbageCollector)\s*\(' git show bc934ef03410b760fbf8e49db1d79485e7e5f887:src/graphics/host_gpu/renderer/cache/textureCache.cpp | rg -n -A35 -B2 'BufferCache::SynchronizeBufferFromImage\s*\(' echo '=== Regression tests ===' rg -n -C5 'read behind a partial formatted read|read behind a full formatted read' tests/ShaderRecompilerComputeTests.cpp ``` Length of output: 25876 --- Script executed: ```shell #!/bin/bash set -u echo '=== Complete baseline image transfer ===' git show bc934ef03410b760fbf8e49db1d79485e7e5f887:src/graphics/host_gpu/renderer/cache/textureCache.cpp | sed -n '1744,1795p' echo '=== Baseline upload and dirty tracking ===' git show bc934ef03410b760fbf8e49db1d79485e7e5f887:src/graphics/host_gpu/memoryTracker.h | sed -n '65,93p' echo '=== Current dirty-byte writeback ===' ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --match 'DownloadBufferMemory' --view expanded cat -n src/graphics/host_gpu/renderer/cache/bufferCache.cpp | sed -n '155,180p;681,728p' echo '=== Tail regression setup ===' rg -n -C7 'part_tail|large_tail|written_tail' tests/ShaderRecompilerComputeTests.cpp ``` Length of output: 13238 --- </dd> </dl> </details> `@Nawid3333` You’re right. The image download on main at `bc934ef` also leaves the transferred bytes without GPU-dirty tracking. I withdraw my request for an eviction test in this PR. One detail: if the base buffer write marks the buffer GPU-dirty, normal collection skips it. Aggressive collection writes back the tracked GPU-dirty bytes, but not the untouched image tail. That does not change the comparison with main. The expanded synchronization range addresses the original CPU-dirty tail finding. I inspected the code and test, but did not run the test. Would you like me to open a follow-up issue for image-download ownership and eviction? Review thread resolved. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2193/head:github-bot/gh-2193'
git switch 'github-bot/gh-2193'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2193'
git switch 'github-bot/gh-2193'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2193'
git switch 'github-bot/gh-2193'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2193'
git switch 'main'
git merge --squash 'github-bot/gh-2193'
git switch 'main'
git merge --ff-only 'github-bot/gh-2193'
git switch 'main'
git merge 'github-bot/gh-2193'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.