Skip to content

test: combine draw-ahead and user-word dependency masks - #78

Draft
JJenkx wants to merge 32 commits into
mainfrom
integration/astro-draw-ahead-user-masks-fa
Draft

JJenkx wants to merge 32 commits into
mainfrom
integration/astro-draw-ahead-user-masks-fa

Conversation

@JJenkx

@JJenkx JJenkx commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

What

Combine upstream boykopovar#6188 draw-ahead and boykopovar#5656 user-word dependency masks on main fa9365ca7, retaining both authors' commits and the published follow-ups from fork #69. This is a validation integration for upstream contributors, not a replacement upstream feature PR.

The masks must be computed for speculative captures as well as serial captures and copied by the shared DrawStageVariant constructor. Preserve current shader serialization fields and advance disk-cache format 36 to 37 for the added invocation field. Decode workers now receive the captured device's stencil-export capabilities, preserving main's merged device-dependent decode behavior without accessing Driver instance state from a static function.

New deterministic tests hold the queue until a table draw is compiled ahead, disable further compile-ahead, promote the existing key, then change an unread pixel user word. Both stages must be reused (or rebuilt and verified under the verify option), with identical rendered pixels. The older serial-only mask regression disables compile-ahead and admits its key before exercising data-only hits, matching current main's cache admission policy.

Tested

Arch Linux, kernel 7.2.9-arch1-1, Ryzen 9 7950X; Radeon RX 6650 XT / RADV Mesa 26.2.4 and lavapipe Mesa 26.2.4 (LLVM 23.1.1). Release, bundled SPIRV-Tools enabled, official vendor gitlinks. The validation source adds the separate build-applied validator repair boykopovar#6476; no private dependency pin is used.

  • Full runtime libraries and the selected draw-ahead, cache-reuse, recorder and shader-disk-cache executables build.
  • 19 CTests pass on each driver, zero CTest skips. On RADV the snapshot reuse test explicitly uses watched dma-buf backing; misalignment-only subcases requiring larger storage alignment do not execute. On lavapipe watched host-import reuse subcases are internally skipped; this is not NVIDIA coverage.
  • Disable only the worker's mask assignment: both new user-word CTests fail on both drivers. Restore it: both pass again with unchanged test-executable SHA-256 0e8213e2ef0e5c2c201471f939e9d9fb5205cd6dfb129eec16fb192b2c1630cc.
  • Conventions and whitespace pass. Windows and the complete CTest suite are untested locally for this integration.

Completed native experiment

One idle Crash Site pair on this integration, with the same position/camera and no input: the control compares every user word; the candidate honors the dependency masks. This isolates the mask optimization within the draw-ahead integration, not the whole integration against unmodified main.

Masks ignored Masks honored
Presents / measured ms 81 / 20008.749 100 / 20092.422
FPS 4.048 4.977
Frame p50 / p99 (ms) 236.510 / 416.645 187.766 / 329.183
GPU busy ms / present 173.465 150.419

Throughput is 22.94% higher in this pair. Both traces completed with no dropped events; single-pair evidence does not establish a general speedup or full gameplay correctness. Both runs ended at their planned 385s watchdog (exit 124), restored the previous 64 MiB udmabuf limit and left no game process. Ordinary close is untested here.

Same 3607-file warm-cache seed copied byte-for-byte into independent directories, same compiler fingerprint a1b6205851787f0f and format37. Both reported 1946 shader hits, 1659 plan hits and zero misses. Private compositor captures at 270s/365s confirm idle Crash Site before/after the 300:20 first-present-clock window. The game window was active at sampled times through the trace in both runs; no focus forcing or input was used. Guest output 3840x2160; window 3072x1728. Cold warm-up and the first control's arrival trace are excluded.

Control validation 3e0885dd63ea30dcf00c2a043c9df4ea0bee3c78, candidate validation 4d213a4bf76a9df4770b64fa734a3620fc636916. Candidate is the public integration plus boykopovar#6476; the control differs by one DrawLookup comparison. Timing traces, audit metadata and summaries. No proprietary screenshots or audio are attached.

