graphics: avoid unnecessary GPU drains for bool predicates #702

Closed
github-bot wants to merge 1 commit from gh-pr/702/head into gh-pr/702/base
Owner

@⁠MehmetCambaz on GitHub · 2026-09-18 16:59 UTC · original
MehmetCambaz:perf/bool-predicate-producer-sync-pr → main · +309 −3 · 6 files · 1 commits · closed without merging

Summary

SET_PREDICATION with wait semantics performed a full GPU drain before every memory-predicate read. The drain ran unconditionally, including when nothing the GPU had queued could change the predicate bytes.

This synchronizes against the actual producer instead. The predicate range is classified by resource ownership:

  • a tracked buffer producer is resolved with a download of that range;
  • image-backed bytes still require a drain, because images carry only write watchers and have no CPU read barrier;
  • with no producer, no GPU work is submitted or waited on.

It also accounts for deferred image write-backs, so guest memory is never sampled before a scheduled WriteBacking has applied its bytes.

Correctness

Image garbage collection schedules a download and defers the write-back into guest memory as a priority operation. It then frees the image, which clears its GPU-modified state immediately. Between those two points nothing reports ownership of the range, while guest memory still holds the old bytes.

The previous unconditional FlushAndWait does not close this: it submits the recorded tick and waits for the GPU, which is exactly what releases the priority runner, but it never waits for the runner itself. A deterministic regression test that holds the write-back pending fails against the old code as well.

So the write-back ranges are now tracked explicitly. A range is published before the priority operation is queued and removed only after WriteBacking has run, and the predicate path treats a pending write-back the same as a live GPU-modified image. After submitting and completing the relevant tick, it waits for the priority operations queued up to that tick — CurrentTick() - 1, the tick just completed. Waiting on CurrentTick() would be a deadlock, since that is the still-open, unsubmitted tick.

Ambiguous ownership fails closed: any image condition selects the drain.

Tests

tests/ShaderRecompilerComputeTests.cpp, registered as pm4_bool_predication_sync and pm4_predicate_writeback:

  • queued buffer producer: the predicate must observe the GPU-written value;
  • direct image producer: the predicate must drain and observe the written value;
  • no producer: the fast path must neither submit nor drain;
  • overlapping and ambiguous ownership: must resolve to the drain;
  • deferred image write-back: an image is GPU-written, its download is scheduled and the image freed, so neither ownership query reports the range. The predicate read must not complete until the deferred write-back has run.

The write-back case is deterministic rather than timing-dependent: a blocking priority operation is enqueued first, and the runner is FIFO, so the write-back is provably still pending while the predicate is read. No sleeps are involved.

Negative validation: removing the wait for pending write-backs, always selecting or never selecting the drain, and ignoring the image producer each make the matching test fail.

ctest passes 40/41. The one failure is kernel_file_system, which does not link on Windows (undefined symbol: main) on unmodified main as well; it is unrelated to this change and is addressed by #565.

Performance

Measured in a profiled Kena workload: wait-enabled bool predicates occurred about 6.6 times per frame, and predicate synchronization cost dropped from roughly 4.6 ms/frame to effectively zero. Drains that are genuinely required remained rare, and waiting for pending image write-backs did not register a measurable cost.

This is real-world validation of the change, not the correctness argument; the correctness argument is the ownership invariant and the tests above.

AI disclosure

AI assistance was used during investigation, implementation and testing. I reviewed the resulting change and validation before submitting it.

**@⁠MehmetCambaz** on GitHub · 2026-09-18 16:59 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/702) `MehmetCambaz:perf/bool-predicate-producer-sync-pr` → `main` · +309 −3 · 6 files · 1 commits · closed without merging ## Summary `SET_PREDICATION` with wait semantics performed a full GPU drain before every memory-predicate read. The drain ran unconditionally, including when nothing the GPU had queued could change the predicate bytes. This synchronizes against the actual producer instead. The predicate range is classified by resource ownership: - a tracked buffer producer is resolved with a download of that range; - image-backed bytes still require a drain, because images carry only write watchers and have no CPU read barrier; - with no producer, no GPU work is submitted or waited on. It also accounts for deferred image write-backs, so guest memory is never sampled before a scheduled `WriteBacking` has applied its bytes. ## Correctness Image garbage collection schedules a download and defers the write-back into guest memory as a priority operation. It then frees the image, which clears its GPU-modified state immediately. Between those two points nothing reports ownership of the range, while guest memory still holds the old bytes. The previous unconditional `FlushAndWait` does not close this: it submits the recorded tick and waits for the GPU, which is exactly what releases the priority runner, but it never waits for the runner itself. A deterministic regression test that holds the write-back pending fails against the old code as well. So the write-back ranges are now tracked explicitly. A range is published before the priority operation is queued and removed only after `WriteBacking` has run, and the predicate path treats a pending write-back the same as a live GPU-modified image. After submitting and completing the relevant tick, it waits for the priority operations queued up to that tick — `CurrentTick() - 1`, the tick just completed. Waiting on `CurrentTick()` would be a deadlock, since that is the still-open, unsubmitted tick. Ambiguous ownership fails closed: any image condition selects the drain. ## Tests `tests/ShaderRecompilerComputeTests.cpp`, registered as `pm4_bool_predication_sync` and `pm4_predicate_writeback`: - queued buffer producer: the predicate must observe the GPU-written value; - direct image producer: the predicate must drain and observe the written value; - no producer: the fast path must neither submit nor drain; - overlapping and ambiguous ownership: must resolve to the drain; - deferred image write-back: an image is GPU-written, its download is scheduled and the image freed, so neither ownership query reports the range. The predicate read must not complete until the deferred write-back has run. The write-back case is deterministic rather than timing-dependent: a blocking priority operation is enqueued first, and the runner is FIFO, so the write-back is provably still pending while the predicate is read. No sleeps are involved. Negative validation: removing the wait for pending write-backs, always selecting or never selecting the drain, and ignoring the image producer each make the matching test fail. `ctest` passes 40/41. The one failure is `kernel_file_system`, which does not link on Windows (`undefined symbol: main`) on unmodified `main` as well; it is unrelated to this change and is addressed by #565. ## Performance Measured in a profiled Kena workload: wait-enabled bool predicates occurred about 6.6 times per frame, and predicate synchronization cost dropped from roughly 4.6 ms/frame to effectively zero. Drains that are genuinely required remained rare, and waiting for pending image write-backs did not register a measurable cost. This is real-world validation of the change, not the correctness argument; the correctness argument is the ownership invariant and the tests above. ## AI disclosure AI assistance was used during investigation, implementation and testing. I reviewed the resulting change and validation before submitting it.
SET_PREDICATION with the wait flag drained the whole GPU before reading a
bool64 predicate from guest memory, even when no queued work could change
those bytes.

