Commit Graph
1530 Commits
Author SHA1 Message Date
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 31812ade8d Pin the runtime sources after the in-place single-pass merge, the ICB resident-list and inline-record reads, the argument table's held retain and the plain event's Vulkan signal
Re-hashes crates/metal2vulkan-validation/runtime-sources.sha256 for 55c7f307a9, 8cccce3ee7,
327cb5f383, feaa100732, ac5104bcb9 and 9dcd1b72f9. RUNTIME_VERSION stays at 1760: this stack
has not landed, so 1760 covers it. Checked: api-signatures --check and refusal-surface --check pass.

(cherry picked from commit b95d10cc1b74b6e5f67297d08c430b61213f5e8a)
2026-11-03 15:58:55 -08:00
Anees Iqbal eab1643a89 Test a plain event's reserved Vulkan signal chaining on the VkQueue
What: tests/event_vk_signal.rs, device tests (`--cfg m2v_gpu`/`m2v_cpu_icd`) that run one
scenario on each kind of event. A command buffer on one command queue waits for value 10
before anything reaches it. The test reserves a signal of 10 (`reserve_vk_signal`,
counter 1, after nothing), and a second command buffer on another command queue waits for
10. A raw submission on the device's extra compute queue then fills a buffer of the
test's own and signals the counter. Both command buffers copy that buffer and must read
the fill. The watcher must then report the value reached (`vk_wait` -> `Reached`).
Sixteen timed rounds follow (reserve, commit a waiter, signal) and print the time from
the raw `vkQueueSubmit` to the waiter's completed handler. video_interop.rs's device,
raw queue, raw submission and caller buffer helpers become `pub(super)` for it, and
`submit_raw` returns when it submitted.

- plain `Event`: both command buffers read `Scheduled` before the raw signal is
  submitted, so their waits were handed to the `VkQueue`. Neither completes in 300 ms
  without the signal, and `WorkCounts::shared_event_waits_held` does not move (0, also
  over the timed rounds).
- `SharedEvent`: both stay `Committed` until the signal (held on the host, as today),
  and `shared_event_waits_held` counts them (18 over the run).

A device with no extra queue runs neither test: the plain event's contract keeps the
caller's signal off a `VkQueue` its waiters are ahead of.

Verified on the M3 Max (MoltenVK), each run through maclock and memcap 12288:
- the two new tests, the runtime's event, interop, reserved-queue and semaphore tests
  (45), and the validation lane's runtime_lane::events, event_round_trips and
  command_queues (25): 70 passed. The lane's submit_costs is an ignored measurement, and
  submit_per_import is Linux-only.
- Negative control: `Device::new_event` built its timeline settable (the host-held path).
  The plain test failed with "a plain event's wait was held: [Committed, Committed]",
  while the shared test passed. Restored and touched.
- Latency, release with debug assertions on (`CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS`,
  because `cargo check --release --tests --cfg m2v_gpu` fails without them on the base
  in tests/draw_again.rs), 3 x 16 rounds: plain median 597-602 us, shared 355-363 us.
  So on MoltenVK the VkQueue-chained wait releases later than the host hold. The 5080
  was not measured.

(cherry picked from commit a25c1a5ade4df5ada1a7c303e980302e62611779)
(cherry picked from commit 9dcd1b72f92b0e7800596beede2877e8b37f87e3)
2026-11-03 15:58:55 -08:00
Anees Iqbal 9b08c12036 Give a plain event the Vulkan signal hooks a shared event has
What: `Event::vk_semaphore`, `Event::vk_wait` and `unsafe Event::reserve_vk_signal`, the
interop hooks `SharedEvent` already had. Both kinds now go through one implementation in
interop.rs (the event's timeline semaphore, `EventTimeline::landing`, and
`EventShared::reserve_signal`). Each new item's doc says it has no Metal counterpart and
what it refuses: `reserve_vk_signal` refuses `DeviceLost` and `OutOfMemory(Host)`, as the
shared event's does; the other two refuse nothing.