{"commit": "3e0885dd63ea", "dirty": false, "env": {"APS5_DRAW_CACHE_ENTRIES": "4096", "APS5_HOST_IMPORT_MIB": "16384", "APS5_PAD_INPUT_FILE": "<path>", "APS5_PIPELINED_DRAWS": "1", "APS5_TRACE_EVENTS": "4194304", "APS5_TRACE_SECONDS": "300:20"}, "gpu": "AMD Radeon RX 6650 XT (RADV NAVI23)", "driver": "radv Mesa 26.2.4-arch1.1", "os": "Linux 7.2.9-arch1-1", "resolution": "3840x2160", "window": {"spec": "seconds 300:20", "first_present": 1745, "ms": 20008.749}, "presents": 81, "frame_ms": {"p50": 236.51, "p90": 303.57, "p99": 416.645, "max": 416.645}, "gpu_busy_ms_per_present": 173.465, "worker_busy_pct": {"queue worker 0x0": 98.884, "queue worker 0x48": 98.122, "queue worker 0x40": 98.91, "queue worker 0x46": 2.752}, "top_phases_ms_per_frame": {"Driver.Packet": 736.242, "Driver.Packet.memory_wait": 442.331, "Driver.Packet.draw": 153.626, "Driver.Draw": 152.645, "Driver.Draw.draw_enqueued": 111.283, "Driver.Packet.dispatch": 59.556, "Driver.Dispatch": 51.818, "Driver.Packet.prepare_memory": 43.988}, "trace_dropped": false, "trace": "aps5-trace-3e0885dd63ea-1734315.json.gz"}
{"commit": "4d213a4bf76a", "dirty": false, "env": {"APS5_DRAW_CACHE_ENTRIES": "4096", "APS5_HOST_IMPORT_MIB": "16384", "APS5_PAD_INPUT_FILE": "<path>", "APS5_PIPELINED_DRAWS": "1", "APS5_TRACE_EVENTS": "4194304", "APS5_TRACE_SECONDS": "300:20"}, "gpu": "AMD Radeon RX 6650 XT (RADV NAVI23)", "driver": "radv Mesa 26.2.4-arch1.1", "os": "Linux 7.2.9-arch1-1", "resolution": "3840x2160", "window": {"spec": "seconds 300:20", "first_present": 1873, "ms": 20092.422}, "presents": 100, "frame_ms": {"p50": 187.766, "p90": 253.541, "p99": 329.183, "max": 329.183}, "gpu_busy_ms_per_present": 150.419, "worker_busy_pct": {"queue worker 0x0": 98.906, "queue worker 0x40": 99.156, "queue worker 0x48": 99.1, "queue worker 0x46": 1.566}, "top_phases_ms_per_frame": {"Driver.Packet": 599.063, "Driver.Packet.memory_wait": 355.878, "Driver.Packet.draw": 125.974, "Driver.Draw": 125.204, "Driver.Draw.draw_enqueued": 93.578, "Driver.Packet.dispatch": 47.844, "Driver.Dispatch": 41.703, "Driver.Packet.prepare_memory": 40.873}, "trace_dropped": false, "trace": "aps5-trace-4d213a4bf76a-1870657.json.gz"}

Upstream relationships

Depends on upstream boykopovar#6188, boykopovar#5656, boykopovar#6326; the included draw-ahead follow-ups retain the source and ownership listed in fork #69. The boykopovar#6188 review concerning snapshot epochs is covered here by the earlier published ordered-snapshot fixture, which advances the epoch at CPU ordering boundaries and exercises watched dma-buf backing on RADV. This does not replace the requested NVIDIA review.

No proprietary assets, screenshots, captured audio, raw title logs or binaries are committed. AI-assisted: yes.

simonbronk and others added 30 commits October 14, 2026 12:02
…itles pass

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guest formatter passed the flags of %o, %u, %x and %X to the host, and
MinGW's printf prefixes a space to %u when the space flag is set: "% u" of 5
gave " 5". C17 7.21.6.1 applies both flags to signed conversions only, and
FreeBSD 11.4 vfprintf clears the sign for every unsigned conversion (nosign).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The MinGW-w64 lgamma overflows to infinity for nonzero |x| at or below 2^-1024. FreeBSD msun e_lgamma_r.c returns -log(|x|) for every nonzero |x| below 2^-56, so take that branch before the host function.

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>
…view

Vulkan cannot view a stencil aspect as UNORM, so an 8-bit UNORM view of
a stencil plane threw. Copy the stencil aspect through a buffer into an
R8_UNORM image of the surface's extent and sample that. The copy is kept
on the surface and refreshed when the surface was written since, or while
it is the bound depth target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t-undefined-bits

fix(libkernel): drop undefined protection bits in sceKernelMprotect
…-unwind-address-overflow-guards

fix(relinker): guard against address underflow in encoded unwind pointers and reject zero FDE CIE offset
…signed-sign-flags

fix(libc): ignore the space and + flags for unsigned printf conversions
…ny-arguments

fix(libc): keep lgamma finite for subnormal arguments on Windows
…e-state-bit

