Commit Graph
553 Commits
Author SHA1 Message Date
Anees Iqbal cee5c7eeb3 Name a draw's read behind a barrier as the cause in the render-pass-split notice
What: a split made so a draw reads a color attachment's texture after a memory barrier
(`Split::AttachedRead`, the pass-start barrier's split among them) is now counted for the
split's degrade notice (`SplitCauses::attached_reads`), whose reason says so: "draws that read
a color attachment's texture after a memory barrier read what its load actions and the draws
before the barrier stored, in a Vulkan render pass instance after theirs, ending N of them".
The `RenderPassSplit` declaration and docs/API.md's catalogue entry list the cause.

Why: such a split counted neither as a barrier split (`self.barrier` is false for a
render-target barrier before any draw, and for one between draws, which records in the
instance) nor as any other cause, so the notice fell to its last reason, "its draws keep
different attachments out of their subpass", which describes no part of this pass. The
conformance replays of the pass-start barrier family showed the split announced on every
barrier row (Apple M3 Max, lavapipe).

How verified: builds (conformance binary, debug). The lane assertion added to
`a_draw_after_a_barrier_at_the_pass_start_reads_the_clear` (the split's reason, and a notice
exactly where a pass split) is NOT yet run; the runtime-sources pin is not re-hashed (the
coordinator's).

(cherry picked from commit 30b797c61b27d4dbe34386c36a27837bb3ed8ead)
2026-11-04 21:54:21 -08:00
Anees Iqbal 34bafa410d Record the pass-start barrier family on the M3 Max (unverified on our side)
WORK IN PROGRESS, parked: recorded on Metal, not yet replayed on the runtime.

pass_start_reads.rs adds 13 conformance cases (pass-start-barrier-*), each a pass that clears a
BGRA8Unorm target and draws a read of it (owned fixture psb_reads):
- 32x32 private and over-a-buffer targets, each with: the barrier then a read at own pixels; the
  barrier then a pixel-coordinate sample; the read and the sample with no barrier; a solid draw,
  the barrier, then the read.
- display-masked-read: a 1728x1216 private target holding an earlier DontCare pass's leftovers
  (61x55, 45x45), cleared, the barrier, a read at own pixels through a 453x100 scissor beside an
  A8Unorm mask over a buffer at texture 3.
- new-texture-chain: two new 896x576 private textures, each cleared, the barrier, a read at own
  pixels through 841x521 (the second beside the first at texture 3), then a target over a buffer,
  loaded, the barrier, and a read of the second over it.
- new-texture-tile: a new 448x576 texture cleared, the barrier, a read over all of it.
Texels are recorded as runs of equal texels (fresh_contents::texel_runs, now pub(super)). Rows
with a barrier accept, beside the M3 Max's recorded answer, the Mac2 answer the case states, by
docs/API.md's accepted difference a-barrier-over-the-render-targets-orders-what-it-names-as-a-
mac2-gpu-s-does (the sentence naming these cases is added to it here). tests.rs bills the 13
cases' cost records to the next whole-set run (AFTER_THE_LAST_RUN).

Verified:
- conformance record on the M3 Max (macOS 27, 3 runs, one outcome each): every row's read
  draws the texels from before its pass, the barrier or not; Metal's validated leg stops the
  barrier ("scope (0x4) cannot contain MTLBarrierScopeRenderTargets on this device; afterStages
  (0x2) can not contain ... MTLRenderStageFragment on this device").
- cases::pass_start_reads unit tests pass (plain target), including
  metal_reads_the_texels_from_before_the_pass_on_the_small_rows against these recordings.
- clippy -p metal2vulkan-conformance --all-targets --all-features -D warnings.

Unverified / owed:
- conformance replay of these cases on the runtime (M3 MoltenVK, 5080, lavapipe): whether each
  barrier row matches the stated Mac2 answer exactly, and which notices each venue announces
  (shared-in-system-memory is declared; shadowed-texture or dont-care-stand-in may be needed).
- times::every_case_carries_its_timing fails until `conformance times --write` runs over these
  13 cases on the M3.
- docs/CONFORMANCE-COVERAGE.md not regenerated.
- new-texture-chain's recording is 1.46 MB of pretty-printed JSON (three 896x576 sites of 1042
  runs each); consider dropping the first texture's site.

(cherry picked from commit 724afbf80b78c14a8824dfb96203df3813fba9aa)
2026-11-04 21:54:20 -08:00
Anees Iqbal 60d3c512a6 Announce copied-host-pages for a buffer that lies in a live copy
What: a no-copy buffer or rebind that lies in the live copy of the same
bytes (`Device::degrade_copied_shared`) announces `copied-host-pages`, its
detail saying it lies in that copy and whether the copy drops the GPU's
writes. docs/API.md says so.

Why: such a buffer makes no copy of its own, but the GPU uses a copy for
it all the same (`Buffer::host_backing` answers `Copied`); before the join
each one was a copy and was announced. A consumer that asks for the kind at
each occurrence (`DeviceOptions::announce_each`) hears it per buffer as
before.

Verified: cargo check of the runtime (all features); the lane runs follow
on the M3.

(cherry picked from commit a4a75f118381a9f049157b1da063ba2fa4c9bff5)
2026-11-04 21:54:20 -08:00
Anees Iqbal 6c4b409fb0 Lay a no-copy buffer over a live copied host buffer's bytes in its copy
What: a copied host buffer (the caller's gate refused the import, or an
admitted import failed) now joins its memory and is placed as an import is
(`HostAliases::join` with `Kind::Copy`, `HostAliases::place`). A later
no-copy buffer over exactly the same first byte and length, of either
storage mode, finds it (`HostAliases::import`: an import of its class,
else the live copy), lies in it through `Device::buffer_in_import`, is
named to it (`copied_as`) and joins its key, with the gate not asked. A
rebind onto such bytes lies in the copy too where its textures were
planned at the copy's offset (its first byte) and no image in place rides
on it; an import keeps the old `!moved` rule. A heap's own copy is placed
but joins nothing; a buffer whose writes are dropped keeps its read-only
view. New counter `WorkCounts::copied_host_buffers_shared`.

Why: two copies of one memory agreed only through the pages (merge back
at the writer's completion, copy in at the reader's commit). reims-vgpu
measured on the M3 (MoltenVK) two textures over one 64x64 BGRA8 surface,
each over its own refused no-copy buffer: a blit write then a blit read in
one command buffer, and a reader committed first on a second queue waiting
on the writer's event, both read all 16384 bytes stale, where Metal and
the runtime in place read the write. The consumer also made a full copy of
the surface per texture per present.

The remaining GPU-to-GPU gap, between a copy and another copy or import of
overlapping but different bytes, is recorded in copied.rs, docs/API.md,
docs/HOWTO.md and docs/FAST-PATHS.md's known gaps.

Verified: cargo check of the runtime with tests; the lane in the next
commit, run on the M3 (see its message).

(cherry picked from commit 69feb791dc6ec3bc2405dbf5b6ae5d0b27d936aa)
2026-11-04 21:54:19 -08:00
Anees Iqbal 3797c098eb Order a pass's clear before a draw that reads it after a barrier at the pass's start
A pass that clears a color and begins with a memory barrier over the render targets (after the
fragment stage, before it) and then samples that color's texture in a draw read the texels from
before the pass. Mac2 GPUs read the clear there (an Intel UHD 630 after the barrier, an AMD
Radeon Pro 5300M with or without it). The draw reads the texture's copy, taken ahead of the pass's
load actions (render/shadows.rs), and a barrier split the pass only where a draw of the current
instance came before it, so a barrier at the pass's start split nothing.

Such a barrier now orders the pass's load actions (`loads_ordered`): the scope form with the render
targets, or the resource form over an attachment's texture, after the fragment stage and before a
stage at or before it, recorded before any draw of the pass. A draw after it that samples the
texture of a color the pass clears (`Texture::cleared_in`) takes the existing after-barrier path:
it records into an instance after the pass's first, which runs the clear and draws nothing
(`next_instance` keeps the first instead of replacing it), so the copy before it holds the clear;
or, where the device has them, it reads through snapshots inside the first instance. The split is
counted as the after-barrier read's (`attachment_read_splits`, `instance_splits_attached_read`)
and reloads stand-ins over a buffer's bytes as one after a barrier does. A pass with such a
barrier but no such draw records as without it.

docs/API.md section 10 gets the accepted difference this ordering is: Apple GPUs do not support
the render-target scope, and the M3 Max reads the texels from before the pass after it.

The owned fixture psb_reads (regen-air-fixtures) holds the functions the lane and the coming
conformance cases draw with: a read and a pixel-coordinate sample of texture 0 at the fragment's
own pixel, channels reordered so a read is told from a skipped draw, and two-texture reads.

Verified on the M3 Max (MoltenVK, debug, --cfg m2v_gpu), runtime_lane::attachment_reads:
- a_draw_after_a_barrier_at_the_pass_start_reads_the_clear: both targets (own image, over a
  buffer), psb_read and psb_sample, the scope alone, with the textures and the resource form:
  the clear inside the scissor, one split each (attachment_read_splits 1, instance splits 1,
  2 instances begun), own-pixel copies of 308 texels (the 20x12 scissor and a pixel round).
- a_draw_after_a_clear_with_no_barrier_reads_the_texels_from_before_the_pass: no split.
- a_barrier_at_the_pass_start_costs_nothing_without_a_read_of_a_cleared_color: a loaded target
  read after the barrier, and a cleared one with a draw reading another texture: no split, as
  many instances begun and copies taken as with no barrier.
Negative control: the same tests on the tree without the runtime change fail at pixel (4, 4),
reading [0, 64, 0, 255] (the texel from before the pass, reordered) where the clear's
[120, 200, 40, 255] is due.

(cherry picked from commit 923095effcd188a93ee5134ecc4dad3fab21b3fe)
2026-11-04 18:50:30 -08:00
Anees Iqbal 1a541744e1 Destroy an event's semaphore where its release goes again, and record NVIDIA's event costs
What: an event's release destroys its timeline semaphore on the releasing thread again, as at
4bbafa667d (event.rs is that commit's again); the device's free thread frees blocks alone. The
semaphore posting goes with its counter (WorkCounts::semaphore_destroys_posted; the API table
blessed: the field removed), its runtime test and its lane rows. docs/FAST-PATHS.md's known gaps
record what making and releasing an event costs on NVIDIA, and why the release is not posted.

Why: NVIDIA's driver runs a vkCreateSemaphore behind a vkDestroySemaphore another thread runs,
so a posted destroy moves its cost onto the program's next event and adds to it. Measured on the
RTX 5080 Laptop GPU with the bench's event modes (each row 1000 events unless said; before and
after interleaved within each hold; CPU package 83-103 C), p50 unless said:

  burst, 1000 made then released     inline: make 143-262 us, release 495-579 us
                                       (0.47-0.57 s a 1000 released)
                                     posted, bound 4096: release 0.2-0.5 us, but the makes
                                       while the destroys drained 1048-1676 us (1.10-1.66 s
                                       a 1000)
                                     posted, bound 64: release 0.5-1.2 us, p99 1.5-2.2 ms,
                                       0.51-0.66 s a 1000; makes unchanged
  steady, make one and release the   inline 203-238 us a pair; posted (64) 390-507 us
  one before, back to back
  steady, 2 ms apart (500)           inline 488-490 us a pair (event), 663-677 us (shared);
                                     posted 260-263 us and 417-421 us
  the driver's own cost              grows with the semaphores live: 98-119 us a make and a
                                     release with one or two live, against the burst's
                                       143-262 and 495-579 us with 1000 live

On the M3 Max (MoltenVK 1.4.2) a pair costs 2.6-2.8 us inline and 5.3-5.9 us posted back to
back, about 45 us either way 2 ms apart; Metal's own newEvent and newSharedEvent take 0.8-1.9
us there. The consumer's guests made no event in a boot of theirs, and their host makes a few a
second, so no shape of use has the posted destroy ahead, and the burst at a program's close,
which posting was for, gains nothing: the device's teardown drains what was posted.

Verified on the M3 Max (debug, --cfg m2v_gpu, under maclock and memcap): 90 runtime tests
(posted_frees, freed_memory, teardown_threads, memory, allocations, event, cpu_copy_layouts)
and 27 lane tests (posted_frees, shared_event, events, pool_churn, staging_batches) pass;
api_signatures and api_surface pass; clippy (plain and --cfg m2v_gpu, workspace, all targets,
all features) and the release check of the runtime's tests are clean. The inline rows above
are the RTX 5080's at 4bbafa667d's event path, which this restores.

(cherry picked from commit 1659544703425cd461106fba2cff7cfe73a02a8a)
2026-11-04 18:50:29 -08:00
Anees Iqbal b2df1add01 Bind a storage view of a whole buffer from its space's start, so draws that move only an offset keep their set 0
What: `bind::instantiate::planned_range` gives a descriptor-form slot read
through a storage view of its `Whole` window the range from the start of
the bound buffer's space to its padded end, whatever the bind offset, and
the bind offset as its `SlotBindOffset` residual. `bind_buffers` (every
draw's and dispatch's instantiation) and `rebind_slots`
(`rebind_draw_slots_into`) take it. Every other slot keeps
`descriptor_range`'s range: uniform views (whose `RangeAtBindOffset`
specialization reads a range from the bind offset), bounded windows, and a
storage view whose range from 0 would pass the view's
`maxStorageBufferRange` (`PlannedBuffer::max_range`) or 2^32 bytes (a
32-bit residual and offset), or whose bind offset lies at or past the
padded end. The tessellation factor and index bindings keep it too.

Why: `EncoderCore::set_zero_of` was 14.3% (draws.10k) and 8.8% (WS-like)
of the encoding thread's samples: every draw allocated, wrote and bound a
set 0 of its own. A `device T *` slot's range started at the bind offset
aligned down, so each new offset wrote another descriptor and neither
`LastSetZero` nor `SetCache` could match.

Vulkan: the descriptor's offset is the space's start (256-aligned, as a
bind at offset 0 has it today) and its range ends where today's ends (the
padded end), so offset + range, and a dynamic binding's effective offset +
range (VUID-vkCmdBindDescriptorSets-pDescriptorSets-01979), are what they
were. dynamic_writes moves that same start into the dynamic offset for
every bind offset. The range is explicit, never VK_WHOLE_SIZE (06715 does
not apply). Hazard ranges are untouched: they come from the plan's use
ranges from the bind offset (`binding::bytes_use`).

Behaviour: a Metal offset m from the bind offset reads byte residual + m of
the range, the same byte as before for every access inside the window. An
access that reaches back before the bind offset (a negative index, the
32-bit offset wrapping) and lands in the buffer's space now reads and
writes the buffer's bytes there, as Metal's does; before, it lay outside
the descriptor range unless it stayed within the alignment's residue. On
a device with robustBufferAccess (or under in-shader containment against
the view's size) accesses are bounded by the larger range [space start,
padded end) instead of [bind offset aligned down, padded end): such an
access before the bind offset is in range and reaches the buffer's bytes
where it was a robust out-of-bounds access (a zero, a value from within
the buffer, or a dropped write). Accesses past the end are bounded as
before.

SEMANTICS_VERSION 1957 -> 1958: instantiated descriptor ranges and
residuals change. golden_hashes_match_the_table passed unchanged here (it
hashes compiled modules, which this does not change); the re-bless on
development decides.

Tests: planned_range's unit tests (the range from 0 and the residual at
every 4-byte offset for base alignments 16, 64 and 256, and a 2^32-byte
buffer at its last word; each fallback equal to descriptor_range's
answer). A device test, set_zero_at_offsets: 9 draws of colored_vertex
moving only two device buffers' offsets reuse 8 sets and bind 1, and draw
what 9 draws of buffers of their own draw (0 reused, 9 bound).
dynamic_multi_variable's moved-offset dispatches now reuse their
predecessor's set (7 of 8) and still answer Metal's values from each
dispatch's own offset. docs/API.md states the range.

Verified: the translator suite, 3324 of 3324 (plain). On the M3 Max
(MoltenVK 1.4.2), debug, --cfg m2v_gpu, under maclock and memcap: 96 of 96
runtime tests (fix 1's set plus set_zero_at_offsets,
dynamic_multi_variable, uniform_bind_offsets, binding_view, range,
rebind_descriptor_slip, rebind_behind_a_wait, depth_ranges, attributes),
and 220 of 220 validation lanes under the validation layer (fix 1's set
plus stage_in_regions, stage_in_strides, padded_loads, escaped_slots,
absent_reads, chosen_pointers, dispatch_*, read_through_views,
guarded_effects, index_fetches, first_vertex, vertex_strides, host_bytes,
pointer_uploads, commands_recorded, runtime_lane::tests, among them
renders::public_render_cases_match_metal and
tests::stage_in_region_cases_match_metal). Negative control:
planned_range forced to fall back fails set_zero_at_offsets ((0, 9)
against (8, 1)) and both dynamic_multi_variable moved-offset tests
((0, 0) against (7, 0)). clippy plain and with --cfg m2v_gpu clean.

Per draw on the encoding thread, release with thin LTO, 3 interleaved
rounds against the parent build, medians:
  draws.10k  11201.7 ->  9212.4 instructions (-17.8%), 616-661 -> 485-495 ns
  WS-like    23121.1 -> 21752.5 instructions (-5.9%)
One round's counts: draws.10k 0 -> 29880 sets reused, 30000 -> 120
vkCmdBindDescriptorSets, 6 -> 60000 vkCmdPushConstants (the residuals;
both stages' writes are pushed where either changes); WS-like 0 -> 3744
sets found in the command buffer's cache, binds unchanged at 4000.

(cherry picked from commit b875660ecbad7dd6f9dfa9f976ef1c2b32bded1e)
(cherry picked from commit b09293e9c22d80e4ae4c505b00ba0e07e6a8165c)
2026-11-04 18:50:27 -08:00
Anees Iqbal cc6b083fc2 Let what every write route of a command buffer may write reach every buffer it made resident for writing
What: what an indirect command buffer's records may hold (WrittenCommands, command_writes) took a
writer's writes only from the encoder that made the buffer resident for writing (Writers: the
state set then, each set after, and that encoder's executions). The routes that mark the buffer
(write_routes.rs) were already the command buffer's. Routes now keeps what all of its routes may
write (states set in any encoder, before the residency or after it, and what executed buffers'
records may name) and adds it to every buffer made resident for writing, at the call that brings
either; an encoder opens with what the ended ones met. For two encoders open together (a parallel
render encoder's) the commit adds what each did not see of the other, and the followers that
sets off are marked outside the command buffer's lock, as the commit's marks are. Writers is
gone: Routes holds a superset of what it held.

Why: Metal runs what a kernel wrote with the buffer resident for writing in any encoder of the
command buffer, before the kernel's or after it (the probe icb_routed_writes.m, M3 Max, macOS
27.0.1). The marks matched that; the summary did not, and an execution of a buffer that inherits
the encoder's state decides on the summary whether the GPU alone runs it, as draws of the one
primitive type it allows. With the residency in another encoder than the kernel's, the GPU alone
ran the kernel's point as a draw of the CPU's triangles, which drew nothing (the previous commit's
lane). The bug is older than the write routes: the summary was per encoder before them too.

What it moves: an execution of a buffer whose command buffer sets, in another encoder than the
one that made the buffer resident, a state that may write what the GPU-alone forms rule out: a
render execution takes the host step where that state may write more than draws of one primitive
type, buffers, resets and cleared barriers; a compute execution in a concurrent encoder orders its
commands where it may set a barrier, and a checked one calls its check where the records may name
a state that may encode. The lanes that made a buffer writable with a state set in an encoder of
its own (indirect_host_steps::encoding_state_set: icb_replay_encode's, which may set pipelines,
dispatch, set threadgroup lengths and barriers) showed it: with it, 6 of the 480 tests of the 40
modules changed (render_merged_executions' GPU forms into a shadowed target took the host step,
6 executions; five dispatch_executions tests saw barriers, check calls and a host step), all
others as before, resident_draws among them (its writer and residency share an encoder: no host
step on its write path, its chunks kept). Those lanes are about the GPU-written path, not about
what the state writes, so the lever now sets icb_reset_encode's state (resets alone, which no
GPU-alone form rules out).