Synchronize against the producer instead. A tracked buffer write is brought
back with a download; image-backed bytes still need a drain because they have
no CPU read barrier.

Deferred image write-backs need explicit care. Garbage collection schedules an
image download and then clears the image's GPU-modified state, so between the
schedule and the priority callback nothing reports ownership of guest bytes
that are still stale. Track the scheduled ranges and keep the predicate path
waiting for those callbacks: a submit-and-wait alone never waits for the
priority runner.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:30:08 +00:00
github-bot closed this pull request 2026-11-26 09:30:08 +00:00
Author
Owner

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

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 7fdb5bff-1302-47d0-8ae2-11afddc75c0e

📥 Commits

Reviewing files that changed from the base of the PR and between 5b7d3343cf and cce148ea00.

📒 Files selected for processing (6)
  • CMakeLists.txt
  • src/graphics/guest_gpu/command_processor/commandProcessor.h
  • src/graphics/guest_gpu/graphicsRun.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.cpp
  • src/graphics/host_gpu/renderer/cache/textureCache.h
  • tests/ShaderRecompilerComputeTests.cpp

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


📝 Walkthrough

Walkthrough

The change tracks deferred image write-backs in TextureCache and exposes range-overlap checks. CommandProcessor classifies predicate synchronization as draining queued work, downloading dirty buffer data, or doing nothing. SetPredication validates the address and uses this targeted synchronization. New compute tests cover image write-back and boolean predication cases, with dedicated CTest registrations and command-line modes.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: ⚪ Minimal · up to cce14

No concrete correctness or stability issue remains; the change is ready to merge after normal checks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 4 files. (2 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main change: avoiding unnecessary GPU drains for boolean predicates. It is concise and specific.
Description check ✅ Passed The description directly explains producer-based predicate synchronization, deferred image write-backs, tests, performance results, and the unrelated test failure.
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 7.69% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 4 files. (2 skipped: 1 unsupported, 1 too large.)


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

**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 17:10 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/702#issuecomment-5733483443) <!-- 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/702#gh-light-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg" alt="Review Change Stack" width="202" height="32"></a><a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/702#gh-dark-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg" alt="Review Change Stack" width="202" height="32"></a> <!-- review_stack_entry_end --> <!-- recent_review_start --> No actionable comments were generated in the recent review. 🎉 <details> <summary>ℹ️ Recent review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Path: .coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `7fdb5bff-1302-47d0-8ae2-11afddc75c0e` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 5b7d3343cf1586e42068f0ce455ab0675ec43ada and cce148ea00cdfefae014d0a3cdb1221b5bada9b8. </details> <details> <summary>📒 Files selected for processing (6)</summary> * `CMakeLists.txt` * `src/graphics/guest_gpu/command_processor/commandProcessor.h` * `src/graphics/guest_gpu/graphicsRun.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.cpp` * `src/graphics/host_gpu/renderer/cache/textureCache.h` * `tests/ShaderRecompilerComputeTests.cpp` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> --- <!-- recent_review_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The change tracks deferred image write-backs in `TextureCache` and exposes range-overlap checks. `CommandProcessor` classifies predicate synchronization as draining queued work, downloading dirty buffer data, or doing nothing. `SetPredication` validates the address and uses this targeted synchronization. New compute tests cover image write-back and boolean predication cases, with dedicated CTest registrations and command-line modes. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"cce148ea00cdfefae014d0a3cdb1221b5bada9b8" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _⚪ Minimal_ · up to `cce14` <!-- final_review_risk_coverage:{"sourceCommitId":"cce148ea00cdfefae014d0a3cdb1221b5bada9b8","coveredCommitId":"cce148ea00cdfefae014d0a3cdb1221b5bada9b8","kind":"reviewed"} --> No concrete correctness or stability issue remains; the change is ready to merge after normal checks. <!-- final_review_risk_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 4 files. (2 skipped: 1… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Title check | ✅ Passed | The title clearly states the main change: avoiding unnecessary GPU drains for boolean predicates. It is concise and specific. | | Description check | ✅ Passed | The description directly explains producer-based predicate synchronization, deferred image write-backs, tests, performance results, and the unrelated test failure. | | 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. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 4 files. (2 skipped: 1 unsupported, 1 too large.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
Author
Owner

@⁠Nmzik on GitHub · 2026-10-21 19:41 UTC · original

Superseded by 840b9f575.

**@⁠Nmzik** on GitHub · 2026-10-21 19:41 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/702#issuecomment-6324933859) Superseded by 840b9f575.

Pull request closed

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