fix(libSceConvertKeycode): ignore the state bit 0x4000000 RE Engine titles pass
…imit-by-mapped-memory

fix(agc): bind a V# past the range limit by the memory behind it
…l-as-unorm

fix(agc): sample a depth surface's stencil plane through an R8_UNORM view
PrepareDrawBindings gave every read-only input it snapshotted per draw a
pooled Buffer of its own. When the unwritten-snapshot map missed, it
collected the range's writes and probed the reuse cache, and on a miss it
allocated a Buffer, copied, and recorded the Buffer in both caches.
Inputs of up to 4 KiB now probe only the map of unwritten slices: a hit
binds the slice an earlier draw of the same collect epoch and tracker
generation copied, and a miss copies the input into a slice of a 4 MiB
host-visible chunk owned by the recorder (a bump allocation and one copy)
and notes it there under the same rule as the unwritten snapshots. Without
a collect epoch (APS5_NO_COLLECT_MEMO), which alone bounds that rule for
CPU stores nothing collected, small inputs are copied every time. The
descriptor points at the slice's offset and range. Larger inputs and moved
shader data keep their reuse caches. Offsets only grow within a chunk and a
full chunk is replaced, never rewound, so no two slices share bytes; the
draw's bindings hold the chunk until their batch completed, and replacing
the chunk forgets the noted slices, so the map pins at most the current
chunk.

Each new slice charges the open batch the chunk space it consumed,
alignment padding included, and the slice that replaces a chunk also
charges the tail it leaves unused, so a chunk's whole capacity is charged
once and a batch's kept bytes cover the chunks it retains (at most one
chunk shared with an earlier, completed batch is not counted). A new
slice counts as kept by its batch, so reusing it there charges nothing; a
slice reused by a later batch is charged once by that batch, as a reused
snapshot is.

The descriptor tests compared snapshot descriptors against offset 0 of a
buffer of their own; they now compare against the snapshot's range, and
the reuse test uses an input above the slice limit. A new test covers slice
placement, alignment, disjointness across chunks, the charge of a chunk
filled by 4-byte slices, the reuse of an unchanged slice within a collect
epoch without a second charge (and its copy every time with collect
memoization off, agc_draw_snapshots_no_collect_memo) and its replacement after a store and a new epoch, and the chunk's
lifetime; agc_draw_snapshots runs the draw snapshot tests.
VulkanDevice copied the cached Graphics::Context (device functions,
limits, the buffer pool reference) for every KnownDrawRejection, Draw and
DrawFromRecipe call, twice per draw on the queue-0 thread. These calls now
take a reference to the context the device built at creation; only
APS5_NO_CONTEXT_CACHE builds one per call, as before.
Every queue-0 draw resolved its parameters, ran the register precheck and
built the draw key on the recording thread (with the incremental register
fingerprints the key still hashes the user words and looks up the five
shader addresses in the registry). A scan thread now executes each queue-0
submission on a copy of the queue state while queue 0 records it, and
publishes per draw packet, in order, the key with its shape, the
parameters and the precheck outcome. Queue 0 takes a record instead of computing them when it
is certain and still matches.

A record is exact for the state the scan executed. Packets queue 0 may skip
(COND_EXEC ranges, predicated packets while predication is armed) or whose
value comes from memory (COPY_DATA into a register) mark the registers they
write as divergent; an unconditional write ends the divergence, CLEAR_STATE,
CONTEXT_STATE and a reset carry it like the state itself, and a whole-state
change under a condition loses the scan until an unconditional reset. A
certain record lists at most 64 divergent registers with the values the scan
had, and queue 0 uses it only when these, INDEX_BASE, the index type, the
instance count, the device and the submission all match its own state; any
other draw takes the full path. Indirect draws are never published.

The precheck's register part becomes PrecheckDrawState so both threads
share it; the metadata pass and the trace stay on queue 0. The scan notes
a dispatch's initiator and group counts in the shader registers as queue 0
does. Pm4 exposes the register offset decode and the registers a COPY_DATA
writes.
Draws whose register key is new (per-frame ring addresses in user data make
most keys new every frame) captured and recompiled their stages on the
queue-0 thread, or, when their shape has an entry, re-read its user words
and recompiled the stages whose captured reads changed. The draw-ahead scan now queues every such draw it publishes
with a Proceed precheck to worker threads (a quarter of the hardware
threads, one to four), which decode the draw from the scan state, capture
and materialize its stages with the same request the queue-0 miss path
builds (DrawStageRequest, DrawStageVariant, shared with it, with the
position export layout the miss path gives the vertex stage, and the pure
data positions of each stage) and insert the variants into the draw cache
under the draw's key and shape. Queue 0 then finds an entry and validates
it as it validates any cached variant, against current memory.