Docs: written_commands.rs and write_routes.rs module docs, IndirectCommandBuffer::command_writes,
render/executions/gpu.rs, the runtime README and docs/API.md section 10.

How verified (debug, --cfg m2v_gpu, M3 Max under MoltenVK): runtime_lane::write_routes passes
(it failed before this commit: After and Before drew no point); the 39 ICB lane modules and
write_routes, 480 tests, pass with the reset lever; the runtime's
tests::write_routes_device::a_route_reaches_every_buffer_its_command_buffer_made_writable (new:
a later encoder's state, one set before the residency, and a parallel encoder's at the commit)
and tests::written_commands pass; clippy -D warnings with --cfg m2v_gpu is clean.

(cherry picked from commit 7d13a4dee21162a972b40fd9868e3e2f9112a677)
(cherry picked from commit 13b9646e48b767defdd189bf156a2a9130b3b857)
2026-11-04 18:50:27 -08:00
Anees Iqbal e924d293c5 Compare against Metal what an execution runs of commands a kernel wrote, by where the command buffer made the buffer resident for writing
What: a new owned fixture, icb_routed_writes, whose kernels write command 0 of an indirect command
buffer: a render command with its state taken from the argument buffer (irw_encode_draw), a
render command of a buffer that inherits the encoder's state, a point at the target's centre
beside the CPU's triangle in command 1 (irw_encode_point), and a compute command with its state
from the argument buffer (irw_encode_dispatch). A Metal probe
(crates/metal2vulkan-conformance/probes/icb_routed_writes.m) and a lane
(runtime_lane::write_routes) run the same four shapes: the buffer made resident for writing in
the kernel's encoder, only in an encoder after it, only in one before it, and nowhere; a later
encoder of the same command buffer executes the buffer.

Why: the marks of a buffer the GPU may write are the command buffer's, while what its records may
hold was gathered per encoder. The lane asks whether an execution runs what the GPU wrote, with the
right state and pixels, wherever the command buffer paired the residency with the writer.

Metal's answers (the probe, M3 Max, macOS 27.0.1, validation off, verified): in the kernel's
encoder, after it and before it, all three kinds ran the kernel's command (green, green, words
0x100 to 0x103). Nowhere: the render command and the point did not run (the CPU's records: red),
the compute command did. docs/API.md records that last difference: no encoder of the command
buffer made the buffer resident for writing, which Metal's contract asks of a function's write,
and the runtime runs the CPU's records there (APART in the lane).

How verified: the lane, debug with --cfg m2v_gpu on the M3 Max under MoltenVK, fails at this
commit, which is the bug the next commit fixes: [(Same, [true, true, true]), (After, [true, false,
true]), (Before, [true, false, true]), (Nowhere, [false, false, false])] against Metal's (with the
compute command apart), the inherited state's executions taking 2, 0, 0 and 0 host steps: with the
residency in another encoder than the kernel's, the GPU alone ran the kernel's point as a draw of
the CPU's triangles, which drew nothing. The render command and the compute command ran right in
every shape.

(cherry picked from commit 25134688d13d1abedab5e3ee5e1ff4c9db442a90)
(cherry picked from commit ba7f047a7987a63a9e1f6fd78ae7093f27326e55)
2026-11-04 18:50:27 -08:00
Anees Iqbal f35128eb43 Mark an indirect command buffer at the call that completes a write route, and let the routes go at the commit
The write routes marked a buffer at its command buffer's commit. An execution's segment is cut
into a part of its own, which waits for the work before it, as it is encoded
(`Segment::host`, from `gpu_written` then), so an execution encoded after the writer in the same
command buffer, in its encoder or a later one, was recorded with the writer's part and ran the
CPU's records: indirect_host_steps' commands_a_kernel_writes_run_after_it and 19 other lanes
drew nothing.

The routes now mark at the call that completes the pair: a write use where a state that may
encode, or an execution whose records may name one, was met in the command buffer; such a state
set, or such an execution encoded, where a write use was. An encoder opens with what its command
buffer's ended encoders met (`Routes::carried`), so a later encoder's execution is encoded as one
the GPU may write, as it was when a write use marked the buffer at its call. The commit still
decides again from what the records name then, and still leaves the followers.

The command buffer's routes held each buffer made resident for writing or executed until the
command buffer itself dropped, past its completion: a released buffer's range and resource ID
stayed taken (indirect_command_buffers' buffer_identifiers_follow_metal_s_encoders,
resource_ids' an_indirect_command_buffer_s_id_is_held_as_metal_holds_it). The commit now clears
them once it decided; what it leaves unmarked is held until completion, as before.

Docs: the gpu_written contract, write_routes.rs, docs/API.md and the runtime README say when.

Verified with the lane commit after this one (debug, --cfg m2v_gpu, this M3 Max on MoltenVK):
the 39 lane modules that execute indirect command buffers, 479 tests, all pass, where B alone
failed 35; the runtime's written_commands, degradation, degradation_catalogue and
degradation_sites unit tests pass; fmt; clippy -D warnings of the runtime and validation crates,
all targets and features, under --cfg m2v_gpu.

(cherry picked from commit e8e85c6936ecc731fa557440033ac9d3e40953e2)
(cherry picked from commit 106af168144e7a76fcc5366e39fec10a3693611c)
(cherry picked from commit 38605155f851abdf697c818c5387c1980af6a0bd)
2026-11-04 18:50:27 -08:00
Anees Iqbal 66c9163ce3 Mark an indirect command buffer written by the GPU only where a route that may write its records meets it
A write residency of an indirect command buffer (useResource:usage: with MTLResourceUsageWrite)
marked it written by the GPU at the call, whatever the encoder's functions could do. Every
execution of it then waited for the work before it and was recorded by a host step, and kept no
chunk. A page whose kernel only counts, with the buffer made resident for writing, paid the host
step every frame (51 to 61% of the write frame in the kept-steps measurement), though no function
of it can reach a record: a function writes records only through an indirect-command operation.

The mark now comes from the routes that can write records (write_routes.rs), decided by
structure alone:
- the commit of a command buffer that made the buffer resident for writing in any of its compute
  or render encoders (residency is the command buffer's) and also set, in any of them, before or
  after, a pipeline state whose functions' indirect_command_writes is not empty (the translator's
  answer from their AIR: the indirect-command operations their bodies may call, every one where a
  body makes a call the translator cannot see into), or executed commands whose records may name
  such a state;
- after a commit that found neither, the first CPU or GPU write that leaves such a state in the
  records of a buffer it executed (the executed buffers hold the commit's unmarked buffers weakly
  until then, released as the command buffer completes; the marks run once the setter let its
  locks go);
- a blit's copy into the buffer or reset of a range in it, at the call, as before.
A heap holds no indirect command buffer and residency sets are refused, so neither is a route.
The mark is for good, as before. It keeps the route that met the buffer first, which the
host-replay notice names: for a state, its functions' names and the kinds of indirect-command
operation they may call; else the route. WorkCounts::indirect_write_residencies_unmarked counts
each commit's write-resident buffers it left unmarked.

The resident_draws fixture gains rd_encode, a kernel that may reset a command and resets none,
regenerated with scripts/regen-air-fixtures; the lane's `encode` path uses it, off the measured
paths.

Docs: the gpu_written contract, the runtime README, docs/API.md (the catalogue's
HostReplayedIndirectCommands trigger and cost, and the contract), the module docs that named the
old rule. api_signatures.tsv blessed (one field).

Verified (debug, --cfg m2v_gpu, this M3 Max on MoltenVK): the resident_draws lane's three tests
pass: a kernel that cannot encode (rd_touch) leaves the buffer unmarked, with no host step in any
of three frames, its two chunks run from the kept recording in the third, one unmarked residency
counted a commit, and the read path's pixels; a kernel that may encode (rd_encode) marks it at the
first commit, a host step every frame, no chunk kept, the same pixels, and the notice names
rd_encode and its reset; every path draws the encoder's pixels. Negative control (neg.py: every
state counted as calling no operation, and no executed buffer's records as naming one): the
encoding test fails (no host step in frame 0), the other passes. The runtime's written_commands
(a new test of the followers), degradation, degradation_catalogue and degradation_sites unit tests
pass. fmt; clippy -D warnings of the runtime and validation crates, all targets and features,
under --cfg m2v_gpu.

(cherry picked from commit 6e1b62a03039dd81a2005afa26a3001de2064110)
(cherry picked from commit 13dac865f4096559a5b97841d893e1da02e160ec)
(cherry picked from commit 862a72c76e82b657ef158ee1c7cbf789240ea745)
2026-11-04 18:50:27 -08:00
Anees Iqbal 968ccc4af0 host_ram: import a window of chunks ahead of the objects, not the whole RAM
What:
- The thread Device::use_host_ram starts now keeps a window of chunks past the one an object
  last took imported (host_ram.rs, Window): one chunk after a take outside the window (and the
  RAM's first chunk before any take), AHEAD_CHUNKS = 4 once a take lands inside it. It never
  imports past the window, never goes back to the RAM's start, and so faults in at most 4
  chunks (256 MiB) that no object took for one take, and at most 1 for a take that starts no
  run. While its window is imported it waits (Wake: a mutex and a condition variable), woken
  when an object takes another chunk or the use ends, holding the device and the RAM only
  weakly, as between chunks before.
- Unchanged: the pacing (SCHED_BATCH, yields, MADV_POPULATE_WRITE in 2 MiB steps), imports with
  the memory lock released, the stop a quarter short of maxMemoryAllocationCount and the
  give-back of untaken chunks.
- Docs: host_ram.rs, Device::use_host_ram, WorkCounts::host_ram_chunks_imported(_ahead),
  docs/HOWTO.md ("One run inside one chunk"), with the numbers below and the burst caveat.

Why: reims-vgpu's time to first present on the RTX 5080 laptop went from 11-12 s to 13.9-86.1 s
with the whole-RAM ahead import, worst at low MemFree, the normal state of a Linux desktop
whose page cache fills memory. Reproduced without a VM (release probe, public API: 16 GiB of
fresh memfd RAM under MADV_HUGEPAGE through use_host_ram, an mmap+munmap sampler, CPU-bound and
bandwidth-bound workers, a toucher faulting its own THP memory, vmstat and PSI):
- The whole-RAM import took 40.4 s at 35.4 GB free with only 21 free 2 MiB blocks, and 57.4 s
  at 17.1 GB free: pgmigrate 4.1-9.1 M pages, PSI memory "full" 6.6-9.6 s, another thread's
  mmap up to 0.96-1.19 s, another thread's 2 MiB faults up to 0.8 s at p99 0.48 s, a CPU-bound
  worker up to 51% slower at p50 and a bandwidth-bound one up to 128%.
- 99% of it is the fault-in of fresh huge pages (direct compaction and reclaim, holding the
  process's memory map lock): per chunk p50 39-123 ms, worst 1.46 s. The import itself (pin and
  vkAllocateMemory) of a resident chunk took 1.7-3.2 ms at p50 (0.56 s for 248 chunks).
- So the thread now faults in only what the objects are about to reach.

Measured on the same laptop (NVIDIA 615.71.09, Linux 7.2), release, one run each, MemFree
1.7-3.0 GB with 82-88 GB of page cache. Pattern: 40 2 MiB heaps at use_host_ram, then 8 bursts
of 128 consecutive heaps (4 chunks) 1 s apart, 2.08 GiB in all, with a toucher writing 1024
2 MiB pages spread over the same RAM (the guest's own faults):
                       ahead  own imports  making max (after the first 40)  PSI full
  adaptive (this)        36        2              26.9 ms                     0.97 s
  fixed 4                36        2              6.6 / 171 ms (2 runs)       0.48 / 0.97 s
  fixed 1                 9       26              372 / 614 ms (2 runs)       2.1 / 2.9 s
  none (no thread)        0       34              544 ms                      1.14 s
  whole RAM (cut at 40 s) 138      2              194 ms                      14.6 s
The 2 own imports are heaps 0 and 32, made as use_host_ram starts. 16 heaps over scattered
chunks, 300 ms apart: chunks faulted ahead adaptive 16, fixed 1 16, fixed 4 38, fixed 16 46;
making p50 adaptive 99 ms, fixed 1 51-60 ms, fixed 4 61-135 ms, fixed 16 160 ms, none 28 ms
(states vary run to run). A window of 8 or 16 bought nothing more for consecutive heaps and
cost more (16: PSI full 1.5 s, guest-fault p99 134 ms). A burst that runs more than 4 chunks
past the last take waits at each chunk past the window, one fault-in each (45-70 ms at p50 in
that state, at worst 0.34 s).

No DevicePolicy switch: this trades speed for speed, and no measurement favoured the whole-RAM
form.

Tests:
- host_ram::tests::a_take_inside_the_window_opens_it_and_one_outside_gives_one_chunk (the rule)
  and ::the_devices_thread_imports_the_window_past_the_last_take_and_no_more (the order: the
  start's one chunk, the window past a take, a held chunk passed, nothing past the window or the
  RAM's end, nothing back after a jump).
- tests::host_ram_device::the_window_ahead_moves_with_the_objects_and_imports_no_more: fresh
  THP RAM of 16 chunks; the first chunk alone before any take; a full window once a heap takes
  it; a run of heaps over the window imports nothing on its own thread; one chunk past a jump;
  a full window again once the run goes on; nothing past the RAM's end; the skipped chunk never
  imported. 14 chunks ahead, 1 by an object, over 259 heap makings, on both devices.
- chunks_are_imported_ahead_so_no_making_waits_for_one and
  the_ahead_thread_leaves_the_allocation_limit_to_the_objects now open the window with a heap
  over the first chunk; the limit test gives back the 3 chunks no object took.

Negative controls (a temporary build with one defect switched on at a time, M3, release,
--cfg m2v_gpu); each test failed as follows:
- whole-RAM order (next_ahead wrapping as before): the order unit test ("none past the start's
  one chunk", Some(1)); the window device test ("the device's thread went on past the window",
  16 chunks).
- a fixed window of 4 for every take: the rule unit test (Window { from: 10, chunks: 4 } after a
  jump); the window device test (13 chunks ahead after the jump).
- the window one slot off: the window device test ("no chunk past it", 6 live).
- no wake when an object takes another chunk: the window device test ("a full window past the
  take", 1).
- no thread: chunks_are_imported_ahead_so_no_making_waits_for_one ("the device's thread
  imported the RAM's first chunk", 0).
- no give-back: the_ahead_thread_leaves_the_allocation_limit_to_the_objects ("the untaken
  chunks went back", 0).
- with no switch, the same binary passes the window device test.

Verified:
- RTX 5080 laptop, release, --cfg m2v_gpu: the host_ram and allocations tests, 30 passed,
  0 failed.
- M3 Max (MoltenVK 1.4.2, macOS 27.0.1), release, --cfg m2v_gpu, under maclock: 28 passed,
  0 failed (the two dma-buf tests are Linux-only).
- cargo clippy --workspace --all-targets --all-features -D warnings, plain and with
  --cfg m2v_gpu; cargo doc -p metal2vulkan-runtime with -D warnings.

(cherry picked from commit 6d72e50ebb7d52e195fea5062bfed989af2877d4)
2026-11-03 17:44:41 -08:00
Anees Iqbal de2b62a868 Check a plain event's waiting command buffer at once, its wait on the VkQueue
What: `landing_waits`, the waits a checked head's submission checks wait to land, now skips
every wait that `EventShared::wait` answers. A plain event's wait for a signal submitted or
reserved before the batch therefore holds no check. The check runs as soon as the batch is
otherwise ready (on the scheduler's thread, or via `claim_check` on a committing thread in
commit_and_submit), and the batch goes with its wait on the VkQueue, as an unchecked batch's
does. A shared event's wait still holds the check until its value is reached, because
`EventTimeline::wait` answers none for it while the host may set the value. So does a plain
event's wait for a signal behind a merge.

Why: reims's 5080 decode path saw no gain from a plain Event, because their platform checks
every command buffer and the checked head was held until the signal landed. The conformance
case event-wait-behind-a-running-signal (previous commit) measured Metal on the M3 Max (macOS
27.0.1): a command buffer whose MTLEvent wait only a still-running signal meets is Scheduled at
once, so it is submitted and checked at once. One whose MTLSharedEvent wait such a signal meets
stays Committed until the signal lands. The old rule was Metal's for the shared event only.

Docs: checks.rs "When." states the split and cites the case. The runtime README
(set_submission_check, commit_and_submit) and RUNTIME-PORTING (the same two rows) say the same.
docs/API.md states no such rule, so it is unchanged.

Lane tests (runtime_lane::submission_checks):
- an_event_wait_a_gpu_signal_in_flight_meets_is_checked_at_once (new). In one try the waiter
  reads Scheduled while the signaller's companion event still reads 0, and the companion read 0
  inside its check. In every try `heads_awaiting_check_signals` does not move, the check runs
  once, and the fill runs. This holds both for a waiter committed before the signaller and for
  one committed with commit_and_submit while the signal is in flight.
- a_submission_detached_while_a_gpu_signal_is_in_flight_fails now covers the SharedEvent alone,
  and asserts that `heads_awaiting_check_signals` counts the held head.

Verified on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu, through maclock and memcap 12288:
124 passed. That covers the runtime's event, interop, reserved-queue, semaphore, check and
scheduler tests, and the lanes runtime_lane::submission_checks, events, event_round_trips,
command_queues and failed_commits. Caught with 8 and 4 fills of 64 MiB (plain), and 8 and 4
(shared).

Negative control: `landing_waits` without the skip (the old hold). The new test failed with "at
commit false: a head awaited its checks' signals", left 2, right 0. The shared test still
passed. Restored and touched.

(cherry picked from commit 3751927c29cee4a1dcbeb9786120245119a328a1)
2026-11-03 16:16:40 -08:00
Anees Iqbal 9e698176bc Record what Metal does with a wait whose signal is already running
What: a conformance case, event-wait-behind-a-running-signal, in the event_orders family, with
two rows, one for MTLEvent and one for MTLSharedEvent. Queue A's command buffer runs 192 fills
of 256 MiB into a private buffer, then signals a companion shared event at 1, then the event
under test at 1. Queue B's command buffer waits for the event at 1, then fills 256 shared bytes.
A is committed, then B. RUNNING_WINDOW (20 ms) later the case reads B's status and handlers,
the shared event's value, A's status, and last the companion. A companion still at 0 proves the
signal had not landed by any of those reads, since one command buffer's signals land in order.
A run whose companion reads 1 records only that fact, so it differs from an answer rather than
passing as one. B's Scheduled status is the proxy for "submitted, and so checked"; the case's
docs say so.

Why: reims's platform sets a submission check on every command buffer, and the runtime holds a
checked head until each value it waits for has landed. checks.rs justified that with "Metal
submits the submission, and checks it, once the signal happened", which nothing had measured.
event-cross-queue-wait reads a waiter only while its signaller is not yet committed, and
event-held-command-buffer only while only the host can raise the event.

Metal's answer, recorded on the M3 Max (macOS 27.0.1): 5 of 5 runs identical, and the
validated leg ran.
- MTLEvent: B reads Scheduled with its scheduled handler run while A still reads Scheduled and
  the companion reads 0. Metal submits it at once, with the wait on the GPU.
- MTLSharedEvent: B reads Committed with no handler run, signaledValue 0, A Scheduled. Metal
  holds it until the signal lands.

The fills measured 156 to 163 ms of GPU time on the M3 Max (a throwaway Metal probe,
GPUEndTime less GPUStartTime, three runs), so the read falls about eight windows before the
signal.

Our side replays divergent on the M3 (MoltenVK) on the plain row: B still reads Committed at
20 ms. A's vkQueueSubmit takes 10 to 27 ms there, in MoltenVK's encoding of our fills by
transfers. A later commit reduces that.

(cherry picked from commit 2efae5489b87b0c37603d1c5e7b51a5222a49414)
2026-11-03 16:16:40 -08:00
Anees Iqbal 289af45922 Give the shadow runs' RTX 5080 Laptop times again, measured with the in-place first pass
The previous commit removed the RTX 5080 Laptop numbers from docs/FAST-PATHS.md because they
described the earlier form of the runs. They are measured again here, with the in-place first
pass and the second keep.

Verified on msi-laptop (RTX 5080 Laptop GPU, NVIDIA 615.71.09), under an exclusive GPU hold with
no VM running. Release builds of the 700-pass probe were made at 36c3063e16 (tip) and at
2bc0f1eac6 (fix), and run interleaved, three processes each. The times are commit to completion
of the second to fourth command buffers of each process:

- passes back to back: fix 6.5-9.1 ms, tip 6.3-9.0 ms;
- with an empty 1x1 encoder between every two passes: fix 9.3-12.2 ms, tip 9.1-12.7 ms.

The fix took 5 shadow copies and kept 2,097,152 texels in every run; the tip took 3 and kept
1,048,576. The figures for the build without runs (40.6-43.0 ms and 44.5-47.1 ms) are the ones
the row already gave.

(cherry picked from commit fa2b1b354d818fd4a373fb5af7ba1c5dd44ce21c)
(cherry picked from commit 8674db962402c9c425765fe0c8430f1383edd6ff)
2026-11-03 15:58:55 -08:00
Anees Iqbal 4bfeb66cd9 Merge a shadowed texture's pass in place until a second pass goes on from it
A shadowed texture's pass that opened a run left its merge to its batch's submission
(`Deferred::RunMerge`). That splits its encoder's commands into a continuation VkCommandBuffer and
records a segment of batch work at the submission. A pass that no later pass goes on from paid for
this and saved nothing. The conformance cases rotated-planes-load-0-64x16 and -32x32, one such pass
each, measured alone on the M3 Max: command_buffers_begun 3 -> 6, command_buffers_submitted 2 -> 5,
submit_infos 1 -> 2, end_command_buffer 3 -> 6, encoder_command_buffers_begun 2 -> 3, batch work
1 -> 2, and one batch barrier and one continuation that the recordings do not have. Reverting the
shadow runs alone restored the recorded counts; reverting the twin-shadow fix changed nothing.

Now the pass that would open a run merges in place as its encoder ends, as a pass alone does, and
only marks where a run may start (`PassRuns::placed`). The pass after it opens the run
(`Joined::Placed`): its image is carried, with no copy in, and it keeps the texture again.

The second keep is required. A run's merge compares its keep with the image its last pass left,
byte by byte, and a byte equal in both keeps the buffer's byte. A first attempt went on over the
in-place pass's keep instead. Bytes that the later passes changed and changed back then kept the
in-place merge's value, and the byte comparisons failed:
- tests::shadow_runs::runs_over_host_pages: 1,176 bytes;
- tests::merge_scratch's passes over host pages;
- the validation lane's many_passes_over_host_pages tests.
So a run of k >= 2 passes costs two keeps, two merges and k - 1 continuations, and a lone pass
costs nothing extra.

Verified on the M3 Max (MoltenVK 1.4.2, --cfg m2v_gpu):
- `conformance cost --runs 8 --alone --show` for both rotated-planes cases: every count that rose
  equals the recording again. The four counts that differ alone from the whole-set measurement
  (command_buffers_deferred, cmd_push_constants, device_memory_allocated,
  queues_sharing_a_vk_queue) also differ with the shadow runs reverted.
- New test tests::shadow_runs::a_pass_alone_merges_in_place. A pass alone: 0 continuations,
  3 shadow copies. Three passes: 2 continuations, 5 copies. The bytes equal a private texture's.
  Negative controls:
  - with the in-place path disabled, it fails at (1, 1, 3);
  - with the pass after a marker opening the run without a keep (`Joined::Opens`), it fails at
    (3, 0, 7).
- tests::shadow_runs and tests::merge_scratch, 10 of 10, with updated counts:
  - runs_over_host_pages: 32 copies, 14,680,064 texels kept;
  - the scissored passes keep at [0, 1, 2];
  - the rebind encodes 4 passes again.
- The runtime's shadow, merge, linear, rebind, re-encode and replay tests: 155 of 155.
- The validation lane's shadow, padded, linear, rotated and surface tests: 145 of 145.
- The 700-pass probe now takes 5 shadow copies and keeps 2,097,152 texels (3 and 1,048,576
  before). Release builds of this tree and of its parent, interleaved, three processes each, the
  second to fourth command buffers: commit to completion was 32.7-35.6 ms against the parent's
  31.6-36.1 ms, and with an empty encoder between every two passes, 61.5-67.2 ms against
  60.4-67.0 ms.

docs/FAST-PATHS.md gives the new counts and the M3 times. The RTX 5080 Laptop numbers are removed:
they described the previous form, and that host was running VMs, so they were not measured again.

(cherry picked from commit 2bc0f1eac676dcc86dadfbd37a81313977515d45)
(cherry picked from commit 55c7f307a92c67125d31b08c33b3f91c7d14a67b)
2026-11-03 15:58:54 -08:00
Anees Iqbal 241ee2c0d1 Keep and merge a run of passes over one shadowed texture once, not once a pass
What: a render pass whose color is a shadowed texture merged back (its truth a buffer's bytes
another writer may write, such as a no-copy buffer's host pages or a Shared buffer's), loaded and
stored, now joins a run of passes (pass_runs.rs) where it may. The run's first pass copies in (or
takes the carried image) and keeps, as before. Each later pass goes on over the image the pass
before it left (ShadowSync::go_on) and keeps nothing. Each pass leaves its merge to its batch's
submission (Deferred::RunMerge, RunWork::Shadow), and the run's next pass takes it over, so the
merge recorded is the last pass's, compared against the first keep. The run holds the keep's
scratch or kept image (RunHeld::Shadow, its MergeLease) until it ends or the command buffer
commits.

Why: consecutive render passes over one merged-back shadowed texture each copied in, kept and
merged the whole texture. 700 one-rectangle passes over a 1024x1024 BGRA8Unorm texture over host
pages took 1,401 shadow copies and 700 merges.

The rule, structural, with no names: a run ends wherever something other than its own passes
could observe or change the bytes, as in the linear runs' list:
- any encoder between its passes that is not a render encoder;
- a render encoder that names the bytes' buffer or its host range, reaches memory it does not
  name, fences, resolves, writes visibility results, records later or renders over a rate map;
- a render encoder with an attachment over those bytes, or whose draws or attachments take a
  shadowed texture over them (the run's own texture bound to a draw included);
- a signal, a wait or a host step (a new batch), and the command buffer's end;
- for a shadow, the encoder no longer carrying the image (the carry dropped).
A shadowed color joins only when it is loaded and stored, has no stand-in and no planes, belongs
to a pass of one render pass instance that is not inline and not inside a predicated laying, is
laid out as one image's texels at level 0 and slice 0, and merges back.

Encoded again: unlike a linear attachment's run, a shadowed texture's run may hold passes over
host pages, which a rebind before the first submission encodes again. Such a pass leaves its run
(RunMerge::leave). The merge it took over records after all (given back), and the pass copies in,
keeps and merges for itself. Where a later pass took its merge over, it keeps the run's scratch
again after its own merge (RunMerge::keep_after), so that later pass's run merges what the passes
after it change. Run segments now record again (Segment::records_again) and splice. An encoder
encoded again takes no pooled scratch or kept image (ShadowMerge::new's `lent`). A run's merge is
resolved at its calls (Deferred::resolved_at_its_calls), so it holds no host pages past commit;
before this, a rebind of such a run was refused with Rebind(EncodedUses).

Two more changes. A run's keep that a later pass writes outside merges and keeps every texel next,
and a run's pass that needs texels the copy-in did not hold copies every texel in. A merge in whole
blocks stays in blocks where the keep holds the pass's area (stores_blocks), under the same
read-to-store window that shadow.rs's Stored attachments already state.

Counted with the existing counters: shadow_copies, shadow_texels_kept and
shadow_merge_dispatches_planned fall from one per pass to one per run. docs/FAST-PATHS.md records
the run and its costs.

Verified on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu, under maclock and memcap:
- tests::shadow_runs (new, all pass):
  - runs_over_host_pages_keep_and_merge_once: 1024x1024 BGRA8Unorm over host pages, rows of 15360
    bytes, with blits, foreign render encoders, reads, CPU byte writes, a signal and an aliasing
    view between runs. Mid-sequence and final reads match a private texture byte for byte, and
    the padding is untouched. Joined: 22 copies, 9 merges. Apart: 112 copies, 54 merges.
  - rebound_passes_leave_their_runs: 3 encoders encoded again, 0 refused, bytes equal.
  - scissored_runs_keep_again_once_and_merge_in_blocks: keeps at passes [0, 1], all in blocks.
- Runtime suites (shadow, merge_scratch, linear_runs): 69 of 69 passed.
- Validation runtime_lane (shadow, padded, linear): 91 of 91 passed.
- Negative controls, each a sabotaged build, source restored and touched after; each fails:
  - go_on off: every pass keeps;
  - follows across encoders: keeps [D0, D8, D9, D10, A11, D12];
  - leave off: 961,469 bytes differ;
  - stores_blocks reverted: every scissored pass keeps.
- Release probe, 700 passes in one command buffer, base a543f6428d against this commit: shadow
  copies 3 against 1,401, texels kept 1,048,576 against 734,003,200, merges planned 1 against 700.
  Commit to completion, runs 1-3: 31.6-35.3 ms against 69.3-99.9 ms. With a 1x1 render encoder
  between every two: 61.6-65.0 ms against 107.4-118.6 ms.
On the RTX 5080 Laptop GPU (NVIDIA 615.71.09), the same probe, runs 1-3: 6.6-10.0 ms against
40.6-43.0 ms, and 9.7-12.3 ms against 44.5-47.1 ms. The same 11 shadow, merge and linear device
tests passed there.
clippy --all-targets --all-features -D warnings passed plain and with --cfg m2v_gpu, and cargo fmt
was run.

(cherry picked from commit bf783428131f46c7289518a50b8505e809ecc8e5)
(cherry picked from commit 99949a4cd08cd042e448484e0b1d2f5da1898db5)
2026-11-03 15:58:53 -08:00
Anees Iqbal 385a2ed40f Record host steps on up to eight threads, so one queue's long step holds back no other queue's
What: scheduler/steps.rs had one thread per device record every host step of every queue, in
hand-over order. It now hands each step to a free thread of a pool, or starts one for it below
THREADS (8); past the cap a step waits for the first thread free, in hand-over order. The first
thread stays until the scheduler stops, as the one thread did; each later one ends after 2 s with
no step. All start at the user-interactive class, each step is still a section of the exit guard,
and where the host cannot start the first thread the scheduler's thread records the step itself,
as before.

Why: the consumer (one device for every guest process) saw WindowServer's present wait 13.6 s in
the host after the page's context had closed. A page's render-bundle ICB execution was recording
a seconds-long host step, and any command buffer whose draw or dispatch has a pipeline still
being made takes a host step too (deferred.rs: RenderPass with making(), Pending), which queued
behind the page's on the one thread. A dead context's step keeps recording, as its command buffer
holds what it uses.

Order is still the scheduler's: only a line's head is handed over, marked stepping until its step
ends, so a logical queue's steps are recorded one at a time in its order, and a head that waits
for an event value, or is behind an earlier commit's conflicting batch (order.rs), is not gated
or handed over (gate_heads takes `behind`).

Audit of what assumed one step at a time device-wide:
- kept chunks (kept_commands.rs): no host step uses them (render executions keep only when
  !step, compute executions only when states.is_none());
- upload and descriptor arenas: per command buffer (State::uploads, State::descriptors); their
  spares are the device's, under a lock; the command pool is per command buffer, recorded under
  its `reencoding` turn, which host_step takes;
- pipeline making: the pool, the budget's turns and the making maps already serve concurrent
  encoders; the in_host_step()-gated branches (Urgency::HostStep, keep_room skipped, kept
  variants not taken back, takes_multi_variable_dynamic, make_at_creation skipped, sampler-set
  count) read a thread-local, so they hold per thread; kept.rs StepNumbers is thread-local and
  per command buffer, whose steps stay sequential, `made` handed on through end_step and the
  scheduler's locks;
- residency: a command buffer's own value, its address index made per residency;
- the scheduler's wake and hand-over: record() marks the inbox under its lock and wakes, as a
  committing thread does; begin_step/end_step are the command buffer's atomics; post pushes
  under the steps' lock;
- the exit guard: sections are counted per thread and in atomics, HOST_STEPS is thread-local,
  called() is atomic; many sections at once were already normal;
- interior mutability used by the steps thread alone: none besides the steps' own state (every
  shared object is Sync and shared with committing threads already);
- notices: every-occurrence notices announced inside steps (each_in_order) of two queues may now
  interleave; Metal orders nothing between such queues.

Docs: the scheduler's "Host steps" section, left.rs, WorkCounts' host-step counters, kept.rs,
RecordsRead::HostStep and FAST-PATHS.md's pipeline-wait row say steps' threads. The
host-replayed-indirect-commands notice already says only resources the execution may reach hold
later batches back, so it is unchanged.

Verified on the M3 Max (MoltenVK, --cfg m2v_gpu, maclock+memcap), with the next commit's lane
test runtime_lane::steps_apart::another_queue_goes_on_while_a_host_step_records: before, queue
B's own stepped command buffer did not complete within 10 s while queue A's step was held (A's
objects kept, and released); after, 18.6 / 18.9 ms in debug. Its ordered checks (a step after
an event A signals, and a pass into A's target) begin only after A's step ends, before and after.
Negative control: THREADS = 1 fails the test again (Stepped, kept and released); restored and
touched. Release, A a real 5000-draw step (2.7 to 5.0 s), B's stepped kind went from 3580 ms
(released: 3359) to p50 1.49 / max 15.6 ms (released: 1.65 / 40.4); idle 1.32 ms p50.
Runtime tests::(scheduler|inbox|host_step|waiter_submits|commit_and_submit|completion_order|
unsubmitted|pipeline_wait_order|blit_order): 50 passed. Lane cases (indirect, kept,
*executions, *host_steps, submi*, steps_apart, resident_draws, event_round_trips,
command_queues): 272 passed. clippy --workspace --all-targets --all-features -D warnings, plain
and with --cfg m2v_gpu: clean.

(cherry picked from commit e15fd6752fe4f714b73dab0ee72d15fce686f3d7)
(cherry picked from commit 229f407b2abe2de5b85bf3d98b2080d0a0667e9d)
2026-11-03 13:34:03 -08:00
Anees Iqbal f6692d84e5 Keep an ICB execution's chunks where its check can see nothing among its commands
Before, any execution given a check (execute_commands_in_buffer_checked) recorded every command at
every commit and kept no chunk, even when the check's needs ruled out everything the buffer's
records may hold. In that case commit never calls the check: RenderExecution::check_sees and
Execute::check_sees answer from the needs and IndirectCommandBuffer::command_writes. A consumer
that hands every execution of own-state commands a check for draws of points, and draws
triangles, never had its unchanged commands run from kept recordings.

Now RenderExecution::keeping declines where `self.check_sees_now()` holds, and Execute::keeping
where `self.check_sees()` holds. The decision is the structural one commit makes for the check,
the check's needs against what the records may hold. When a later write makes the records hold
something the check looks for, it forgets the chunks it reaches. At the next execution
check_sees is true, so keeping declines and the execution records inline, calling the check with
every command.

Docs: the "Which executions" lists in render/executions/kept.rs and indirect_execute/kept.rs, and
docs/FAST-PATHS.md's kept-recordings row.

Tests (runtime_lane::kept_commands), counting records read, chunks and commands kept and
contexts made (WorkCounts::indirect_chunks_kept and kept_contexts_made show the kept path ran),
and the commands the check was called with:
- a_checked_execution_keeps_where_its_check_sees_nothing (render). With needs for states that
  may encode indirect commands, which the inherited state can't, the check sees nothing:
  [N, 0, 0, 0], then [N, 0, 0, 3], then [0, 3, N, 0], and the check is called 0 times. With
  needs for draws of points, which the records hold, the check sees: [N, 0, 0, 0] three times,
  and the check is called with all 3N commands.
- a_checked_compute_execution_keeps_where_its_check_sees_nothing: a compute execution checked for
  every kind. Its records hold no draw and no state that may encode, so it keeps as above, and
  the check is called 0 times. No fixture kernel encodes indirect commands, so compute has no
  "check sees" leg.

Verified on the M3 Max, debug (--cfg m2v_gpu), on lane 7583fe5d99 with the first-execution ruling
cherry-picked beneath it:
- nextest -j 8 over every runtime_lane module that executes an indirect command buffer: 39
  modules, 473 tests, all pass.
- Negative control: keep only with no check at all (the condition before). Both new tests fail
  at "the second records three chunks to keep" ([600, 0, 0, 0] where [600, 0, 0, 3] is expected).
- Negative control: keep whatever the check (render). The render test fails at "a check that sees
  keeps nothing" ([0, 3, 600, 0] where [600, 0, 0, 0] is expected).
- fmt --check, clippy -D warnings (runtime and validation, all targets and features, m2v_gpu),
  metal2vulkan tests::fast_paths 19/19.

Needs a RUNTIME_VERSION bump. No SEMANTICS_VERSION: no translated module changes.

(cherry picked from commit d75cb04ac8ed9d4616b10aa13d26af869a32d405)
(cherry picked from commit efafed587dd062f7d87bd9c9868ccb035e9ddc26)
2026-11-03 13:34:03 -08:00
Anees Iqbal 24dc3f20bb Keep an ICB range's chunks from their second execution, and forget a written chunk in one store
A range's first execution no longer pays for keeping. Before, every execution of CPU-encoded
commands recorded each 256-command chunk apart, in a KeptContext of its own (a command pool, a
descriptor arena and uploads), so it could run that recording again later, even when no later
execution came. Now a chunk is recorded to keep only from its second execution with no write
reaching it since. The first execution since a write records inline, as before 922caf3199, and
keeps nothing. A consumer that re-encodes every command each frame now pays nothing for keeping.

- kept_commands.rs: KeptChunks notes which chunks an execution that may keep its commands ran
  since a write last reached them. look_up answers each chunk of a range as Kept::Recording (a
  kept recording), Kept::Again (run before, nothing kept) or Kept::First, and notes each as run.
  IndirectCommandBuffer::kept_chunks answers None, so the execution records inline, when every
  chunk is First. When some chunks are kept and others are not, a First chunk records apart from
  its command buffer's own pool and arenas, with no KeptContext, and is not kept. An Again chunk
  records apart in a KeptContext and is kept.
- KeptChunks is dense: one ChunkState per chunk (kept recording, stepped, seen) up to the
  furthest chunk looked up, plus a flag for whether any chunk holds a state. KeptChunks::wrote
  costs one store per chunk the written range covers, whatever the number of kept chunks, and
  returns at once while no chunk holds a state. Before, it ran BTreeMap/BTreeSet::retain over
  every kept and stepped chunk on each setter call.
- WorkCounts::kept_contexts_made counts the KeptContexts made (api_signatures.tsv).
- Docs: kept_commands.rs, render/executions/kept.rs, indirect_execute/kept.rs and
  docs/FAST-PATHS.md (the kept-recordings row).
- examples/icb_setters.rs --kept now executes three times before each repetition: the first
  keeps nothing, the second records every chunk to keep, and the third runs all of them from
  those recordings.

Tests:
- runtime_lane::kept_commands asserts kept_contexts_made beside the records read and the chunks
  and commands kept.
  - A once-executed range makes no context: [N, 0, 0, 0].
  - Its second execution keeps every chunk: [N, 0, 0, 3].
  - Its third runs them: [0, 3, N, 0].
  - After a write, the written chunk records inline again and the next execution keeps it.
- kept_commands::tests::a_write_costs_the_chunks_it_covers asserts the count of chunk states
  wrote() looks at.

Verified on the M3 Max:
- Debug device lanes (--cfg m2v_gpu, nextest), with the live compute flags fix from stack22
  applied locally (not part of this commit): every runtime_lane module that executes an indirect
  command buffer (39 modules, 471 tests) pass.
- Negative control for the ruling (each chunk keeps from its first execution), debug:
  3 of the 5 kept_commands tests fail, a first execution making 3 contexts where 0 are expected
  and a written chunk making 2.
- Negative control for wrote() (it walks every chunk state): a_write_costs_the_chunks_it_covers
  fails, looking at 1000 states where 1 is expected.
- Unit tests: kept_commands::tests 2/2 and metal2vulkan tests::fast_paths 19/19.
- cargo fmt --check and clippy -D warnings (runtime and validation, all targets and features,
  --cfg m2v_gpu) are clean.
- icb_setters compute --kept (release, instructions per command, median of 30, two runs each):

  | | before (2c542021bf) | after |
  |---|---|---|
  | compute command, nothing kept | 2528.7 / 2529.1 | 2428.1 / 2427.7 |
  | compute command, 64 chunks kept | 5947.8 / 5945.5 | 2586.5 / 2583.9 |
  | set_kernel_buffer, 64 chunks kept | 1129.6 / 1129.6 | 456.9 / 456.3 |

  With three executions, the third runs all 64 chunks from kept recordings (the
  bench prints [64]), at 2583.9 and 456.3 instructions.
- conformance cost --alone indirect-render-commands-inherited-state reads arena_pools_made 1,
  argument_objects_retained 2 and argument_tables_retained 1, the recorded bounds. With a first
  execution's KeptContext these read 3, 6 and 3 (the cost run that held its record back).
- execution_costs (release) on a loaded host: wall times are dominated by host load. An earlier
  pair of runs read the first execution as slower (render n=1024 all re-encoded commit 2.88 to
  6.55 ms), but the parent then read 6.55 ms itself under the same load. Time Profiler, test
  thread CPU, same case and count, this change on 2b55ab415e against its parent:
  - render n=1024 one re-encoded, 300 executions: 611 to 610 ms;
  - compute n=1024 all re-encoded, 80 executions: 336 to 333 ms;
  - render n=1024 all re-encoded, 120 executions: 782 to 859 ms. This is the inline path's
    whole-range read: RenderExecution::commands collects the range into a second
    Vec<Option<Command>> (memmove 0 to 25 ms in RenderExecution::record), and render_records
    reallocates as it grows. The same profile has IndirectCommandBuffer::edit, whose code is
    the same in both builds, up 31 to 40 ms, so part of the difference is load.
  A later run of this commit's tree read render n=1024 all re-encoded at 2.37 ms commit, one re-encoded
  at 0.61 ms, and compute n=1024 all re-encoded at 3.49 ms.

Needs a RUNTIME_VERSION bump. No SEMANTICS_VERSION: no translated module changes.

(cherry picked from commit a54756c6a4f7fbe9ae82d732e8de46a19f4f86e5)
(cherry picked from commit 71e798c081648ea3818abbffc7538a3061456c75)
2026-11-03 13:34:02 -08:00
Anees Iqbal cf7eae4420 Hold each device to maxMemoryAllocationCount; the ahead import stops short of it and gives back
What:
- allocations.rs (new) counts each device's live VkDeviceMemory allocations, by its
  handle, at the runtime's two doors:
  - creation::allocate_memory, where every allocation goes;
  - release::object for vkFreeMemory, where every free goes.
  tests/exit_guard.rs already holds every allocation and free to those doors. So the count
  covers pooled and dedicated blocks, every host-pointer import (no-copy objects' own, guest
  RAM chunks, fresh pages) and every dma-buf import, with no caller passing it. A device is
  registered once its priming, which frees all it allocates, is done. Its registration goes
  with it.
- At the limit, creation::allocate_memory refuses with ERROR_TOO_MANY_OBJECTS and does not
  call the driver. The refusal is counted in WorkCounts::memory_allocations_refused_at_limit.
  Callers handle it as they handle the driver's own refusal (memory.rs frees kept empty
  blocks and tries again).
- The ahead-import thread stops where one more import would leave the device fewer than a
  quarter of its limit (Allocations::room_ahead). The remaining chunks are left to the
  objects over them, imported on demand as before.
- Once an allocation leaves the device fewer than that quarter, a thread is spawned
  (Device::give_back_ahead_near_the_limit). It runs with no lock of the allocating caller
  held, and frees every chunk the ahead thread imported that no object took and only its
  slot holds. Counted in WorkCounts::host_ram_chunks_given_back. An object over such a chunk
  later imports it as it is made.
- Scope: the ahead thread is started only in Device::use_host_ram (host_ram.rs, the one
  exit_guard::spawn of import_ahead). That call refuses a device without
  VK_EXT_external_memory_host, and its chunks are host-pointer imports
  (import_chunk -> memory::import_host). A no-copy object's own imports, by pointer or of
  the caller's dma-bufs (dma_buf.rs), never touch the RAM source and never start the thread.
  So RADV's per-object dma-buf imports are unchanged and never put all of RAM in GTT. That
  holds as long as the consumer calls use_host_ram only on devices that refuse dma-buf views,
  which reims-vgpu does: its os/linux/host_ram.rs hands the RAM only to devices that need
  imported pages mapped from their files.

Why:
- VUID-vkAllocateMemory-maxMemoryAllocationCount-04101: "There must be less than
  VkPhysicalDeviceLimits::maxMemoryAllocationCount device memory allocations currently
  allocated on the device". Nothing counted allocations before.
- Importing ahead makes one allocation per 64 MiB of guest RAM whether or not an object ever
  uses the chunk. So the thread must leave the limit to the objects and never be the reason
  an allocation is refused.
- The spec's minimum limit is 4096, so the margin is at least 1024 allocations.
- The give-back runs on its own thread because the door may be called under the device's
  memory lock, which a chunk's free takes. A free of device-address memory can also wait for
  batches in flight (freed_memory.rs).

Limits:
- RTX 5080 laptop (NVIDIA 615.71.09): maxMemoryAllocationCount 4294967295, read by the device
  test.
- M3 Max (MoltenVK 1.4.2, macOS 27.0.1): 1073741824, read by the same test.
- At those limits, the margin and the refusal never come into play in practice. They hold
  for a device with a small limit.

Verified on the RTX 5080 laptop, release, --cfg m2v_gpu: all 25 host_ram and allocations
tests pass. Among them, the new device test
the_ahead_thread_leaves_the_allocation_limit_to_the_objects:
- It holds the device to a small limit (Allocations::limit_to, test-only). With 0 live, the
  limit is 5 and the margin 1.
- The thread imports 4 chunks of a 12-chunk fresh RAM and stops.
- An object over the 5th chunk imports it on demand. That allocation brings the device
  within the margin, and the 4 untaken chunks are given back (host_ram_chunks_given_back 4,
  host_ram_chunks_live +1).
- Buffers of blocks of their own are then made until the device holds its limit. The next
  is refused at the door (Vulkan(VkResultCode(-10)),
  memory_allocations_refused_at_limit +1), with none of the thread's chunks live.
On the M3 Max, release, --cfg m2v_gpu, the same test passes, the same way: limit 5, 4 chunks
ahead, given back, then 2 buffers made and the next refused at the door.

The runtime's whole host-side suite passes (1218 tests).

The unit tests allocations::tests cover the refusal and room, the margin and the single give-back,
and a registration's life.

Not verified: a real device with a small limit (none of ours has one). The case where more
than a quarter of the limit's allocations land before the give-back thread frees the
chunks. That case is a race, bounded by the margin.

(cherry picked from commit 15543aa261afa12b13bcda954fc5cb51063a6b0f)
(cherry picked from commit 3766b1338e9b92367712cc4e9cf8f9a19dbe85e8)
2026-11-03 12:36:58 -08:00
Anees Iqbal f739bea1eb host_ram: pace the ahead import, and import host pointers with the memory lock released
What:
- The thread that imports a used RAM's chunks ahead now runs as the system's batch work:
  SCHED_BATCH on Linux, with its nice value kept, and the utility QoS class on Apple's systems.
- It yields between chunks.
- On Linux, before each chunk's import, it faults the chunk's pages in 2 MiB at a time with
  MADV_POPULATE_WRITE, yielding between steps. That changes no byte. A kernel that refuses
  the advice leaves the faults to the import, as before.
- memory::import_host (it was Memory::import_host) makes the vkAllocateMemory import with
  the device's memory lock released, as import_own_pages and new blocks already do. It
  re-locks only to record the block. Its callers are the chunk import (host_ram.rs) and a
  no-copy object's own import (buffer_descriptor.rs).
- No CPU pinning, and no kernel, boot or module parameter.

Why: a reviewer accepted pinning all of guest RAM ahead on condition that the thread does
not stall the host while a VM starts.
- The pin of a 64 MiB chunk holds the VMM process's mmap lock while it faults in fresh pages.
  Every mmap, munmap, and every page fault queued behind one, waits on that lock.
- The chunk import used to run under the device's memory lock, so every other placement on
  the device waited for it too.
- A low-weight thread that holds those locks is worse, not better. On the RTX 5080 laptop
  (24 threads, kernel 7.2), a thread faulting in 64 MiB pieces of a fresh THP memfd ran
  against 24 or 48 spinning threads at nice 0. Another thread's mmap+munmap waited:

    policy        24 busy: p99 / max     48 busy: p99 / max     chunks faulted in 6 s
    default       0.23 / 12.4 ms         3.6 / 26.9 ms          883 / 276
    SCHED_BATCH   1.4 / 12.4 ms          11.2 / 13.9 ms         850 / 581
    nice 19       131 / 511 ms           164 / 1012 ms          4 / 2
    SCHED_IDLE    0.004 / 1039 ms        0.005 / 1419 ms        1 / 1

  So the thread keeps the default weight (SCHED_BATCH only marks it as batch work) and paces
  itself by yielding and by faulting in small steps.

Measured on the same laptop, release build, 16 GiB of fresh THP memfd RAM imported ahead
whole. "Unpaced" is the parent commit (df5beeecaa, in stack19 as 97a69f70ab). A sampler
thread timed mmap+munmap of one page every millisecond:

  run                                           time      mmap p99 / max   >10 ms   compact_stall / fail / allocstall_normal
  unpaced, idle, first run of a hold            5088 ms   57.8 / 98.8 ms   76       2411 / 183 / 67
  paced, idle, right after it                   8374 ms   7.5 / 45.9 ms    32       930 / 209 / 0
  unpaced, idle, calm memory (x3)               1515-1824 ms  5.2-6.4 / 6.7-6.8   0   none
  paced, idle, calm memory (x3)                 1552-1600 ms  4.9-5.0 / 5.3-6.6   0   none
  unpaced, 24 threads busy (x3)                 2212-5649 ms  9.7-19.2 / 12.3-24.9   7-238   none
  paced, 24 threads busy (x3)                   3720-6693 ms  0.27-1.6 / 1.9-7.7     0       none

- The earlier unpaced measurement (batch at df5beeecaa) was 3.47 s, with compact_stall 1152
  and allocstall_normal 54.
- Compaction follows the host's memory state, not the pace. Only the first run of each hold
  met page cache to reclaim and fragmented free memory, and the hold that had it ran unpaced
  first. So the compaction rows are not a like-for-like comparison.
- The pace costs time only when the CPUs are busy, where the thread now shares them. In
  return, the process's other threads wait at most a few ms for the memory map lock.
- In calm memory, the remaining ~5 ms p99 is the import's pin of 64 MiB of resident pages.

Verified at the tip of this branch (this commit and the next), on the RTX 5080 laptop with
--cfg m2v_gpu, release: the host_ram device tests pass, including
chunks_are_imported_ahead_so_no_making_waits_for_one (4 chunks ahead in 31.6 ms, the slowest
of 40 heap makings 52 us). Clippy is clean with all targets and features, plain and with
--cfg m2v_gpu.

(cherry picked from commit aff66f6a5dc424d97854c0908dee022475e8dc01)
(cherry picked from commit 9bbe4518ceff598e5fa0172d5624f6af7a75b6a2)
2026-11-03 12:36:58 -08:00
Anees Iqbal 81531d6c10 Keep the used resources out of root tables the commit points elsewhere
Every draw and dispatch whose functions read loaded pointers uploads a root table per stage
that reads one. Each table embedded the whole resident set: every bound buffer, every
Buffer and Heap made resident, every listed range, sorted and coalesced per command
(resident_entries). The runtime then copied and uploaded those bytes and added each range
to its command buffer's root_ranges. Yet the commit points every table at the command
buffer's own resident set (State::point_root_tables; a host step's table is pointed at
once), so the GPU never reads the embedded copy. With N draws among N resident resources
that was N^2 work and bytes: 13% of the M3 profile of the argument-table shape at N 2000.

BindState::resident_apart is a consumer's opt-in, not part of the shape. It says the
consumer points every root table of the command at a resident set it uploads apart
(ResidentSet, RootTable::resident_fields). That set must hold every Buffer and Heap of
used_resources and every listed range, as well as the table's own ranges. With the flag, a
root table's own resident set holds the bound buffers alone (resident::table_entries), and
RootTable::resident_ranges lists only those. Without it, nothing changes, and replay
preprocess tables keep resident_entries either way.

The runtime sets the flag on the states whose tables go through binding::root_table:
RenderLowering::refresh_bind_state, the compute bind_state and dispatch_tiles_resident. It
leaves it off for gpu_execute and the GPU form, whose tables carry live ranges and are
pointed nowhere. The set the commit points at already holds what was dropped:
State::make_resident adds the joined residency's resident_ranges (every encoder's used
buffers and heaps) beyond the live buffers, and first_submission's remake does too.
Counted: WorkCounts::root_table_ranges_noted (State::root_table).

Functions: bind::resident::{table_entries (new), coalesced (new), bound_allocations (new),
resident_allocations, resident_entries}; bind::graphics and bind::dispatch build root tables
from table_entries; BindState gains resident_apart; State::root_table counts its ranges.
docs/API.md says what the flag asks of the consumer.

Verified:
- bind::resident::tests::a_state_resident_apart_keeps_the_used_resources_out_of_its_tables
  (300 pseudo-random states whose bound buffers, used buffers and heaps and listed ranges
  nest, overlap, touch and repeat): without the flag the table holds resident_entries; with
  it, the bound buffers' set. A set made of the table's ranges plus the used and listed
  ranges, as the runtime makes its own, resolves every address alike either way. The shape
  is unchanged. A negative control (an empty table under the flag) fails it.
- bind::resident, bind::heap, bind::graphics, bind::dispatch and pipeline::api_tests pass
  (74 tests).
- M3 numbers at the tip of this series are in its last commit. At N 300, every counter but
  the new ones is the parent's on every path and binding of both shapes, barriers and uses
  included, except the upload arena's buffers parked and recycled (54 -> 4: smaller tables).
  The pixels are the parent's too.

(cherry picked from commit dcda2dc0368867436fb37ac78af79265088d6596)
(cherry picked from commit d6f17f77ab484eef479aa15df9c08055cf1101da)
2026-11-03 12:36:57 -08:00
Anees Iqbal 5b5f1847d8 Find a state's heap members by search where it lists them in token order
A handle table's bytes (bind::heap::table_bytes, inside every draw's and dispatch's
instantiation) and a plan's heap elements (BindingPlan::heap_elements, which the runtime
asks for at each draw) found each heap member's used-resource entries through a map built
for the call over every used resource: a BTreeMap entry and a Vec a token, for every
resource made resident, at every command. A pass of N draws among N resident resources so
cost N^2. In the M3 profile of the argument-table shape at N 2000 these two were 44% of the
frame.

BindState::used_in_token_order is a consumer's opt-in, not part of the shape. It says it
lists used_resources in token order (each entry's token at least the one before, so a
token's entries lie together; a debug build asserts it). The binder then finds a member's
entries by search, O(members x log n), and without the flag it gathers them as before
(UsedByToken::{Listed, Gathered}). The runtime sets the flag on every state it lists from a
residency: Residency::used_resources lists in token order, and tile_resources keeps that
order.

Functions: bind::heap::{UsedByToken::of, UsedByToken::get, member_id, handle_table_bytes,
heap_elements}; BindState gains used_in_token_order; the runtime sets it in
RenderLowering::refresh_bind_state, the compute bind_state, dispatch_tiles_resident,
gpu_execute's total and the GPU form's preprocess. docs/API.md says what it does.

Verified:
- bind::heap::tests::a_state_in_token_order_finds_its_members_by_search: 200 used
  resources, members among buffers, one listed twice under one ID. The ordered state is
  searched (Listed), the same state without the flag is gathered, and both give equal
  tables and heap elements and the same internal errors for a member with two IDs and a
  member not listed.
- The rest of bind::heap and pipeline::api_tests (the serde round trip names the field)
  pass.
- M3 frame times at the tip of this series are in its last commit.

(cherry picked from commit d23e702339ce57f4a75cfae9f4a8247ff6875bd4)
(cherry picked from commit a38aeff46479332628c5350d73f7fc319635c713)
2026-11-03 12:36:57 -08:00
Anees Iqbal 12f58a227f Keep no chunk of a buffer of mesh or patch draws alone: none of their draws is plain
922caf3199 records an execution of commands the CPU encoded chunk by chunk, each chunk
apart from a KeptContext of its own (a command pool, descriptor arena and uploads), and
keeps a chunk whose draws are all plain. A mesh draw and a patch draw are never plain
(render/executions.rs clears RenderLowering::replay_plain for both), so on a buffer whose
command types hold neither DRAW nor DRAW_INDEXED every chunk recorded apart was found not
plain, noted, and its execution finished through the apart encoder. That cost a command
pool and two more primaries, each with a barrier, on the first execution, and kept
nothing. RenderExecution::keeping now admits only a buffer whose command types intersect
DRAW | DRAW_INDEXED (the test settle already makes). A buffer of mesh or patch draws
alone records as it did before 922caf3199. A buffer that mixes them with draws of
primitives keeps today's path. docs/FAST-PATHS.md's known gap lists the buffers that
still record at every commit.

Runtime behaviour: such a buffer's executions record no chunk apart. An execution of a
chunk of resets alone on one of them, which draws nothing, is no longer kept either.

The cost gate showed the redundant work as three conformance rises, now withheld in the
records, all from 922caf3199. Each case measured alone, debug, M3 Max, over 8 runs:
- indirect-mesh-commands-object-threadgroup-lengths: command_buffers_begun 11 -> 9,
  continuations 3 -> 1, submitted 8 -> 6, cmd_pipeline_barrier 14 -> 12,
  end_command_buffer 11 -> 9, encoder_command_buffers_begun 9 -> 7.
- mesh-commands-unordered-draws: 9 -> 7, 3 -> 1, 6 -> 4, 11 -> 9, 9 -> 7, 8 -> 6.
- mesh-commands-own-state: 10 -> 8, 3 -> 1, 7 -> 5, 13 -> 11, 10 -> 8, 8 -> 6.
command_pools_made fell 2 -> 1 in each. Every gated count equals its value at
c00efdc7c0, 922caf3199's parent. The remaining differences are scheduler_sleeps,
scheduler_wakes_host and submit_stalls_on_work, which the race rule names.

Test: runtime_lane::mesh_commands::a_buffer_of_mesh_draws_alone_records_no_chunk_apart
executes the CPU's own commands on a buffer of both mesh kinds twice, after another
buffer's execution. It asserts the first execution begins as many command buffers as
the second, and that both draw Metal's words. Verified on the M3 Max (--cfg m2v_gpu):
it passes with the fix, and fails without it (left 9, right 7). own_commands_draw_metals_words,
which now shares encode_own, passes. clippy -D warnings, all targets and features, with
--cfg m2v_gpu, is clean for metal2vulkan-runtime and metal2vulkan-validation.

RUNTIME_VERSION and the runtime-sources pin are left to the stack.

(cherry picked from commit 132d0aeea055b9a3819c82619a12e3c4adf32646)
(cherry picked from commit 2a23d1882ceb4cd21506af2a66f92f8258b5b2b2)
2026-11-03 11:08:02 -08:00
Anees Iqbal 61a9508e92 Build visibilityResultType: Accumulate takes a pass's results into the buffer's words
RenderPassDescriptor gains visibility_result_type (MTLVisibilityResultType: Reset, the default
and today's behaviour, and Accumulate). Under Accumulate no query result is copied over its
offset's word: every query of an offset, the first one too, is copied into the upload region the
continuations already use, and the crate-owned combine takes them into the word as the buffer
holds it. The combine already loaded the destination word as its accumulator, so Accumulate is
the first query becoming one more source. A `Boolean` word ORs the device's results in; a
`Counting` word is summed in through a new table mode of the combine, into the word's low 32 bits
alone, wrapping there, its high 32 bits kept (ContinuedResult::low_half / in_low_half). That last
part is what the M3 Max answered when recorded: 0xffff_fff8 plus 16 samples writes 8, and
0xffff_ffff_ffff_fff8 plus 16 writes 0xffff_ffff_0000_0008. A plain 64-bit sum was divergent there.
An offset set with no draw after it keeps its word, because a query with no draw adds 0. Where a
no-copy buffer's bytes start off a multiple of 8, so the results land in an upload region, the
words are now copied into that region before the combine (Landing::inward). Reset records exactly
what it did before.

Conformance: RenderPass gains visibility_type (typed()), and words() appends it only where it is
not Reset, so existing fingerprints read as before. Both sides set it. There are four new
visibility cases, recorded on the M3 Max (macOS 27.0.1): visibility-counting-accumulate (two
command buffers; words 100/5/7/0xffff_fff8/u64::MAX-7), visibility-counting-accumulate-one-command-buffer
(two passes in one command buffer, read once), visibility-counting-accumulate-revisit, and
visibility-boolean-accumulate (words 0/2/3 under covering and non-covering draws, an offset set
with no draw, then a second command buffer). The family's acts key states the type, and a joined
shape adds a command-buffer input. Cost and timing records for the new cases are not written here.

Lane tests (runtime_lane): accumulated_counts_add_to_the_words,
accumulated_booleans_or_into_the_words, and
host_bytes::accumulated_visibility_results_land_where_their_bytes_lie. Unit tests: the combine's
accumulated_counts_are_summed_into_the_low_half, its plan's table mode, and the type's raw values.

Coverage: coverage.tsv marks MTLRenderPassDescriptor.visibilityResultType implemented (its unused
"visibility" group is removed), and METAL-COVERAGE.md is regenerated. MTLVisibilityResultType joins
the enum table, so metal_enumerators.tsv and CONFORMANCE-COVERAGE.md are regenerated. The API
signatures are re-blessed. REFUSALS.md is regenerated: VisibilityResultType::from_raw is one more
UndefinedValue site. The regeneration also picks up two bind/graphics.rs sites the committed file
was missing. The degrade docs (landed results, Boolean) state Accumulate.

Verified on the M3 Max under MoltenVK 1.4.2:
- The 52 visibility-touching lane tests pass: visibility, host_bytes, depth_never, amplified_draws,
  degrade_notices and the framebuffer_fetch split pass.
- The visibility family's replay is all announced (no divergence), after the low-half change.
- Negative control with Accumulate forced to Reset: all three Accumulate lane tests fail, and all
  four new cases replay divergent.
- Negative control with no inward copy: the landing test fails at 4 bytes past a page (2 read 0,
  100 read 16).
- Before the low-half change, visibility-counting-accumulate replayed divergent at words 3 and 4.
- The combine's low-half test fails on the interpreter without the high-half select ([8, 1] for
  [8, 0]).
clippy (plain and --cfg m2v_gpu), rustdoc and scripts/api-docs are clean.

SEMANTICS_VERSION: no translated shader changes, but the owned combine module's words do
(main's call). RUNTIME_VERSION and the runtime-sources pin are not touched here.

(cherry picked from commit 1c172968ad6492cebcae2a568fc99e90565d4d11)
(cherry picked from commit 9f47ebcf006920f7561a16a77f77e422de7201c1)
2026-11-03 11:08:01 -08:00
Anees Iqbal d806c0a792 Write Boolean visibility results as the device's nonzero query result, without the resolve
Metal's Boolean visibility result is nonzero where any sample passed and 0 otherwise. The
Apple M3 Max writes 1; Metal on the AMD Radeon Pro 5300M and the Intel UHD Graphics 630
(macOS 26.7.1, the reims-vgpu team's probes) writes the samples that passed. The runtime
had a crate-owned dispatch (bind::visibility_resolve_module) after every pass with a
Boolean offset whose only job was to rewrite that word to exactly 1. Under AGENTS.md rule
1 the device's native answer is the only form: a Boolean result is now the imprecise
occlusion query's own result, which Vulkan states as "When any samples are passed,
boolean queries will return a non-zero result value, otherwise a result value of zero is
returned" (occlusionQueryPrecise). Across a split pass's render pass instances the
combine still ORs the continuations, so zero stays zero exactly where no instance passed
a sample. Counting queries stay precise.

- Runtime: the resolve's plan, uploads, sets and dispatch are gone from visibility.rs, and
  OwnedModule::VisibilityResolve from owned_kernel.rs. A pass with no continuation now
  records only vkCmdCopyQueryPoolResults. The combine's in-place words are declared as
  shader reads and writes for every combined offset (they were declared only for Boolean
  ones). A new precision degradation, DeviceBooleanVisibility
  (device-boolean-visibility), is announced where a pass's Boolean results record; its
  catalogue entry is in docs/API.md section 9 and a device-gaps row in docs/FAST-PATHS.md,
  as for the other native-answer kinds.
- Translator: bind/visibility_resolve.rs and its tests are deleted (VisibilityResolve,
  VisibilityResolveModule, visibility_resolve_module leave the public surface). Its
  shared helpers (windows, words_buffer, u32_value) move into visibility_combine.rs; the
  combine's plan tests take the two refusal cases only the resolve's tests held. No
  translation output changes.
- Conformance: a new Loosening::Nonzero, and an allowance may name one element of a byte
  region as <site>/<byte offset>. The visibility family loosens each Boolean result's word,
  and only that word, by Nonzero, justified by device-boolean-visibility, which its Boolean
  cases also declare at the notices site. Every other word still compares exactly. No
  recording changes. README and docs/CONFORMANCE-COVERAGE.md (regenerated) say so.
- Validation lane: every Boolean expectation reads the word by its contract
  (visibility::by_contract: nonzero and not the buffer's starting word reads as 1), in
  visibility, framebuffer_fetch, host_bytes, depth_never and amplified_draws; the notice
  is a new lane site (visibility::BOOLEANS) taken by
  boolean_results_announce_the_device_s_value and expected where other tests' notice sets
  are exact. boolean_results_are_copied_with_no_dispatch counts one query result copy and
  no vkCmdDispatch for a pass of two Boolean offsets.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings with
--cfg m2v_gpu; the runtime's degradation catalogue and site tests, the translator's
combine, owned-division, resolve-helper users', api_surface and api_signatures tests;
the conformance suite's 1024 device-free tests. The device lane tests run on the M3 with
the next step.

(cherry picked from commit a4976cdc3734c21c1b9ed4cf603bbf6bab2523f0)
(cherry picked from commit 34e44e3a12a46e6ff4b651cc4689002690d680fc)
2026-11-03 11:08:01 -08:00
Anees Iqbal 9b60da4bee host_ram: import a used RAM's chunks ahead, on a thread of the device's
What: Device::use_host_ram now starts a thread ("m2v-host-ram", through exit_guard::spawn)
that imports the RAM's 64 MiB chunks one after another, ahead of the objects over them. It
goes on from the chunk past the one an object last took, then from the RAM's start. It
skips a chunk whose lock is held (an object is importing it) and one it failed to import
(left to the first object over it, as before). It stops once every chunk is imported, the
use ends, the device goes or is lost, or the process exits (each import inside an
exit_guard section). It holds the device and the RAM weakly between chunks. An object over
a chunk the thread has not reached imports it on its own thread, as before. One over the
chunk being imported waits for that one import. New counter:
WorkCounts::host_ram_chunks_imported_ahead.

Why: a consumer makes 2 MiB heaps over consecutive fresh guest RAM (memfd). Each 32nd heap
was the first object over a chunk. Its making waited for the chunk's import, which faults
in and pins 64 MiB of fresh pages. That took ~7.5 ms exclusive on the RTX 5080 laptop, and
0.4-4.0 s in a shared boot with compaction (compact_stall +10,889). Keeping chunks imported
for the RAM's life already held at the start of this branch (a chunk stays in its slot
while the use lasts). Measured here: a heap made again after every heap was dropped
imported 0 chunks.

The trade-off: the whole RAM is resident and pinned from soon after use_host_ram, not only
the chunks objects touch. 16 GiB of fresh THP memfd RAM took 3.47 s on the thread, with
compact_stall 1152, compact_fail 56, pgmigrate_success 935291 and allocstall_normal 54,
all off the making threads. No kernel, boot or module parameter is needed. Recorded in
docs/HOWTO.md ("One run inside one chunk").

Vulkan rules relied on (checked against the 1.4.366 spec): the import itself is
Device::import_chunk, unchanged, under VUID-VkImportMemoryHostPointerInfoEXT-pHostPointer-01749
"pHostPointer must be a pointer aligned to an integer multiple of
VkPhysicalDeviceExternalMemoryHostPropertiesEXT::minImportedHostPointerAlignment",
VUID-VkImportMemoryHostPointerInfoEXT-handleType-01750 "pHostPointer must be a pointer to
allocationSize number of bytes of host memory", VUID-VkMemoryAllocateInfo-allocationSize-01745
"allocationSize must be an integer multiple of ...minImportedHostPointerAlignment", and
VUID-VkMemoryAllocateInfo-memoryTypeIndex-01744 "the value of memoryTypeIndex must be one of
those returned by vkGetMemoryHostPointerPropertiesEXT". The spec's "Externally Synchronized
Parameters" list names no parameter of vkAllocateMemory, so the thread's imports may run
while other threads use the device. Each chunk's import is made once, under the chunk's own
lock. A chunk is freed only on the existing path (vkFreeMemory's memory parameter is
externally synchronized: one owner frees it).

Verified on the RTX 5080 laptop (NVIDIA 615.71.09), release, --cfg m2v_gpu:
- All 21 host_ram tests pass, among them the new device test
  chunks_are_imported_ahead_so_no_making_waits_for_one. It covers 4 chunks of fresh memfd
  RAM under MADV_HUGEPAGE, imported ahead in 32.5 ms. Then 40 heaps of 2 MiB over
  consecutive runs: 0 chunk imports, 0 host-pointer imports and 40 chunk-bound buffers
  during the makings, the slowest making 78 us. Heap 33 passes a CPU write -> GPU read ->
  GPU write -> CPU read round trip. A heap made again after all were dropped imports
  nothing. The other device tests hold the thread back (Device::hold_host_ram_imports,
  test-only), so they still see each chunk imported by its first object.
- Negative control: with the spawn disabled, the new test fails ("the device's thread
  imported 0 of 4 chunks").
- On the M3 Max (MoltenVK, macOS 27.0.1), release, --cfg m2v_gpu: all 19 host_ram tests
  pass (the two dma-buf tests are Linux-only). In the new test, 4 chunks were imported ahead
  in 7.2 ms; across the 40 makings the slowest took 35 us.
- Unit test the_devices_thread_goes_on_past_the_chunk_an_object_took_then_from_the_start
  covers the order, the skip of a held or failed chunk, and the end.

Heap makings, 128 heaps of 2 MiB over fresh THP memfd RAM (wall time per
new_heap_with_bytes_no_copy):

  case                                          p50       p90       max      makings > 5 ms
  before, 1 GiB RAM                             0.001 ms  0.002 ms  7.39 ms  heaps 0, 32, 64, 96
  after, made at once                           0.001 ms  0.003 ms  7.54 ms  heaps 0, 32, 64, 96
  after, made once the thread is done (122 ms)  0.001 ms  0.002 ms  0.05 ms  none
  before, 16 GiB RAM                            0.001 ms  0.002 ms  7.54 ms  heaps 0, 32, 64, 96
  after, 16 GiB, made once done (3468 ms)       0.001 ms  0.002 ms  0.03 ms  none

Made at once, the makings outran the thread: 5 chunks were imported during them, 4 of
them by the thread. Once the thread is done, no making waits for an import.

(cherry picked from commit 7baa553a75515909f2ce9701c1e1bea4c408845a)
(cherry picked from commit 97a69f70ab96d37dcdf269192a6935f8c4126749)
2026-11-03 10:11:04 -08:00
Anees Iqbal 51c7059a40 Regenerate docs/REFUSALS.md: KernelStageIn's site and the rebind_slots range refusals
python3 scripts/refusal-surface/refusal_surface.py on this tree. Two rows move:
- KernelStageIn's runtime site is indirect_execute.rs's dispatch now, where the kept recordings
  of unchanged indirect commands moved the refusal (two commits back), not record;
- BufferRange and DescriptorRangeExceeded gain bind/graphics.rs's rebind_slots, a site the base
  had added without regenerating the table.
The device replay's ReplayFaults::ADDRESS was no refusal, so its removal moves no row;
tests/api_surface.rs names ReplayFaults alone, and api_signatures.tsv dropped the constant with
it (scripts/api-signatures --check passes).

Needs no version bump: a generated document.

(cherry picked from commit 07d7e05255a3d15ba98094389a680e96440eefa0)
(cherry picked from commit 3d66d7436109ffbd80c5e6adf0ef1d92b26d70e5)
2026-11-03 09:25:30 -08:00
Anees Iqbal 185bbd6328 Host steps: record off the scheduler's thread, order by what the execution reaches, make only named states
A batch executing indirect commands the GPU may write waits for its gate, then its host step
records the commands from their records. Three costs fell on every other queue meanwhile:

- The step ran on the scheduler's thread, which submitted nothing while it recorded (thousands
  of draws take milliseconds).
- Its footprint was unknown (tracker::ordered's None), so every later batch of another queue that
  made a tracked use was held behind it until it was submitted.
- At commit, the render settle made a VkPipeline for every live state that supports indirect
  command buffers, times the topology class's primitive types (1,280 lookups and 513 makings for
  256 live states on the measured frame), and the step waited for all of them, up to the command
  buffer's bound.

Now:

- The scheduler hands each step to a steps' thread (scheduler/steps.rs, started at the first
  step, user-interactive like the scheduler's, recording inline where the host cannot start it),
  which records the steps in order, each a section of the exit guard, and wakes the scheduler.
  The batch is marked as stepping meanwhile (CommandBufferShared::begin_step/end_step), so it
  waits and no pass hands it over twice.
- commit bounds a step's uses where it can (Segment::bound): for a compute execution, the
  resources the command buffer made resident and the ICB's storage (and an indirect range's
  copy); for a render pass, the pass's own uses, the resident resources and each execution's
  storage. CommandBufferShared::footprint uses that bound, so only a later batch sharing one of
  those is held. An execution that inherits buffers, is gated or preprocessed, reaches tile
  memory, has shadows or lends visibility stays unbounded (None), as before.
- The render settle makes the states the CPU set on the executed commands
  (IndirectCommandBuffer::set_render_states, each state once), or the inherited one. A draw of a
  state a GPU-written record names that no settle made is begun at the step, made on its thread
  or handed to the device's pool and waited for until the command buffer's bound, as before; it
  holds no other queue's batch, and it is counted.

On the kept recordings of the commit before (item 1), set_render_states reads the states the CPU
set from the buffer's per-command map (Commands::states, a range of it), each state once.

New counters: WorkCounts::host_steps_recorded, host_step_nanos, and host_step_pipelines_made
(the VkPipelines a step began itself, made on its thread or handed to the device's pool and
waited for: counted at the variant's making on the step's thread and at pipeline_pooled).
The degrade notice host-replayed-indirect-commands states the new cost (degradation.rs and
docs/API.md, same text).

Verified on the M3 Max (MoltenVK 1.4.2), release, runtime_lane::host_replay_frames (the next
commit: 256 live states, an ICB of 5000 draws naming 4, made resident for writing by a compute
pass each frame, and a presenter clearing a texture on another queue every 8.33 ms), the parent
and this tree run alternately twice, 60 frames each after 4 cold ones, on a loaded host:
- the presenter: 80 of 244 and 73 of 192 ticks presented before (commit to completion median
  16.9 and 16.4 ms, p90 40.8 and 23.7 ms), 186 of 186 and 185 of 189 after (1.13 and 1.13 ms,
  p90 1.49 and 2.23 ms); heads held behind earlier commits 23 and 13 before, 0 after;
- the first frame's commit: 377 and 168 ms before (513 variant pipelines made, 1,284 looked
  up), 5.3 and 5.1 ms after (9 made, 24 looked up); a steady commit 2.38 and 2.33 ms before,
  0.14 ms after;
- the frame itself (commit to the last completion): median 28.7 and 24.4 ms before, 23.3 and
  24.6 ms after, within the host's noise; the host step takes about 20 ms of it
  (host_step_nanos), recording the 5000 draws.
The consumer's ICB repro (one state, 5001 draws, the ICB made resident for writing, another
queue's one-dispatch command buffers meanwhile), same runs: that queue's commit to completion at
the 99th percentile 53.5 and 24.3 ms before, 2.96 and 3.71 ms after, 140 and 119 command
buffers in 40 frames before, 2,281 and 2,062 after; the frame alike (21 to 26 ms).
Tests: runtime_lane::render_executions::
a_host_step_makes_the_pipeline_of_a_state_only_a_gpu_written_record_names (a blit-copied record
naming a state, of another variant, that the CPU set on no executed command: both commands draw,
the step's beginning of that state's VkPipeline is counted, and the step's time).

--cfg m2v_gpu under the validation layer, on this tree before the pipeline_pooled count and the
test: 234 tests of the indirect_*, kept_*, render_executions, render_gpu_executions,
render_merged_executions, mesh_commands and executions lanes; 1,644 tests of the runtime crate's lib and the
commands_recorded, dispatch_executions, generated_executions, kept_variants, device_commands,
queue_order, submission_checks and grouped_submissions lanes. clippy -D warnings, plain and
--cfg m2v_gpu; rustdoc -D warnings; scripts/api-signatures --check.

Needs a RUNTIME_VERSION bump (what a run submits, when, and its counts) and a runtime-sources
pin.

(cherry picked from commit 4b05004999403684a2bdf4f3994108b53c7dc776)
(cherry picked from commit 3831ba7e1298203779597feb0ea2943f77f9f5df)
2026-11-03 09:25:30 -08:00
Anees Iqbal 565fbd9153 Run unchanged indirect commands from kept recordings, chunk by chunk
An execution of an indirect command buffer read, decoded and recorded every
command again at every commit, so an unchanged execution of 16384 draws cost
about 44 ms of commit on the M3 Max and 64 ms on the RTX 5080 laptop, where
Metal's costs 2 ms. A profile of the render case put a third of it in the
records' decode and moves and the rest in recording the draws.

Now an execution of commands the CPU encoded records them in chunks of 256
(kept_commands.rs). A render chunk records into a secondary of its own, begun
for simultaneous use against the instance's compatible pass, through an
encoder over a core of its own whose effects the pass's core takes
(EncoderCore::capture, absorb); a compute chunk records as a segment of its
own, behind a barrier from everything before. Each chunk takes its command
pool, descriptor arena and uploads from a context of its own, lent to the
command buffer while it records and held by every command buffer that runs
it. A chunk whose recording is plain (every draw passes draw_again's keep
test but for being replayed, no step outside its command buffer, nothing its
command buffer alone holds, no released state) is kept on the buffer with
what it was recorded from: the encoder's inputs (RenderKey, ComputeKey: the
inherited state, the pass's compatible pass, shape, extent and sample
positions, the encoder's state and scissors, the resident resources), each
address its commands named and what it resolved to, and the no-copy moves.
A later execution of the chunk under equal inputs, every address resolving
as before, nothing detached and every held object alive, runs the kept
command buffer and notes its uses, keys, holds and executions again
(EncoderCore::run_kept), reading no record. Every CPU write of a command
forgets its chunk under the lock the write takes; the buffer's first GPU
write forgets them all; a recording from records written meanwhile is not
kept. A chunk that is not plain records the rest of the range as before and
is noted, so later executions of it record as before until a write reaches
it. The buffer's per-command state moves to a map, so a buffer of commands
never encoded holds nothing for them.

WorkCounts::indirect_chunks_kept and indirect_commands_kept count the kept
path. docs/FAST-PATHS.md's known gaps list the executions that still record
every command at every commit.

Verified on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu, under the
validation layer: runtime_lane::kept_commands, 5 tests: unchanged render
commands run 3 kept chunks of 600 commands reading no record, into another
target and twice in one pass; a command written again or reset records its
chunk alone; a blit's reset runs no kept chunk and its commands draw nothing;
another residency or range records again; compute commands the same, with a
command written again and a blit reset. 446 of 448 tests of the 33 lanes
that execute indirect commands pass; the two others
(extended_range_blends half outputs, padded_loads loading pass) are among
the MoltenVK reds the parent already has. clippy -D warnings, plain and
--cfg m2v_gpu, for the runtime and validation crates; the runtime's
kept_commands unit test; the translator's fast_paths, api_signatures and
api_surface tests.

Needs a RUNTIME_VERSION bump and a runtime-sources pin.

(cherry picked from commit 21b9438ec5b8cbf7a1e79c5dfbf84cdad7b43d91)
(cherry picked from commit 922caf3199378b029bafc201429f80b0d43bb048)
2026-11-03 09:25:29 -08:00
Anees Iqbal b74a0a4866 commit_and_submit: run a head's submission checks on the committing thread
What: a thread in CommandBuffer::commit_and_submit now runs the submission
checks of the head committed first of all itself, without the scheduler's
lock, right before it submits that head, where the head is ready but for its
checks (no host step, no group, no storage-form switch, no rebind) and every
event value it waits for was reached on the device or by the host. It then
passes again under the lock (Inbox::pass_again, which takes nothing in) and
submits that head first, and so on up to PASS_SUBMISSIONS batches in all. A
head whose checks wait for a submitted GPU signal to land, or whose checks the
scheduler's thread took first, stays the scheduler thread's, as before.

Why: reims's Vulkan platform sets a check on every command buffer it commits,
so commit_and_submit never submitted at commit for them (plain_ready held out
every checked head). Metal checks a submission as it submits it, on whichever
thread submits, so running the check on the committing thread is Metal's
behaviour; the check follows the submission handler's rule there (no lock the
caller holds, no GPU wait).

How:
- Held::checks_taken marks a batch whose checks were taken, by check_heads
  (left to the scheduler's thread, replacing its Left::holds lookup) or by a
  committer (claim_check), so the two never both run them.
- claim_check looks at Order::first_mut (the head take_first would take), so
  no head is passed over: commit order holds across threads.
- The committer's handlers keep their Turns tickets: each pass under the lock
  takes its own ticket, and its handlers run before the next check.
- The check runs through run_work -> CommandBufferShared::run_checks, the
  scheduler's own path, so a code (or a panic) fails the submission exactly
  as there (fail_submission, the CB completing with Injected(code)).
- plain_ready now holds out only a checked head whose checks are still to run,
  so a head whose checks ran goes with any plain pass.
- Counted: WorkCounts::batches_checked_at_commit (new), beside
  batches_submitted_at_commit; classified as Submission by its "batches_"
  prefix in the conformance cost rules.

Verified on the M3 Max (MoltenVK, --cfg m2v_gpu, maclock, load 50-90):
- New tests in tests::commit_and_submit:
  - a_checked_command_buffer_is_checked_and_submitted_on_the_committing_thread:
    40 of 40 checked and submitted on the caller, check then handler, before the
    call returned; batches_checked_at_commit 40.
  - a_refusing_check_fails_its_submission_alike_at_commit_and_on_the_scheduler:
    two submissions split by an event signal, the second refused with code 8:
    identical status, error, completed-handler status, submissions seen, bytes
    and event value on both paths.
  - checked_command_buffers_keep_commit_order_across_commit_and_commit_and_submit:
    2 threads x 500 checked CBs, commit and commit_and_submit in turn: checks
    and submission handlers in commit order, each check once; 308 of 1000
    checks on a committing thread.
  - The five commit_and_submit tests: --stress-count 10, 10/10 passed.
- Negative controls:
  - claim_check answering None: all three new tests fail (0 checked at commit).
  - claim_check neither honouring nor setting checks_taken: the order test
    fails 4/4 (checks out of commit order, checks run twice).
- runtime_lane::submission_checks' in-flight test gains a commit_and_submit
  variant whose wait is met only by a GPU signal in flight: its check ran only
  after the signal landed and never on the caller, Event and SharedEvent.
  submission_checks, grouped_submissions and queue_order lanes: 24/24 passed.
- Runtime tests matching scheduler|check|teardown|completion|submission|inbox|
  order: 169/169 passed. Conformance cost, fast_paths and api_signatures
  tests 38/38; clippy -D warnings (runtime + validation, --cfg m2v_gpu) clean;
  public rustdoc clean. api_signatures.tsv blessed (one new field).

(cherry picked from commit 91d0ea691a95649cbdc7828d4cc9ee6762a7ae53)
(cherry picked from commit 6c5fca926e855ee7d7236bc850bb9b281f4dd9cd)
2026-11-03 07:56:21 -08:00
Anees Iqbal 0e7e09a064 Answer a required threadgroup size's threads as a state's maxTotalThreadsPerThreadgroup
A compute or tile state whose descriptor states requiredThreadsPerThreadgroup now answers that
size's threads as its maxTotalThreadsPerThreadgroup. The answer is lowered only where this device
holds fewer threads for the kernel than the size. A state that requires no size keeps today's
answer, the compiled pipeline's limit. Before this change every state answered the compiled limit
(1024 on a full device) whatever size it required. Metal answers the size.

Measured on the M3 Max under macOS 27.0.1. Each state came from a source compiled once and never
before, with an integer baked into it:
- Compute: exactly W*H*D. 1x1x1 gives 1, 3x1x1 gives 3, 3x3x1 gives 9, 7x3x1 gives 21, 8x8x2
  gives 128, 1x1x64 gives 64, 32x32x1 and 1024x1x1 give 1024. No size gives 1024.
  [[max_total_threads_per_threadgroup(128)]] with 8x8x1 gives 64.
- Tile (threadgroupSizeMatchesTileSize on or off): W*H*D rounded down to a multiple of 4.
  1x1, 2x1 and 3x1 give 0, 3x3 gives 8, 7x3 gives 20, 2x2 gives 4, 6x6 gives 36, 8x8 gives 64,
  16x16 gives 256, 32x32 gives 1024. A tile dispatch of the state's own size runs no thread
  where the threads are not a multiple of 4 (1x1, 2x1, 3x3, 7x3). The command buffer completes
  with no error.
- Metal keeps a state it compiled and hands its limit to a later state of the same function
  that differs only in the required size. For compute this was seen in the same process; for
  tile, in the same process and in a later one. A compute state with 8x8x1, and one with no
  size, answered 16 after a 4x4x1 state of the same MTLFunction. An 8x8 tile state answered 16
  after a 4x4 one, and its 8x8 dispatch ran no thread. The module doc's earlier "the state's
  maxTotalThreadsPerThreadgroup stays the kernel's own" reads like such a measurement: a
  function compiled first with no size.

Rule 1 does not cover this: it is an API value Metal reports, not arithmetic. So the runtime
answers Metal's first-compile rule and does not imitate its cache. Following the owner's
decision, a tile state also answers the size's threads where Metal rounds them down, and its
dispatch of that size runs. Metal runs no thread there, which is its own defect. docs/API.md's
accepted differences records both and Metal's cache answer.

How:
- ComputePipelineState::max_total_threads_per_threadgroup answers
  pipeline::reported_max_total_threads(required size, compiled limit). A tile state's
  RenderPipelineState answer goes through its tile function's compute state, so it follows.
- The compiled limit moves to pipeline_max_total_threads_per_threadgroup (crate-private). The
  replay and folded indirect-dispatch paths (gpu_execute, indirect_dispatch) read it, so no
  dispatch path changes.
- Docs: the additions module's measurement, the tile module's answers, the render and compute
  accessors, the translator's descriptor fields and ComputePipelineMetalInfo, and docs/API.md's
  accepted differences.

Tests:
- tests::pipeline::a_required_size_is_the_states_thread_limit (CPU): the rule, the device's
  lower limit, no size, and axes whose product overflows.
- runtime_lane::compute_threadgroups::a_compute_state_with_a_required_size_answers_its_threads
  and runtime_lane::tile_states::a_tile_state_with_a_required_size_answers_its_threads
  (--cfg m2v_gpu): states made through the runtime with and without a size.

Verified:
- cargo clippy -D warnings, plain (metal2vulkan, metal2vulkan-runtime, metal2vulkan-validation)
  and with --cfg m2v_gpu (metal2vulkan-validation);
- RUSTDOCFLAGS=-D warnings cargo doc (metal2vulkan, metal2vulkan-runtime);
- scripts/api-docs;
- the metal2vulkan-runtime and metal2vulkan-air suites: 1715 passed, 4 skipped;
- the device lanes on the M3 Max through MoltenVK (tile_states, compute_threadgroups,
  tile_threadgroups, indirect_dispatches, indirect_executions, function_tables): 124 passed.
  With the old answer put back, both new device tests fail ("left: 1024, right: 1" at 1x1x1).

No version bump and no pin here: they come at stacking.

(cherry picked from commit 94fbec600e2155fff4c05b88894155054569621e)
(cherry picked from commit 09be67cab1968bbadcc698456fb245ec6e94f20a)
2026-11-03 07:56:21 -08:00
Anees Iqbal 7e48216b37 Make the canonical encoding's image scratch without zeros
What: under ExtendedRangeBlitPolicy::Canonical, a blit into a compressed BGRA10_XR or
BGRA10_XR_sRGB image rewrites its texels through a scratch buffer: a copy out, one dispatch a
region, a copy back. The scratch was made with Device::own_buffer, which zeroes a Private buffer
in a submission's first work (a copy of the device's zeros on a device with unified memory, a fill
on a discrete one), in a command buffer of its own. The copy out writes every byte the dispatches
and the copy back read (the regions, tightly packed) and nothing reads the alignment gaps, so the
scratch is now made with Device::unzeroed_buffer (Private, tracked as before), as shadow_merge's
fully written scratch already is. Nothing the program or Metal observes changes; the work counts
do.

Why: the whole-set conformance cost check on the M3 Max read compressed-blits-bgra10xr and its
sRGB twin over their records since 4b194d24af (which added the Canonical form and which the suite's
exact policy selects). Each case alone, cost --runs 8 --show, debug build, MoltenVK 1.4.2:
- 452c17aa2c (before) -> 4b194d24af: command_barriers 5 -> 24, command buffers begun and
  submitted 11 -> 14 (batch work 2 -> 5), cmd_copy_buffer 2 -> 7, cmd_copy_buffer_to_image
  7 -> 12, cmd_copy_image_to_buffer 6 -> 11, cmd_pipeline_barrier 18 -> 44, 9 dispatches.
- 4b194d24af -> this change: command buffers begun and submitted 14 -> 11 (batch work 5 -> 2),
  cmd_copy_buffer 7 -> 2, cmd_pipeline_barrier 44 -> 37; nothing else moved. The copies out and
  back, the dispatches and the encoder's barriers around them are the rewrite itself.

Test: runtime_lane::compressed_blits::extended_range_blits_write_metal_s_encoding_under_the_canonical_policy
now asserts that a blit into each Private texture, compressed or not, records no buffer-to-buffer
copy and makes no zero fill (WorkCounts::commands_recorded.cmd_copy_buffer +
new_buffer_zero_fills), under both policies.

FAST-PATHS: the Canonical row's cost column no longer lists the zeroing command buffer, and says
its figures were taken while it ran.

Verified on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu: the test passes; with the scratch made by
own_buffer again it fails under Canonical ("BGRA10XR optimized true, 64 high, blitted in on Apple
M3 Max under Canonical", left 1, right 0) after passing the Kept leg. Conformance suite (no cfg):
1010 passed. Runtime behaviour changes (counts only): RUNTIME_VERSION is left to the stacker.

(cherry picked from commit 409aafaca513c03f6bad3378de1f0d8af6fdc5f0)
(cherry picked from commit 2b5f0731c54fa66350e88c82fceaed9909dc442a)
2026-11-03 07:56:21 -08:00
Anees Iqbal 7996b9a164 Mark a queue long by its command buffer's own GPU time, not the host's view of its head's age
What: a command queue is now marked long where one of its command buffers' own timestamps (its
first batch's start to its last's end) span over LONG_HEAD (2 ms), in the completion turn that
read them (CommandBufferShared::place_gpu_times), before the turn finishes it. The waiter's
host-age check in command_buffer/completion.rs (HeadWatch, Device::head_watch) is removed, and
went_long returns at once unless the device shares. A device whose command buffers write no
timestamps the host reads (gpu_times_from_host, a driver whose timestamps wait for every queue's,
or no calibrated timestamps) no longer shares: queue_switch_check::timed() gates the check, and
recall settles Unchecked and counts the new WorkCounts::queue_sharing_untimed where the device has
two VkQueues of one family to share. Two runtime extensions, doc-hidden, for the lanes and the
probe: CommandQueue::vk_queue_sharing() (its VkQueue and long mark) and Device::shares_vk_queues().

Why: the host's view of a batch's age as its VkQueue's oldest also holds its wait for the GPU to
start it and the waiter's lateness to see it complete, so short command buffers marked their
queues long for good. On the RTX 5080 Laptop GPU, 2x3 runs in a slow stretch had each thread's
queue marked long mid-run (at 20 ms to 1,238 ms) and settled apart, the PerQueue placement, at
PerQueue's rates. Measured cause, with a diagnostic build printing each host-age mark beside the
command buffer's own GPU span: beside another process's 30 ms command buffers, draws of 11 and
16 us of GPU time were seen 2.0 and 2.3 ms after they became their VkQueue's oldest, 1.8 and 2.1
ms of that before they started; that run's thread queue settled apart and ran at PerQueue's
4.1k. In the runs without contention, every true mark had a GPU span within 1.2 ms of its host
age (the 30 ms command buffers and the probe's 2.7 ms sizing one); under contention the sizing
command buffer's host age exceeded its span by 4.2 ms. Neither suggested alternative fits: the false
marks came mid-run, not only in a queue's first command buffers, and decaying the mark after short
heads would let the trap and alternating shapes' long queues rejoin and stall the compositor again.

Tests: tests::queue_share_device gains a_device_that_answers_gpu_times_from_the_host_does_not_
share_and_counts_it (expected, not run, to fail without the gate on the 5080: there it printed
"Unchecked ... could share: true", so the recorded Idles verdict would make it share), and
asserts queue_sharing_untimed == 0 elsewhere; its isolation runs print each queue's VkQueue and
mark over the run. The queues lane's a_queue_joining_another_s_busy_vk_queue_is_announced_once
now makes its device under QueueSharingPolicy::Adaptive (over the lane's exact_answers()), lets
the busy queue's fills be submitted first, and asserts queue_joins > 0 exactly where the device
shares, saying why where it does not. cross_queue_shadows gains the signal-in-between and the
waiting-writer cases on one VkQueue: no spin, Adaptive, the check settled, queue 2 joining queue
1's busy VkQueue; they assert the join, neither queue long, the hold still withheld while the
waiting writer has not completed, and the bytes.

Docs: QueueSharingPolicy::Adaptive, the FAST-PATHS row (the rule, the untimed exclusion, the new
ranges), docs/API.md (the policy section and the notice), the queue-sharing notice's cost text,
queue.rs and queue_share.rs; api_signatures blessed (additions only).

Verified on the RTX 5080 Laptop GPU (NVIDIA 615.71.09, msi, under gpu-locks, no VM), release
probe:
- 2 threads x 3 in flight, 10 runs each in turn: Adaptive 48.3, 28.0, 50.7, 52.9, 28.1, 53.7,
  48.6, 29.9, 31.5, 53.0k against PerQueue 21.4, 24.9, 27.8, 28.0, 27.6, 27.4, 27.1, 23.3, 26.9,
  27.3k, Adaptive above PerQueue in each pair; no thread's queue marked long in any run (gone long
  1 each: the probe's sizing queue). The 28-31k runs keep the shared placement, with waiter parks
  0.23 against 0.02-0.05 per command buffer in the fast ones: a host-side mode, not a move.
- Beside another process's 30 ms command buffers, 3 runs each: the old rule 4.1k (a thread's
  queue marked long by its host age), 5.2k, 6.6k; this rule 6.7k, 5.4k, 5.1k (no mark); PerQueue
  4.1k, 4.1k, 4.0k. There, draws' own spans reached 1.16 to 1.52 ms (timesliced), under the bound.
- Isolation, 3 runs each: trap and slow-alternating 64 completions over 10 ms under Adaptive (the
  one first-long stall, at most 26.4 to 30.1 ms) against none under PerQueue (at most 5.6 to
  9.7 ms); alternating none under Adaptive (at most 5.7 to 9.8 ms) against 7, 0, 0 under PerQueue.
  Unchanged from the host-age rule's runs.
- 8 threads: 3 in flight 53.4k, 54.4k against 27.8k, 27.4k; 1 in flight 50.1k, 49.3k against
  14.0k, 13.9k.
- Device tests (debug, --cfg m2v_gpu): tests::queue_share_device 8/8, the joining lane test and
  cross_queue_shadows 7/7 (the one-VkQueue cases: X's and Y's queues both on VkQueue 1, neither
  long, holds withheld 2, gated copies in 2). The compositor isolation test, old rule and new in
  turn, 3 each: p99 2.66-2.94 ms against 2.16-2.83 ms, 0 stalls, the same placement (the
  compositor alone on VkQueue 1, the application long on VkQueue 0, gone long 1). Its one earlier
  failure under this rule (p99 7.93 ms, 20 stalls, 5,579 of ~9,600 commits made) ran right after a
  74 s compile inside the hold, with the same placement and gone long 1: host load, not the rule.
On the M3 Max (MoltenVK, no sharing), tests::queue_share*, command_queues, cross_queue_shadows,
gpu_time and host_memory: 90/90. clippy -D warnings plain and --cfg m2v_gpu; RUSTDOCFLAGS=-D
warnings cargo doc; fast_paths, degradation*, api_signatures, api_surface, work_counts pass.
No RUNTIME_VERSION bump or pin here.

(cherry picked from commit 4fd88b7564cd9cd3651543bb3f8cd529b021709e, two claims corrected to what was run)
(cherry picked from commit eb0153e9d0fe6d272f2411c65f0a1ecda2c78bc2)
2026-11-03 06:50:11 -08:00
Anees Iqbal 50b41ecc54 Draw the kept draw again rebound after texture and sampler binds too: rewrite those slots alone
A vertex or fragment texture or sampler bind forgot the encoder's kept draw, so a draw after one
took every step: the compositor shape (a buffer and a texture bound before each draw) never
reached the bind tail.

Now:
- Texture and sampler binds keep the kept draw (log_keeping), as buffer binds do; the next draw
  compares the tables' stamps.
- BindingPlan::rebind_draw_slots_into (was rebind_draw_buffers_into) takes buffer, texture and
  sampler slots. A texture or sampler slot decides none of the commands. It answers Ok(false)
  for a texture buffer's texel range and a YCbCr texture's planes.
- binding::rebind_into writes a changed texture's or sampler's image descriptor as bind_into
  does (image_descriptor, through the encoder's memo, its samplers kept for retaining). It
  answers Ok(false) for a changed texel buffer, YCbCr image or argument sampler.
- The draw rebound brings in texture and sampler slots and stops where every step would differ:
  - a memoryless texture its functions use (the full path fails the command buffer there);
  - runtime samplers' address modes other than the kept draw's;
  - a changed shape (a sampler of other addressing, which the pipeline's specialization
    reads, takes every step);
  - a plan that samples or writes a color attachment's texture;
  - an extended-range shadow.
  It retains the new samplers and notes whether its uses read an image (Kept::reads_images).
- Docs: rebound.rs, WorkCounts::draws_rebound, docs/API.md, api_signatures.tsv.

Check: tests::draw_again::draws_after_texture_and_sampler_changes_rebind_what_every_step_binds
(tob_sample). It covers another texture each draw, another sampler of the same shape, both,
and samplers of other addressing. It checks rebound counts (0 for the last), commands, state
commands, noted uses and pixels against every step, with the debug cross-check on every second
hit. It fails without the change (0 rebounds). The buffer test's slot-of-another-class case is
now more slots than a draw rebound takes (samplers 0 to 8). Passes on the M3 (MoltenVK) with
the draw_again tests; clippy clean, plain and with --cfg m2v_gpu.

(cherry picked from commit ecf97956b214836a1309affe539aff8454239e97)
(cherry picked from commit 8472edf4c0ae174c3dab7bc667cecfa6874aa942)
2026-11-03 05:51:19 -08:00
Anees Iqbal e3f2c95dfe Draw the kept draw again rebound: after buffer, offset or bytes binds, rewrite those slots alone
A render encoder's kept draw (render/draw_again.rs) drawn again after calls that bound other
buffers, offsets or inline bytes at vertex or fragment buffer slots now rebinds only those slots
(render/draw_again/rebound.rs, WorkCounts::draws_rebound), where it took every step of a draw.

- Translator: BindingPlan::rebind_draw_buffers_into(state, slots, commands) writes again, over
  the same draw's commands of a state of the same shape, only what the buffer slots decide: their
  descriptor ranges at their places, the SlotBindOffset, SlotGuestBase and pulled-stride push
  fields that read them, and their vertex buffers' offsets. Ok(false) for a device-address slot,
  an argument or root table, a per-bind stride's vertex binding, a mesh, patch or de-indexed draw,
  or a uniform view a written slot may alias. docs/API.md says so; api_signatures gains it and
  WorkCounts::draws_rebound.
- Runtime: buffer and bytes binds keep the kept draw (log_keeping); the draw compares its tables'
  stamps with the kept draw's. On a difference, the tables' changes since (argument_table::
  changed_since: buffer slots alone, at most 8) are brought into the kept bind state
  (refresh_changed), and the draw goes on only where its shape stays, its variant and plan then
  the bind state's kept settle (LiveBind::settles_kept). It rewrites the commands
  (rebind_draw_buffers_into), set 0's writes and dynamic offsets (binding::rebind_into), push
  bytes and vertex buffers, and its uses whole (command_uses_into), and takes the checks a draw
  takes of them: a pulled attribute's reach, the stages' function tables, the attachments' reads;
  it stops at a pass whose fragments wrote memory, a shadowed texture among its uses, a barrier
  its fragments need after earlier geometry writes, or a detached buffer. It records with set 0
  as any draw finds or writes it (EncoderCore::set_zero_of), its uses noted as any draw notes
  them, through the kept draw's recording parts against what its command buffer holds; a notice
  met at each occurrence forgets it once recorded, as every step does. The kept parts (set-0
  writes that hold no keeper, dynamic states, the rest of its recording) live in the bind state's
  storage (LiveBind::kept), filled at the keep alone: a draw that takes every step pays one
  KeptStorage::keep and nothing per recording.
- Checked in builds with debug assertions: the first rebound draw of a kept draw and every second
  after it take every step instead, which must keep the draw, with the same commands, set-0
  writes, dynamic offsets, push bytes, vertex buffers and uses.

Tests: tests::draw_again::draws_after_buffer_changes_rebind_what_every_step_binds (MoltenVK, M3):
draws after offset and bytes changes rebind (draws_rebound == the draws again but those the check
takes), with the same commands of every kind, state commands, noted uses and pixels as the same
draws each taking every step, every draw at its own offset and color; a sampler bind between them
takes every step. Negative control: the translator not rewriting a changed slot's range fails it
at the cross-check ("other commands"). metal2vulkan's tests::engine_graphics_binder rebind test:
1360 rebinds over stage-io plans equal a full instantiate, and its negative control fails.

host_ab encode, release, 10k draws per command buffer, us/draw, offset case (one
set_vertex_buffer_offset before each draw), measured on this change before its last revision
(which moved the kept parts' fill from every full draw's recording to the keep and dropped three
Arc clones a keep; its own numbers come with the next landing):
  Apple M3 Max, MoltenVK 1.4.2, three interleaved rounds (median / mean of round p50s / max p90):
    lock fix 1.561 / 1.550 / 1.591  ->  0.550 / 0.548 / 0.592
  RTX 5080 Laptop GPU, thread CPU per draw, host_ab threads workload, one thread:
    lock fix 2.006 (shared PSO), 2.001 (own)  ->  0.541, 0.585; on 8 threads 10.3 Mdraws/s (was 2.9)
The unchanged draw (static) holds: 0.044 -> 0.046 on the M3.

(cherry picked from commit 2ee3520ff104094afde523e2eebf7bc8a9a9626d)
(cherry picked from commit d00975ea7da92da4886a29f1ebda6397f64202b1)
2026-11-03 05:51:18 -08:00
Anees Iqbal d07650b362 Warm passes: judge the byte budget on every device, and say what pipeline_bytes counts
What: tests::warm::a_byte_budget_stops_the_pass no longer skips its 1-byte leg when the pass
counted no driver bytes. That leg runs over a directory of its own, which holds none of the
records' driver data, so it now asserts that the pass wrote records' data (driver_saves > 0),
counted it (pipeline_bytes > 0), and stopped after the first record, on every device. A new test,
a_pass_over_its_records_own_directory_counts_only_what_it_writes, warms records over the directory
whose creations made them and asserts that the pass counts driver bytes exactly where its makings
wrote data. Where it wrote none, it asserts that a 1-byte budget stopped nothing.
WarmStatistics::pipeline_bytes, Device::warm, the runtime README and docs/HOWTO.md now say that a
making whose data the directory holds already adds nothing. Over that directory the budget binds
only where a making writes new data.

Why: the consumer read pipeline_bytes 0 on every boot of the RTX 5080, though the warm pass made
248 pipelines, and asked whether the counter is broken there (a making's keep on a thread
without the pass, or a path that never keeps). Measured with a scratch diagnostic at 1bb0b87a5a,
not committed:
- RTX 5080, a fresh directory: 23,800 bytes counted, 3 records' data written.
- The 5080 over the records' own directory: 0 bytes, 0 written, 2 unchanged, 2 found.
- M3 Max on MoltenVK 1.4.2: 13,362 bytes and 3 found respectively.
So keep() runs on the pass's thread and counts on NVIDIA too, and the consumer's 0 is the true
value. Their records come from the boot before, over the same directory, whose creations wrote
every making's data. The old test's skip branch could have hidden a broken counter; now a pass
that writes data and counts none fails.

Verified: tests::warm on the M3 (MoltenVK 1.4.2), 6 passed. The 1-byte pass over a fresh
directory counted 8,003 bytes with 1 record's data written; the pass over its own directory
counted 0 bytes, wrote 0 and found 3. cargo clippy -p metal2vulkan-runtime --all-targets
--all-features -D warnings with --cfg m2v_gpu; public rustdoc clean. The RTX 5080 run is in the
hand-over.

(cherry picked from commit 83cc2dbe6fb610c6ad59a741a7170812611cf703)
(cherry picked from commit 1d43003372f23275ceb7fcc463a34abedbeff9a7)
2026-11-03 04:54:41 -08:00
Anees Iqbal aa9b38e6fd State the padded sRGB twins' code and decode bounds as measured
DevicePackConversion's documented bound for the extended-range and
padded conversions said "a code within one" of Metal's. For
R10Unorm_X6_sRGB and RGB10A2Unorm_sRGB that is wrong. Metal's write of
these formats rounds the value clamped to [0, 1] to 2^-13 (nearest even)
and then looks it up in its encode table (R10X6_SRGB_ENCODE_FIRST). The
device writes the MSL transfer by its own maths, times 1023, RoundEven.
In the transfer's linear segment, one 2^-13 step spans 1.6 codes, so the
two can land two codes apart.

Measured: for each 2^-13 step over [0, 1], the f32s at and next to both
edges, where Metal's code is constant within a step and the device's
code rises with the value. The device's code (exact transfer) lies at
most two from Metal's table. It reaches two only below 0.0031308: at
1.5/8192, just above 6.5/8192, and at 24.5/8192. Everywhere else it is
within one, beyond the Pow's bound. Metal's recorded writes and stores
of RGB10A2Unorm_sRGB on the M3 Max under macOS 27.0.1
(rgb10a2-srgb-writes, -stores-f, -stores-h) show exactly that: three
words each, at k/16384 for k = 3 and 49, and at the 1.5/8192 special.

Metal's decode of RGB10A2Unorm_sRGB's colour (the rgb10a2-srgb-reads
recording, every code) lies up to 1.637 steps of 2^-13 from the exact
transfer (code 952: Metal 0.84912109, exact 0.84932096). That is the
1.64 the docs gave for R10Unorm_X6_sRGB only.

So artifact.rs's DevicePackConversion, the FAST-PATHS air.pack row and
API.md's catalogue entry now give, for those two formats only: a colour
code within two below 0.0031308, and a decoded colour within 1.64
steps. Doc text only: the device's conversion is unchanged (rule 1),
and so is behaviour. No version bump.

(cherry picked from commit 8bfaab43bd6c6368c41d58caa7e9c91fe64820d5)
(cherry picked from commit e728f0fa394c46c528d2f99df89a33751f5691d7)
2026-11-03 04:10:31 -08:00
Anees Iqbal e94d068b3b State the queue sharing row's measured rates over the 5080's spread
What: docs/FAST-PATHS.md's queue sharing row now gives each shape's measured range with its
run count, in place of the first three-run set's.

Why: two more sets on the RTX 5080 Laptop GPU (NVIDIA 615.71.09, release, one-draw command
buffers, each thread its own queue) widened the ranges:
- 2 threads with 3 in flight: Adaptive 27.0k to 46.5k a second in 13 runs after a hold's first.
  It fell within one hold, from 42.5k to 27.0k, while PerQueue stayed at 25.6k to 27.5k. Two
  more runs gave 15.4k and 17.7k; in both, one of the two queues was marked long as it began
  (gone long 2 or more, against 1 in every fast run). PerQueue: 25.2k to 27.7k in 14.
- 2 threads with 1 in flight: 16.9k to 20.7k against 10.1k to 11.5k (5 each).
- One thread over 16 queues in turn: 21.7k to 43.3k against 10.2k to 11.1k. Over 2,048:
  20.0k to 39.2k against 10.2k to 11.2k (4 each).
The 8-thread shapes keep their three-run ranges. One third of one hold, where both policies
fell to 8.1k to 13.0k, is left out. Under PerQueue the pair of VkQueues made no difference:
2 x 3 with the second queue 1, 7 or 13 places after the first ran 25.6k to 27.5k.

Verified: tests::fast_paths (19 passed).
(cherry picked from commit adb362078504cca24358e8d9c331eb1b831a2b57)
(cherry picked from commit 27999318cbb31bc8a46f24a28c40a6b80c7e2f4d)
2026-11-03 03:36:43 -08:00
Anees Iqbal 549609b26f device-color-conversion: state the measured unorm rounding at a tie
The note's doc said every Vulkan driver measured but MoltenVK rounds the
f32 product with ties to even and that Metal "rounds a half toward zero".
Neither fits an exact tie in an 8-bit unorm attachment: Metal stores 0x80
for 0.5 (127.5), and the RTX 5080 stores 0x7f, which ties to even would
not give. "A half" meant a half-float channel, which read as 0.5.

Measured over every 8-bit code's exact value and every tie with two f32
steps either side, BGRA8Unorm and RGBA8Unorm:
- Apple M3 Max, macOS 27.0.1, plain Metal (a probe of our own): all 1531
  inputs store the exact product rounded to nearest, the tie up; 128 of
  them differ from the f32 product rounded with ties to even. 0.5 -> 0x80,
  f32(1.5/255) -> 2, f32(2.5/255) -> 3.
- RTX 5080 Laptop GPU, NVIDIA 615.71.09, through the runtime (the
  color_writes lane's pipeline, plain draw and an indirect command
  buffer's draw of the same state): plain and ICB identical in every
  channel; every input on a tie or up to two f32 steps above one stores
  the lower code (0x7f, 1, 2 for the three above), every other input
  Metal's code; 638 of 1531 inputs differ from Metal.

The doc now says so (artifact.rs, the color_writes module, API.md's
catalogue entry), names the half-float channel plainly, and keeps the
ties-to-even claim for ANV, RADV and lavapipe only, as earlier
measured; the RTX 5080 is no longer among them.

The fragment stage records DeviceColorConversion on the 5080 for that
pipeline, plain and ICB alike (verified: both stages' notes printed, and
with device-color-conversion asked at every occurrence the plain draw and
the ICB's replayed draw each announced it once).

Docs and comments only.

(cherry picked from commit 5021f1c4ba7f29a6dc54f76f4d12402795af7162)
(cherry picked from commit e21d7c945b383ddfbfe54a8d82fc89342e6f7d13)
2026-11-03 03:23:03 -08:00
Anees Iqbal be47523f80 State queue sharing's residual stall and the unshared form for queues that must never wait
What: docs/FAST-PATHS.md's queue sharing row, docs/API.md's policy bullet and the runtime
README's new_command_queue_unshared entry now state the residual stall exactly: once per logical
queue that goes long, for a queue that joined its VkQueue during its short phase, about one long
command buffer's length. They also say a queue that must never wait (a compositor's) is made
with Device::new_command_queue_unshared. The row's cost column carries the measured rates.
The queue_share example's rates mode takes --threads, --in-flight and --one-vk-queue for one
shape. It prints each command buffer's GPU end and commit to its completed handler, the
submission, scheduler and wake counts per command buffer, and the busiest threads' CPU from
/proc (Linux).

Why: on the RTX 5080 Laptop GPU (NVIDIA 615.71.09, release, 3 runs a side), the trap and
slow-alternating shapes cost a shared compositor 64 completions over 10 ms, at most 29.4 to
30.6 ms, in every run, with one join each. That is the first long command buffer of the
application it joined during the application's short phase. PerQueue had none in 5 of those
6 runs and 4 in the sixth (at most 3.7 to 10.7 ms). An unshared compositor had none over 10 ms
in any run. No join rule built on what a queue has shown can avoid the first one: the long
command buffer gives no sign before it runs. A re-pick at submission would not either: the
compositor holds about 4 uncompleted command buffers at each commit (p50 commit to handler
0.78 to 0.87 ms at a 208 us period), and the stall is all or nothing in a queue's own order.
So the docs name the unshared form as the answer for such a queue.

The probe settled the 2 threads x 3 in flight drop (15.4k against 26.0k a second in one run):
it was the lock hold's warm-up. In the hold's first runs both policies ran slow (11.1k and
10.4k), and later runs gave Adaptive 46.5k and 39.7k against PerQueue's 25.2k and 26.5k. Two
queues on one forced VkQueue ran 38.1k to 46.6k under PerQueue and 41.4k to 49.9k pinned under
Adaptive, so one VkQueue is not slow in the runtime's path. No runtime thread was busy in the
slow runs (scheduler 10%, handler threads 5%, waiters 3%), and every shape made one
vkQueueSubmit per command buffer.

Verified: tests::fast_paths, degradation_catalogue and degradation_sites (25 passed); clippy of
the example with all features.

(cherry picked from commit b1dbea95dad3a5a156191df01084db0f86cb67a0)
(cherry picked from commit 24af60dbf8175da8e60ea24f38f9103c20c23e8b)
2026-11-03 02:49:35 -08:00
Anees Iqbal 510e0c0cca Share VkQueues between command queues where the GPU idles at each switch, with an unshared opt-out
What: a new DevicePolicy switch, queue_sharing: QueueSharingPolicy { Adaptive (default),
PerQueue }; exact_answers() selects PerQueue. Under Adaptive, on a device whose own self-check
finds its GPU idle when consecutive work comes from another VkQueue, a command queue chooses its
VkQueue again each time it makes a command buffer while it holds no other uncompleted one (the
slot take with held.all == 1, under its slots lock): it joins the busy VkQueue of its family
whose oldest batch has run under 0.5 ms, the most batches in flight first, then the latest
submission (Device::pick_vk_queue: one pass of atomics over the round robin's VkQueues, no lock).
A queue whose batch ran over 2 ms as its VkQueue's oldest is marked long by the waiter that saw
it complete, under the completion's pending lock, before the turn that finishes it
(command_buffer/completion.rs); no queue joins a long queue's VkQueue, and the long queue moves
once more at its next idle point, to the least recently used idle VkQueue no long or unshared
queue holds. Its mark moves with it and a dropped queue subtracts its marks. Presenting queues and
a queue that lent its VkQueue (with_vk_queue, pinned from then on) never move. A queue's vk_queue
is now an atomic; everything that reads it does so between a command buffer's make and its
completion, when no move can happen.

The self-check (queue_switch_check.rs) is the runtime's own, kept like the in-place check's, not
a DriverFact row: on a thread of its own, once per driver, release and runtime, 24 rounds of two
timestamp-only batches held behind one host-signalled gate on two same-family VkQueues against
24 on one; the switch cost is the difference of the median gaps; Idles above 20 us, DoesNotIdle
below, Unchecked where the device has no calibrated timestamps, no two VkQueues of one family, or
a run failed. Its verdict is written as one record in the shader cache's content directory and
read back as the next device of the same driver, release and runtime is made. Before the verdict,
every queue keeps the VkQueue it took at creation.

Device::new_command_queue_unshared(count): a queue that never moves and that no adaptive queue
joins; a queue already on its VkQueue leaves at its next idle point. Placement where the device
shares: a round-robin VkQueue no command queue holds, least recently used first; else one no
long or unshared queue holds, the fewest queues first; else the round robin's next. Why that
order: an empty VkQueue gives isolation at once, with no wait for another queue's idle point; of
the empty ones the least recently used is the one least likely to hold a moving queue's work in
flight (a queue that just left it may still have batches there, and the unshared queue would
wait behind those); where none is empty, the least held one has the fewest queues to move off,
each at its own next idle point, so isolation arrives soonest, and a VkQueue a long or unshared
queue holds is never taken since that would put the opt-out behind exactly the work it opts out
of. A queue's claim of a VkQueue and an unshared queue's are ordered so that two at once never
both succeed: each counts itself there first, then reads the other's count (SeqCst both sides).
Under PerQueue, and where the device does not share, it is
new_command_queue_with_max_command_buffer_count. A count of 0 and a lost device are refused.

Why: NVIDIA 615.71.09 on the RTX 5080 Laptop GPU leaves the GPU idle 56 to 62 us whenever its
next work comes from another VkQueue, so one VkQueue per command queue, round robin, capped eight
threads' one-draw command buffers at 25,800 to 29,500 a second (GPU idle 60% of its time at the
switches), where one VkQueue ran 54,700 to 58,700 (the audit that set this design). Moving only
at idle points keeps every queue's own order without a cross-queue fence. The cost is the
runtime Degradation kind QueueSharing ("queue-sharing", performance), announced once per device
at the first join, in CommandQueue::command_buffer on the making thread: the first long command
buffer of a queue that shared holds the command buffers committed behind it on its VkQueue for
its whole length. The opt-out exists so a compositor never pays even that one stall.

Counted: WorkCounts::queue_moves, queue_joins, queues_gone_long, long_queue_settles,
queue_moves_off_unshared, joins_withheld_from_unshared, queue_switch_checks_run and
queue_switch_checks_recalled. The policy keys no profile (tests::fast_paths), so
SEMANTICS_VERSION does not move. Docs: FAST-PATHS row, docs/API.md (the policy and the notice
catalogue), the runtime README (the opt-out, with_vk_queue's pin), queue.rs's module doc on
isolation; REFUSALS regenerated (the new site of MaxCommandBufferCount); api_surface and
api_signatures (additions only). The example queue_share runs the workloads under either policy.

Verified: cargo clippy --workspace --all-targets --all-features -D warnings, and the runtime and
validation crates with --cfg m2v_gpu; RUSTDOCFLAGS=-D warnings cargo doc --workspace
--all-features --no-deps; nextest of tests::queue_share (the choice, settling, the unshared order,
the record), tests::fast_paths, tests::degradation*, api_surface, work_counts: 66 passed. On the
RTX 5080 Laptop GPU (release) the check answered Idles at 51.3 us, and its form measured 49.0 to
50.7 us in five more runs, where a chained form measured 53.2 to 59.3 us. The device tests
(tests::queue_share_device, runtime_lane::command_queues::a_queue_joining_...) are not yet run
on a GPU in this commit.

(cherry picked from commit a2f17a5132faf0312fb3953d634e21c927cde62e)
(cherry picked from commit 862b2cb49a9481d0a2a19fb1bc3acec79932d1bd)
2026-11-03 02:49:35 -08:00
Anees Iqbal 888dbbbf2f Refuse each constants-block record outside the typed model by LLVM's name
What: `Feature::Constant { code: u32 }` becomes
`Feature::Constant { record: ConstantRecord }`, in the front end and the
translator, which re-exports the new `ConstantRecord`. ConstantRecord is
non-exhaustive, one variant per LLVM name:
- Select, ExtractElement, InsertElement, Compare;
- ShuffleVector (CE_SHUFFLEVEC and CE_SHUFVEC_EX);
- BlockAddress, UnaryOp, DsoLocalEquivalent, NoCfi, GepWithInrange;
- PtrAuth (PTRAUTH and PTRAUTH2), Byte (BYTE and WIDE_BYTE);
- PtrToAddr: a CE_CAST of `CAST_PTRTOADDR`.
Each record is matched from its code (`codes::cst_unsupported`). A code
LLVM does not define stays `UnknownRecord`.

A refusal now reads `Constant { record: Select }` where it read
`Constant { code: 13 }`. The names and codes come from
`LLVMBitCodes.h` of the local LLVM 21.1.8 and 23.1.4 toolchains
(`ConstantsCodes`, `CastOpcodes`).

WIDE_INTEGER stays malformed, on purpose, with a comment that says why.
LLVM writes it only for an integer wider than 64 bits. The type table
already refuses those types (`Feature::Type`). So a WIDE_INTEGER that
reaches the constants block has a type of at most 64 bits, which LLVM
never writes.

Why: a refusal should name what it refuses. The inline assembly record
(code 30) reached a consumer as a bare `Constant { code: 30 }`; it now
decodes, and this names the rest of the class.

Verified (debug):
- metal2vulkan-air suite passes, including `constant_errors_are_typed`:
  - each of the 15 refused codes yields its name;
  - CE_CAST opcode 13 yields PtrToAddr, opcode 14 is malformed;
  - WIDE_INTEGER of an i32 is malformed;
  - code 60 is UnknownRecord.
  At the base the test does not compile (no ConstantRecord), and the
  refusal there was the bare code.
- The translator's api_surface, api_signatures (blessed: the new enum,
  its variants, the changed variant) and refusal_surface tests pass.
- clippy -D warnings, workspace, all targets, plain and --cfg m2v_gpu.
- docs/REFUSALS.md regenerated (the row's doc text).

The census changes no outcome: no private-corpus row was refused with a
constants-block code at d3e66f9415 or after the bit-manipulation change
(nvidia-rtx5080-laptop and moltenvk-m3).

SEMANTICS_VERSION 1954 -> 1956 (a refusal's class changes): the lane's
value plus one after f19e887e4a takes 1955.

Golden tables: none move (no fixture holds such a record).

(cherry picked from commit 2af3e7891ee1ce7893107ff69f32ea879a06a56c)
(cherry picked from commit 94412279d2b277a2b9cfc11a83fc1e231ef91ecb)
(cherry picked from commit 3f5560c3fd7da0edab9a10d6b951986d8fcc6f80)
2026-11-03 02:25:30 -08:00
Anees Iqbal a1ee191fd1 Filter a 3D mipmap chain by compute where the driver's blits do not filter a volume
the_device_s_blit_chain_filters_each_level_and_is_announced failed on the
Apple M3 Max through MoltenVK 1.4.2 for its 3D textures only. Measured there:
vkCmdBlitImage with VK_FILTER_LINEAR from level 0 of an 8 x 8 x 4
R8G8B8A8_UNORM image into level 1 does not answer Vulkan's linear filter, the
average of the eight texels around each destination centre. Of the level's
128 bytes, 4 lie within a code of it, 67 within a code of source slice
2z + 1's four texels alone, and 2 of slice 2z's alone. 2D, 2D-array and cube
blits filter as Vulkan states. NVIDIA 615.71.09 on the RTX 5080 Laptop GPU
filters the same 3D image correctly, and the test passes there. So this is a
driver difference, and FAST-PATHS row 73's claim of the blit chain "where its
blits filter the format" did not hold for a volume on MoltenVK.

Following the runtime's driver-defect pattern:
- New RuntimeDriverDefect::VolumeBlitsUnfiltered, with Affected { MOLTENVK,
  clean: &[] } in driver_defects.rs, keyed by driver as the other defects are,
  never by the release. Its doc holds the measurement.
- `plan_mipmaps` takes the driver's defects. A 3D texture on such a driver
  takes the compute filter (MipmapPlan::Filter) where the filter computes the
  format. Elsewhere the blit chain stays, announced as before
  (device-filtered-mipmaps). Nothing is refused, and no note is added.
- blit_texture.rs passes the device's defects. The mipmap_plan unit tests pass
  them too.
- New unit test a_volume_takes_the_compute_filter_where_the_driver_s_blits_do_not_filter_it.
  It fails without the change.
- tests/driver_defects.rs lists the defect for MoltenVK.
- api_signatures.tsv has the new variant, and FAST-PATHS row 73 names the
  defect. REFUSALS.md regenerated with no change.
- mipmap_chains expects the compute filter for 3D textures where the device
  has the defect, each level still within a code of the filter. Its diagnostic
  print is removed.

Verified: cargo nextest run -p metal2vulkan-runtime for the mipmap_plan and
driver_defects tests passes, and the new test fails without the change. The
lane test's M3 rerun follows.

(cherry picked from commit a160bb01e43d7e5f4916b700012663a4020cf2a7)
(cherry picked from commit 7e77515beeb4d938a67de4b659ad31b8bed3394f)
2026-11-03 02:03:18 -08:00
Anees Iqbal 822263b1b7 Hold the precise trig at NaN operands to what its stage records
The owned fixture precise-trigonometric-functions-at-nan-operands-under-fast-math
calls precise sin, cos, tan and sincos in a fast-math entry. MoltenVK compiles
an entry in one math mode, so those precise calls take their fast forms. On
the Apple M3 Max through MoltenVK 1.4.2, sin, cos and sincos of a NaN answer 0
(and other words keep payloads such as ffc00000 or 7fc12345) where Metal
answers 7fc00000. The live stage already records
PrecisionNote::DeviceTranscendentals and NativeNanEncoding, and the runtime
announces both. Apple states no answer at a NaN operand under fast math. The
test, though, held every NaN word to Metal's canonical NaN on a profile with
MetalCanonicalNans.

What changed:
- owned_float_fixtures_answer_metal takes the case's notes. A NaN word's bits
  are the device's where the stage records NativeNanEncoding. A function's
  answer word (not the operand word, DFL_TRIG_OPERAND) may be a number where
  it records DeviceTranscendentals.
- Each note the answers needed must be recorded. Every recorded note must be
  announced, checked once over the test's notices, so a once-per-device
  announcement is not lost between cases.
- DeviceTranscendentals' doc (pipeline/artifact.rs) and its docs/API.md entry
  now say that a NaN operand may answer a number in such an entry.

No note is added: the stage recorded both before the change.

Verified: runtime_lane::driver_deviations::owned_float_fixtures_answer_metal
passes on the Apple M3 Max through MoltenVK 1.4.2 (--cfg m2v_gpu), together
with the next commit's minimum rows.

(cherry picked from commit 91f122b133c93af4b155a258d088e0001ff55a72)
(cherry picked from commit 54a9b15a1fe0a27e8bf9d2a3a236813b9c117347)
2026-11-03 02:03:16 -08:00
Anees Iqbal 78f6377e4a FAST-PATHS: an empty command buffer is not submitted, so drop its old commit-to-completion number
The commit-to-completion entry measured an empty command buffer against a bare barrier (51.6 µs
against 45.1 µs on a Radeon 780M). Empty command buffers make no vkQueueSubmit now; the submit
path's bench measured commit and wait at 2.6 µs on the RTX 5080 and 1.8 µs on the M3 (p50). The
timestamp cost on MoltenVK and its switch are unchanged.

(cherry picked from commit f7abac8bbb7971b7bb9fd2c8638af94d7f96f51e)
(cherry picked from commit bef265b91124cc376bbeda1fead475bd87ebf805)
2026-11-03 01:40:30 -08:00
Anees Iqbal 36f5029870 commit_and_submit: the committing thread submits for itself
A runtime extension. CommandBuffer::commit_and_submit commits as commit
does, with the same checks and refusals. Then, where no submission pass is
under way, the calling thread becomes the passer (Scheduler::
submit_at_commit, Inbox::pass_once_then). It takes in the inbox and submits
the ready heads committed first, in commit order, up to PASS_SUBMISSIONS,
while each needs no host step, no submission check, no group, no storage-
form switch and no rebind (plain_ready with Passer::Committing:
submits_without_the_program's handler exclusion dropped, the rest kept).

Still counted as the passer and outside the state lock, it runs their
submission handlers, then lets go of what the pass held; a last reference
goes through let_go_elsewhere. It then counts out, wakes the scheduler's
thread where it left work or a commit was handed to it meanwhile, and makes
an owed completion turn. The commit is posted with no mark and no wake
(Inbox::post_quietly, Hand::Pass), so the scheduler's thread is not woken
for work the committer takes. A plain transition to Scheduled runs inline
as its batch is published; one with scheduled or submission handlers goes
to its queue's context as before. Called from the runtime's own threads (a
handler on the scheduler's thread or a waiter) it commits as commit does.
Plain commit is unchanged: Metal's commit returns before scheduling.

Submission handlers keep submission order whichever thread runs them.
Each pass that takes batches with submission handlers takes a ticket
under the scheduler's lock, in pass order (State::handler_ticket), and
runs them once every earlier ticket's ran (Turns). This departs from
the design's "handlers then count out": the scheduler's own pass counts
out before running its handlers, so a counted committer alone cannot
keep them in order. The new order test showed it: without the turns its
handlers ran out of commit order in 4 runs of 4.

Counted: WorkCounts::scheduler_passes_at_commit,
batches_submitted_at_commit (the conformance cost's scheduler_ and
batches_ prefixes already cover them). Docs: the method, the scheduler
and inbox module docs, add_submission_handler's thread bullet, the
runtime README's extensions, RUNTIME-PORTING, and FAST-PATHS's "commit
returns at once". api_signatures blessed (3 added); REFUSALS regenerated,
unchanged.

Verified on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu:
- tests::commit_and_submit, 6 runs:
  - the submission handler ran on the caller inside the call, reading
    Committed, 40 of 40, with the scheduled handler on a handler thread;
  - 1000 command buffers from 2 threads alternating commit and
    commit_and_submit: handlers in commit order, 362 to 449 of them on a
    committing thread;
  - a checked head and the one behind it were left to the scheduler's
    thread, with 0 batches at commit.
- Negative control: Turns::wait made to return at once failed the order
  test 4 of 4 (e.g. 238, 239, 240, 255, 256, 241).
- The runtime suite: 1512 passed.
- clippy -D warnings with and without --cfg m2v_gpu, and rustdoc
  -D warnings, clean.

RUNTIME_VERSION and the runtime-sources pin follow at hand-over, on the
lane tip.

(cherry picked from commit 5909e96c63004822e2a22d4cbf27b998f90e75a8)
(cherry picked from commit 40a67ba10398c38f13494fcdf3f64c2925f7eba8)
(cherry picked from commit 4270a52b85cfcd8c5a3cd8ea201b1a731a261eac)
2026-11-03 01:40:28 -08:00
Anees Iqbal 1e44dcf8da Drop the call of MSL's empty inline assembly at decode: asm sideeffect "", "" of void ()
What: decode drops a call whose callee is the inline assembly expression `asm sideeffect "",
""` at the call type `void ()`, the way it drops the markers: the call takes a record number
but no instruction. The match is structural and exact:
- the call type is `void ()`, not vararg, with no arguments;
- the template and the constraint string are empty (no operand, result or clobber);
- `sideeffect` is the only flag (no alignstack, inteldialect or unwind).
Any other inline assembly stays an indirect call through its constant. post_check refuses it
as InlineAsm by name where an entry reaches it.

Why: MSL accepts exactly one asm statement, an empty `asm("")` / `asm volatile("")`. A
template, an operand or a clobber is "illegal asm statement" (Metal 32023.922). That statement
always compiles to this call, attributes {convergent nounwind}. It assembles to no
instruction and names nothing it reads or writes. Its `sideeffect` only constrains Metal's
optimizers: they may not remove it or move a memory access across it, and a loop holding it
is kept. A shader generator writes it into loop bodies for that reason. No value a race-free
program computes depends on it. The decode-only refusal of the previous commit still ended
the consumer's VM, so the drop is what fixes their S1. Refusing it would refuse every
pipeline whose generator writes it.

The edge, documented in docs/API.md's accepted differences ("Inline assembly"): a racy spin
loop over plain (non-atomic) memory could tell the barrier is gone, and MSL's memory model
leaves that loop undefined. A loop with a visible effect runs every iteration either way.
The drop records no note and no degrade: it is no precision difference, no value changes.

Fixture: engine/kernel_inline_asm's asm_in_loop now stores every partial sum, the final sum
and its iteration count. The trip count comes from a buffer. All three entries translate.
REFUSALS.md is regenerated: InlineAsm's doc and its reach mark, now `none`, since only
hand-written AIR can hold another asm.

Verified (M3, macOS 27):
- engine_inline_asm, through both llvm-as and xcrun metal-as:
  - asm_in_loop, asm_in_helper and asm_free translate, link and validate on all 19 committed
    profiles;
  - asm_in_loop on the CPU interpreter with n = 6 over 4 threads writes every expected word
    in both scheduling orders: every iteration stored;
  - synthetic modules with "nop", "~{memory}", an "=r" result, no sideeffect, and alignstack
    each refuse as InlineAsm naming the expression; the empty one translates.
- Negative control: with the drop disabled, all three engine tests fail.
- metal2vulkan-air suite: 492 pass.
- metal2vulkan: the air_input, air_canon and air_abi sweeps and the api surface and
  signatures checks pass. The text-shape sweep discounts the dropped call, as it does the
  markers.
- clippy -D warnings in both configurations.
- Golden printout of kernel_inline_asm re-blessed: only that file.

Still owed a bless on development, new rows only:
- golden_hashes.tsv: the fixture's cells, all new;
- public_fixture_expectations_engine.tsv: 2 fixtures.
SEMANTICS_VERSION stays 1950, landing together with the previous commit.

(cherry picked from commit 53c6faaf4d2215fc3e629b39803f47979d71f765)
(cherry picked from commit f9361582833d1f5ca0c151d42d68e3cfa7e228af)
2026-11-03 01:11:49 -08:00
Anees Iqbal 6e67fd2a08 Decode inline assembly constants; refuse a reached call of one as InlineAsm
What: the bitcode reader now decodes CONSTANTS_BLOCK record 30 (INLINEASM, LLVM 13+, which
names its function type) and the older spellings 18, 23 and 28 (typed by their pointer's
pointee) into a new constant, Const::InlineAsm, which keeps the template, the constraint
string and the four flags as written. A call through it stays Callee::Indirect. Canon's
post_check refuses such a call that an entry reaches as Unsupported(InlineAsm), not
implemented, naming the expression (`asm sideeffect "", ""`). An entry that reaches none
translates, even when other functions of its module call assembly.
- The verifier holds the constant to LLVM's rules: a `ptr` in address space 0, never another
  constant's operand or a global's initializer, and only ever a call's callee.
- A record that does not fit its spelling is MalformedRecord: an undefined flag bit, a
  function type that is none, a string past the record, a byte above 255, a trailing operand,
  or an old spelling over an opaque pointer.
- Feature::InlineAsm is new in both crates (REFUSALS.md regenerated, reach mark `app`).
- The validation AIR writer spells the constant back.
- The constant interner charges the strings to the ledger.

Why: the consumer's sweep refused a whole render pipeline as `Constant { code: 30 }` (a
WebGPU deferred-rendering page in Safari), so the pass drew nothing. The record was refused
as it was read, so every entry of the module was lost, whether or not it called the assembly.
MSL accepts exactly one asm statement: an empty template with no operands and no clobbers.
`asm("nop")`, `asm volatile("" ::: "memory")` and `asm volatile("" : "+r"(x))` are all
"illegal asm statement" (Metal 32023.922). It always compiles to `call void asm sideeffect
"", ""()`, attributes `convergent nounwind`.

Fixture: engine/kernel_inline_asm, our own MSL, holds three entries.
- asm_in_loop: the statement in a loop body.
- asm_in_helper: the statement in a noinline helper.
- asm_free: no assembly of its own.
Its .ll and .air.ll are from scripts/regen-air-fixtures (LLVM 21), and its golden printout
is blessed (tests/air_input/kernel_inline_asm.txt, only that file changed).

Verified (M3, macOS 27):
- New reader tests: every spelling decodes, every malformed form is typed, and an aggregate
  holding the asm fails verification.
- New engine tests, through both llvm-as and xcrun metal-as: asm_free translates, links and
  validates on all 19 committed profiles; asm_in_loop and asm_in_helper refuse as InlineAsm by
  name.
- Negative control: with record 30 refused as before, all four tests fail.
- metal2vulkan-air suite: 492 tests pass.
- metal2vulkan: the air_input, air_canon and air_abi sweeps and the api surface and
  signatures checks pass.
- metal2vulkan-validation fixture, writer and audit tests: 74 pass.
- clippy -D warnings in both configurations, plain and --cfg m2v_gpu.

Tables owed a bless on development, new rows only:
- golden_hashes.tsv: 114 new cells, 3 entries x 19 profiles x 2 spellings.
- public_fixture_expectations_engine.tsv: 2 new fixtures.

SEMANTICS_VERSION 1950: refusals change class (Constant -> InlineAsm, or a translation).
api_signatures.tsv is blessed: additive (the InlineAsm struct and variants). A consumer that
matches Const or Feature exhaustively must add the new variants.

On the lane: SEMANTICS_VERSION is 1953 here, after the specialization folding's 1952.
(cherry picked from commit 8b418fbd6c)
(cherry picked from commit c8a7e910204a6cedad2b257a10cb095d83c213e3)
2026-11-03 01:11:48 -08:00