shader: cap loop iterations so a bad shader cannot hang the GPU #986
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!986
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/986/head"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@wuboo on GitHub · 2026-10-02 21:01 UTC · original
wuboo:pr/shader-loop-watchdog→main· +283 −7 · 4 files · 7 commits · closed without mergingProblem
A guest shader can contain a loop that does not exit when it is fed values it never sees in a correct frame: a null descriptor, a ballot that stays false, a compare-exchange that never lands. The GPU then runs that loop until the process is killed.
On Astro Bot's world scene this showed up as frames of about 50 seconds. The loops were pinned by a wave-wide
*Zerotest (fixed separately in #985) and each one ran to the iteration cap, once per vertex. At 65536 iterations that was already ~50 s/frame. A cap of 2^20 on the same shader would be about sixteen times longer, which is still a hang from the player's point of view.Current main has no
KYTY_SHADER_LOOP_LIMITand no iteration counter on emitted loops.Change
Every latch of a structured loop increments a function-scope counter. A conditional branch that already leaves that loop for its merge block is forced to take that exit once the counter reaches the cap. No new edge is added: the loop takes an exit it already had.
The same cap stops two loops that are not in the guest CFG:
The cap is on by default at 65536.
KYTY_SHADER_LOOP_LIMIToverrides it.0disables it, which is how the SPIR-V size baselines are measured (the counters add variables, loads and stores that those fixtures reject).65536 is the cap that was measured against the pinned world-scene shader. It is large next to loops that actually terminate, and small enough that a shader which hits it returns in tens of seconds rather than minutes. Raising the default to 2^20 would change the semantics less often for a genuinely long loop, and would make the failure mode we already hit much worse.
Tests
shader_cfg_tests, Release, macOS,KYTY_VS_LANE_FROM_INDEX=0: exit 0.Size baselines run with
KYTY_SHADER_LOOP_LIMIT=0and keep their previous word counts. With the limit set to 65536, the structured-loop fixture still validates and gains a function variable, and the dispatcher loop gains a third phi (opcode 245 count goes from 2 to 3).Release
kyty_emulatorfrom this branch links.Limits
The forced exit returns whatever values the existing edge produces. A loop that needed more than 65536 iterations for a correct result will stop early. Set
KYTY_SHADER_LOOP_LIMIThigher, or to 0, if a title has a legitimate loop that long.The cap is counted per back edge, not per guest instruction. Nested loops each have their own counter. The dispatcher fallback counts dispatched blocks instead of latches.
@coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original · edited 2026-10-05 23:33 UTC
📝 Walkthrough
Walkthrough
The SPIR-V emitter now applies a configurable limit to atomic retries and to structured and dispatcher loops. BDA pointer lookup checks page indexes before accessing the page table. Tests check watchdog-enabled loop output, malformed and out-of-range limits, and watchdog-disabled size baselines.
Suggested reviewers:
nmzikPriority: ⬆️ High
Change: Bug fix
Merge Risk: 🟡 Moderate · up to
fb0aeSome shaders can still run without a loop bound, and heavily contended subword stores can silently fail. These paths should be corrected before merging.
Security Architecture Review
Security architecture risk: 🟡 Moderate · up to
fb0aeThe change reduces hang and invalid-memory risks, but exhausting the retry limit can silently discard shared-memory updates while execution continues. Protection against nonterminating loops also remains incomplete.
Retained concerns
Security review details
Security Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❓ 1
❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 23.08% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 3 files. (1 skipped: 1 too large.)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
Comment
@coderabbitai helpto get the list of available commands.@ -362,0 +385,4 @@return kDefaultLimit;}return static_cast<uint32_t>(parsed);}@coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original · edited 2026-10-02 22:07 UTC
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
ShaderLoopLimit()turns invalid input into "disabled".strtoulreturns 0 for a non-numeric string such as"off"or"abc", and 0 disables the watchdog. A typo inKYTY_SHADER_LOOP_LIMITtherefore removes the GPU-hang protection without any warning.Treat input that does not parse as the default limit instead of 0.
Proposed fix
📝 Committable suggestion
✅ Addressed in commits af3d1fe to def17ab
@ -724,0 +857,4 @@state.loop_counter_variables.emplace(info.id, std::pair {counter, merge});}}}@coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original · edited 2026-10-02 21:55 UTC
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 9310
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 41978
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 41757
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 25276
Guard unconditional loop latches before branching back to the header.
When a structured loop has
node->condition == 1,ShaderCFG.cppemits an unconditional branch fromrepeattoheader.EmitBackEdgeGuardonly increments the counter.GuardLoopConditionruns only forConditionalBranch, and the counter setup excludes unconditional branches to the loop merge. Therefore, this loop has no cap-triggered exit and can execute without an emitter-enforced bound even whenKYTY_SHADER_LOOP_LIMITis nonzero. This violates the documented guarantee that bad shader data cannot hang the GPU.Suggested fix
✅ Confirmed as addressed by @wuboo
@coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original · edited 2026-10-02 21:55 UTC
On
tests/shaderCfgTests.cppline 14274 (outdated):🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 13391
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 29173
Use a portable environment helper for
KYTY_SHADER_LOOP_LIMIT.shader_cfg_testssupports Windows Clang toolchains, includingclang-cl. These unqualified calls use the POSIXsetenv, which the Windows CRT does not provide. Use a helper that calls_putenv_son Windows andsetenvelsewhere.Do not add RAII restoration of the original environment value.
mainintentionally sets the watchdog to"0"before the suite, and the test restores that same baseline for later tests.✅ Confirmed as addressed by @wuboo
@coderabbitai[bot] on GitHub · 2026-10-02 21:12 UTC · original · reviewed
Actionable comments posted: 3
🧹 Nitpick comments (1)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
a461b09e-8c1e-490a-a9d2-abd871fa3ef2📥 Commits
Reviewing files that changed from the base of the PR and between
e317465d8aand 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33.📒 Files selected for processing (4)
src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.hsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpptests/shaderCfgTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 3 remain after this review.
@ -724,0 +857,4 @@state.loop_counter_variables.emplace(info.id, std::pair {counter, merge});}}}@wuboo on GitHub · 2026-10-02 21:54 UTC · original
Partly right. Breaks to the loop merge were already capped, but a loop with an unconditional latch and no counted break (or one that only leaves via return) had no edge to force. Fixed in d0c393c5: the latch now branches to the loop merge once the back-edge count reaches the cap. A no-break fixture covers it.
@wuboo on GitHub · 2026-10-02 21:54 UTC · original
On
tests/shaderCfgTests.cppline 14274 (outdated):Fixed in def17ab4. The test sets KYTY_SHADER_LOOP_LIMIT through SetEnvForTest(), which uses _putenv_s on Windows and setenv elsewhere.
@ -362,0 +385,4 @@return kDefaultLimit;}return static_cast<uint32_t>(parsed);}@wuboo on GitHub · 2026-10-02 21:54 UTC · original
Fixed in af3d1fe2. Only a plain decimal overrides the default. An empty, non-numeric, negative or larger-than-u32 value keeps the 65536 cap, and 0 still disables it explicitly.
@wuboo on GitHub · 2026-10-02 21:54 UTC · original
Re the nitpick on asserting the structured condition: def17ab4 makes the structured-loop test count
OpUGreaterThanEqual(2: the break and the latch) andOpSelect(1). Without the latch fix the test fails.@ -724,0 +857,4 @@state.loop_counter_variables.emplace(info.id, std::pair {counter, merge});}}}@coderabbitai[bot] on GitHub · 2026-10-02 21:55 UTC · original
@wubooThanks for the clarification. My original claim was too broad: conditional breaks to the loop merge were already capped.The supplied code now registers unconditional latches and branches to the loop merge when the back-edge count reaches the cap. This addresses the missing exit for loops without a counted break. Thanks for adding the no-break fixture.
✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@coderabbitai[bot] on GitHub · 2026-10-02 21:55 UTC · original
On
tests/shaderCfgTests.cppline 14274 (outdated):@wuboo, thanks for the fix. The file now definesSetEnvForTest(), which calls_putenv_swhen_WIN32is defined andsetenvotherwise.TestNewShaderRecompilerSpirvSizeBaselinesandmaincall this helper. No baresetenvcall remains outside the helper.If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@coderabbitai[bot] on GitHub · 2026-10-02 22:04 UTC · original · reviewed
🧹 Nitpick comments (1)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
b5ae0941-6fc1-42f8-9e92-b604648d6a56📥 Commits
Reviewing files that changed from the base of the PR and between 2ec78118ddaadc17cfcb3cdda73ef55e9cc1ac33 and def17ab4a27512413f329a5dd50c4b9505dbd080.
📒 Files selected for processing (3)
src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.hsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpptests/shaderCfgTests.cpp🚧 Files skipped from review as they are similar to previous changes (3)
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 1 remain after this review.
@ -362,0 +385,4 @@return kDefaultLimit;}return static_cast<uint32_t>(parsed);}@coderabbitai[bot] on GitHub · 2026-10-02 22:07 UTC · original
@wubooThanks for the fix. Invalid non-numeric input now retains the 65,536 cap instead of disabling the watchdog. Explicit0still disables it.If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@wuboo on GitHub · 2026-10-02 22:19 UTC · original
Second round:
strtoullskips leading whitespace and accepts a sign, so+0and0parsed as 0 and turned the watchdog off. The value now has to start with a digit; otherwise the default cap stays. An explicit0still disables it.+0and0are added to the bad-value checks, and with the old parser the test fails.OpUGreaterThanEqualand oneOpSelect. The same check fails with the limit at 0.Full CPU
ctestmatches main: 34 pass. The 16 Vulkan-dependent tests can't run in my headless setup on either side.@coderabbitai[bot] on GitHub · 2026-10-02 22:26 UTC · original · reviewed
ℹ️ Review info
⚙️ Run configuration
550644da-07cc-43f9-bd14-2c2efa70062e📥 Commits
Reviewing files that changed from the base of the PR and between def17ab4a27512413f329a5dd50c4b9505dbd080 and 44a858b40407991f790381300b57bafdf62db153.
📒 Files selected for processing (2)
src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.htests/shaderCfgTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
@rohit267 on GitHub · 2026-10-05 13:16 UTC · original
Tested this on Black Myth: Wukong (PPSA23226, RTX 4070, driver 595.71) together with #985. Both are needed there: #985 alone still ends in VK_ERROR_DEVICE_LOST on the UE5 Nanite persistent-culling shader, and with both applied the game boots to its title and menu.
One bug in the forced-exit path. In
EmitStructuredTerminator, the "unconditional latch" case replacesOpBranch targetwithOpBranchConditional(over, exit, target). That is a new edge into the exit block, which the comment says it is not. If the exit block starts with anOpPhi, the phi is one incoming value short and the module fails validation:NVIDIA's compiler does not reject it.
nvgpucomp64.dlldereferences a not-found index of -1 and the process dies with an access violation inside the driver DLL, so the symptom looks like a driver crash rather than a bad module.--shader-validation truereports it immediately.Fix: do not force the exit when the exit block begins with a phi; those loops keep the conditional exit they already have. The patch is 14 lines in
spirvEmitterProgram.cpp(BlockStartsWithPhiplus one extra condition) and is attached below.Related note for tuning: with the 65536 default the Wukong boot/loading screen runs at about 1 fps; at
KYTY_SHADER_LOOP_LIMIT=4096the title screen runs at 5-6 fps and at 512 at about 8 fps. GPU timestamps show the three Nanite persistent-culling dispatches (1440 groups each) taking ~13-20 ms each at 4096 and ~2.6-3.1 ms at 512, i.e. their time scales with the cap, so their loops are still reaching the cap rather than exiting on their own, even with #985 applied.@wuboo on GitHub · 2026-10-05 13:50 UTC · original
Thanks for testing this on Wukong, and for the patch. That's a real bug: the forced exit from an unconditional latch adds an edge into the exit block, so a leading
OpPhiends up one incoming value short. NVIDIA's compiler crashing on it instead of rejecting it matches what you saw.I took your approach: loops whose exit block starts with a phi keep the exit they already have, and don't get the forced one. I considered adding a phi operand for the new edge instead, but there is no real value to supply for an edge that never carried data, so skipping is simpler and safer. Your change is in the branch with you as co-author, plus a test: an unconditional latch whose exit block reads a phi. Without the change it fails validation with exactly the 2-vs-3 error you quoted; with it, it passes. The other CPU tests are unchanged.
On the limit: 65536 is a correctness safety net, not a performance setting. If the Nanite persistent-culling loops still hit the cap at 4096 and 512 (their time scaling with the cap), they aren't exiting on their own. That looks like a separate problem, probably in how that shader's loop condition is translated, so I'd track it in its own issue rather than tune the default here. If you can share the shader hash or a dump, that would help.
@rohit267 on GitHub · 2026-10-05 15:09 UTC · original
Thanks, and thanks for the co-author credit.
Shader details for the loop-cap issue. Black Myth: Wukong (PPSA23226, v01.000.021), RTX 4070, Windows, #985 + #986 applied.
The Nanite persistent-culling compute shaders are all dispatched as 1440 groups x 64 threads (GPU time per dispatch, from Vulkan timestamp queries):
That is close to linear in the cap, so every group runs to the cap.
539ebc039e965dfd in Kyty's log: code_words=4448, 3047 decoded instructions, CFG 132 blocks / 3 loops / 3 back edges (157 blocks after structurizing), 283072 SPIR-V words, wave64, 64 S_CBRANCH_EXECZ.
What I saw in the decoded RDNA2 listing of 539ebc039e965dfd:
s_branch 0x100at 0x4198, withs_endpgmat 0x419c. The only branches to the endpgm ares_cbranch_vccnzat 0x2c0 and 0x324.v36 == 0 && s58 <= LDS[0]. LDS[0] holds the old value returned bybuffer_atomic_add v1(=1), ... offset:4 glc, a claim counter that lane 0 writes with exec=1.buffer_atomic_add ... 16, offset:12) returns an index >= s60.buffer_store_dwordx2 -1,-1 glcat 0x417c.I deleted the game and my dumps, so I can't attadentifies the shader in any Wukong run. Happy toopen this as its own issue.
@wuboo on GitHub · 2026-10-05 15:35 UTC · original
Thanks, that's a very useful breakdown. Yes, please open it as its own issue with these numbers and the listing notes; it's a separate problem from this PR.
From your description, the loop only leaves through the two
s_cbranch_vccnzexits, and both depend on the claim counters at offsets 4 and 12 crossing the capacities in the constant buffer. Every group running to the cap suggests those counters never reach the exit condition on our side. Three things I'd check first, none of them verified yet:-1slot markers) are reset before each dispatch. If the reset is a CP fill/DMA or a small compute pass that we skip or reorder, the shader starts from a state where the exit can't be reached. The0x23b2you saw in the CPU-side view may be stale for the same reason.buffer_atomic_add ... glcreturn value written by lane 0 withexec=1reachesLDS[0]and the other lanes on a wave64 shader. We recently found a DPP lane op that silently degraded to identity, so a cross-lane path here is worth a targeted test.If you can dump the counter values at offsets 4 and 12 right before and after one of these dispatches, that would show which of the three it is.
@rohit267 on GitHub · 2026-10-05 15:46 UTC · original
Opened #1072 with the numbers and the listing notes. On the counters: I only have one before-dispatch snapshot, and it is the CPU-side view, so it may be stale. Offsets 4 and 12 read 0 and 0, offsets 16 and 20 read 0x23b2, and the slot queue started with zeros rather than 0xFFFFFFFF. I don't have after-dispatch values, and I've removed my Wukong setup, so I can't capture them now. #1072 has a short snippet that does a before/after dump; could you or someone with the game run it?
@overlordxrz-source on GitHub · 2026-10-05 22:04 UTC · original
Verified this branch locally (reviewed the diff, built and tested rather than just reading):
shader_cfg_tests: Passed (2.0s)scalar_provenance_tests+resource_tracking_tests: Passedx86_64macOS no-Qt build (CMAKE_OSX_ARCHITECTURES=x86_64, clang,KYTY_BUILD_LAUNCHER=OFF), Release — links clean (only the usual prebuilt-FFmpeg platform warnings).GPU-harness tests were not runnable here (no Vulkan loader in this environment — same pre-existing failure as on clean main).
One heads-up for landing: this branch no longer rebases cleanly onto current
main(cdb64bf).spirvEmitterMemory.cppwas refactored toConstantDeviceAddressafter this branch's base, so the BDA out-of-range-guard hunk needs a semantic re-merge (keep thein_range/out_of_rangeguard, port it onto theConstantDeviceAddresshelpers).spirvEmitterInternal.h/spirvEmitterProgram.cpp/shaderCfgTests.cpphunks are pure additions and apply cleanly.The watchdog approach (force an existing exit at 65536,
KYTY_SHADER_LOOP_LIMIToverride,0disables) looks right as a safety net for the Wukong Nanite spin in #1072 — it turns a kill-the-process hang into bounded GPU time while the real forward-progress root cause is investigated.@wuboo on GitHub · 2026-10-05 23:19 UTC · original
Thanks for checking this against current main, and for the pointer to the
spirvEmitterMemory.cpprework.I rebased the branch onto current
main(cdb64bfd). The conflict was only in the BDA page-table guard inDefineGetBdaPointer.spirvEmitterInternal.h,spirvEmitterProgram.cppandshaderCfgTests.cppapplied as plain additions. I kept the guard's semantics (in_rangeon the page index, an out-of-range page is treated as a missing page, page 0 only as a safe index for the load) and re-expressed it with the helpers that function uses on current main. Note that main no longer hasConstantDeviceAddressanywhere insrc, andDefineGetBdaPointernow usesConstantU64/ConstantU32, so the guard uses those:ULessThan(page64, ConstantU64(CACHING_NUMPAGES)), thenSelectfor the index, thenLogicalOr(base == 0, !in_range)for the fault path.Testing: the full ctest list matches a fresh build of main exactly (the same tests need a GPU and are skipped here in both runs).
shader_cfgpasses. I also checked the new tests fail without the fixes: with the emitter changes removed the watchdog test aborts, and without the phi fix spirv-val rejects the OpPhi.The Co-authored-by trailer for Rohit Mahto on the phi fix is preserved.
@coderabbitai[bot] on GitHub · 2026-10-05 23:29 UTC · original · reviewed
ℹ️ Review info
⚙️ Run configuration
6c4376a0-ed01-4cdb-b925-d610bba5cc76📥 Commits
Reviewing files that changed from the base of the PR and between 05eac940afad6c7c9794ac554ae0fdc82a5df41d and
fb0aec0bad.📒 Files selected for processing (4)
src/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.hsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterProgram.cpptests/shaderCfgTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
@overlordxrz-source on GitHub · 2026-10-06 00:32 UTC · original
Re-validated the rebased branch (
fb0aec0b, ontocdb64bf): clean x86_64 macOS no-Qt Release build,shader_cfgpasses. The rebase resolutions read right — guard semantics preserved with main'sConstantU64/ConstantU32helpers, and the phi-exit skip is the safer choice (no synthetic value to supply). Nothing further from me; good to go from the validation side.@Nmzik on GitHub · 2026-10-08 13:40 UTC · original
This is a hack!
@wuboo on GitHub · 2026-10-08 16:15 UTC · original
Agreed that a default-on cap changes shader semantics and can hide translation bugs — that is exactly what happened here: the world-scene "hang" turned out to be the split-Wave64
*Zerobug (#985), and rohit267's Nanite numbers show Wukong still hitting the cap. I'll drop this PR as is. Two smaller pieces seem worth keeping, if you agree:Longer term, a host-side timeout on command buffers with a clear device-lost report is probably the right protection. Happy to open these separately if that direction works for you.
Pull request closed