perf(agc): the draw pipeline retires finished commits on a reaper thread #6617
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/6617"
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?
Imported from boykopovar/AnyPS5. Originally posted by TheAggie on 2026-10-15T23:11:17Z.
What
With pipelined draws the committer is the thread the queue worker waits for. After each commit it popped the item from the pipeline's deque under the pipeline mutex, which destroyed the commit's closure right there: the decode's programs, the compiled results, the stage captures, the regions, the snapshots and the rest, twenty or more heap frees a draw, on the critical thread and with the lock held while the worker's enqueue waited for it.
DrawPipeline::runmoves the finished item out under the lock and hands it toretire, which queues it for a reaper thread. The reaper destroys batches: it is woken only when 64 items have gathered, and otherwise checks every 2 ms, so the committer pays one deque move and no wake per draw. (Waking it per commit cost more than it saved.)APS5_NO_COMMIT_REAPER=1destroys the item in place as before, though after the lock.ShaderMemoryreturns its pages to the destroying thread's pool (as it already did on the committer), and the rest are plain frees.Tested
Windows 11, NVIDIA GeForce RTX 5070 Ti, MinGW-w64 GCC 15.2.0, on main
ce991f1ec.ctest: 1278 of 1297 pass, 14 skipped.guest_call_trace_abortandwindows_backtrace_reportfail, and fail the same way on plain main here;agc_driver_prepared_graphics_prebuild_0/_1andundeliverable_host_exceptionfail under my test runner because it skips their environment changes and pass pattern, and pass run with those.agc_driver_gpu_indirect_arguments_misaligned_writer_ahead, new on this main, does not compile with MinGW (alignas(65536)exceeds the object file maximum of 8192) and was left out of the run. The pipelined, draw-cache and PM4 tests (13) also pass withAPS5_NO_COMMIT_REAPER=1.APS5_BATCH_CAP=256, audio muted, same build with and without this change, two alternating runs each: audio produced in the heavy intro scenes 52-53% of real time without, 55-56% with (the base here also carries #4943, #5609, #6312, #6538, #6539 and #6566, which make its draws hit the cache; the change itself is independent of them).Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-16T01:55:57Z.
Review: COMMENTED
On Linux this crashes draw tests at process exit. Each test prints its final success line, then dies with
double free or corruption (out)or a SegFault.APS5_NO_COMMIT_REAPER=1makes the crash go away.Machine: NVIDIA GeForce RTX 3070, driver 595.99.02, Vulkan 1.4.329, Ubuntu 26.04 (kernel 7.0.0-38), i7-8700. GCC 15.2 (glibc), Release,
BUILD_TESTING=ON,ANYPS5_GPU="NVIDIA GeForce RTX 3070". Head74dad0097merged intomain5d9dcc42d(clean merge).main5d9dcc42dAPS5_NO_COMMIT_REAPER=1agc_driver_draw_cache_reuse_off, 20 runsagc_driver_inactive_vertex_point_size, 20 runspipelin|draw_cache|agc_driver_pm4(30 tests), 3 runsdraw_cache_reuse*)ctest -R "^agc|shader|recompiler" -j1(flip, display andlds_atomics64excluded): 7 failures, against 1 onmain. The 6 new ones are allSegFaultorSubprocess abortedat about 1.58 s:draw_cache_reuse_off,inactive_vertex_point_size,mesh_index_cache,msaa_enable_single_sample,sample_mask_drawandstencil_ref_export_unused. The remaining failure isstore_over_untracked, which fails onmaintoo (#6347).A repeated draw reused the cached draw without graphics pipeline libraries, thendouble free or corruption (out), thenSubprocess aborted. The test's own checks have already passed at that point.This is probably a lifetime problem.
reap()loops forever and nothing stops or joinsreaper.Queue0()'s pipeline is leaked on purpose, so the reaper is still running duringexit(). Whatever was retired in the last ~2 ms is then destroyed on the reaper thread while static destructors tear down the pools and caches their closures return memory to. Onmainthe closure is destroyed beforeoutstandingdrops, so nothing outlives the last drain. I did not take a backtrace. The env toggle and the timing (after the test's last line) both point there. A drain or shutdown that flushesretiredon the caller would probably fix it, as would joining the reaper.GPUs tested: NVIDIA GeForce RTX 3070, driver 595.99.02, Ubuntu 26.04
Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by fma-rc on 2026-10-16T04:17:44Z.
Review: CHANGES_REQUESTED
I measured this in Astro's Playroom's heavy gameplay scene on an RTX 5080. The base is main
5d9dcc42dwith and without this PR, hidden, with a 20 s window and two alternating rounds. Main gave 12.17 and 11.72 FPS; this PR gave 12.76 and 12.81. In the trace, queue 0 waits 4.4 µs per draw for room instead of 6.0, and the frames match main's.The exit crash jotitadev reported reproduces on AMD too. On a Radeon 680M (RADV),
agc_driver_draw_cache_reuse_offaborts withdouble free or corruption (!prev)in 5 of 10 runs with this PR. It passes 10 of 10 withAPS5_NO_COMMIT_REAPER=1, and 10 of 10 on main. My Playroom runs end with a kill, so they never reach that path.Imported from boykopovar/AnyPS5. Originally posted by parl0v on 2026-10-16T22:14:03Z.
Data point from a CPU-bound scene on Windows: RTX 3060 12 GB (NVIDIA 617.42), i5-12400F, Windows 10 19045, MinGW GCC Release. Minecraft Dungeons II (PPSA16064 01.100.100), title screen, no input, 200 s rows,
APS5_PROFILE_DRAW=1 APS5_PROFILE_GPU=1;mainbc3c0fc13vsmain+ this PR, interleaved with five other PRs in one batch, two rounds. FPS is the mean of the last 10[present]windows, GPU busy and idle gaps per frame over the last 8. This scene is CPU-bound on this machine (45-47 ms of idle gaps per frame).main74dad0097)Above
mainin both rounds and the only one of the six outside the spread: the idle gaps drop by 3-4 ms per frame with GPU busy unchanged, so the time comes off the CPU side, as you'd expect from moving the retirement off the recording thread. In earlier batches on this scene the largest single-PR gains were +1.3 to +1.6 %. 0 fatal.AI-assisted: yes (Claude Code)
Imported from boykopovar/AnyPS5. Originally posted by parl0v on 2026-10-16T22:59:02Z.
A second title for comparison, same box and build (
mainbc3c0fc13vsmain+74dad0097): Sword of the Sea (PPSA25344) title screen, 200 s rows, three rounds alternating.mainFlat here, which fits: this scene has about half the idle gaps per frame of the Minecraft Dungeons II title (24 ms against 45 ms), so there is less CPU-side waiting for the reaper to take off. No regression, 0 fatal.
AI-assisted: yes (Claude Code)
Imported from boykopovar/AnyPS5. Originally posted by eliyarson on 2026-10-17T00:17:32Z.
I tested this PR locally and found a double free in some
agc_tests. Below: the finding, then a measurement of destroying the closure outside the mutex on its own.Setup. Upstream main at
72c5eed1fplus local diagnostic patches (my local branch f62f3f762). Section 1 and the earlier batch in section 2 have #6617 applied on top; the table in section 2 is that base without #6617. Release, Linux (CachyOS), Ryzen 9 5950X, RTX 3080 Ti, NVIDIA 610.57.04. Hades II hub, pinned to cores 8-15,24-31 withtaskset, save data restored and checked before every run.1. Double free in the tests.
ctest -R '^agc_'run aborted inagc_driver_draw_cache_reuse,agc_driver_draw_cache_reuse_offandagc_driver_msaa_enable_single_sample, andagc_driver_stencil_ref_export_unusedcrashed. A-j1re-run of the failing tests aborted in the same four. WithAPS5_NO_COMMIT_REAPER=1orAPS5_PIPELINED_DRAWS=0they passed.draw_cache_reusepassed. The cause is from reading the code: the reaper is never joined andDrawPipelineis leaked, so up to 63 retired items can outlivedevice.Reset()inDriver::stop()and be destroyed afterwards without the GPU lock.DrawPipeline::Quiesce()(wait foritemsempty, set a stop flag underretireMutex, join the reaper, destroy the rest), called inDriver::stop()before the GPU lock, gave no abort in 11 runs with the reaper on (ten at-j1, one at-j4). That is not proof the race is fixed. It is about 30 lines; I can send it as a commit.run()moves the item to a localdone, drops the lock, then callsretire(std::move(done)), soQuiesce()can return while the committer holds the last popped item. Aretiringcounter (incremented under the lock when the item is moved out, decremented after the destroy), withQuiesce()waiting foritems.empty() && retiring == 0, closes it forQuiesce(). With the reaper, makingDrain()wait for it too would likely cost the gain; that is inference, not measured. I have not added the counter on top of the reaper.2. Destroying the closure outside the mutex accounts for part of the gain on its own. Same binary, only that change, no reaper thread, toggled by an environment variable. n=4 per arm, interleaved (OFF ON ON OFF ON OFF OFF ON), no crashes:
In an earlier batch (n=4 per arm, interleaved, Quiesce fix applied), #6617 with the reaper gave 71.09 ± 0.47 FPS and with
APS5_NO_COMMIT_REAPER=166.27 ± 1.47. The reaper-off path also destroys the item after the lock is released, so its roughly 4 FPS gain over a plain baseline build is probably the same effect (untested). If so, about half the gain is the unlocked destroy and half the reaper, which costs about 2.2 ms/frame of CPU on another core. The batches used different binaries at different times, so I am not comparing numbers across them.One title, one machine, pinned cores. No unpinned runs, no other game, no TSan.
3. The patch. The variant from section 2 is below. The game runs used the opt-in version of the switch; with the default flipped (
APS5_NO_COMMIT_DESTROY_UNLOCKED=1restores destroying inside the lock) I re-ran theagc_tests in both modes, not the game. It is against current main (85643f75e):git apply --checkpasses andDrawPipeline.cppcompiles; I have not done a full build or run tests on that base. It does not apply on #6617's head (74dad0097): it replaces #6617'srun()change instead of stacking on it, so on the PR theretiringdecrement would move to afterretire()returns. It covers only the no-reaper case. I can push it as a branch on my fork or as a commit on top of this PR if you want it; I will not open a separate PR.Drain()must return only after it finished. Without&& retiring == 0it failed 20 of 20; restored, 0 of 20.Overlaps()andPendingLabel()scanitemsonly. Before, the closure was destroyed insidepop_front()under the mutex, so they could not run during the destroy; now they can, and the item is not visible to them while it is destroyed. That assumes closure destructors do not touch guest memory.LLM assistance used. I ran the builds and tests.
Imported from boykopovar/AnyPS5. Originally posted by milescoviello on 2026-10-17T06:48:16Z.
A Linux data point on how much this costs the committer in another title, from a profile and not a measurement of this PR. Metal Gear Solid 4 (PPSA18194), Ubuntu 24.04, i7-13700K, RTX 4070 Ti (595.99.02), Release, pad input.
main0dc15620d2plus what MGS4 needs here (#6814, #6842, #6237) and #6917. In this scene the committer holds the GPU mutex for about 7.9 s of every 10 s (APS5_PROFILE_DRAW, 124k commits per 10 s).perf record -F 199 --call-graph dwarffor 6 s at 225 s; 555 of the samples haveDrawPipeline::runon the stack:Driver::commitDraw.std::functionmanager ofDriver::draw's commit closure, that is destroying it fromitems.pop_front():_Sp_counted_base::_M_release,free,_int_free.So in MGS4 about a tenth of the committer's time goes to the closure frees this PR moves off it. I haven't run this PR on MGS4.
AI-assisted: yes (Claude Code)
Imported from boykopovar/AnyPS5. Originally posted by Pacuka on 2026-10-18T12:30:43Z.
Linux data point: The Smurfs - Dreams (PPSA21607, Unreal Engine), CachyOS, Ryzen 9 5950X, RX 6650 XT / RADV Mesa 26.2.4, main
9f25d0bf5+ this PR + #6566 + #6208 + #6501 (+ unrelated local rendering fixes). Same spot in the Smurfs' Village, standing still,APS5_PROFILE_DRAW=1:APS5_NO_COMMIT_REAPER=1(#6566 only): 74–79 presents per 10 s, ~75 us per commit.70 us per commit (+7%).The committer is the bottleneck in this title (~120k commits per 10 s), so the commit time maps straight to frame rate. No rendering differences or aborts.
AI-assisted (Claude Code).
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-19T06:51:31Z.
Review: DISMISSED
Thanks for the measurements. Reading the diff, the crash jotitadev, fma-rc and eliyarson reported has two causes in
DrawPipeline.cpp:reap()loops forever (l.198-209), so therunningCommitters.fetch_subthat used to endrun()now sits after it (l.210) and never runs;run()no longer decrements it. Put it back at the end ofrun().Stop()(l.213) joins only the committer. Retired items (up to 63) outlivedevice.Reset()inDriver::stop()and are destroyed afterwards without the GPU lock, which fits thedouble free or corruptionat exit that goes away withAPS5_NO_COMMIT_REAPER=1. The reaper needs a stop flag set underretireMutex, a final drain ofretired, and a join inStop(), so every closure is destroyed before the device goes. eliyarson'sQuiesce()plus aretiringcounter (his comment above) covers the window between popping the item andretire().Also, the
perflabel asks for theaps5-summary.jsonllines of a capture onmainand one with the change, from the same title and scene, plus thetools/trace_digest.pyoutput; the third-party numbers help but the form asks for them in the PR.Imported from boykopovar/AnyPS5. Originally posted by JJenkx on 2026-10-19T17:15:38Z.
Following the teardown reports above, I tested a shutdown follow-up on main
7a015c0946e2f421b7977129dc7fc255a133019bplus this PR at74dad00977cd0485dfc2965ed6371b68fe779cb6.Source: integration branch, retaining this PR's authored commit. The follow-up 9b3ce9fc4d joins the committer first, then signals the reaper to flush its last batch and joins it before
Stop()returns. This covers the pop-to-retire window on the normal external shutdown path without changing ordinaryDrain(). It also puts the committer-count decrement back at the end ofrun(); merging this PR into this main otherwise leaves it after the endlessreap()loop.Regression tests cover a captured object's blocked destructor and a 65-item batch tail. The blocked-destructor test passes on main, fails with the unmodified PR integrated into main (
Stop returned while a closure destructor was still running), and passes with the follow-up. This reproduces premature shutdown, not an allocator-corruption backtrace.Validation on the same Linux / Radeon RX 6650 XT / RADV machine, with Vulkan required, shader cache disabled and Khronos validation enabled:
draw_cache_reusemodes andinactive_vertex_point_size.APS5_NO_COMMIT_REAPER=1: 11/11 pass.draw_cache_reuse_off, andinactive_vertex_point_size20 times each: 80/80 executions pass.VUID-errors in those passing runs. Conventions check passes after documenting the existing fallback switch.The expanded suite command is:
ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validationwere set; exact commands, layer/ICD paths, patches and verbose logs are in the evidence bundle.These are shutdown/test results. The subsequent title measurement is pinned to the original sources above and is only one ordered pair. The existing committer self-stop/detach behavior is preserved and is not covered by the synchronous shutdown claim. AI-assisted: yes.
Refresh on main
48790e0233fd2237aac77f25683339d3bc0d4c8fReplayed the same four patches onto this main without merge commits: refreshed integration branch, candidate
a976a27f7afba52ddaa06c938fbb4f610257b042, shutdown follow-up.git range-diffreports all four patches unchanged, retaining the original PR author's commit.Reran the same 11 tests on main plus the regression tests, the refreshed candidate, and the candidate with
APS5_NO_COMMIT_REAPER=1: 11/11 pass in each arm on the same RX 6650 XT / RADV machine with Vulkan required, shader cache disabled, and Khronos validation enabled. No skips, missing-layer messages, orVUID-errors. Fulllibsbuild and conventions pass. Fresh logs, exact commands, source patches, and range-diff.The earlier negative control, 80-run stress result, and native benchmark were not repeated on this refreshed base. No new performance claim. AI-assisted: yes.
Imported from boykopovar/AnyPS5. Originally posted by JJenkx on 2026-10-19T17:35:35Z.
Native-title follow-up to the shutdown tests above: Record of Lodoss War -Deedlit in Wonder Labyrinth- (
PPSA05347), stationary opening forest with tutorial text. Same machine, scene, scripted inputs and settings; separate per-source caches warmed by running the scene once and restarting. One main-then-candidate pair.7a015c0946e2f421b7977129dc7fc255a133019b.1365624ca52d572b5c0d772249f9de8c53f262f5= that main + this PR's authored commit + the shutdown follow-up/regression tests linked above.b6583dd8687f359c2caea295cde23e4732b73433by the post-test PR audit; these numbers apply to the exact pins above.main official summary:
candidate official summary:
Official
tools/trace_digest.pyoutputs: main, candidate. Traces: main, candidate. Evidence bundle includes exact source patch/attribution, protocol, commands, reports, full measured terminal log, screenshots and digests. No dropped trace events. Ryzen 9 7950X / RX 6650 XT / RADV Mesa 26.2.4, Linux 7.2.9. AI-assisted: yes.Imported from boykopovar/AnyPS5. Originally posted by eliyarson on 2026-10-21T23:30:21Z.
Thanks @adriadam10. I read @JJenkx's follow-up
9b3ce9fc4d(branchreview/commit-retirement-sync156) against the two causes and the pop-to-retire window I described earlier. This is from reading the code; I have not built or run it.runningCommitters.fetch_subis back at the end ofrun().Stop()joins the committer, then setsreaperClosingunderretireMutex; the reaper destroys what is left inretiredand exits, andStop()joins it.Driver::stop()callsStop()beforedevice.Reset().run()only onceitemsis empty, and eachretire()returns before it checks again, so the last one has finished before the reaper is told to close. WithAPS5_NO_COMMIT_REAPER=1the destroy runs on the committer, which is joined first.That covers what my
Quiesce()andretiringcounter were for, so neither is needed and I am not offering a patch for them. The one path I can't say is covered isStop()called from the committer thread itself (detach, no reaper join), which @JJenkx already notes.@TheAggie, if you pull this into #6617: @JJenkx's replay of it on newer main is
3f563df36onreview/commit-retirement-sync158, which they report unchanged byrange-diff.The no-reaper variant from my earlier comment (closure destroyed after the lock is released, no reaper thread) is now on my fork as branch
rb/commit-destroy-unlocked, rebased on current maina6dcea927. It is on by default;APS5_NO_COMMIT_DESTROY_UNLOCKED=1turns it off. Itsretiringcounter only makesDrain()wait for that unlocked destroy; it is not theQuiesce()counter above, and like the patch in that comment the branch replaces #6617'srun()change instead of stacking on it. On Linux (RTX 3080 Ti) it builds andctest -R agcpasses apart from one skipped test and the threeagc_driver_sample_order*tests, which also fail on that main. I have no FPS numbers on this base: Hades II on current main aborts during the hub load (native multisample depth metadata fill transition is not implemented, the path #6300 works on), so the numbers in my earlier comment are from the older base only.For the
perflabel: @JJenkx posted one main/candidate pair for Record of Lodoss War. I can add a Hades II pair (aps5-summary.jsonllines for main and for the change, same scene, plustools/trace_digest.pyoutput) if that helps. I have not run it yet; on current main it needs the hub-load abort above fixed first.LLM assistance used.
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-22T04:04:17Z.
I'm picking this up alongside @adriadam10 because it is part of a stack that gets PPSA04263 further on current
main. The two open change requests still apply to74dad00977, in particular @adriadam10's:reap()loops forever and teardown double-frees (as @jotitadev saw on Linux). I'm checking whether that still reproduces on currentmainand how small the fix is. @TheAggie, if you can push a fix, that's the quickest path. Otherwise I'll propose one here for you and the reviewers to look at.Imported from boykopovar/AnyPS5. Originally posted by johandavidcm on 2026-10-22T06:35:19Z.
Windows data point from Yakuza 0 Director's Cut (PPSA31327), which is committer-bound in gameplay. Windows 11 Pro 26200, RTX 4070 (617.42), Ryzen 7 7800X3D, WinLibs GCC 15.2.0, Release, character standing still in Kamurocho.
main80565c594+ #8098 (the title's audio) + #8117. Change: this PR (74dad0097), which merges cleanly onto that base.APS5_NO_PAD_INPUT=1).APS5_TRACE_SECONDS=170:60in gameplay. Builds were interleaved over three batches.Driver.Packetgoes from 338 to 309 ms per frame, andGraphics.Drawfrom 290 to 281 ms, consistent with the worker waiting less on the committer.Replicated on current
main0c6a5bd59(+ #8098 + #8117). This PR still merges cleanly. Same scene, window140:60, 2 runs each:Summary lines (one run of each build)
AI-assisted: yes
Imported from boykopovar/AnyPS5. Originally posted by fma-rc on 2026-10-22T19:17:10Z.
Review: APPROVED
Read
8326fb0768, it fixes the crash I reported. The reaper now exits onreaperStopping, drains what was retired before it stopped, andStop()joins it after the committer, so nothing retired outlives the device. A retire after the stop destroys the item outsideretireMutex, which is right.closingandreaperStoppingboth stay set afterStop(), so later commits run and are destroyed inline, which matches how the committer already behaves after shutdown. The new test checks both the reaper count and the closure lifetime. Runs on RADV are in my comment above.Pull request closed