Why: reims-vgpu signals a session event from its own Vulkan video decode submission, and
used `SharedEvent` only because it was the one type with these hooks. The host may set a
shared event's value, so a command buffer's wait for a reserved signal of one is held on
the host until the device's watcher sees the signal land (`shared_event_waits_held`).
They measured that at 130-340 us p50 per decode on an RTX 5080. A plain event
(`MTLEvent`) has no host set, so its timeline is not settable and `EventTimeline::wait`
answers the reserved index: the scheduler hands the wait to the `VkQueue` at once, before
the caller's signal is submitted if it comes later. Timeline semaphores allow a wait
before its signal (Vulkan's queue forward progress). No scheduler change was needed.

The host-signal fallback for a failed submission (`vkSignalSemaphore` to the counter)
moves the semaphore itself. So it releases the waits chained on the `VkQueue`s just as the
submission's signal would. It is not a Metal host set: `EventTimeline::set` is reached
only from `SharedEvent::set_signaled_value` and `encode_signal_event_scheduled`, which
takes a `SharedEvent`. A plain event therefore stays unsettable. The plain event's
`# Safety` adds that the caller's signal must not wait for a command buffer that waits
for it, neither for its completion nor behind it on the same `VkQueue`, since such a
wait may be submitted before the signal.

Docs: interop.rs, event.rs and event_timeline.rs module docs, the runtime README's
interop list, and `DeviceOptions::extra_queues`/`reserved_queues`. The API signature
table is re-blessed with the three new methods (`--check` passes). No public type or
refusal is new, and docs/REFUSALS.md regenerates unchanged.

Verified: the device tests of the next commit on the M3 (MoltenVK). With fmt, clippy
--workspace --all-targets --all-features -D warnings, plain and with --cfg m2v_gpu,
rustdoc -D warnings for the runtime, and `cargo check -p metal2vulkan-runtime` with no
feature.

(cherry picked from commit df62d9e4801d0bb27a8692f6e352a187745a11b6)
(cherry picked from commit ac5104bcb959d3d41485d4dd4b3e0cd98c662e2f)
2026-11-03 15:58:55 -08:00
Anees Iqbal aa45239a83 Retain an argument table into its encoder without looking at it where every object bound since was held
What: a draw's retain of a stage's argument table (`ArgumentTable::retain`,
`retain_exclusive`) walked every object the table binds whenever any call
had changed it since the encoder last retained it, which a draw after a
`setVertexBufferOffset:` or a rebind of an already-used buffer always has.
Each setter now notes, as it binds an object, whether the encoder holds it
already (`HeldBy::is`, from an earlier retain of one of its tables) and
whether the table was last retained into that encoder
(`ArgumentTable::note_bound`, `RetainedBy::unheld`). A retain of a table that
encoder retained last, whose every call since bound only objects it held,
looks at nothing: the encoder holds every object the table binds, each until
its command buffer completes, and keeps its key. Any other retain (an object
bound that the encoder did not hold, a table another encoder retained last,
a table's copy, which starts unheld) walks every object as before.

Why: `retain_into` was 7.1% (draws.10k) and 5.1% (WS-like) of the encoding
thread's samples in the Time Profiler, the walk over the (Buffer, u64) and
Texture maps repeated at every draw though it took nothing.

Checks: in builds with debug assertions the table keeps the HeldBy addresses
of what its last retain held and of every object bound since while held, and
the skipped retain asserts every object it binds is among them
(`RetainedBy::check_held`). `WorkCounts::argument_tables_held_at_bind`
counts the skipped retains (a new public field; api_signatures blessed).
encoder_holds' rebound leg draws a third time after binding the no-copy
buffer again and asserts exactly one such retain there, none in the other
legs, and that the retains still took (1 table, 1 object).

Verified on the M3 Max (MoltenVK 1.4.2), debug, --cfg m2v_gpu, under
maclock and memcap: the runtime's argument_table, encoder_holds, blit_holds,
draw_again, retained, shared_draw_locks, argument_buffers, argument_encoder,
rebind_*, pending_rebind, descriptor_key_at_draw, resident_uses,
no_copy_lies, draw_shape_notices and direct_arguments tests, 66 of 66, and
the validation lanes draw_*, render_arguments, rebind*, argument_*,
frame_costs, resident_draws, handed_objects, inline_bytes, keep_alives,
used_resources, renders, view_base_offsets, function_tables,
wrapped_buffers, host_memory and guest_frame_costs, 148 of 148. (One
earlier run failed draw_again's two rebind tests with begin_command_buffer
counted 1 against 0 between their runs; both passed in the rerun.)
Negative controls, each failing the encoder_holds rebound leg: the note
dropped from set_buffer_with_stride panics in check_held; the skip turned
off fails the held-at-bind count (0 against 1). clippy plain and with
--cfg m2v_gpu, and cargo check --release --tests with m2v_gpu, clean.

Per draw on the encoding thread (thread_selfcounts), release with thin LTO,
3 interleaved rounds against the parent build, medians:
  draws.10k  11465.9 -> 11216.4 instructions (-249.5, -2.2%)
  WS-like    23655.8 -> 23123.4 instructions (-532.4, -2.3%)
(ns not quoted: the host was loaded through the rounds, 600 to 1400 ns
both sides.)

(cherry picked from commit 868046533e2930dbf189ddb3d93dd87c0e6cbe40)
(cherry picked from commit feaa100732a409e7078d1c86f41728e3a9d14967)
2026-11-03 15:58:55 -08:00
Anees Iqbal 27f052e7ec Read an inline ICB execution's records a chunk at a time, each run collected once
An execution of commands the CPU re-encoded before it is a first execution, which records
inline. A consumer that sets every command again before each execution has only those. Before,
such an execution read its whole range's records at commit before it recorded any:
IndirectCommandBuffer::read_records collected them into a Vec grown by doubling, named_records
zipped them with their states into a second, and Execute::commands and RenderExecution::commands
wrapped each in Some into a third. A CommandRecord holds 4 stages of 32 buffer bindings, about
3 KB, so 16384 commands are some 50 MB a copy, out of the cache by the time they are recorded.
On the RTX 5080 laptop, compute n=16384 all re-encoded committed in 64.8 and 67.7 ms with
a54756c6a4 against 48.6 and 47.8 ms for its parent, which recorded each 256-command chunk apart
in a kept context.

Now:
- kept_commands::pieces gives the runs of an inline range an execution reads and records in
  turn: its chunks of 256, or the range whole where every command must be seen before any is
  recorded (the caller's check where it may see something, and the command buffer's
  executed-commands handlers, which hear of the execution once) and for the host step, which
  reads the records as the GPU and the CPU left them.
- Execute::record and RenderExecution::record read a piece, announce the commands of it that
  run otherwise than Metal's may, call the check, report to the handlers and record it, before
  they read the next. The host step's read is written_commands, as before. A kept render
  execution's rest of the range, after a chunk that is not plain, reads a chunk at a time too.
- read_records makes its lists at their length and takes each record as its caller holds it;
  named_records names the states in place in the list it returns, and the commit path records
  from that list, with no Option a command.
- WorkCounts::indirect_record_runs_read counts the runs of records read at once
  (api_signatures.tsv).
- Degradation::ReleasedCommandState is announced once a piece, as a kept execution announces it
  once a chunk.
- Docs: the "When." bullets of indirect_execute.rs and render/executions.rs, and pieces' own.

Tests:
- kept_commands::tests::pieces_are_the_chunks_or_the_range_whole.
- runtime_lane::kept_commands::an_inline_execution_reads_its_records_a_chunk_at_a_time (render,
  600 commands, [records read, runs read]): the first execution [600, 3]; with a check that sees
  (draws of points) [600, 1], the check called with 600 commands.
- an_inline_compute_execution_reads_its_records_a_chunk_at_a_time: [600, 3]; with an
  executed-commands handler [600, 1], the handler hearing once of commands 0 to 599.

Verified:
- On the M3 Max, debug (--cfg m2v_gpu), nextest -j 8 over every runtime_lane module that
  executes an indirect command buffer: 39 modules, 477 tests, all pass.
- Negative control, debug (pieces gives every range whole): both new lane tests fail at "the
  first execution, a chunk at a time" ([600, 1] where [600, 3] is expected).
- metal2vulkan-runtime kept_commands::tests 3/3; fmt --check; clippy -D warnings (runtime and
  validation, all targets and features, m2v_gpu).
- M3 Max, release, Time Profiler of execution_costs compute n=16384 all re-encoded, 2 untimed
  and 20 timed executions, inclusive CPU, lane 7583fe5d99 (keeps from the first execution) /
  d75cb04ac8 (before) / this change: CommandBuffer::commit 1077 / 1186 / 928 ms (49.0 / 53.9 /
  42.2 ms an execution), IndirectCommandBuffer::records 274 / 336 / 142 ms, memmove 213 / 297 /
  117 ms. execution_costs on this loaded host, commit medians of two rounds: compute n=16384
  all re-encoded 47.65, 47.00 / 52.93, 57.44 / 44.32, 42.98 ms; compute n=1024 all re-encoded
  8.34, 3.48 / 3.05, 3.95 / 3.82, 3.26 ms; render n=1024 all re-encoded 2.31, 6.59 / 2.49,
  2.97 / 2.07, 2.19 ms. The M3's render n=16384 all re-encoded row is load-dominated (ranges
  reaching 77, 97 and 156 ms), so the 5080's below is that row's evidence.
- RTX 5080 laptop (NVIDIA), release, execution_costs compute and render, 2c542021bf (parent),
  a54756c6a4 (before) and a54756c6a4 with this change's runtime part, interleaved, commit
  medians of two rounds: compute n=16384 all re-encoded 47.01, 46.41 / 63.07, 61.83 / 44.24,
  43.79 ms; render n=16384 all re-encoded 39.96, 39.38 / 56.40, 56.27 / 36.88, 36.89 ms;
  compute n=1024 all re-encoded 2.86, 2.82 / 3.15, 3.10 / 2.66, 2.70 ms; render n=1024 all
  re-encoded 2.40, 2.46 / 2.52, 2.47 / 2.23, 2.23 ms; the one re-encoded and unchanged rows
  within 0.1 ms of each other but one 0.97 ms reading of this change's compute n=1024 one
  re-encoded (its range 0.68 to 0.97, the other round 0.73).

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

(cherry picked from commit 678b2925c08269249a1aad3ef3d126d94bbf460a)
(cherry picked from commit 327cb5f3837ae38e055a4273e5254987601e43cf)
2026-11-03 15:58:55 -08:00
Anees Iqbal d9490a1a10 Compare an ICB execution's resident list with its kept chunks' once, then by pointer
Before, an execution that may keep its commands compared the resources its encoders made
resident with each kept chunk's, whole, at every chunk: RenderKey and ComputeKey held the
(Vec<UsedResource>, Vec<ResourceKey>) of Residency::kept_key, and KeptChunk::runs_again compared
the slices for each chunk, and each chunk recorded to keep cloned the lists. With one resource
made resident a draw, as a consumer's slot-own shape does, both grow with the draw count, so an
execution of N commands cost about N * N / 256 element comparisons.

Now the list is an Arc-shared ResidentKey, one an execution, which the chunks it records share.
Its PartialEq compares by pointer first. ResidentMet compares the execution's own list with each
distinct list among the kept chunks it meets once, whole, and remembers the answer; where they
are equal the execution's key takes the kept chunk's Arc, so its later chunks compare by pointer
and the chunks it records to keep share that list.

- kept_commands.rs: ResidentKey, ResidentMet, KeptChunk::key; the module docs.
- render/executions/kept.rs and indirect_execute/kept.rs: RenderKey and ComputeKey hold a
  ResidentKey, and record_kept asks ResidentMet::same before runs_again; their "The key" docs.
- WorkCounts::kept_resident_keys_compared counts the whole comparisons (api_signatures.tsv).
- runtime_lane::resident_draws: each_path_draws_what_the_encoder_draws runs three frames a path,
  so its third execution runs kept chunks (before, each path ran one frame, its first execution,
  which keeps nothing), and assert_bounded holds the whole comparisons to one a frame.

Tests (runtime_lane::kept_commands, [chunks run kept, whole comparisons]):
- an_execution_compares_its_resident_resources_once (render, 600 commands): [0, 0], [0, 0],
  then [3, 1]; two executions in one pass [6, 2]; after a write to chunk 1, [2, 1], [2, 1] (the
  chunk recorded to keep again under the list met), then [3, 1].
- a_compute_execution_compares_its_resident_resources_once: [0, 0], [0, 0], [3, 1], [3, 1].

Verified on the M3 Max:
- Debug (--cfg m2v_gpu), nextest -j 8 over every runtime_lane module that executes an indirect
  command buffer: 39 modules, 475 tests, all pass.
- Negative control, debug (ResidentMet::same compares whole at every chunk): both new tests fail
  with [3, 3] where [3, 1] is expected. Run before resident_draws' check took three frames; that
  check's bound is expected to catch it too (not run).
- fmt --check; clippy -D warnings (runtime and validation, all targets and features, m2v_gpu).
- Time Profiler, release, resident_draws "slot own read" at N 5000 (18 chunks kept a frame), 40
  timed frames after one to warm, before (d75cb04ac8) and after, inclusive CPU over the run:
  <[UsedResource] as PartialEq> 51 to 1 ms, KeptChunk::runs_again 85 to 23 ms,
  RenderExecution::record_kept 156 to 93 ms, ResidentMet::same 1 ms, and the test thread's
  Draws::frame 280 to 214 ms.
- resident_draws slot own at N 2000 and 5000, release, interleaved before after before after:
  wall times on this loaded host move by up to 3x between runs of the same build (the untouched
  encoder path read 6.4 and 17.1 ms at N 2000), so they decide nothing. Each read frame ran 7 and
  18 chunks kept at N 2000 and 5000 in both builds.

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

(cherry picked from commit 4a9ea522ae6786900a0e4ee0e476fe5178962980)
(cherry picked from commit 8cccce3ee7e039761610f5241ead70231aa3a657)
2026-11-03 15:58:54 -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 965d002a37 Pin the runtime sources after the twin shadows' copy-back and the dropped command buffer case
Re-hashed; the twin shadows' copy-back fix (5d3ee8792e) changes what runs record
and rides this stack's RUNTIME_VERSION 1760.

(cherry picked from commit 36c3063e1654fcfb824ff48fafc3691e38b4e934)
2026-11-03 15:58:54 -08:00
Anees Iqbal e068edfdde Pin that a dropped, uncommitted command buffer touches no host memory once dropped
What: runtime_lane::dropped_uncommitted. A pass of two draws of the owned ob3_index_buffer
fixture (a vertex function, rasterization disabled, that marks seen[min(vertex_id, 7)]) writes a
no-copy buffer over a second mapping of a page of guest RAM (a shared memory object, as
runtime_lane::host_memory maps it; GuestRam is now visible to the lane's modules). The state's
creation predicts a point list, so the line's and the triangle's draws each hand their own
pipeline's making to the device's pool: the test asserts both went to the pool
(pipelines_pooled +2, from an idle pool) and that the pool was still busy as the encoding ended,
so the pass was left pending (Deferred::RenderPass, making()). The command buffer is dropped
uncommitted, the buffer let go of, and the page unmapped in place at once (replaced by a
PROT_NONE mapping, so a CPU access faults). After the makings finish (pipelines_settled), a
command buffer committed on the same queue draws with the pipelines now made through a no-copy
buffer over the next page, and completes without error. The dropped page keeps every byte, the
next page holds exactly the eight marks, a third page is untouched, and the validation layer
reports nothing (host_memory::on_device).

Why: the consumer now relies on this contract to unmap a guest task's pages as soon as its
objects go: an uncommitted command buffer's deferred work, a pipeline-pending draw among it,
never reaches the scheduler, which takes committed batches only and hands a host step over only
for a committed line's head (gate_heads).

Verified on the M3 Max (MoltenVK, --cfg m2v_gpu, debug, under maclock and memcap): the case
passed 8 of 8 runs, the pending assertion included; the host_memory lane (25 cases) passed beside
it, 3 of 3. Negative control: committing the command buffer before its drop (the deferred work
reaching the scheduler) fails the case, "the dropped command buffer's draws reached the guest
page": on this GPU a write through the no-copy buffer lands in the shared object's page even
after the CPU's view of it is unmapped, which is what the guest RAM check reads. Restored and
touched. A hook that hands an uncommitted buffer's step over from inside the runtime is not
practical for this lane: validation reaches the runtime only through its public API, so it would
be a hidden public entry point in a published crate for one test. clippy --workspace
--all-targets --all-features -D warnings, plain and with --cfg m2v_gpu: clean.

(cherry picked from commit a35b1b6a2ecbb449b6562bb2678f2d62e2997ce9)
(cherry picked from commit 3f7ac2c41f47f76219c4407f530532a60cc5cea8)
2026-11-03 15:58:54 -08:00
Anees Iqbal dd986f0aae Drop a carried shadow's image when another shadow over its bytes writes them back
What: ShadowSync::copy_back, which records a copy back or a merge of one shadowed texture's
writes into its truth, now also drops from the encoder's carry (ShadowCarry) every carried image
of another texture that shares that truth. The dropped texture copies in again at its next use.
The doc of copy_back and ShadowCarry's list of what ends a carry say so.

Why: copy_back already left every other texture over the bytes that the encoder had met no
longer current (or stale inside the written rectangle). An image the command buffer carried from
an earlier encoder, for a texture this encoder never met, stayed carried: the shadow copies are
recorded through EncoderCore::shadow_command, which never reaches ShadowSync::wrote. So the next
pass over that texture rendered over texels the bytes no longer held, and wrote the result back.
This breaks the module's copy-in rule, under which a texture copies in again after another
shadowed texture over its bytes wrote them. The fix is structural: whatever writes a truth
through one shadow ends the carry of every other shadow over that truth, whether merged back or
copied back.

Verified on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu, under maclock and memcap:
- tests::shadow_twins: both cases pass. They failed on the commit before, which is the negative
  control (3,927 and 5,318 bytes differed). With the fix, every pass after a pass over the other
  texture copies in again: 76,800 texels copied in, none taken from the carry.
- The unit case in a_carried_surface_is_dropped_by_anything_that_lets_another_writer_in passes;
  before the fix it fails.
- The runtime's shadow, merge_scratch, linear_runs, dirty_pages, blit_cover, cpu_copy_layouts,
  fresh_pages, copied_log, in_place and linear_plan tests: 123 of 123 passed.
- Validation runtime_lane shadow, padded and linear: 91 of 91 passed.
clippy --all-targets --all-features -D warnings passed plain and with --cfg m2v_gpu, and cargo
fmt was run. RUNTIME_VERSION and the runtime-sources pin are unchanged.

(cherry picked from commit 73b62e05fd00b75b5ef1ff74952307fc68020197)
(cherry picked from commit 5d3ee8792e7a7f65985cf806de1e829e11b6e8c5)
2026-11-03 15:58:54 -08:00
Anees Iqbal 9b83a62a41 Test two shadowed textures over one buffer's bytes, each carried past a pass over the other
What: a device test, tests::shadow_twins, with two cases:
- a_merge_leaves_its_twins_carried_image_to_copy_in_again: host pages, merged back;
- a_copy_back_leaves_its_twins_carried_image_to_copy_in_again: a Private buffer, copied back.
Each case makes two RGBA8Unorm textures, A and B, of 200x96 texels over the same bytes of one
buffer, rows 1024 bytes apart. One command buffer alternates passes over them, each loading and
storing its texture and blending a rectangle that overlaps the one before, with blits reading
one texture's texels. The same steps over one private texture of the same first texels are the
reference: every read and the texels left must match byte for byte, and the bytes between the
rows must keep theirs. A case is also added to the shadow state machine's unit test
a_carried_surface_is_dropped_by_anything_that_lets_another_writer_in: an encoder that writes
through a twin and never meets the carried texture must leave that texture to copy in again.

Why: the module's copy-in rule says a texture copies in again after another shadowed texture
over the same bytes wrote them. The carry across encoders (ShadowCarry) does not follow it. A
pass over A copies back or merges as its encoder ends, which writes the bytes, but B's image,
carried from an earlier encoder, stays carried. The next pass over B then renders over texels
the bytes no longer hold, and its merge or copy back writes the result.

Verified, on this commit's runtime (7583fe5d99, development 7626ab77fa), both fail. They are the
negative control for the fix that follows:
- On the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu, under maclock and memcap: the read of A after
  the second pass over B differs from the private texture's in 3,927 bytes over host pages and
  in 5,318 bytes over the Private buffer.
- The unit case: the carried texture copied in 16,588,800 texels where 24,883,200 were expected,
  as its image was taken from the carry after the twin's merge.

(cherry picked from commit e6135c3250269277856d6fab2b23b3c3821a6194)
(cherry picked from commit 72da0c7468c89b49a56e08a4a2d29a5f35fa47bd)
2026-11-03 15:58:53 -08:00
Anees Iqbal f32168731d Pin the runtime sources after shadowed-texture pass runs and kept resident uses
Re-hashed with the runtime sources at RUNTIME_VERSION 1760.

(cherry picked from commit a3b2691758c379468f3613147d2e393b85837181)
2026-11-03 15:58:53 -08:00
Anees Iqbal b840a64a3d Bump RUNTIME_VERSION to 1760: shadowed-texture pass runs, kept resident uses
Consecutive passes over one shadowed texture copy in, keep and merge once per
run (99949a4cd0), and a draw keeps its uses of what its encoder made resident
while its plan and residency stay the same, listing them first among its uses
(02ef82edcb), which can reorder entries within one barrier. Both change what a
run of an unchanged artifact records, so recorded runs are held to the new
version.

(cherry picked from commit 4ef52e714128d318329ab722df91b22210a66a6a)
2026-11-03 15:58:53 -08:00
Anees Iqbal 626bd347d2 Keep a draw's uses of what its encoder made resident while its plan and residency stay the same
A draw's uses (binding::command_uses_into) held a use for each resource the encoder made
resident that its binding plan lists (UseTarget::Used), made again at every draw with two sets
of the keys reached through the resident set and named otherwise: work of the count of the
resources made resident, at each draw. On the resident-draws lane (runtime_lane::resident_draws:
each draw binds a resource of its own among N made resident), that made a frame of N draws
quadratic in N.

A draw's CommandUses (kept in LiveBind::uses) now holds those uses first, with the keys of the
buffers among them that no texture use of them names, and what they were made for: the plan,
compared by address through a Weak (so no other plan has that address while it is kept), and
the residency's generation. A draw of the same plan under a residency of the same generation
keeps them, makes its other uses, and works the resident keys out again only where the keys
its other uses name changed, or a use added since took one out (CommandUses::settle_resident).
Those uses are a function of what is compared: each one's resource is the residency's under its
token, whose contents a generation names (residency.rs), its access and stages are the plan's,
and its key and range are the resource's identity and length, which no call changes. The key
leaves out buffer::host_cells_moved: a no-copy buffer's move (HostCell::replace, at a rebind or
a detach) changes where its bytes lie, its pages' base and device address, which a binding
reads; a use's key is the buffer's identity and its range its length from 0, shifted for a heap
buffer by its fixed offset in the heap (Buffer::tracked), and neither is under the cell.

The uses of what the encoder made resident now come first among a command's uses, where they
came at their place in its plan's list. The consumers that compare a command's uses by position
with the last command's (EncoderCore::touch_reaching, NotedApart::fresh, InstanceShadows::add)
compare like with like across draws of one plan. With that order every suite and lane below
passes, and the lane's cases draw the same pixels and move the same counters.

Counted: WorkCounts::resident_uses_made, the uses of resources made resident that draws worked
out (0 at a draw that kept them). WorkCounts gains that field, so a struct literal of it (the
lanes' counters, not part of the API) must name it; the signature table is blessed. Builds with
debug assertions check every draw that kept them against the uses command_uses makes whole, and
count the checks (binding::kept_resident_checks).

Tests (--cfg m2v_gpu, with debug assertions):
- tests::resident_uses::draws_keep_the_uses_of_what_their_encoder_made_resident_until_it_or_their_plan_changes:
  two encoders over the resident-draws fixture's entry shape, the second over other resources
  of the same residency's shape. Each draw after the first keeps the uses (0 made, its kept uses
  checked against those made whole) but the draw after a use_resource between draws, the draw
  after one of another plan (which lists none), and the second encoder's first draw, of the
  first's last plan under another generation, which make them again. With ResidentOf::holds ignoring the
  generation, the debug check fails at the second encoder's first draw ("a command kept uses of
  what the encoder made resident not its own"); with it ignoring the plan, the draw after the
  other plan's indexes another plan's uses and panics (index out of bounds).
Verified on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu, with debug assertions: the runtime's
whole suite, 1588 of 1588; the validation crate's runtime lanes over residency, argument
buffers, indirect command buffers, executions, draws, frame costs, heaps, handles, attachment
reads and degrade notices (resident_draws::each_path_draws_what_the_encoder_draws among them,
300 draws a case under the debug check), 234 of 234; clippy over the workspace with all targets
and features, plain and at --cfg m2v_gpu; cargo check of the runtime's tests in release at
--cfg m2v_gpu, no warning; the signature table checked.

Measured, M3 Max, release (--cfg m2v_gpu --cfg m2v_system_alloc), resident_draws, a frame's
median of 5 (ms), at the parent and with this:
  | case | N 500 | N 1000 | N 2000 | N 5000 |
  |---|---|---|---|---|
  | entry own encoder | 20.2 -> 7.7 | 81.1 -> 25.0 | 351 -> 91.8 | 2576 -> 525 |
  | entry own read | 20.9 -> 8.6 | 80.0 -> 27.9 | 355 -> 96.2 | 2542 -> 550 |
  | entry own write | 22.0 -> 9.5 | 83.2 -> 29.0 | 355 -> 98.9 | 2597 -> 549 |
The slot shape and the entry shape at offsets of one buffer move within their noise. Every
case drew the same pixels (its hash) and moved the same counters but those of timing (arena
recycling and eviction, scheduler sleeps) and resident_uses_made (its plan's uses at each
frame's first draw: 502 a frame at N 500, 0 at every later draw). Still quadratic: 15.4, 25.0,
45.9 and 105 us a draw; at N 2000 the draws' noting of the kept uses (EncoderCore::note_reaching,
46% of the samples), the instance's gathering (InstanceShadows::add, 17%) and the pass's reads
(PassStartReads, 12%) walk them at each draw, and uses_into is 0.3%.
reims-vgpu's draws.10k (its draw_cost harness, the runtime leg, through its run.sh on the M3
Max; median [range] of 9 runs, two interleaved runs each), instructions a draw: 11473.9
[11463.0, 11480.2] and 11478.8 [11471.2, 11481.6] at the parent, 11387.0 [11373.8, 11392.7] and
11387.1 [11378.9, 11404.4] with this: 87 fewer (0.8%), the two sets no longer made at each draw.
host_ab on the RTX 5080 Laptop (encode, us a draw, median and range of 6 runs over two exclusive
holds), at the parent and with this: static 0.059 and 0.059, offset 0.462 and 0.465, bind 0.753
and 0.740, compositor 1.012 and 1.002, host 0.518 and 0.515: within their ranges, as those
shapes make nothing resident.

(cherry picked from commit f6bc17a568bd6b1424089faf8e26584bd159fbb8)
(cherry picked from commit 02ef82edcb8c8042b313d8773a58575447e07795)
2026-11-03 15:58:53 -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 eab0350e04 Rename linear_run.rs to pass_runs.rs: runs of passes merged once, not only linear ones
What: the module that merges a run of passes over one linear attachment once
(5d2b237e1a) becomes pass_runs.rs, its LinearRuns PassRuns, the command buffer
state's linear_runs pass_runs, and Deferred::LinearMerge Deferred::RunMerge.
No behaviour changes; the docs and code otherwise read as before.

Why: the next commit lets a run be one of passes over a shadowed texture merged
back too, through the same machinery, so the names stop saying "linear".

Verified: cargo clippy -p metal2vulkan-runtime --all-targets --all-features
-D warnings is clean on this tree (plain cfg); cargo fmt --all.

(cherry picked from commit 3d902362669724a733f59e6dc1b16f05ea3c088e)
(cherry picked from commit f7f91bb05d64b172c01d44a8a73d1ba3de5194e0)
2026-11-03 15:58:52 -08:00
Anees Iqbal 462e45784c Pin the runtime sources after the steps' threads pool
Re-hashed; the pool of steps' threads rides this stack's RUNTIME_VERSION 1759,
which no landed tree carries yet.

(cherry picked from commit 4bbafa667db0bb9b4d62821d877f161c178c88e9)
2026-11-03 13:34:03 -08:00
Anees Iqbal 79fc675104 Check that another queue's work goes on while a host step records, and measure it
What: runtime_lane::steps_apart. Queue A executes resident_draws' entry shape (an argument-table
entry a draw, each position in a buffer of its own, made resident, the commands resident for
writing), so a host step records it; its executed-commands handler, which runs inside the step,
holds the step. Meanwhile B, a queue a kind, commits work that shares nothing with it: a blit
fill read back (plain), its own execution, a host step of its own (stepped), and a copy out of a
texture A rendered before, after an event A signalled (ordered). The test checks each completes
within 10 s with what it wrote while A's step is held, both with A's objects kept and with every
one of them (command buffer, draws' resources and commands, queue) let go of while the step is
held, A's completed handler still running. It checks too that two steps Metal orders after A's,
one after an event A's command buffer signals and one a pass into A's target, each on a queue
of its own, begin only after A's step ends. The ignored `steps_apart` measures each kind's
commit-to-completion, without the layer, idle and while a real step of STEPS_APART_DRAWS (5000)
draws records, A's objects kept and let go of once committed (`STEPS-APART` lines).

Why: the consumer's WindowServer present waited 13.6 s behind a closed page's host step; the
previous commit moves steps onto a pool of threads, and this is the check that fails without it.

Verified on the M3 Max (--cfg m2v_gpu, maclock+memcap), debug: fails before the previous commit
(stepped did not complete, kept and released; plain 1-3 ms, ordered 4-8 ms) and with its
THREADS set to 1; passes after it (stepped 18.6 / 18.9 ms). Release, during a 5000-draw step
of 2.7 to 5.0 s, before -> after: stepped 3580 ms -> p50 1.49 / max 15.6 ms (released 3359 ->
1.65 / 40.4); plain p50 0.44 -> 0.26 ms, max 22.5 -> 20.0; ordered p50 0.45 -> 0.27, max 18.3 ->
20.7; idle (4000 each, after) plain 0.22 / 0.79, stepped 1.32 / 10.98, ordered 0.25 / 0.49.
The release check wrote the debug assertion of compute/live.rs out of the way only by its base,
7583fe5d99, which carries 2d8616c747.

(cherry picked from commit 8a34da8a90f12b270c5db821e0c5139b093776bd)
(cherry picked from commit bc500877c42a4dd36826b845b84253dbd729c585)
2026-11-03 13:34:03 -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 fada224c2a Pin the runtime sources after keeping checked executions their checks cannot see
Re-hashed; the change rides this stack's RUNTIME_VERSION 1759.

(cherry picked from commit 67590d6dd404806fd75e8662cc0d86c40e4d32dd)
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 b47ff009ed Pin the runtime sources after first-execution keeping and the sampler listing count
Re-hashed with the runtime sources at RUNTIME_VERSION 1759.

(cherry picked from commit bfbbb2262ccc683625a243ac2f513bf8b8733ae7)
2026-11-03 13:34:03 -08:00
Anees Iqbal 9fa0967d11 Bump RUNTIME_VERSION to 1759: an ICB range keeps from its second execution, sampler listings count a going state
An indirect command buffer range's first execution now records inline and
keeps nothing, its second keeps (71e798c081), and a listing of the sampler
states that finds one going counts a slot change first (16afd35fa0). Both
change what a run of an unchanged artifact records or binds, so recorded runs
are held to the new version.

(cherry picked from commit 367ca0fe5695510df3dc5e89aa69348cf45cd9ce)
2026-11-03 13:34:02 -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 96e42d349f Count a sampler slot change where a listing finds a state going
A compute dispatch's debug check (LiveDispatch::check_whole) panicked once in seven runs of
runtime_lane::cache::makings_on_several_threads_each_read_their_own_cache: "a dispatch's bind
state brought in place that is not the one made: its argument samplers".

Cause. ResourceIds::samplers lists sampler slots' holders by Weak::upgrade, keyed by the count
of slot changes. A state whose last handle is gone on another thread no longer upgrades, but
its ID's slot is given back, and the change counted, only later, in IdHold's drop (after
SamplerShared's drop and heap_sets::sampler_gone). A listing taken in that window left the
state out at the count a listing taken while it lived was taken at. A compute encoder's kept
bind state (kept across encoders through SpareLiveDispatches) kept its listing while
listed_at == Some(changed), so it went on listing the going state, and the check, which lists
again, found the two apart.

Fix. A listing that finds a slot whose state no longer upgrades counts a slot change before it
reads the count. Every listing returned at one count then lists the same states, and a listing
kept from before the state started going is at an older count. The render side's raw-count
check (LiveBind::listed_at against Device::sampler_slots_changed) and the dispatch memo key
need no change: a memo holds its states strongly, so none of them can be going, and a render
draw that keeps a listing without taking one is ordered before a release that has not finished.

Release builds bound the stale listing without the check. It reached only the bind state's
listing: the device heap set skips argument-sampler writes, and every layout binds the device's
sampler table. So no live state read another sampler. The extra entry could change the
argument samplers' shape class, and so the plan, until the slot was given back.

Test: tests::sampler_release (a device test). A cfg(test) hook (sampler::going) holds the
dropping thread inside SamplerShared's drop, so the order is the same at every run. The test
lists a state through a compute dispatch, ends the encoder, drops the state on another thread,
held mid-release, then dispatches from the kept state and lists again.

Verified on the M3 Max, MoltenVK, --cfg m2v_gpu, debug:
- Without the fix the test fails with the lane's panic (compute/live.rs:254:9, "its argument
  samplers"). With it, the test passes 5 of 5.
- The runtime's and validation's sampler, argument-buffer, resource-ID, heap-set and
  draw-again tests: 177 of 177 pass.
- The lane test passes 20 of 20 (nextest --stress-count 20) under the GPU lock.
- cargo clippy --workspace --all-targets --all-features -D warnings is clean, plain and with
  --cfg m2v_gpu.

(cherry picked from commit d0f906514415c05e21b5f5851c61a1866f33808d)
(cherry picked from commit 16afd35fa0b536a75289e8e8d08b9f72490a6a82)
2026-11-03 13:34:02 -08:00
Anees Iqbal 589b3e3223 Build the settled-record tests only with debug assertions, as the counter they read
tests::draw_again's two settled-record tests read render::bound::dynamic_compares, a counter
that exists only in builds with debug assertions, so a release build of the runtime's tests
under --cfg m2v_gpu failed to compile (an unresolved import). The import, their helper
(compared_by_each) and the two tests now carry #[cfg(debug_assertions)], as
tests::shared_draw_locks does for its counter.

Verified on the M3 Max: cargo check -p metal2vulkan-runtime --all-features --tests --release
with --cfg m2v_gpu fails at the parent with error E0432 on that import, and passes with this
change; clippy over the runtime's tests at --cfg m2v_gpu passes.

(cherry picked from commit 92d96723e4ae02c8c162de0b87539d2d8a8a86f3)
(cherry picked from commit c6b22216a5b9903cbc25498196afbe9605cf5abb)
2026-11-03 13:34:02 -08:00
Anees Iqbal 7626ab77fa Pin the runtime sources after the kept compute state's flags
Re-hashed; the change rides this stack's RUNTIME_VERSION 1758.

(cherry picked from commit 7583fe5d99c0d0c584d0e70475a6dae74c923ba1)
2026-11-03 12:36:59 -08:00
Anees Iqbal 62b0650c1a Set a kept compute state's token-order and resident-apart flags as its whole state has them
LiveDispatch::refresh brings a compute dispatch's bind state in place, but left
BindState::used_in_token_order and resident_apart at false, where
DispatchTables::bind_state (d6f17f77ab, a38aeff464) sets both. The debug check
check_whole then failed on every kept compute dispatch (616 of 1837 lane cases
and 11 runtime device tests), and release builds bound kept compute states
without the search and the trimmed root tables. Neither flag is part of the
bind shape, the residency lists its used resources in token order, and a
dispatch's memo is filled only after refresh, so nothing kept predates them.

Verified: the indirect_dispatches, predication, first_use and stage_in_strides
lane cases, 37 of them, pass under --cfg m2v_gpu on the M3 Max (debug).

(cherry picked from commit 2d8616c74700cce4a28bcad52229a49e82aa9567)
2026-11-03 12:36:59 -08:00
Anees Iqbal 7333ad21e6 Bless the golden tables and printout for the resident_draws fixture
The resident-draws lane's fixture (engine/resident_draws, b023bcd97f) is new:
its rows of the engine fixture inventory, its golden hashes and its golden AIR
printout are blessed from the tests (bless_engine_inventory, the air_input
ignored test, bless_golden_hashes). Only rows of the new fixture were added;
no other cell moved.

(cherry picked from commit a74a825bbf23c8ad347212cfc0d0ed4d6c819a0d)
2026-11-03 12:36:59 -08:00
Anees Iqbal 52cd1f328d Pin the runtime sources after the paced ahead import and the allocation-count limit
Re-hashed. The paced ahead import (9bbe4518ce) and the device's hold to
maxMemoryAllocationCount (3766b1338e) change runtime behaviour, and ride this
stack's RUNTIME_VERSION 1758, which no landed tree carries yet.

(cherry picked from commit f38faec4d71a5866120b916bed24feac20d23376)
2026-11-03 12:36:58 -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 b2ac8d2abb Pin the runtime sources after the settled draw record
Re-hashed: the settled record records the same commands, so RUNTIME_VERSION
stays 1758.

(cherry picked from commit d760d09a0a5022720876860825fa9d55f82b7e4a)
2026-11-03 12:36:58 -08:00
Anees Iqbal 7479e83c7a Compare no dynamic state on a rebound draw whose command buffer's record holds what it sets
A rebound draw recorded through the kept draw's recording, whose loop over the pipeline's
dynamic states compared each state's value with what the command buffer's record (render/bound.rs)
holds, at every draw: on reims-vgpu's draws.10k shape on the M3 Max that loop was 11.1% of the
runtime leg's time (1760 of Recording::record's 2267 self samples of 15874, by its code range in
the disassembly), every compare answering that the state is set already.

A record now counts the recordings recorded through it and its beginnings again
(Bound::records), and a kept draw keeps the count just after its recording, or the last draw
rebound after it, recorded through its instance's record (Kept::settled). Where the record's
count is still that, nothing was recorded through it since, so it holds the pipeline and the
dynamic states that recording set, of the values a rebound draw sets again (the kept draw's
state, topology and primitive restart, through the kept recording): the rebound draw records
with the states no value of a record holds (KeptStorage::unheld, which every draw sets as before)
and compares none of the rest (Recording::settled). The pipeline's check stays. The commands
recorded are the same; only the compares are left out.

Tests (--cfg m2v_gpu):
- tests::draw_again::draws_rebound_compare_no_dynamic_state_their_record_holds counts, per draw,
  the compares of a dynamic state's value the encoding thread made (render::bound::dynamic_compares,
  builds with debug assertions): 0 at each rebound draw, some at a draw taking every step. With
  the rebound draw's settled check made never to hold, it fails: each rebound draw compared 16.
- tests::draw_again::draws_after_a_state_set_or_a_barrier_set_what_every_step_sets: 15 draws with
  another blend color before the 3rd, a barrier inside the pass before the 7th and a barrier
  that splits the pass before the 11th, draws rebound between them, record the same commands of
  every kind, state commands and pixels as the same draws each taking every step, and the draws
  after the blend color and the in-pass barrier compare their states again (the one after the
  blend color records a state command).
- render::bound::tests::a_record_counts_its_recordings_and_its_beginnings_again.
The debug cross-check of a draw again carries the count over as it does the stamps.

Measured: reims-vgpu's draws.10k (its draw_cost harness, the runtime leg, through its run.sh on the
M3 Max; median [range] of 9 runs), instructions a draw: 12357.6 [12352.4, 12373.1] and 12356.9
[12351.1, 12392.5] at the step before (two runs), 11339.5 [11336.2, 11353.0] with this: 1018
fewer (8.2%). CPU ns a draw stayed within its ranges on a loaded host. The 5080 A/B (static, offset,
bind, compositor, host) had not run when this was committed.

Verified at its first base (691332c6c3) on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu, with debug assertions: the runtime's
whole suite, 1566 of 1567, the one failure the second test above as first written (its split case
asserted per-draw compares where the draws after a split record after their calls; changed to
check them by commands and pixels), then tests::draw_again's 10 of 10; clippy over the workspace,
plain and at --cfg m2v_gpu. The validation crate's runtime lanes
(frame_costs, render, draw_*, hazards, sync coverage, shadows, attachments, executions,
degrade_notices): 299 of 300, the one failure a lane of compute and blit commands alone
(degrade_notices::a_kernel_s_stores_into_private_bit_memory_reach_only_its_own_command_buffer),
which passed alone at the step before and in a rerun of degrade_notices' 18 lanes with this.

(cherry picked from commit 43094ca1b960f8b006b320d3cb569e1fb67a8921)
(cherry picked from commit 20f53150d91087e92de9ad06404e6f6cbb780425)
2026-11-03 12:36:58 -08:00
Anees Iqbal 35110091d4 icb_setters --kept: the setters' cost after executions that kept every chunk
A consumer's frame executes the buffer and then encodes it again. After an
execution kept its chunks' recordings (kept_commands.rs), each CPU write
forgets the chunk it lies in through KeptChunks::wrote. With the --kept flag,
the compute row now also times its encoding in that state. Before each
repetition, untimed, a compute encoder executes every command twice, each
time in a command buffer that is committed and waited for. The second
execution runs every chunk from the first's recordings, and the bench prints
indirect_chunks_kept for each second execution. This mode submits GPU work;
the other modes still submit nothing.

Verified on the M3 Max (MoltenVK, release) under maclock, one run, median of
6 repetitions x 16384 commands, every second execution running all 64 chunks
from kept recordings:
- parent e3444f3273: compute command 10187.8 instructions (589.3 ns), after
  the kept executions 13788.8 (826.3 ns); a set_kernel_buffer pass after them
  2728.2 a call.
- df69cd7b7a: compute command 2528.7 (163.4 ns), after the kept executions
  6140.9 (406.7 ns); set_kernel_buffer after them 1168.2 a call, against 441.1
  with nothing kept.
Both sides pay about 725 instructions more per setter while chunks are kept:
KeptChunks::wrote's retain walks over the kept chunks and the stepped set. That
is the figure to compare a one-store invalidation against.

(cherry picked from commit ac8eae71c9d063369c6568a2b38fb2fd30e22f47)
(cherry picked from commit 2c542021bff8d4bb7f500b63e69cf35e6005bf3c)
2026-11-03 12:36:58 -08:00
Anees Iqbal c667003ee6 Pin the runtime sources after the resident-draws costs and the cross-queue handler order note
Re-hashed with the runtime sources at RUNTIME_VERSION 1758; the translator's
bind/ sources are among the hashed files.

(cherry picked from commit cbb8bfbc5b8a1c52315c4919841e13187a95e215)
2026-11-03 12:36:58 -08:00
Anees Iqbal bf7420081a Bump RUNTIME_VERSION to 1758: resident buffers by address index, heap members by search, root tables without the used resources
Residency::resolve looks addresses up in an index (9b680cf8da), a state in
token order finds its heap members by search (a38aeff464), and root tables the
commit points elsewhere no longer embed the used resources (d6f17f77ab). The
last changes what a run of an unchanged artifact records (smaller root tables,
fewer upload-arena buffers), so recorded runs are held to the new version.

(cherry picked from commit 014ecaea6f4482c4a561bc3f7ed95d5cef6b6c64)
2026-11-03 12:36:58 -08:00
Anees Iqbal 34a49930d4 Say that two queues' completed handlers start in no guaranteed order, as on Metal
What: one sentence in follow.rs's module docs. A command buffer and the command buffer of another
queue it waited for run their completed handlers on two handler threads. The signaller's are
dispatched first, but which starts first is not guaranteed, as on Metal.

Why: the docs said the signaller's handlers are dispatched first, which a reader could take as a
start order. Metal gives none.

Verified on the M3 Max under macOS 27.0.1, with a Swift probe of the same shape as submit_path's
cross row (A fills 16 bytes and signals an MTLEvent, B on another queue waits for it and fills
16 bytes, each with a scheduled and a completed handler), 2000 rounds per row at gaps of 0,
100 us, 300 us and 2 ms, over three legs:
- MTLEvent: Metal started B's completed handler first in 2-127 of 2000 rounds (0.1-6%), and B
  read A's status short of Completed in 0-73.
- MTLSharedEvent: Metal started B's first in 0-2 of 2000.
- In the same session the runtime at 13a5607aff started B's first in 0 of 2000 on every row.
The status and completion-seen order the runtime keeps is unchanged. Comment only.

(cherry picked from commit 67aa3ecaea7c2696372767c30dfc3cde820c4f61)
(cherry picked from commit b75ff3ee9c4f5534cc666ff5e5789be9dfc82f1a)
2026-11-03 12:36:57 -08:00
Anees Iqbal 48036daff0 Hold the resident-draws lane to the draws' own bindings
The resident-draws lane checks what a frame costs of the resources made resident, whatever
their count (assert_bounded). Root-table ranges noted are at most two a draw for the
entry shape: its own binding in each stage that reads through it. The slot shape notes
none, since its functions read no pointer. At most one address index is made per indirect
command buffer execution, and none for the encoder's own draws. The check
(each_path_draws_what_the_encoder_draws, N 300, both shapes and bindings, all three paths)
asserts it a frame; the measurement asserts it over each case's timed frames.

Verified on the M3 (release, --cfg m2v_gpu --cfg m2v_system_alloc):
- The check passes under the validation layer.
- The measurement at N 500, 1000, 2000 and 5000, 3 frames, passes its bounds. Each ICB
  frame made one index. The entry shape noted N ranges a frame (one a draw), the slot shape
  none.
- At N 300, with RESIDENT_DRAWS_DUMP, every counter matches the parent's, apart from the new
  counters and the upload arena's buffers parked and recycled. The pixel hashes match too.

Frame medians, parent (dd56c64399) -> this tip:

  | case | N 500 | N 1000 | N 2000 | N 5000 |
  |---|---|---|---|---|
  | entry own encoder | 46.8 -> 19.6 | 207 -> 78.6 | 915 -> 331 | 6636 -> 2502 |
  | entry own READ | 46.8 -> 20.8 | 211 -> 77.3 | 978 -> 344 | 6682 -> 2492 |
  | entry own WRITE | 45.4 -> 21.6 | 204 -> 80.7 | 970 -> 341 | 8408 -> 2474 |
  | entry one encoder | 8.8 -> 3.0 | 11.7 -> 5.0 | 15.9 -> 8.9 | 33.2 -> 20.6 |
  | slot own READ | 1.3 -> 1.3 | 2.3 -> 1.7 | 4.9 -> 4.0 | 27.7 -> 15.9 |
  | slot own WRITE | 3.9 -> 3.6 | 6.1 -> 5.6 | 12.3 -> 11.1 | 47.4 -> 33.2 |

The slot shape's encoder path and its one-buffer binding are unchanged.

The entry shape with a buffer a draw is still quadratic: 2.7x faster, not linear. What
remains is each draw's walk of the plan's Used(token) uses (binding::command_uses_into and
the code that consumes those uses), which is the draw path's to note once per change of the
residency.

(cherry picked from commit 671b5886674abe5861d5b9a5f1cc6d81f7f28ca9)
(cherry picked from commit b55feb05a51910c40552e425772bb8e539d31c6c)
2026-11-03 12:36:57 -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 af7da0a0c0 Look resident buffers up by Metal address in an index, not a scan
Residency::resolve finds the resident buffer a Metal address lies in, for each binding
address of an indirect command buffer's records that commit or a host step records
(RenderExecution::buffers, indirect_execute's dispatches, kept_commands' resolutions and
runs_again). It scanned every resource made resident for each address, so a pass whose N
draws each bind a buffer of their own among N resident cost N^2 compares.

Now a residency holds an AddressIndex of its buffers and heaps' own buffers by Metal
address, made at the first resolve after a resource was made resident (Residency::join
resets it): the pieces of the space between their starts and ends, each with the first made
resident of those holding it, and each end with the first made resident ending there. It is
made in n log n, and a look costs log n. It answers exactly what the scan answered: the
first resource made resident holding the address, else the first whose end it is (an empty
binding), else the live table. Counted: WorkCounts::resident_address_indexes_made.

Functions: Residency::resolve, Residency::join (resets the index); new AddressIndex::
{of_used, of, first_holding}; WorkCounts::resident_address_index_made.

Verified:
- tests::residency (CPU) compares the index with the scan at every start, end and their
  neighbours, over disjoint, adjacent, nested (heap before and after its buffers),
  overlapping, empty and overflowing sets and 200 pseudo-random ones; it passes.
- M3, release, runtime_lane::resident_draws at the tip of this series: each_path_draws_
  what_the_encoder_draws passes under the validation layer. One index is made per ICB
  frame at N 300 to 5000. Slot shape, a buffer a draw, N 5000, frame medians against the
  parent: ICB READ 27.7 -> 15.9 ms, WRITE 47.4 -> 33.2 ms. At N 300 every counter but the
  new ones, and the pixels, are the parent's.

(cherry picked from commit 570058d7a0a36377d7511efb7829a7d86ead672b)
(cherry picked from commit 9b680cf8da27ee4eb163d5b7d695cfd61d4162af)
2026-11-03 12:36:57 -08:00
Anees Iqbal ff48dcac15 Check that resident-draws paths draw alike, and dump their counters
The resident-draws lane gains a check and a comparison knob.

- each_path_draws_what_the_encoder_draws (a device test, under the validation layer): for
  both shapes, 300 draws (past a chunk of an indirect command buffer's records) with a
  position buffer a draw and with one buffer at offsets, on the encoder, ICB READ and ICB
  WRITE paths, draw exactly the pixels the encoder's draws of one buffer draw. The WRITE
  path's host step resolves each record's binding among the resources made resident, so
  this is the device leg of that resolution.
- RESIDENT_DRAWS_DUMP=1 prints every counter a measured case's frames moved (from
  WorkCounts' Debug form, the time counters left out) and a hash of what its last frame
  drew, to compare two builds' uses, barriers and output.
- The target is shared and read back; the sampled texture is filled.

Verified: built (release, --cfg m2v_gpu); the device test's run is reported with the
residency changes that follow.

(cherry picked from commit dd56c64399b19589c1538e2173b41efccaed216f)
(cherry picked from commit bb0dac90c20c862a13f84198c8208833df6cc3e5)
2026-11-03 12:36:57 -08:00
Anees Iqbal c08e280864 Measure draws that each bind a resource of their own among many resident
A lane measurement (ignored, release, --cfg m2v_system_alloc) of a pass whose draws each
bind a resource of their own while the pass makes every one resident, as a page's render
bundle does with a bind group a draw: runtime_lane::resident_draws, over the new public
fixture resident_draws.metal.

Two shapes: slot (draw i binds position i as vertex buffer 0) and entry (draw i binds entry
i, 24 bytes, of one argument table: a position pointer, a texture ID and a sampler ID, as
vertex and fragment buffer 0, which both functions read through; the pass makes the
positions, the table and the texture resident). Each with a position buffer a draw or one
buffer at offsets, and on three paths: the encoder's own draws, an indirect command
buffer's execution made resident for reading (commit records it) and for writing (a host
step records it). It prints each case's frame time (encoding to completion), per-draw time
and the device's counters; RESIDENT_DRAWS_COUNTS, _FRAMES and _ONLY narrow it.

Verified on the M3 (release, 3 timed frames): the entry shape with a buffer a draw is
quadratic on every path (frame medians N 500 47 ms, N 1000 201 ms, N 2000 898 ms, encoder,
READ and WRITE alike), against 3.1 ms and 9.3 ms at N 500 and 2000 with one buffer; the
slot shape stays linear (1.5 us a draw on the encoder at N 2000).

(cherry picked from commit 8f27ac59877cec5b6c1286954ba3f9c8d1207644)
(cherry picked from commit b023bcd97ffe9762b1dbe4e5cbff6957ac7ddc5e)
2026-11-03 12:36:57 -08:00
Anees Iqbal 410990ead6 Pin the runtime sources after linear merge runs, runtime-own check textures and in-place ICB setters
Re-hashed with the runtime sources at RUNTIME_VERSION 1757.

(cherry picked from commit 2eb90a284f6400b964249762665e4e1f88dee105)
2026-11-03 11:48:37 -08:00
Anees Iqbal 408763813b Bump RUNTIME_VERSION to 1757: linear merge runs, runtime-own check textures, ID after refusals, in-place ICB setters
A run of passes over one linear attachment now merges once after its last pass
(0bf36f1a1c), zeroed shadow merges borrow pooled scratch (83d6cb557e), the
in-place check's textures take no texture ID (9c75fb4774), a texture takes its
ID only once its making cannot be refused (8b3fc9ec8b), and an indirect
command's setters write its field in place (d507c87849). Each changes what a
run of an unchanged artifact records or answers, so recorded runs are held to
the new version.

(cherry picked from commit 3575e053d8d75cb685f93ed45b26552f831f0de3)
2026-11-03 11:48:37 -08:00
Anees Iqbal be686f18a0 Write an indirect command's field in place, adding to what its records hold only what is new
Each Metal-shaped setter (IndirectCommandBuffer::edit) paid about 2000
instructions, almost all for bookkeeping around a write that costs 130-213. It
copied the whole 2248-byte record out of the mapped storage (zeroed, then
moved through a Result), wrote the field into the copy, copied the field back,
decoded the copy again for its action and barrier, looked the command up in
the per-command BTreeMap of states (16384 entries), then took the summary's
own mutex to add what usually was there already. The 41% of its time in
memmove and 30% in edit's own copy loops were those copies. The BTreeMap
lookup came in with 565fbd9153 (kept recordings): with the dense Vec before
it, 9ec100ba7c and b7652d85a2 measure 8652.5 instructions a render command
and 565fbd9153 measures 10501.9.

Now, under the one hold of `pipelines` the write already took:

- The field goes straight into the mapped record. CommandRecord::write_field
  validates the record and writes the field's words there, as it did into the
  copy, and leaves the record unchanged on a refusal. Readers that read
  records together with states (read_records) still read under the same lock.
- The records' address is read from the storage once, at creation. The
  storage is runtime memory, never a heap's, a mirror or host pages, so its
  mapping is fixed for its life. Before, contents() cost about 65
  instructions on every call.
- CommandStates::added keeps what the CPU's edits have added to
  WrittenCommands so far. The summary only grows, so an add that is already
  covered changes nothing, in the summary or in any buffer a blit copied the
  records into. Such an add is skipped. The record is read for its action and
  barrier only where the edit can change them (an action or barrier field), or
  where the GPU may have written the records (gpu_written, set at the encoding
  call, before any GPU work that may write them is committed). Otherwise every
  action and barrier in a record was left by an edit that already added it.
  The state lookup happens only on the rare add that grows the summary. Only
  an edit puts a state in CommandStates, and it adds that state, so the lookup
  is needed nowhere else.

Every refusal, and the order of refusals, is unchanged; the setters' checks
are untouched. The records, what the records may hold, the CPU-write count and
the kept-chunk invalidation are as before. One case reads differently: when
the GPU races a setter's edit and leaves the record undecodable, the state the
setter would have set is now not set. The parent set it and then returned the
same internal error.

Verified on the M3 Max (MoltenVK, release, examples/icb_setters), median of 5
runs x 6 repetitions x 16384 commands, runs interleaved with the parent's
e3444f3273 build:
- render command: 10351.4 -> 2667.9 instructions; 590.1 -> 234.9 ns (runs
  194.9-272.3); 2110 -> 732-971 cycles.
- compute command: 10177.2 -> 2528.7 instructions; 583.6 -> 128.8 ns (runs
  116.4-186.3).
- per call, one pass of the call over the buffer: set_vertex_buffer 2003 ->
  446, set_fragment_buffer 2002 -> 444, draw_primitives 2096 -> 634,
  set_render_pipeline_state 2288 -> 751, set_kernel_buffer 1998 -> 441,
  concurrent_dispatch_threadgroups 1996 -> 534, set_compute_pipeline_state
  2243 -> 718 instructions.
- Time Profiler, render: before, _platform_memmove 41.5% self, edit 29.0%,
  write_field 6.2%, pthread_mutex_lock 3.4%, OwnBytes::shape 3.2%,
  RecordView::new 3.0%, WrittenCommands::add 2.1%. After, edit 25.1%,
  RecordView::new 24.1% (write_field's validation, the first touch of each
  record's lines), set_buffer 13.8%, write_field 10.6%,
  pthread_mutex_lock 9.1%. No memmove; WrittenCommands::add and
  Buffer::contents are gone.

tests::indirect_command_buffer_device (device tests, m2v_gpu/m2v_cpu_icd)
runs a model of the parent's setter beside the buffer. The model writes the
field with write_field into a copy of the record as it stands, then adds the
record's writes and named state every edit. The mix covers render and compute
commands, fields that add something and fields that add nothing, refusals and
taken calls mid-command (PipelineWithoutSupport, ForeignObject, a slot at the
limit, IndexBufferRange, CommandType, RenderState, an imageblock past 16 bits),
a threadgroup length landing on the next command and one past the record, a
command's reset and a range's, a GPU-left draw after written_by_gpu, a record
that does not decode, and a blit-copy target's summary. After every call the
storage bytes, both summaries and cpu_writes must equal the model's. Verified:
both tests pass here and, as the same file, on the parent e3444f3273. Two
negative controls fail as they should: ignoring gpu_written misses the
GPU-left primitive type and draw, and ignoring the set state misses PIPELINE.
clippy --all-targets --all-features -D warnings passes, plain and under
--cfg m2v_gpu; rustdoc -D warnings passes. Named::union becomes pub(crate)
for the bookkeeping.

(cherry picked from commit df69cd7b7a60e1d054ba2786494e6668ed64d8de)
(cherry picked from commit d507c878497317b071b50c0f0160cc6ec715f190)
2026-11-03 11:48:37 -08:00
Anees Iqbal da7b285ec7 icb_setters: the CPU cost of an indirect command buffer's setters
A bench for the cost a consumer pays to encode indirect commands on the CPU,
every field of each command set by its own Metal-shaped setter, one thread,
nothing executing. It has the shape of the consumer's report (rgk-icb-2):

- render: a buffer of 16384 commands of DRAW alone, 2 vertex buffers and 1
  fragment buffer, nothing inherited. Each command is indirect_render_command_at,
  set_render_pipeline_state, set_vertex_buffer twice, set_fragment_buffer and
  draw_primitives.
- compute: CONCURRENT_DISPATCH, 3 kernel buffers. Each command is
  indirect_compute_command_at, set_compute_pipeline_state, set_kernel_buffer
  three times and concurrent_dispatch_threadgroups.

Each repetition encodes every command once, over the last repetition's, and is
timed as a whole: wall time, and on macOS the thread's own instructions and
cycles (libSystem's thread_selfcounts, readable unprivileged). It prints the
median a command with the lowest and highest. `--calls` also times each call
kind alone, and the record format's own write_field of the same fields (no
lock, no check): the floor of a setter's write. The pipeline states come from
the owned fixture runtime_examples.ll through llvm-as. Nothing is submitted.

Verified on the M3 Max (MoltenVK, release) at this commit's parent e3444f3273:
median of 5 runs x 6 repetitions x 16384 commands, each run's median a command:
render 588.0-599.4 ns, 10350.9-10351.9 instructions, 2107-2145 cycles; compute
578.3-588.1 ns, 10176.3-10177.5 instructions, 2083-2105 cycles. --calls: about
2000 instructions a buffer setter and 2288 for set_render_pipeline_state, where
write_field of a field costs 130-213.

(cherry picked from commit 5a88c91634f289aaaf9d866ecdf36b949f3ee45d)
(cherry picked from commit 46a4a5d15cb7423a031650f9fc136e7470912174)
2026-11-03 11:48:36 -08:00