Repository navigation
feat(agc): record graphics batches into sealed command streams - #22697
chitters2004 wants to merge 165 commits into
Conversation
The committer spends about 3.6 us of each draw recording its Vulkan commands (pipeline begin or continue, binds, push constants, draws). A per-device encoder thread now records them: while a draw records, the device table's vkCmd entries copy each call on the open batch, arrays included, into a chunk, and the encoder replays the chunks in order into the batch from its own command pool. Every other access to the open batch waits until the encoder has recorded everything posted: Recorder functions read the batch through live(), Submit waits before vkEndCommandBuffer, a by-name vkCmd lookup or a table call on the batch outside the window waits too. So the batch holds the same commands in the same order as inline recording. APS5_RECORD_INLINE=1 keeps inline recording. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…worker first The recorder cached raw Vulkan pointers for barriers, binds, push constants, dispatches and buffer updates, so the indirect mesh argument kernel recorded inside an encoding window overtook the window's queued commands and bypassed the pool mutex. With an encoder the recorder now caches the encoder-wrapped entries. A draw that throws after its commands were queued released its owners while the encoder could still record against them; the draw and its keep step now settle queued recording while unwinding. The encoder starts its worker before it publishes itself and patches the dispatch table, so a failed thread start leaves nothing dangling. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…am without waiting Copies, buffer updates, image copies and colour clears recorded while an encoding window is open are packed into the encoder's stream with their region arrays, bytes and clear colour, instead of draining the encoder and recording directly. The occlusion segment's vkCmdBeginQuery and vkCmdEndQuery go through the encoded table, so beginSegment and endSegment no longer drain the encoder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ign producers The unwind guard in keepRecordedDraw and recordDraw now outlives the owners of queued commands (the kept draw state and the sample-order objects), so the encoder drains before they are released. A thread other than the window's owner that calls a patched command on its buffer, or looks up a vkCmd function while the window is open, now throws instead of racing the producer. Checkpoint marker writes inside a draw window quiesce first. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…e transfer test Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… window Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A recorder whose encoder table lacks the begin or end query entry keeps the raw query functions, which do not go through the encoder stream, so the segment begin and end settle the encoder first in that case. A new test draws through the encoder with one draw inside and two outside each occlusion segment and requires the exact sample count with and without the query hooks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An exception while the encoder thread replays a chunk used to escape the thread and end the process. The encoder now stores the first failure, skips every later chunk so nothing more is recorded into a command buffer in an unknown state, and rethrows it from Settle and Quiesce on the producer's thread, including at submission. Window close, the unwind guard and the destructor wait without rethrowing, so a failure never throws from a destructor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each aps5-summary.jsonl line gains an encoder object: chunks posted, commands recorded, waits on the encoder and their time per frame, summed over the threads that produced or waited in the window. The counts are taken only while a trace records. trace_digest.py validates the field and adds an encoder table to the interval digest when a run posted chunks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…che allocation test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A replay failure is stored per command buffer with the thread that produced it. The encoder skips later chunks for that buffer only; the next settle on the producing thread rethrows it once, and settles on other threads never do. Submit finishes the batch's buffer first: a buffer whose replay failed is refused, with the original error if its producer has not seen it yet. Freeing the buffer drops the failure, so a reused handle starts clean. A device past the four encoder slots now records inline: Attach returns no encoder instead of throwing. discard drains without rethrowing, and copySegments and foldSamples settle before their raw query copies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agc_driver_recorder now builds its recorder with the device table, so the suite records through the encoder and agc_driver_recorder_record_inline runs the same suite inline. It also checks that a recorder past the encoder slots records and submits inline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A replay failure now lives in a CommandEncoder::Recording owned by the recorder batch, instead of in a per-encoder list keyed by command buffer and producer thread id. - Each chunk points at the recording of the window it was appended in. The worker stores the exception in that recording and skips its later chunks; other batches carry on. - The recorder reports the failure once, at the next settle of the open batch, on whichever thread holds it. Submit on any thread first carries an unreported failure to its caller, refuses a batch whose failure was already reported, and discards the failed batch, so the recorder recovers with the next batch. No thread id is kept, so a reused id cannot receive another thread's failure. - Posting, settling and the worker's failure path no longer allocate: chunks move through intrusive lists, and the error is the exception_ptr already held by the worker. Quiesce and Settle are noexcept, which removes Drain, Finish and Forget. - The debt entry records that table calls outside a window and raw calls into a failed batch still reach the driver; the batch is never submitted. Tests: FailedReplayStaysWithItsRecording, FinishCarriesAnUnreportedFailure, PostingNeverAllocates and ReplayFailureNeedsNoAllocation in agc_driver_command_encoder, and the recorder suite's encoder failure test (a failure recorded on a thread that has exited, Submit on another thread, recovery). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A table call that the encoder cannot copy (update, copies, clears, and barriers or render-pass begins with a pNext chain) settles the window and is dropped when the window's recording has failed, so nothing more reaches a batch whose replay failed through its window. - Submit inside an encoding window throws std::logic_error instead of ending the batch while the window still targets it and points at its recording. - A chunk whose buffer fails to grow returns to the spare list instead of being dereferenced after it was cleared. - The handoff spin window is computed when the encoder is built, so a later settle never runs its first-use initialisation. Tests: DirectCallsSkipAFailedRecording and AppendFailureKeepsTheWindow in agc_driver_command_encoder, and a Submit inside a window in the recorder suite's encoder failure test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in boykopovar#17943's head 7a03091: each batch owns a CommandEncoder::Recording, Quiesce and Settle never throw, posting is allocation-free, and direct calls into a failed window are dropped. The packed transfer and query records replace the settle-then-direct entries, so the direct entry template is gone. The transfer test opens its windows with a recording. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Packed copy, update, image copy, clear and query records in a window whose recording failed must reach neither the driver nor another recording. Begin and end queries around nested windows of two recordings stay in program order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A batch that is discarded instead of submitted, after a failed replay or a failed submit, left the segments it closed in the Recorder's pending samples. The next SamplesTotal or fold then waited on query slots that never ran: an unreset query hangs the wait, a reused one returns a stale count. A batch that folded earlier, submitted segments before it was discarded also took them with it, so their samples were lost. Each batch now counts the segments it closes and keeps the ones it folds. On discard its own segments are dropped and the folded ones from earlier batches go back to the front of the pending list. Folds reserve that list before recording, so a failed allocation cannot leave a recorded fold whose segments are still pending. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in main's guest_job_manager_worker_spin fixes (boykopovar#18200, boykopovar#18213, boykopovar#18214), which the Windows guest-test job needs; the merge has no conflicts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in main's guest_job_manager_worker_spin fixes (boykopovar#18200, boykopovar#18213, boykopovar#18214), which the Windows guest-test job needs; the merge has no conflicts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflicts: - tests/cmake/agc_driver_recorder_tests.cmake: main (boykopovar#9884) registered agc_snapshot_read_into_staging where we registered agc_encoded_segments; kept both. - tests/Recorder.cpp main: main added the --snapshot-read-into-staging-only branch where we added --encoded-segments-only; kept both. boykopovar#17943 merges with main cleanly, so main is merged here directly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — no blocking findings
Nothing blocks this; the points below are optional.
What I ran
Reviewed head 34ddf73d353bae7aa277105d7beab592694a6dc1 using the prepared review materials and selected head-file excerpts. I ran no tests or builds.
sed/rg excerpts from the prepared review folder; no test or build commands
Results
| Check | Result | Note |
|---|---|---|
| Prepared review materials | passed | Description, commits, manifest, diff, and file list inspected |
| Tests and builds | not run | No execution checks performed |
Negative control
Not run; no tests were executed.
Findings
Blocking
None identified in the inspected excerpts.
Non-blocking
core/libs/prx/libSceAgcDriver/Graphics/src/SealedBatch.cpp:28: If failures arrive out of order,FailureLatch::FailupdatesfailedSerialto the lower serial but keeps the prior error. For example, a replay failure at serial 2 followed by a submit failure at serial 1 leaves waiters receiving the serial 2 exception. Store the reason when the lower serial replaces the current failure. Pinned source
Sources
The failure-latch behavior above is based on the pinned source. The prepared description and test excerpts were also consulted; author-reported test results were not independently run.
Not verified
Of the 48 changed files listed as reviewed in files.json, I read excerpts from 8: CommandStream.cpp, CommandStream.hpp, CommandThunks.cpp, Recorder.cpp, Recorder.hpp, SealedBatch.cpp, SealedBatch.hpp, and tests/SealedBatch.cpp. The other 40 changed files were not read. Full text was unavailable in the review folder for Execution/src/VulkanDevice.cpp, Graphics/src/GuestBufferMemory.cpp, tests/Graphics.cpp, tests/Recorder.cpp, and tools/tests/test_trace_digest.py; their changed hunks were not inspected. No tests, builds, or runtime behavior were verified.
To get this to a good state
Nothing is required. The error-latch note above is optional follow-up.
MarcZX10 change request on 6bc031b asked: Changes are required before merge: make secondary command buffers recorded into streamed batches valid for replay. His later review of the current head 34ddf73 states no blocking findings (Blocking: None identified in the inspected excerpts.) so the request no longer applies.
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — no blocking findings
The prepared diff and selected stream and replay code were inspected at head 8fa09f381b577c20ef607703b0011d4258b7675b; the review is incomplete because full text for five reviewed files was not bundled and the pinned reader could not write its read log in this read-only run.
What I ran
Inspected the prepared description, commits, manifest, diff, and selected bundled source text. The attempted repo_read.py source read could not complete because it tried to write reads.jsonl; no tests or negative controls were run.
sed -n ... files/...
rg -n ... files/...
python3 repo_read.py cat ...
Results
| Check | Result | Note |
|---|---|---|
| Prepared review bundle | passed | Metadata and diff inspected |
| Selected source review | not run | Reader could not log in read-only run |
| Tests and negative control | not run | No execution performed |
Negative control
Not run; no tests were executed.
Findings
Blocking
None identified in the inspected portions.
Non-blocking
None.
Sources
Not verified
The files listed as reviewed total 48. Full bundled text was read for 3 repository files, with targeted excerpts inspected from CommandThunks.cpp and Recorder.cpp. Full text was unavailable for VulkanDevice.cpp, GuestBufferMemory.cpp, Graphics.cpp, tests/Recorder.cpp, and tools/tests/test_trace_digest.py; other reviewed files and the remaining changed code were not read. No behavior, test results, or author-reported runs were independently verified.
To get this to a good state
Nothing is required.
ligmaSec
left a comment
There was a problem hiding this comment.
I followed the copies for push-descriptor image, buffer and view arrays through replay. The code only demotes the unsupported or chained push variants, while the debt fragment lists vkCmdPushDescriptorSetKHR as a command that demotes. Please make the documented boundary match this head and keep the demotion-path fixture alongside the worker replay and poisoned-stream checks. The paired recorder and new sealed-batch tests are queued. I did not repeat the recording benchmark.
AI-assisted: yes.
|
@MarcZX10 Good catch, fixed in 8fa09f3.
New test AI-assisted: yes |
# Conflicts: # core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
The merge of main put setWriteOnlyHazards(false) from boykopovar#23919 in queue(). Here a sealed batch can wait in sealedBatches while a new open batch records, so clearing the flag at queue time can drop the newer batch's write-only hazards, and PacketExecution then skips a seal it needs. Clear it in sealOpen, where the open batch is moved out, as main does.
|
I pushed |
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — no blocking findings
Nothing blocks this; the points below are optional.
What I ran
Reviewed head 45c9ad4aaa30209084f1cc4d75fc4c4b2fde419e using the pinned repo_read.py reader and the prepared review files. No tests or builds were run.
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/CommandStream.cpp 1 136
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp 1 300
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp 5210 5390
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/SealedBatch.cpp 200 390
Results
| Check | Result | Note |
|---|---|---|
| Targeted source review | passed | No concrete defect found in inspected paths |
| Tests and build | not run | Would require compilation |
| Full changed-file review | not run | Review remains incomplete |
Negative control
Not run; a negative-control test would require compiling the changed C++ code.
Findings
Blocking
None identified in the inspected portions.
Non-blocking
None.
Sources
The targeted inspection covered the command stream, command thunks, sealed-batch replay, recorder submit path, and Vulkan device thunk registration at the pinned head: CommandStream.cpp, CommandThunks.cpp, SealedBatch.cpp, Recorder.cpp, and VulkanDevice.cpp.
Not verified
This was not a complete review of all 48 changed files. The following changed files were excluded from the prepared files/ folder because they exceeded its size limit: core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp, core/libs/prx/libSceAgcDriver/tests/Graphics.cpp, core/libs/prx/libSceAgcDriver/tests/Recorder.cpp, and tools/tests/test_trace_digest.py; only targeted VulkanDevice.cpp hunks were read through the pinned reader. Other changed tests and documentation were not fully inspected. Runtime behavior on a physical console and CI results were not verified.
To get this to a good state
Nothing is required. Optional: complete review of the remaining changed files before treating this as a full review.
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — no blocking findings
I found no concrete defect in the stream and replay code I inspected, but review coverage is incomplete.
What I ran
Reviewed head 8a0cc4c294e48e075ab7a59a876fe15ba0acae6f using repo_read.py in the Linux review sandbox; no compiler or build tool was invoked, and no base merge preview was run. Reader calls returned the requested source ranges, then reported a read-only error when trying to append its log.
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/include/CommandStream.hpp 1 166
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/CommandStream.cpp 1 136
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp 1 240
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp 200 450
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp 430 580
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp 451 700
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp 701 850
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/include/SealedBatch.hpp 1 215
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/SealedBatch.cpp 1 390
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp 5293 5390
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp 5391 5505
python3 repo_read.py cat core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp 5670 5740
Results
| Check | Result | Note |
|---|---|---|
| Inspected stream and replay paths | passed | No concrete defect found in read ranges |
| Automated tests and build | not run | No tests or build invoked |
| Full changed-file review | not run | Six of 48 reviewed paths inspected |
Negative control
Not run; no test or mutant was executed.
Findings
Blocking
None in the inspected ranges.
Non-blocking
None.
Sources
- Command stream demotion and replay
- Streamed rendering and descriptor commands
- Sealed batch replay lifecycle
- Recorder queue and submit path
Not verified
Read source ranges from CommandStream.hpp, CommandStream.cpp, CommandThunks.cpp, SealedBatch.hpp, SealedBatch.cpp, and Recorder.cpp. The other 42 paths listed under files.json → reviewed were not individually inspected. The prepared full-text snapshots also excluded Execution/src/VulkanDevice.cpp, Graphics/src/GuestBufferMemory.cpp, tests/Graphics.cpp, tests/Recorder.cpp, and tools/tests/test_trace_digest.py for size; these files were not read through the reader. Tests, runtime behavior, and hardware behavior were not verified.
To get this to a good state
Nothing is required. Optional: complete review of the remaining changed paths before making a formal approval decision.
MarcZX10
left a comment
There was a problem hiding this comment.
Reviewed — no blocking findings
The inspected materials show no verified blocking defect, but the review is incomplete because most changed files and hunks were not examined.
What I ran
Reviewed head 0570eab599244e9c5746f2e371f09811b2b4a4da. Read the prepared description, commit list, manifest, files list, and selected hunks from diff.patch; used repo_read.py to inspect CommandStream.cpp, SealedBatch.hpp, part of SealedBatch.cpp, and parts of CommandThunks.cpp. No tests or other checks were run.
Results
| Check | Result | Note |
|---|---|---|
| Prepared review materials | passed | Read description, commits, manifest, files list, and selected diff sections |
| Focused source inspection | passed | Inspected selected stream, batch, and thunk code |
| Tests and runtime checks | not run | No execution checks performed |
Negative control
Not run.
Findings
Blocking
None verified in the inspected sections.
Non-blocking
The review is incomplete; the inspected sections do not support a merge recommendation.
Sources
No external sources used.
Not verified
The prepared description and commit list were read. The full diff and most changed files were not read. In particular, changed files marked included: false in the manifest (VulkanDevice.cpp, GuestBufferMemory.cpp, Graphics.cpp, and Recorder.cpp) were not inspected through the reader. The remaining files listed under reviewed in files.json were also not fully read. No behavior, test results, or performance claims from the description were independently verified. Reader output was available, but its attempt to record calls failed because the run folder is read-only.
To get this to a good state
Nothing is required.
Optional: complete the review of the remaining changed files and relevant hunks before relying on this review as a merge recommendation.
What
Records a graphics batch into a command stream and replays it into a command buffer at
Submit, replacing the per-window command encoder. This is row 4 of the sealed-batch design.It claims two things and no speed:
Submitstill replays and then waits for that replay before it submits, on either executor.It does not claim parallel encoding pays. A replay bench on an RTX 3080 with 3,000-draw batches bounds what moving
vkCmd*recording off the drawing thread can save at 0.35 us/draw (direct 0.63, append 0.28).Every
vkCmd*resolution (the device table,Context::Function,deviceProcinVulkanDevice.cpp, the AMD marker and NV checkpoint lookups) returns the thunk for that name from one list (APS5_COMMANDSinCommandList.hpp). A thunk given an untagged handle calls the driver; given the open stream's tagged handle it copies the call and its arrays into the stream.tests/test_command_resolver_sites.pyfails on avkCmdname outside the list or a resolution that skips the thunk.Every command in
APS5_COMMANDShas a streamer that copies its arrays and structs into the stream (CommandStreams(id)is true for all 69, includingvkCmdPushDescriptorSetKHR,vkCmdExecuteCommands,vkCmdSetCheckpointNV,vkCmdSetDepthBias2EXTandvkCmdBindShadersEXT). Push descriptor writes are deep-copied by descriptor type: image infos, buffer infos and texel buffer views, each array copied into the record and the write's pointer redirected to it.vkCmdExecuteCommandscopies the secondary handles: its only caller, the pooled depth-only path behindAPS5_PARALLEL_ATLAS, executesRecordingPoolsecondaries that are recorded and ended before the call and kept with the batch until it retires, so replay records the same execute into the replay primary inside the replayedvkCmdBeginRenderingKHR(withVK_RENDERING_CONTENTS_SECONDARY_COMMAND_BUFFERS_BIT). A stream handle passed as a secondary is refused with alogic_erroron a streamed or demoted stream (agc_command_thunks), andagc_driver_depth_plane_sampling_streamed_secondariesrecords four pooled depth-only draws into separate surfaces, requires each to land in a streamed batch that is replayed with no direct, demoted or failed batch, and reads every surface back.A batch demotes only for what cannot be copied by value: a
pNextchain on any streamed struct (inline uniform blocks and acceleration structures carry their data that way), a descriptor type with no array to copy, or a command that would take its stream past its byte cap. The prefix replays in order into a real command buffer and later calls record there. The profile line counts demotions by command andsType(the cap counts asstream byte cap).APS5_NO_STREAMED_PUSH_DESCRIPTORS(a RuntimeSwitch, toggled byAPS5_AB) demotes a batch at its first push descriptor instead, for an in-boot A/B.Per-stream byte cap: the budget's outstanding bytes divided by its outstanding batches, 64 MiB / 16 = 4 MiB by default, so outstanding stream memory is bounded at 16 × 4 MiB. The check comes before a new chunk is allocated or charged, in the chunk-growth branch of
reserve: a command that does not fit demotes the stream, is built in scratch storage and runs on the command buffer, so a stream is never charged more than its cap. An append that fits in its chunk does no extra work. The batch demotes rather than ends because the cap is reached inside avkCmd*call: a render pass may be open and a draw half recorded, so there is no point at which the recorder could end the batch and start the next one. Demotion keeps every command in order and frees the stream's chunks. A stream with no way to demote (none in the recorder) is poisoned instead, so the batch is refused rather than growing.Entry points have no fixed global limit. Each command keeps 8 thunk slots as its fast path. When a command sees a ninth distinct driver entry point,
CommandThunk(name, real, device)returns that command's keyed thunk and records the entry point under the device's loader dispatch key, in a registry owned per device (ForgetCommandDevicedrops it beforevkDestroyDevice). For a real command buffer, the keyed thunk reads the buffer's dispatch key and calls that device's entry point.ForgetCommandDeviceclears a node and a later device reuses it, so the storage is bounded by the peak number of devices registered at once, not by how many were ever created.Submitseals the stream as aSealedBatch, replays it (inline on the submitting thread by default;APS5_ENCODE_THREAD=1uses one worker with its own pool), then submits the replayed buffer. A replay failure is latched for the life of the recorder: that batch is not submitted, its completions do not run, and every laterSubmitthrows the stored error without submitting. A replay fails only when the driver refuses to record or end a command buffer, so the recorder treats the device's graphics work as ended rather than retrying on a state it cannot verify.A draw that throws while recording poisons the open stream (
Recorder::UnwindGuard);Submitthrows instead of submitting part of a draw. Direct batches keepmain's behaviour.Failure paths:
Syncstops at the first failed wait, as perf(agc): drop per-batch fences when a timeline tracks completion #20066 has it onmain: the batch it did not reach stays in flight and unsettled, and the device is idled once (not at all on device loss). A failed submit saved before the waits is still reported first.~RecorderrepeatsSyncuntil nothing is in flight, so teardown no longer destroys batches the GPU still holds;vkQueueSubmitthat loses the device latches the loss, and after itSubmitrefuses direct batches as well as streamed ones. Any othervkQueueSubmitfailure queued nothing: the batch goes throughunqueued(), gives its serial and hold back, and the recorder carries on, unless a newer batch was already sealed behind it, which latches the failed serial. This reverses the earlier choice that every laterSubmitthrows, becausemain'sagc_driver_host_import_lifetimeexpects the next copy to submit;Direct batches no longer pay the thunk's handle test. Each batch picks its command table once, when it opens:
StreamedCommands(), whose entries append to the stream without the thunk's handle test.The draw state (
CommandState) and the per-draw bind and draw calls inDraw.cpprecord through that table. Other sites keep the thunk, which is correct in both modes.Release, 4 vCPU, medians of 21 interleaved rounds, each variant called through the same table load, ns per command:
At -O3 the typed call is not free: it keeps two predictable null checks (the batch has a table, the table has the entry). With the checks removed it measures +0.00 ns, so they are the whole cost. That is about half the thunk's cost, which matches the fork CI's Release figure (typed +0.35 ns, thunk +0.70 ns). Under ASan: raw 1.83, thunk +15.9, typed +0.47. A keyed lookup (past the 8 slots) costs 3.8–3.9 ns at the first node and 6.1–6.3 ns at the fourth (Release -O2, 3 runs).
Serial waits end when the waited batch can no longer complete.
WaitSerial,WaitSerialForandSyncwait in 100 ms slices and check the failure latch each time, so a waiter on a batch whose replay failed, or that the device lost, gets the stored error instead of waiting forever.Admission:
WorkBudget::TryOpenrecords the batch directly instead of waiting when too many streams are encoding or outstanding, and counts the refusals.Removed:
CommandEncoder, the encoding window inDraw.cpp, the adaptive policy, the drain at by-name lookups and table calls,APS5_NO_RECORD_ENCODER,APS5_NO_ADAPTIVE_ENCODER,APS5_QUIESCED_SEGMENTS,APS5_ENCODER_IDLE_SPIN_USandAPS5_PROFILE_ENCODER.APS5_DIRECT_BATCHES=1andAPS5_RECORD_INLINE=1record every batch directly.API points a parallel encoder will need, found while scoping async submit and kept out of this PR:
pendingLabelSince) until it is queued;HoldNextSubmit) must be captured per batch when it is sealed;Each promise from our #18173 reply (issuecomment-6933127916), where it is in the code and what covers it. Tests are in
tests/SealedBatch.cpp(agc_sealed_batch) unless named otherwise.SealedBatch:OutcomepluserrorundererrorMutex;AwaitandErrorrethrow itSealedAndFailedAppendsPoison,InlineReplayFailureReachesTheLatchReplay(stream, target, real)reads only the stream and the table it is given. The one per-thread value is aboolguard (ReplayThreadScope, aHostThreadSlotwith no destructor) that refuses appends from a replay threadSingleExecutorOwnsItsPoolAndThreadreplays on the executor's own thread; theappendOnReplayThreaddeath test;agc_driver_recorderwithAPS5_ENCODE_THREAD=1releaseReplaysetsReplayReleasedapart fromOutcome;Retirableneeds replay released, submit returned and GPU releasedRetirementOutlivesTheStream,FenceBeforeReturnStaysHeld,CancelDoesNotImpersonateTheWorker, thedestroyUnretireddeath testCommandStreamhas its own tagged handle, and the thunks find the stream from the handle, with no shared open-batch state. The budget's counters are atomic. The recorder itself keeps one batch open, and up to 16 sealedTwoThreadsAppendToTwoStreams: two threads append 20,000 records each to two open streams sharing one budget, throughEmplaceand the streamedvkCmdSetCheckpointNV; each stream replays exactly its thread's sequence and the budget holds both charges.TwoThreadsChargeOneBudgetAtOnce: each thread keeps charging (up to 16 × 20,000 streams, failing after 60 s) until both have charged 20,000, so their charges certainly overlap; the budget must hold the sum. A non-atomicChargemutant is caught in 10 of 10 runs. Also run under TSan (standalone build, 3 runs, no reports)CommandBufferPool,CreateReplayPool,BorrowReplayPool;EncodedandRetirecarry the worker index.SingleExecutorcreates its pool on its own threadSingleExecutorOwnsItsPoolAndThread,ReplayPoolCreationDoesNotLeakFailureLatch,WaitObservingFailure;WaitSerial,WaitSerialForandSynccheck the latch every 100 ms slice. A submit that loses the device latches; any other refused submit gives its serial back to the next batch and the recorder carries on, unless a newer batch was already sealed behind it, which latchesFailureReachesSerialWaiters;agc_driver_recorder(deferredBatchTests: the waiter on a failed replay; the waiter on a refused submit, which ends when the next batch completes that serial; the waiter on a refused batch with a newer one sealed behind it, which sees the failure)VK_ERROR_DEVICE_LOSTthe recorder waits for the device to go idle, then callsDeviceIdleAfterLoss;GpuDoneis ignored after a loss, so nothing is recycled before the idleDeviceLossHoldsResourcesUntilTheDeviceIsIdle;agc_driver_recorder(sealed and direct device loss)WorkBudget: admission refuses at 16 outstanding deferred batches (open to retirement) or at 64 MiB charged, and the recorder opens a direct batch instead; at 4 batches encodingChoosesays direct. Each stream is capped at outstanding bytes / outstanding batches (4 MiB), checked before a chunk is charged; a command that would pass it demotes the streamBudgetBoundsWorkThroughRetirement,AdmissionOpensDirectInsteadOfWaiting,StreamByteCapDemotesTheBatch: charged bytes stay at or under the cap after every append, and one command larger than the remaining cap demotes with nothing charged for it, with and without a prefix. Mutants caught: no cap check, no pre-check, and a check after chargingrealCommandsbelong to each recorder. Thunks keep 8 slots per command; past them, the keyed thunk resolves through a registry owned per device and keyed by the loader dispatch keyEntryPointsBeyondTheSlotsAreKeyedByDevice: two devices past the slots route to their own entry points, an unregistered device's buffer throws, a conflicting entry point on one device throws, a forgotten device's key can be reused, a stream handle still streams, and 200 create and destroy cycles of distinct devices leave the storage at the peak of 2 live devices. A reader on device A's buffer races a writer cycling forget A, register B, forget B, register A on the same node for 2 s: no call reaches B and storage stays at the peak. Mutants caught: keyed thunk replaced by slot 0,ForgetCommandDevicekeeping entries, a conflict accepted, no node reuse, and no version recheck (10 of 10 runs)Submit; moving it off the drawing thread is Nesyth's #22190Streamer<CmdPushDescriptorSetKHR>deep-copies eachVkWriteDescriptorSetand its image, buffer or texel-view array by descriptor type; demotes onpNext(inline uniform blocks, acceleration structures) or an uncopyable type; behindAPS5_NO_STREAMED_PUSH_DESCRIPTORS, on by defaultSpecializedStreamersKeepEveryArgument(5 writes over all three array kinds, with garbage in the ignored pointers, every caller struct overwritten with 0xA5 before replay),PushDescriptorsDemoteOnlyWhatTheyCannotCopy(inline uniform block, acceleration structure, mutable type, switch off). Mutant: buffer infos not copied is caught atCmdPushDescriptorSetKHRagc_command_resolver_sitesfails on avkCmdname outside the list, andEveryListedCommandStreamsfails on a listed command without a streamerEveryListedCommandStreams; fidelity covers 27 specialized streamers in 31 calls. Mutant: thevkCmdBindShadersEXTstreamer removed fails with "vkCmdBindShadersEXT is listed but has no streamer"This is the complete stream API for the encoder pool: every recorded command streams, demotion is limited to
pNextchains, uncopyable descriptor types and the byte cap, outstanding work is bounded in batches and bytes, and the resolver has no fixed global limit. No further stream work is needed for batch encoding. Order: #17943, #18029, this PR, then Nesyth's batch encoding on #22190.Credit: the deferred batch encoding, async submit and stream-handle thunk design is Nesyth's (#18173).
Tested
The runs below are on
055f2959feeor a commit with the same tree, unless marked as on the head. Since then,94af04a7baachanged only test mocks (fake command-buffer handles no longer carryCommandStream's tag bit), and the head4c5b2394f72splitsRecorder::SubmitintoSealand a queue step; its runs are under "Seal and queue split" below.Linux, llvmpipe:
agc_command_thunks,agc_command_thunks_direct_cost,agc_command_resolver_sites,agc_sealed_batch,agc_driver_recorder,agc_driver_recorder_record_inline,agc_streamed_segments,agc_driver_streamed_mesh_arguments,agc_runtime_switches, the threeagc_stream_guard_*death tests and the fiveagc_pipeline_cache_allocation_*. Everything else passes in every job (agc_driver_streamed_mesh_argumentsskips on the sanitizer runners), andagc_driver_recorderandagc_driver_recorder_record_inlinefail, with no sanitizer reports. On the Linux gate and under ASan and TSan both stop atvertexWindowMirrorTests("a kept vertex window was not mirrored"), before their encoder cases; on Windows both stop at "an unchanged draw input was copied again", asagc_driver_recorderdoes on base. This ismain's failure: fork CI failsagc_driver_recorderthe same way on baseb412486d3e, and test(agc): skip the draw input mirror cases on devices whose memory is all device-local #20831 fixes it.ASAN_OPTIONS=detect_leaks=0) withAPS5_NO_INPUT_MIRRORS=1, both recorder tests run to the end and pass, and so doesagc_driver_recorderwithAPS5_ENCODE_THREAD=1.agc_sealed_batchandagc_command_thunks, 3 runs each, no reports (about 870k racing keyed lookups per run).ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation) ran onef9e679b761, the commit that adds the last streamers; the commits after it change only the byte-cap check, the resolver registry and tests. The layer loads in every run, andagc_driver_recorder,agc_driver_recorder_record_inline,agc_streamed_segmentsandagc_driver_streamed_mesh_argumentsreport no VUID. Against basefff1677881a(run on80d642ce25a), this PR adds no VUID: both show the same device-creationVUID-VkDeviceCreateInfo-pNext-pNext, andagc_driver_native_depth_clearsthe same 6VUID-vkCmdDraw-None-07629on both.Each fix below has a test that failed before it:
VK_ERROR_DEVICE_LOSTfollowed by a demoted batch: "a direct batch reached vkQueueSubmit after the device was lost";WaitSerialon the serial of a batch whose replay fails, on a real timeline semaphore: "a wait on the serial of a batch whose replay failed did not end";Syncafter a failed fence wait now expects perf(agc): drop per-batch fences when a timeline tracks completion #20066's behaviour (agc_recorder_batch_fencesFailedWait: the batch it did not reach stays in flight and unsettled, one device idle, none on device loss); draining every batch instead fails it in all three modes. Teardown with a wait that fails inside~Recorder: with oneSyncthere, "a sealed batch was destroyed before the GPU released it";agc_driver_host_import_lifetime): with the old latch the next copy inherits the error;GpuDonegives "a sealed batch was destroyed before the GPU released it". UnderAPS5_RECORD_INLINEthe deferred case does not run and says so;Other tests and the mutants they catch:
resolveImageView, zeroed barrier dependency flags;APS5_DIRECT_BATCHESgives a direct batch and the next batch defers again; a throw underUnwindGuardpoisons the batch,Submitrethrows it and the next batch replays; apNext-chained barrier demotes, later calls record directly and the demotion is counted by name; a failed replay is not submitted, its completion does not run, and the nextSubmitalso throws without submitting; a failed prefix replay during demotion refuses the batch with no submit and frees every command buffer (mutant: no free of the poisoned stream's buffer gives "1 still allocated");Submit: removing the poison checks fails with "the poisoned batch was replayed", removing the latch check with "a batch after a failed replay was submitted", and swallowing the replay error with "a batch whose replay failed reached vkQueueSubmit" (the test's submit wrapper refuses to reach the driver while no submit is expected); aTryOpenthat never refuses times outagc_sealed_batch; a direct batch withoutlatch.Failleaves a wait on the failed serial running forever;StreamedCommands()(mutant: a direct batch without its table, "did not take the driver's command table");agc_command_thunks_direct_costis a gate: it times productionContext::ForBatch(typed) andContext::Resolved(thunk) against a raw table call, in rotating order over 21 rounds, and fails when the typed overhead is more than three quarters of the thunk's where the thunk adds at least 0.5 ns, and more than the thunk's own plus 0.1 ns where it adds less (skipping when the thunk adds under 0.2 ns, and only reporting under ASan and TSan). On fork CI's EPYC 7763 the thunk adds about one cycle (+0.27 to +0.32 ns) and the typed call the same, so only the second limit applies there. Mutant (ForBatchalways takes the fallback): fails 3/3. The check that a batch's table was built against the context's table isContext::BatchFor, made once where a batch is looked up (CommandState::FunctionsForand theCommandStatemethods), soForBatchitself stays a null check. A version that compared tables insideForBatchon every command failed this gate on fork CI's EPYC 7763; withBatchFor, Release g++ -O2 on 4 vCPU, 6 interleaved rounds, typed adds +0.14 to +0.30 ns over raw, against +0.62 to +0.65 ns with the per-command compare and about +0.0 ns before the table check existed. Mutant (BatchForignores the table):agc_command_thunksfails;agc_command_resolver_sitesfails when aCommandStatesetter orrecordDrawCommandsImplresolves a command outside the batch's table or passesForBatchanything butfunctionsorcontext.BatchFor(functions)(mutants: aSetScissorthroughResolved,ForBatch(nullptr, ...), and aCommandStatesite throughBatchFor(nullptr)), and when the thunk is removed from the AMD marker lookup.GTA V (PPSA04263, content 01.011.001), Windows 11 (10.0.26320), RTX 3080 (PCIe Gen4 x16), NVIDIA 621.24, Ryzen 7 5800X, 3840x2160, Defender real-time protection on. city-franklin-house save, standing still; each window is
APS5_TRACE_SECONDS=92:30, 30 s starting 92 s into the boot, after the scene reaches its standing point (86–88 s), with no other trace or profile switch. Warm shader caches, one warm-up per build, and every run passed the machine-quiet check. Both arms carry the same m14561 layer (#20845 and #14561, without which GTA aborts on dithered alpha-to-coverage). The base arm is #18029 merged withmainof 2026-11-17, and the PR arm is that plus exactly this PR's diff (same patch-id).tools/trace_digest.pysummary lines, one boot per arm:**seconds 92:30** from present 2485: 264 presents, frame p50 112.1 / p90 117.8 / p99 151.2 / max 171.4 ms, GPU busy 27.0 ms per present**seconds 92:30** from present 2469: 272 presents, frame p50 106.7 / p90 114.1 / p99 186.3 / max 302.0 ms, GPU busy 26.9 ms per presentAPS5_ENCODE_THREAD=1: frame p50 110.8 / p90 122.4 / p99 189.7 ms, 261 presents.Graphics.Draw119 ms on base, 233 ms here). Our later spikes are frames of 170–256 ms with no large traced slice inside them. One boot per arm cannot tell whether either differs between the arms.APS5_DIRECT_BATCHES: 120.3 ± 2.5 against 125.2 ± 2.1 ms/frame, a difference of +5.0 ± 3.3 ms, so no clear effect;APS5_NO_STREAMED_PUSH_DESCRIPTORS: 116.7 ± 1.6 against 116.3 ± 1.3 ms/frame, −0.4 ± 2.1 ms, no effect.APS5_PROFILE_DRAW=1, untimed boot), per 10 s: about 7.6k deferred and 0.7k direct batches (all opened direct because admission refused them), 0 demoted, 0 poisoned and 0 failed replays. Over the boot:[recorder] batches: 91984 deferred, 8093 direct (8093 refused by admission), 0 demoted (by command/sType: none), 0 poisoned; 91983 replayed, 0 replays failed.Seal and queue split (head
4c5b2394f72):agc_sealed_batch,agc_driver_recorder,agc_driver_recorder_record_inline,agc_driver,agc_command_thunksand the kept-bytes tests. No VUIDs on either side, and every failing test also fails on baseb412486d3e. On the Linux gate and under ASan and TSan, the 2 recorder tests stop atmain's kept-vertex-window failure described above. On Windows they stop at "an unchanged draw input was copied again", which base gives foragc_driver_recordertoo, andagc_driver_storage_flush_orderingfails on both sides.agc_driver_recorder_record_inlineis new, so the run's report counts its failure against the change, but it runs the same cases asagc_driver_recorder. ASan reports nothing. TSan reports 54 races inagc_driver, in its label-polling tests (tests/Submit.cpp) andPm4::WaitSatisfiedUnchecked; the previous head94af04a7baagives the same 54 at the same sites (run).94af04a7baaagainst the head, both with the m14561 layer and neither merged withmain, so their absolute numbers are not comparable with the pair above. The scene reached its standing point at 90.6 s (previous head) and 87.2 s (head), so the92:30window starts 1.4 s and 4.8 s after it.**seconds 92:30** from present 2455: 216 presents, frame p50 130.9 / p90 152.5 / p99 289.0 / max 324.4 ms, GPU busy 28.0 ms per present**seconds 92:30** from present 2459: 217 presents, frame p50 131.0 / p90 145.8 / p99 298.3 / max 305.0 ms, GPU busy 27.3 ms per presentFixes and
mainre-merge (head07c9482420f):vkCmdResolveImageis thunked and streamed, and a submit that queued nothing carries on (above). ThenSyncstops at the first failed wait, the typed-path check moved toContext::BatchFor, and a device-lost finish test.mainof 2026-11-19, which brings feat(agc): select occlusion counter blocks with PIXEL_PIPE_STAT_CONTROL #22465:Recorder::foldSamplestakesmain's newblocksparameter and keeps this branch's body (batch.commands, no encoder quiesce). ThreeENVIRONMENT.mdrows that an earlier merge here dropped (APS5_NO_ADAPTIVE_ENCODER,APS5_QUIESCED_SEGMENTS,APS5_NO_RECORD_ENCODER, still read by perf(agc): record transfers in the encoder stream without waiting #18029) are restored.mainmerge (74f5b8692d; the head adds onlymaina4b1bce2a6..711ab41a6e, which touches no AgcDriver file): Linux passes 85 of 85 with no VUIDs. Windows passes 84 of 85, and the one failure,agc_driver_frame_replay_cold_pipelines, also fails on basea4b1bce2a6. TSan fails the same 12 tests (agc_driver_frame_replay_*andagc_driver_host_import_lifetime) asmaina4b1bce2a6does (run), on races inrestoreGroup'smemcpy,Pm4.cpp:690and the test harness.VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation(ASAN_OPTIONS=detect_leaks=0,APS5_NO_INPUT_MIRRORS=1):agc_command_thunks,agc_command_thunks_direct_cost,agc_command_batch_failure,agc_command_batch_fence_failure,agc_driver_recorder,agc_driver_recorder_record_inline,agc_recorder_batch_fences,agc_sealed_batchand the threeagc_driver_pipelined_sample_dumptests pass, and so doesagc_command_resolver_sites. The layer loads; the only VUID is the device-creationVUID-VkDeviceCreateInfo-pNext-pNextin the sample-dump tests, from the same device setup as on perf(agc): record transfers in the encoder stream without waiting #18029.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
Summary by CodeRabbit