The key holds registers only, and validation compares captured memory, so
a worker compiles only draws whose compile request depends on nothing else
(DrawAhead::CompilesAhead). A mesh draw takes the descriptor of its index
buffer from its packet into its hidden user words, and an instanced
tessellation draw numbers its hull patches by its packet's counts (queue 0
does not cache those): a skipped draw of one buffer would otherwise leave
its compile under the key an executed draw of another buffer finds. Both
are left to queue 0, as indirect draws are.

Admission. The driver caches a key at its second sight, or at its first
when its shape was seen before and has no entry, so that a key that never
comes back does not push a live entry out. A key the workers compile is
consumed by queue 0 at its own draw, so the scan compiles keys on their
first sight too. An entry inserted ahead is no sighting: it goes on
probation, whatever the key's earlier sightings, since queue 0 may skip its
draw. It lives in the draw cache beside the others, in its own list bounded
by the cache's size, so probation entries push out only each other and
never an admitted entry. A queue-0 draw that found a probation entry
counts as a sighting under the same rule at the point where the driver
sights an absent key, so only a draw it would consider caching sights it
(no instanced tessellation draw, no indirect draw drawn on the CPU), once
per draw (the entry itself does not count as its shape's entry); the
sighting that admits the key promotes it into the cache's order, so a key
is admitted at the execution that would have admitted it without
compile-ahead. The sighting and the decision to insert queue 0's own
compile are one step under the cache mutex (admitDrawKey), so a probation
entry a worker inserts while queue 0 compiles the same key counts this
execution's sighting as the absent key would have. A worker never inserts into an existing
entry, and it builds its entry before it takes the cache mutex, so queue
0's lookups wait for no more than the map and list update. An insert builds the entry and its list node before it changes the
cache, and traces and reserves the evictions that follow before it, so it
either completes, evictions included, or leaves the map, the lists, the
shapes and the variant accounting as they were. APS5_TRACE_DRAW_CACHE,
whose eviction trace can still throw, keeps the workers out. Entries an insert evicts or replaces
are released after the cache mutex is, so queue 0's lookups do not wait for
their destruction.

Speculative reads. A worker may read guest memory before queue 0 passes the
waits that order it after CPU or GPU stores, and memory a skipped or
divergent draw names may be unmapped meanwhile. Under a
GuestMemory::SpeculativeReadScope, Read copies through the kernel
(process_vm_readv on the own process, ReadProcessMemory on Windows) into
the capture's private buffer: no C++ evaluation of the worker accesses guest
memory, so a concurrent store is not a data race, and an unmapped page
fails the copy instead of faulting. No flush hook runs, and every other
guest memory access (compares, committed reads, stores, FlushGpuWrites)
throws in that scope. The compile reads only the private copy, and the
variant records exactly the words it was compiled from; queue 0 compares
them with memory after its waits and flushes, so a capture holding stale or
torn words is used only when memory then holds exactly those words.
Without a working kernel copy no workers run.

Lifetime. Every guest read of a job and its cache insertion are pinned to
the job's draw. Queue 0 passes a draw before executing it and retires its
submission when it ends (also on an exception); passing waits for pinned
sections at or before that position, later pins are refused, and retiring
drops the submission's queued jobs and scans and stops its scan; a scan
checks for retirement before it allocates its records. So no worker reads
guest memory for, or inserts an entry of, a draw queue 0 passed or a
submission that retired, including draws inside a false COND_EXEC.

The scan decodes ahead only with registered shaders: raw programs would be
read from memory and NoteRawGraphicsDraw, which refuses later shader
registration, must only follow a draw queue 0 executes. Submissions
without a direct draw are not posted, nor is a submission that arrives
while the scanner is still busy with an earlier one, so queue 0 copies a
submission for the scanner only when the scanner can start on it. A debug probe or APS5_INSERT_COMPARE
keeps the workers out. The print-once flags in DecodeState become atomics
now that two threads decode. Driver::DrawAheadStatistics counts published
records, records queue 0 used, compiled and dropped jobs (a draw whose
decode fails ahead is dropped), and APS5_PROFILE_DRAW reports them per 10 s
([draw-ahead]).

DrawCacheReuse counts queue 0's own admissions, data hits and inserts, so
it turns compile-ahead off (DrawAhead::SetCompileAhead). The new test
holds queue 0 behind a WAIT_REG_MEM and requires every draw behind it to be
compiled ahead, its published record used, reused without misses and
to render the pixels of the uncached path (debug probe), then to keep
their entries through their second and third sight; a draw executed once,
then compiled ahead inside a false COND_EXEC, stays on probation and is
admitted at its next execution; two executions of an indirect draw the
queue draws on the CPU do not promote the probation entry of a skipped draw
with the same registers, and the direct draw is then admitted at its
second execution, as without compile-ahead; mesh, instanced tessellation and indirect
draws are not compiled ahead; a submission whose
1024 draws lie in a false COND_EXEC inserts nothing after it retired; a
table read by the fragment shader, stored by the CPU while queue 0 waits or
by WRITE_DATA before the draw, renders the stored value. It runs again
under APS5_VERIFY_DRAW_ENTRIES, where queue 0 recompiles each hit and
compares its capture and its compilation (SPIR-V module, variant,
bindings, push constants) with the workers'. DrawAheadRaw requires that a raw
draw the queue skips leaves shader registration open.
A draw that misses its recipe (every draw of an entry the workers just
compiled) validated its shaders against the state, looked up or built the
vertex input layout and built the pipeline stage mask and the resource
content key on queue 0.
These depend only on the decoded state and the compiled stages, so the
draw-ahead worker computes them once (Graphics::PrepareDraw) and stores
them on the entry, tied to the exact variants it compiled (weak references,
so a released or replaced variant never matches). Queue 0 passes them to
Graphics::Draw when its hit matched those variants, refreshed no stage data
words, is not indirect and the stage count is unchanged; otherwise, and for
rect lists and emulated barycentrics, it computes them as before. The
prepared vertex input layout is shared with the draw like a retained one. Rotated and replaced entries keep the record.

A speculative failure never surfaces. An exception in the scan, a draw's
resolve or decode, or a worker's capture and compile means only that the
draw has no precomputed result (for a scan exception, the rest of the
submission has none): no record is published and no entry inserted. An
exception in PrepareDraw drops only the prepared state: the compiled entry
is still inserted and queue 0 prepares the draw itself. PrepareDraw's
shader validation keeps its failure to itself: only queue 0 records one in
the failures KnownValidationFailure reports, since the draw that fails it
ahead may be one queue 0 skips or draws nothing for (a draw of zero
instances returns before its shaders are validated). Queue 0 then
performs the draw exactly as without draw-ahead, on current memory.
This is not a silent fallback: that serial path is the authoritative implementation and throws on a genuine error,
while what the speculation saw (stale, torn or not yet mapped memory, a
context stack it cannot follow past a skipped packet, a vertex layout the
draw never builds) is not an error of the draw. A guest read refused to a
speculative reader, whose draw the queue has already passed or whose range
is inaccessible, throws GuestMemory::SpeculativeReadRefused.

The test renders, as the uncached path does, a draw whose buffer
descriptor is invalid while the worker compiles (the capture records the
invalid words) and repaired before the draw, a draw whose table is mapped only after the worker's read, a draw
after a CONTEXT_STATE push in a skipped COND_EXEC (the scan executes it,
fails on the next push and publishes nothing more), and an indexed draw
of restart indices only whose vertex stride exceeds the device limit (its
prepared layout fails, the draw builds none). An indexed draw of fetched
vertices compiled ahead draws through its prepared vertex input layout and
writes the pixels of the uncached path, and a zero-instance indexed draw
whose vertex program exports no position, compiled and prepared ahead,
draws nothing as without draw-ahead; a speculative read of an inaccessible
range is refused. Each pass sets NUM_INSTANCES.
Every cache hit validates each stage's captured runs, and two of its
checks scanned linearly: StorageTexture::AnyPendingOverlaps compared every
run with every pending image, and AnyShadowedOverlaps took the shadow
registry's mutex once per run. With compile-ahead almost every draw is a
hit, and these checks were two thirds of a stage validation in ASTRO BOT's
crash-site hub.

AnyPendingOverlaps now asks the pending list's sorted, merged range index
(PendingList::MayOverlap, the one PendingStorageOverlaps uses), which holds
exactly the union of the pending images' guest ranges, so its answer is
unchanged; images being flushed are still compared one by one.
AnyShadowedOverlaps takes the registry mutex once for all runs.

The unit shadow test and the store-over-untracked test check a list of
runs that overlaps only through its last run, and one that does not
overlap at all.
A data-only hit (boykopovar#494) reused a cached stage only when every user data word
of the stage was unchanged. A stage records the user words it depends on when
it is captured: the words its SRT walk reads (GetUserData), the words its
binding layout forwards into shader data, and the vertex fetch table words of
its vertex stage info. A cached stage is now a candidate when only words
outside that set changed; its captured memory is validated as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants