Commit Graph
1530 Commits
Author SHA1 Message Date
Anees Iqbal 31a8967645 Retains hold shared objects by reference, once each, and drop the holds residency and blit_at made
Every resource an encoder made resident was boxed into its retains, though its residency holds it
and its encoder's record holds the residency until the command buffer completes; blit commands
boxed the buffers blit_at had already held by reference; and each dispatch boxed its pipeline
state, variant objects, pipelines and samplers again.

- encoder.rs: made_resident no longer retains (the residency holds the resource; the record
  holds the residency until completion, as command_buffer's own sync_heaps already relied on).
  Compute's sync_heaps and carry_residency likewise; Residency::carry returns nothing.
- retained.rs: a shared hold looks among the last 8 shared objects the encoder held and holds
  none again (the encoder holds it until completion, so no other object has its address
  meanwhile); each object still goes where its earliest hold goes.
- compute.rs: a dispatch holds its pipeline state (ComputePipelineState::held), variant objects,
  pipelines, samplers and flat-call buffer by reference; a memo hit borrows the made pipelines
  instead of cloning the list, and sets the memo's made list only where it is empty.
- blit.rs, blit_fill.rs, blit_texture.rs, two_planes/buffer_rows.rs: the retains of buffers
  blit_at held go; staging buffers and textures are held by reference.

Everything is still held until the command buffer completes. The same commands, barriers and
notices.

Checks: tests::retained::an_object_held_lately_is_held_once_until_the_holds_go (fails without the
recent-holds look: 12 holds for 3); the runtime GPU suite's encoder_holds and blit_holds legs,
which drop every object after the commit and check it lives until completion, pass.

Release, M3 Max, MoltenVK 1.4.2, host_ab percall (allocations deterministic; times interleaved
twice, ns per call):

| call | allocs before | allocs after | ns before | ns after |
|---|---:|---:|---:|---:|
| use_resources_read_256 | 277 | 16 | 10542-10583 | 7333-8208 |
| use_resources_read_1 | 6 | 3 | | |
| use_resource_read_write | 5 | 2 | | |
| use_heap | 8 | 5 | | |
| dispatch | 14.16 | 8.15 | 831-839 | 759-762 |
| copy_buffer_1k | 2.08 | 0.06 | 303-312 | 277-289 |
| fill_buffer_256 | 4.06 | 3.04 | 272-278 | 256-259 |
| copy_buffer_to_texture | 8.63 | 6.56 | | |

host_ab calls allocations: many_dispatch 46 -> 41, many_dispatch_resident 47 -> 44,
wide_dispatch 32.6 -> 27.5, many_blit_copy 11 -> 9, wide_blit_copy 2.5 -> 0.5; their times
within run-to-run noise (five interleaved rounds).

Verified on MoltenVK: the runtime GPU suite 1505/1505; the validation runtime lanes 533/535, the
two failures failing the same at the base.

(cherry picked from commit 3fc8182b1768af73cde54d2e9d717fa200f84593)
(cherry picked from commit 16d063c2ee9a70fd9dcc51d8b03abe8f69a07859)
(cherry picked from commit 5c880c7a5e082a417000448098c5ea5348a838d7)
(cherry picked from commit 367a4572f3c1cc951e0d2fb9f31a2f65af830f62)
2026-11-03 01:40:27 -08:00
Anees Iqbal eb25ca898d The tracker orders each command by one use list, kept in the encoder's storage
Each ordered command built its use list twice (EncoderUses::barrier, then record_reaching), each
time through a fresh Vec and a fresh hash map, then a sort. The two lists differ only for
untracked uses.

- tracker.rs: EncoderUses::order compares and records a command in one call. The uses are merged
  in place (merge: a stable sort by key, then each key's equal ranges joined), into two lists the
  encoder keeps and clears per command; the second list (what the command is recorded with) is
  the compared one where every use is tracked, and made apart, in its own kept storage, only where
  one is not.
- encoder.rs: track calls order.

The same uses in the same order, so the same barriers: merging_in_place_keeps_each_key_and_range_once_in_order
checks the merge against the map-based form it replaces over 2000 random commands.

Check that fails without it: tests::tracker::an_encoder_orders_its_commands_in_storage_it_keeps
(with a fresh Vec per command, the storage moves at the second command).

Release, M3 Max, MoltenVK 1.4.2, host_ab, before and after interleaved three times (each a median of
3 rounds):

| workload | before | after |
|---|---:|---:|
| many_blit_copy (ns) | 786-824 | 645-654 |
| wide_blit_copy (ns) | 535-570 | 384-396 |
| many_dispatch_resident (ns) | 3458-3595 | 3260-3414 |
| wide_dispatch (ns) | 2398-2527 | 2148-2301 |
| dispatch_resident_moving_256 (us/dispatch) | 1.78-2.39 | 1.65-1.69 |

Allocations per call (percall, deterministic): dispatch 18.16 -> 14.16, copy_buffer_1k 6.07 ->
2.08, fill_buffer_256 8.06 -> 4.06, copy_buffer_to_texture 12.56 -> 8.63, fill_in_own_encoder
20.6 -> 17.6; calls many_blit_copy 14 -> 11, wide_blit_copy 6.5 -> 2.5.

Verified: the runtime's tracker and host_aliases tests; the runtime GPU suite on MoltenVK
1504/1504.

(cherry picked from commit a4f9f1c9a908c6289d4096cd37c32fa7a8866b94)
(cherry picked from commit 55b4ba442f60e0a39630639ec383d760c8e2b945)
(cherry picked from commit 4be1a7d13048620e22a628ec2dbb13e76660451b)
(cherry picked from commit 56649bbf80d15bb6a0dbe0decfa898e5def0ce0f)
2026-11-03 01:40:26 -08:00
Anees Iqbal a4546da224 Compute dispatches keep their bind state between dispatches, and pipelines keep four plans
A compute encoder's dispatch that did not take what the last one settled rebuilt its whole bind
state, listing every resource the encoder made resident, and each pipeline state kept one plan, so
per-dispatch cost grew with the resident count and two encoders of one pipeline with different
resident sets planned again at every dispatch.

- compute/live.rs: the encoder keeps its bind state (LiveDispatch), brought in place at each
  dispatch as a render encoder's draw does (live_bind.rs): the kernel table is read again only
  where its stamp, interface, sampler maps or no-copy moves changed, and only the slots calls
  changed where the table keeps them; the used resources are listed again only where the
  residency's generation, a no-copy move or an indirect command buffer's slot changed; the shape
  is kept while no change may have changed it. Debug builds check the whole state against one
  built from scratch at every dispatch. The state goes to the device's spares at the encoder's
  end (four kept), with its memo let go first, so a kept state holds nothing alive.
- DispatchMemo stays the "nothing changed" shortcut, now owned by the live state.
- pipeline/mod.rs: a pipeline state keeps four plans, least recently used first out, found by
  identity and then compared in place (BindState::position_of_shape), with the same key.
- The ICB and host-step dispatch paths keep the fresh path.
- WorkCounts: dispatch_shapes_made, dispatch_shapes_found, dispatch_used_resources_listed.
- residency.rs: the Generations doc says what is listed once per change, and where.

The same Vulkan commands, barriers, notices and refusals at the same calls; retains unchanged.

Checks that fail without it:
- runtime_lane::dispatch_work::dispatches_list_what_their_encoder_made_resident_once_a_change:
  with the residency reuse forced off, every offset change lists again ((1,0,1) for (0,0,1)).
- dispatches_take_what_their_state_planned_for_the_same_shape gains a third encoder of the first
  shape: with one kept plan it plans again ("an encoder of the first shape", 0 for 1).

Release, M3 Max, MoltenVK 1.4.2, host_ab encode (3 rounds, median, us per dispatch), base 096b427da3:

| workload | before | after |
|---|---:|---:|
| dispatch_resident_moving_0 | 2.090 | 1.757 |
| dispatch_resident_moving_16 | 2.570 | 1.754 |
| dispatch_resident_moving_256 | 11.472 | 1.764 |
| dispatch_resident_moving_4096 | 209.803 | 1.799 |
| dispatch_offsets | 2.186 | 1.929 |
| dispatch_churn | 2.164 | 1.928 |
| dispatch_static (memo hit) | 0.846 | 0.848 |
| dispatch_resident_4096 (memo hit) | 0.961 | 0.807 |

host_ab calls: many_dispatch 6397 -> 4095 ns and 74 -> 49 allocations; many_dispatch_resident
5331 -> 3496 ns, 78 -> 50; wide_dispatch 2825 -> 2293 ns, 40.9 -> 36.6. percall allocation
counts unchanged.

Verified on MoltenVK (with the tracker change that follows also applied): the runtime GPU suite
1504/1504; the validation runtime lanes, but for two failures that fail the same at the base
(function_tables::tables_and_handles_answer_as_metal_s_do,
predication::every_dispatch_form_runs_in_each_pass_past_the_copies).

(cherry picked from commit 8f350dddbe5c1cb3f5a486413b19ff23aa4f16c6)
(cherry picked from commit 5b3671810c7d658fd4223d5a6c97c1e33443e8a2)
(cherry picked from commit 03fe129bd31904ddf5013631ce104bb47438eaa9)
(cherry picked from commit 6457fa412ca00092e5b0a8603e05cbd99cd130b4)
2026-11-03 01:40:26 -08:00
Anees Iqbal f2097a3b2e host_ab: dispatch_resident_moving variants, the output's offset moved each dispatch
The encode workload's dispatch_resident_moving_{0,16,256,4096}: as many
dispatches of the tiny kernel after none, 16, 256 or 4096 buffers made
resident, each after set_buffer moved the output buffer's offset. The
existing resident variants change nothing between dispatches, so every
one after the first takes the dispatch memo and none shows what a
dispatch that changes a binding costs at a resident count: these do.

Verified: built in release; the variants run on the M3 (MoltenVK) and
print dispatch_resident_moving_*_encode.

(cherry picked from commit fea089d4527bab194df36adb68b1b02bdc7d7cc3)
(cherry picked from commit e5732c19aa1b21c56cc5fa8d1bb1c3ce21e32c0e)
(cherry picked from commit 09da9fc3166c4f3c8b2e4e26d5fe68620228014b)
(cherry picked from commit 09dab5495d35b14ed952fa67257809aa271e6357)
2026-11-03 01:40:26 -08:00
Anees Iqbal e20534ec36 The bitcode audit's text scanner skips the empty inline assembly decode drops
What: text_fingerprint no longer counts a call of `asm sideeffect "", ""` at the call type
`void ()` (llvm-dis's `call void asm sideeffect "", ""()`, then attributes or metadata
only). That's the one structure decode drops. Any other inline assembly stays an indirect call:
a flag, a template, a constraint or an operand.

Why: since decode drops that call, the decoded fingerprint of engine/kernel_inline_asm had 1
call where the text had 3 (2 through <indirect>), and public_fixtures_audit_as_matches failed
on stack5's gate.

Verified: bitcode_audit tests 8/8 on the M3, among them public_fixtures_audit_as_matches (which
failed in the gate before this) and the new the_text_scanner_skips_the_empty_inline_assembly_decode_drops
(two dropped spellings, four kept); clippy -p metal2vulkan-validation clean.

(cherry picked from commit bd573b20de31f693b5e1df1663432624f76a44e5)
2026-11-03 01:11:50 -08:00
Anees Iqbal ac27f24b99 Pin the runtime sources after the shadow carries counted per queue
(cherry picked from commit 51b78cff4a5d6f7e80c5548dd88c25f72078fb70)
2026-11-03 01:11:50 -08:00
Anees Iqbal b39f2c16b7 Bless the golden hashes and engine fixture expectations for the inline-assembly fixtures
Six fixtures that call MSL's empty inline assembly now translate; their golden hashes and engine
expectations are additions only (0 rows removed).

(cherry picked from commit ce6f4b3c97a2bdf6f72d3767f2b459601098d4a6)
2026-11-03 01:11:49 -08:00
Anees Iqbal 842f5d14fc Bump RUNTIME_VERSION to 1742: shadow carries counted per queue
A run of an unchanged artifact and plan may now record fewer shadow copies in than before: a
command buffer's later encoder takes the image its earlier one left holding a shadowed texture's
truth unless an encoder of a command buffer of another logical queue ended with the texture in
between (shadow.rs's Touched), where any other command buffer's encoder did before. Such an
encoder then reads the bytes as of its command buffer's commit, as Metal shows them, where it
read them at its own run. 1742 is the number this change was given (1741 is compute-bind's).

(cherry picked from commit 595aec07c672d2559cd8513fc0b639a3b81bbdda)
(cherry picked from commit 84dc66611d06acb1081c7a06a1799bbbad007498)
2026-11-03 01:11:49 -08:00
Anees Iqbal 8882051ff8 Carry a shadowed texture's image past other command buffers of its queue: count encoder ends per queue
What: ShadowCopies::touched, the count of encoder ends by which a command buffer's carry
(ShadowCarry: an earlier encoder of it left the shadow's image holding the truth, so a later one
takes no copy in) is dropped when another encoder ended with the texture in between, is now
counted by the logical queue of each encoder's command buffer (shadow.rs's Touched). A carry
counts the ends of other queues' encoders alone. A command buffer's carry names its queue
(ShadowCarry::on, at CommandBuffer::new), and so does a segment core's (EncoderCore::segment_raw).
A carry of no queue named counts every end and an encoder of none counts against every carry, as
before: ShadowCarry::default, which the shadow unit tests' harness keeps.

Why: a queue's batches go in commit order, only its head at a time (scheduler/mod.rs, The
order), so no other command buffer of the same queue runs between two encoders of one on the
GPU. The device-wide count still dropped the carry when such a command buffer's encoder ended in
between at encode time. With one queue encoded on several threads that is the common case, and a
dropped carry is not only a second copy in: the later encoder then reads the buffer at its own
run, a CPU write made after the commit among it, where Metal shows every encoder of a command
buffer the bytes as of its commit (shadow.rs, Copy in). Shadows are made on every device: a
texture over a buffer whose rows have bytes between them is one wherever it runs
(linear_plan.rs, Aliasing).

Tests:
- tests::shadow::only_another_queue_s_encoder_drops_a_carried_surface: an encoder of the same
  queue's command buffer between, or while the encoder was open, keeps the carry; another
  queue's, or one of no queue named, drops it; three of the same queue's command buffers
  interleaved each keep their own. With the per-queue filter removed it fails (verified).
- runtime_lane::parallel_encodes::a_shadowed_texture_keeps_each_command_buffer_s_bytes now
  requires the 4-thread runs' (shadow copies, texels copied in, texels a carry spared) to equal
  the serial runs'. Before the fix the M3 Max measured [256, 8192, 8192] serially and
  [384, 16384, 0] on 4 threads; now [256, 8192, 8192] both ways.
- runtime_lane::parallel_encodes::guest_pages_follow_the_commit_order_however_the_command_buffers_were_encoded
  (new): an 8x8 RGBA8Unorm texture at 48-byte rows over a no-copy buffer of guest pages whose
  memory carries a log (HostMemory::with_dirty_pages); per run the CPU writes its bytes and tells
  the log, then 8 command buffers of one queue write it through a kernel and copy the pages out,
  read it, fill a row of its bytes by a blit and read it, and read it in two encoders. 12 runs
  serially and 12 on 2, 3 and 4 threads out of commit order, committed in order: every read and
  copy is the CPU model's, the pages end holding it, every byte the GPU wrote is in the
  runtime's reports to the log, and each run's reports and gated copies in equal the serial
  run's. The M3 Max: gated (gated, whole, skipped, bytes whole, bytes copied) serially
  [96, 66, 0, 24576, 18048], on 2 to 4 threads [96, 58, 3, 24576, 16224]; the whole and skipped
  figures follow when an earlier command buffer's completion reports land against a gate that
  reads the log at its submission, not the encode order.

Verified on the M3 Max (MoltenVK 1.4.2) under --cfg m2v_gpu: 200 tests pass (the three above;
parallel_encodes, parity::sequences::parallel, framebuffer_fetch::storage_forms, device_copies,
no_copy_textures, pitched_surfaces, in_place_textures, host_memory, buffer_textures,
texture_buffers, first_use_writes; the runtime's tests::shadow, dirty_pages*, copied_log*,
blit_holds, encoder_holds, heap_tiled, fresh_unwritten). clippy -D warnings clean for the
runtime and validation crates, all targets and features, plain and --cfg m2v_gpu.

(cherry picked from commit 6620453fdf0cab82040027a0e15ff2599d93ce25)
(cherry picked from commit dcf89ec07399bd509c4c17390000a657e5739c3a)
2026-11-03 01:11:49 -08:00
Anees Iqbal 1272fd8159 Print the storage form beside an encoding command buffer's line without a run of spaces
What: the PARALLEL-STORAGE-FORM line of
runtime_lane::framebuffer_fetch::storage_forms::a_target_fetched_beside_an_encoding_command_buffer_keeps_its_answers
had ten spaces in the middle of a sentence, left from a line join; the words are the same.

Why: the line is read in run logs.

Verified: a string literal alone changed; cargo fmt --all clean; the runtime-sources pin is
unchanged (pin-compute.py: 57f7e1cd...).

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

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

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

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

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

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

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

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

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

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

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

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

On the lane: SEMANTICS_VERSION is 1953 here, after the specialization folding's 1952.
(cherry picked from commit 8b418fbd6c)
(cherry picked from commit c8a7e910204a6cedad2b257a10cb095d83c213e3)
2026-11-03 01:11:48 -08:00
Anees Iqbal ac6af3e663 Bless the golden hashes for the fold fixtures
What: crates/metal2vulkan/tests/golden_hashes.tsv gains the rows of the fold fixtures the
specialization folding added (fold_config_direct, fold_config_struct, fold_loop_ops and their
kernels): 20 rows, 380 cells across the committed profiles. No existing cell changes (the diff
adds lines only), so no translation of an existing fixture moved.

Verified: the bless test ran on this tree; golden_hashes_match_the_table passes after it.
(cherry picked from commit 5c739c7cdc0905808d95ca4997883a1a769a53ab)
2026-11-03 00:45:20 -08:00
Anees Iqbal 6b872ef450 Pin the runtime sources after priming vkResetDescriptorPool in the exit guard's table
What: crates/metal2vulkan-validation/runtime-sources.sha256 recomputed on this tree
(pin-compute.py: listed=58 inputs=495, ab88770d...). The pinned inputs this stack changed are the
runtime's exit_guard.rs and device/prime.rs: vkResetDescriptorPool is listed in the exit guard's
section table and primed, so a predicated loop's run again resets its descriptor arena inside a
section instead of calling ash's panicking stub. No cached artifact or answer changes, so
RUNTIME_VERSION stays 1740. The spec-fold commits in this stack change no pinned input.

Verified: pin-compute.py on this tree prints the pinned value.
(cherry picked from commit 81a8c4c0ef3c9a0b28a29399b58fe88750552eee)
2026-11-03 00:45:19 -08:00
Anees Iqbal 6dfe490940 Bump SEMANTICS_VERSION to 1952: specializations fold constant fields and unroll
What changed in the output for unchanged keys: SCCP reads the integer
fields of a never-written constant global as their constants; a
static initializer's integer conversions are evaluated lane by lane
(a pipeline that was `Unsupported{StaticInitializer}` now compiles);
an `fcmp` of a subnormal constant is no longer folded; and a loop of
constant trip count whose counter decides a branch is unrolled where
the folded copies are no larger. A cached artifact or key from before
could hold the old module or refusal.

Verified: the version is read by every key and artifact
(`cache::SEMANTICS_VERSION`); the golden table's cells that this
series moves are only new rows (the fold fixtures), which re-bless on
development.

(cherry picked from commit 5e77fa94e0c552271eb23196d6a8efc9d8fd4874)
(cherry picked from commit 1a09cb4ee302f310b72f5cc9389afe320fff42c7)
2026-11-03 00:45:19 -08:00
Anees Iqbal 0b70fb0dd3 Add the fold fixtures, their word bounds and the configuration kernel's cases
What: six owned MSL fixtures, written for this project, under
`fixtures/public/engine/` with their `.ll` and `.air.ll` from
`scripts/regen-air-fixtures` (Metal 32023.922, SDK 27.2, recorded in
`TOOLCHAIN`): `fold_config_struct` (a fragment uber shader reading its
ten function constants from a program-scope `constant` struct its
static initializer fills, one read at a run-time index) and
`fold_config_direct` (the same reading the constants directly);
`fold_loop_extract` (a 4x4 loop of constant trip counts indexing a
`uint4` of opcodes into a 16-case switch) and `fold_loop_extract_baked`
(the same with one specialization's constants written in);
`fold_static_init_widen` (`uint4(kOps)` of a `uchar4` constant); and
`fold_config_kernel` (a kernel of the struct's shape, its opcodes
widened to `uint4`, read through `kGeneric ? buffer 1 : kConfig`).
`tests::engine_specialized_folds` bounds the specialized fragment
stage of the struct within an eighth of the direct form's words and
the loop's within an eighth of the baked form's, each with the same
precision notes, and compiles the widening kernel (another constant
value is other words). The inventory rows and the `air_input`
printouts of the new fixtures are blessed (0 moved cells); six
authored cases over `fold_config_kernel` (four specializations: both
layers, the first only, the second only, a count of zero; and the
generic path over two configurations in buffer 1), each with buffer 1
holding a configuration the specialization must not read.

Verified (measured, nvidia-rtx5080-laptop profile):
- On 17a1c34c1c all three fixture tests fail (struct 22895 words
  against 1737; loop 3952 against 2612; the widening kernel refused
  `Unsupported{StaticInitializer}`); on this branch they pass (1815,
  2296, compiles).
- The six cases on Metal (M3 Max, macOS 27.0.1, Xcode 27B52), recorded
  under `local-metal`: the generic path over a configuration answers
  exactly as the specialization over it (both: 039867ee..., second:
  676085...). The MoltenVK candidate (moltenvk-m3, MoltenVK 1.4.2) on
  the stated and robustness-off legs: Match on all 12 runs. That run
  needed the C3 reference list to name this host's current Xcode
  (27B52, Metal 32023.922; the list names 27A266a, 32023.921), so it
  ran against a scratch copy of the list, and its reference Metal rows
  and candidate rows are not committed. Before this series the kernel
  is refused (`Unsupported{StaticInitializer}`).
- Note sets (precision notes, translator), before -> after: struct
  drops DeviceArithmetic, DeviceNanEncoding and NativeDivision and
  equals the direct form's set; the loop drops DeviceNanEncoding,
  NativeDot and NativeMix and equals the baked form's set; the direct
  and baked forms are unchanged; the widening and configuration
  kernels go from refused to compiled (the kernel noting
  FastMathRewrites and NativeNanEncoding, its one float arm). Every
  dropped note is of an operation on a path the constants exclude.
- Translation census of the private corpus, nvidia-rtx5080-laptop,
  before (17a1c34c1c) and after (this series): 16872 common rows, 0
  new FALLBACK; 4 rows that were `NeedsInput(LinkedFunction)` now
  translate; of the 15499 rows both translate, 1 smaller (8452 -> 6625
  words) and none larger, 83262314 -> 83260487 words; slowest row 694
  -> 438 ms, the largest allocator peak 176706374 bytes in both, the
  peak worker RSS 225 -> 235 MB (one row, its allocator and ledger
  peaks unchanged); budgets gate passes.
- The corpus's largest uber fragment specialized (numbers only): all
  features off 192380 -> 160 words, four other sets 200495 -> 311,
  200495 -> 1670, 208557 -> 5522; the generic path 194574 words in
  both, its translation 63.7 -> 64.4 ms (median of five, release).

Golden tables to re-bless on development: `golden_hashes` (380 new
cells, these fixtures' 20 entries on 19 profiles; no moved cell) and
the authored compile census (`authored-compile.tsv`, six new cases).

(cherry picked from commit ca13dd4df89b61e1d454935ec7284ee2a5892823)
(cherry picked from commit 36221a92f30889f8ddf8045d0282b6050fe7cf09)
2026-11-03 00:45:19 -08:00
Anees Iqbal c7db26da1b Keep an unrolled entry only where it comes out no larger than its loops
What: canonicalization runs the unrolling rounds (and the SCCP after
each) on a trial body and keeps it only where its size is at most the
entry's before unrolling; otherwise the loops stay as they were and
the trial's undefined-constant reads are dropped with it. The size is
`unroll::live_size`: the instructions that stay once unobserved code
is deleted (every one that is not pure, and every pure one those read,
directly or through others), not counting unconditional branches and
PHIs of one entry, which the copies leave where their blocks join.

Why: with the previous commit alone, a translation census of the
private corpus on the nvidia-rtx5080-laptop profile (no constants
supplied) grew 87 of the 15499 rows both builds translate and shrank
20: 83262314 words in all before the series, 84265507 after (+1.2%),
the largest growth 9546 -> 62171 words (6.5x) and 50185 -> 123245
(2.5x). Those loops' counters pick among a few cheap arms of a body
they run many times, so the copies add more than they decide away, and
the module is what the driver compiles. The fixture this item is for
still unrolls: `fold_loop_extract` specialized is 2296 words (the
baked form 2612). `engine/simd_divergent` `uniform_continue_k`, whose
38 golden cells the previous commit moved, now stays a loop and its
cells are as they were.

Not a speed-for-accuracy choice: either way the program computes the
same answers (unrolling copies every operation as it is), so
`docs/FAST-PATHS.md` has no row for it.

Tests: `canon::tests::unrolling` reworked: the switch's default arm is
80 operations, so copies taking the cheap arms are smaller than the
loop (unrolled, including at `TRIPS`), and copies taking the default
are larger (the loop stays, for supplied and for unsupplied lanes).

Verified: `cargo nextest run -p metal2vulkan-air -p metal2vulkan
--all-features -E 'package(metal2vulkan-air) |
test(/engine_arena|engine_specialized_folds|engine_simd_emulated|golden_hashes_match/)'`:
556 of 557 passed, golden_hashes failing only on the 380 new cells of
the fold fixtures (20 entries on 19 profiles) and no moved cell;
clippy on the crate with all targets and features.

(cherry picked from commit 8dc34fec499b1803bf13b0b1fe57ce1df8241f48)
(cherry picked from commit b1fe70ab5e41dbcf4d2879b7475b76aa1f5fc62c)
2026-11-03 00:45:19 -08:00
Anees Iqbal 568857fa6e Never fold an fcmp of a subnormal constant
What: `Folder::fcmp`, which SCCP and the static-initializer interpreter
use to fold `fcmp` of two constants, declines when either operand is
subnormal in its own format (half, bfloat, float, double): the
comparison stays in the module for the device. A NaN operand still
folds, answering by the predicate's order (ordered predicates false,
unordered true), which is exact.

Why (a rule-1 tightening): the fold is an exact IEEE comparison on the
host, but a device that flushes subnormals compares one as a zero of
its sign, so `1e-40 > 0` is true on the host and false there: the
answer is the device's. The unrolling of the previous commit widens
this fold's reach (a copy can hand it a float PHI's first-iteration
constant), so the existing rule is narrowed rather than left. Unrolled
copies fold no float arithmetic: SCCP folds none (fold.rs), and the
unroller's own exit evaluation evaluates no float operation or
comparison; only `fcmp` under this rule folds.

Tests: `canon::tests::float_compares` (normal operands fold exactly,
signed zeros equal; a NaN answers by its predicate's order; a subnormal
on either side, against zero or a normal, stays an `fcmp`; the least
normal still folds). Negative control: with the decline disabled,
`a_subnormal_operand_is_the_device_s_to_compare` fails.

Verified: `cargo nextest run -p metal2vulkan-air --all-features` (501
passed); clippy on the crate with all targets and features.

(cherry picked from commit 1fe73c062b2102400fbc7534a54184ca8a9212c9)
(cherry picked from commit c142a5c80c068cdf88df9a39dbacd011c4653e20)
2026-11-03 00:45:19 -08:00
Anees Iqbal a5e163422c Unroll the loops whose constant trip count decides a branch of their body
What: after SCCP (and the constant-field reads), canonicalization
unrolls each outermost loop whose exits the constants decide and whose
counter decides a branch or switch of its body (`canon::unroll`), then
runs SCCP again, which folds what each copy decides and deletes the
paths no copy takes; at most 4 rounds, so a nest is taken one level a
round. A loop qualifies when it is reducible with one preheader edge
and one back edge from its latch; it is left only from its header or
latch, each a conditional branch with one way out; its exits are
decided iteration by iteration by integer arithmetic, comparisons,
selects, element and member accesses and constant-global reads of its
header's PHIs and constants (no float operation or comparison is
evaluated); a non-exit branch or switch of its body tests a value
computed that way from its own or its nested loops' header PHIs; and
its latch carries no `llvm.loop.unroll.disable`. Each copy is the
loop's blocks with the header PHIs replaced by that iteration's
values; every instruction is copied as it is, with its flags; a value
used after the loop is the last iteration's.

Why: an uber shader that feeds a `uint4` of function-constant opcodes,
indexed by a 4x4 loop's counters, to a 16-case switch kept every case
of every iteration: 3952 words where the same shader with the
constants written in is 2612. Unrolled and folded it is 2296.

The ceilings are fixed: 64 iterations (`TRIPS`), 8192 instructions
over one loop's copies (`UNROLLED`), 32768 instructions added per
entry over all rounds (`GROWTH`), 4 rounds, 256 instructions evaluated
to decide one iteration's exits (`SLICE`). They are not a
speed-for-accuracy trade, so `docs/FAST-PATHS.md` has no row for them:
unrolling changes no operation and runs each the same number of
times, so a loop past a ceiling stays a loop and computes the same
answers. The ceilings bound only how large the copies grow, and so the
translation's time, memory and output size.

Rule 1: nothing new is evaluated on the host in float. The existing,
documented rule that SCCP folds `fcmp` of two constants (exact IEEE
comparison) is unchanged; a copy can give it new operands where a float
PHI's first iteration value is a constant.

Golden drift: `engine/simd_divergent` `uniform_continue_k` (its
`for (i < 8)` loop branches on `i & 1`) is unrolled, moving its 38
cells (`.ll` and `.air.ll` on 19 profiles); `engine_simd_emulated` runs
it on the CPU interpreter at every width and local size and its output
is unchanged. The table is re-blessed on `development`.

Tests: `canon::tests::unrolling` (six iterations over constant lanes
fold to straight-line code in order; past `TRIPS`, a run-time bound,
`unroll.disable` and run-time opcodes stay loops; at `TRIPS` it
unrolls; undefined lanes unroll to the default case).

Verified: `cargo nextest run -p metal2vulkan-air -p metal2vulkan
--all-features -E 'package(metal2vulkan-air) |
test(/engine_arena|engine_specialized_folds|engine_simd_emulated/)'`
553 passed; golden_hashes fails only on those 38 cells and the new
fixtures' rows; clippy on the workspace with all targets and features.

(cherry picked from commit a99e888de1d35e42de962b678c2f1c00f7383b22)
(cherry picked from commit c1ce0edbd491c3c8fd5ede8e331d5eb958c6bb25)
2026-11-03 00:45:19 -08:00
Anees Iqbal 702c733247 Read the integer fields of a never-written constant global as their constants in SCCP
What: SCCP folds a load of an integer, `bool`, integer-vector or
integer-aggregate field of a global that is in the constant address
space, marked `constant`, not externally initialized and has an
initializer (a program-scope `constant` whose static initializer the
specialization evaluated, or a literal one) to the initializer's value
at that field. A `getelementptr` with constant indices into such a
global is its address constant in the lattice (an interned GEP
constant expression); the instruction is kept and goes when nothing
uses it. So the loads through a `select` the function constants
decided, through by-value copies and through member and element paths
fold, and SCCP folds the selects, branches and switches they decide
and deletes the blocks no path reaches, before SPIR-V.

Why: an uber shader that collects its function constants into a
`constant` struct (`constant Config kConfig = {...}`) read every field
through memory, so a specialization kept every path of the shader: the
fixture added later in this series grows to 22895 words where the same
shader reading the constants directly is 1737.

How it is decided: by structure alone (the global's address space, its
`constant` flag, no external initialization, a constant initializer;
the constant space is read-only to entry functions and only the static
initializer writes it, and those stores are already folded), never by a
name. Rule 1: only integer leaves fold (`const_loads::integers_only`,
an iterative walk capped at 4096 members); a float field's load stays,
for the device to read. The existing rule that SCCP's whole-global load
folds any type (a float function constant included) is kept unchanged.

Tests: `canon::tests::constant_fields` (a struct of an i8 flag, two
`<4 x i8>` opcode vectors and a float, filled by a static initializer
and read through a function-constant `select`: each integer field
folds, the float load stays; the generic path and a run-time index stay
loads). Two existing tests read fields of closed constant globals that
now fold, so they read through byte GEPs instead (`engine_arena`), and
the deeply nested written global test reads with a volatile load to
keep its global.

Verified: `cargo nextest run -p metal2vulkan-air -p metal2vulkan
--all-features -E 'package(metal2vulkan-air) |
test(/engine_arena|engine_specialized_folds/)'`: 524 of 525 passed,
the failure the loop fixture this item does not cover (it needs the
unrolling of the next commit). Clippy on both crates, all targets and
features. The note-set diff, budgets and census of the series are in
the commit that adds the fixtures.

(cherry picked from commit d2d28d5bc7b1aee22e081eb65318e781d4569660)
(cherry picked from commit c39a2591179ab18cbd41b4279109d97190119a61)
2026-11-03 00:45:19 -08:00
Anees Iqbal 572ccac1be Evaluate a static initializer's integer conversions lane by lane
What: the static-initializer interpreter evaluates `air.convert` of an
integer or `bool` source to another integer or to `bool`, for a scalar
and for each lane of a vector, at every width and signedness:
zero- or sign-extended by the source's signedness (a `bool`
zero-extended), truncated, or `x != 0` to `bool`, as C++ converts.
`Folder::convert_int` does it; the existing scalar integer-to-float
conversion (rounded to nearest even) is unchanged and still the only
conversion to a float it evaluates.

Why: `constant uint4 kWide = uint4(kOps)` over a `uchar4` function
constant compiles to `air.convert.u.v4i32.u.v4i8` in the static
initializer, which the interpreter refused, so every pipeline over such
a configuration was `Unsupported{StaticInitializer}` (FALLBACK).

Rule 1: no float arithmetic or float conversion is added. A vector
converted to floats is still not evaluated and its initializer is still
refused as before (`a_vector_converted_to_floats_is_not_evaluated`);
the scalar integer-to-float rule (an MSL constant expression the
pipeline build evaluates once) is kept as it was.

Verified: `cargo nextest run -p metal2vulkan-air --all-features` (492
passed, new `canon::tests::conversions`: u.v4i32.u.v4i8, s.v4i32.s.v4i8,
u.v2i8.u.v2i32, u.v4i1.u.v4i8, u.i32.s.i8, f.f32.s.i8, and the vector
float refusal); clippy on the crate with all targets and features.

(cherry picked from commit 3c04fb47b2a826229d299ea57d23956e2ed0cc23)
(cherry picked from commit 8f71dfd76357c5bf5a1632239782bdcd41683078)
2026-11-03 00:45:19 -08:00
Anees Iqbal 58bd181a01 Reset priming's descriptor pool through a helper of its own, outside the objects' unsafe block
The previous commit's reset release was a closure made inside Primer::objects' unsafe block, so
its own unsafe block warned as unnecessary (an error under -D warnings). Primer::hold_reset holds
the reset as Primer::hold holds a release, with its own unsafe block and safety comment. Same
order and calls.

Verified: cargo clippy -p metal2vulkan-runtime --all-targets --all-features -D warnings, plain
and --cfg m2v_gpu, clean.

(cherry picked from commit 81d1caeb4cc6a30b7efe81c12b091929882c2e52)
(cherry picked from commit bd3f40febe4fa44f712e7924a9096886904698c3)
2026-11-03 00:45:18 -08:00
Anees Iqbal 5b6523d296 Prime and list vkResetDescriptorPool in the exit guard's table: a predicated loop's run again resets its arena in a section
A predicated loop that runs past its copies settles each run again inside a section of the exit
guard (command_buffer/rerun.rs RunArenas::settle), where DescriptorArena::reset calls
vkResetDescriptorPool. Inside a section the device's functions are the exit guard's table alone
(device/functions.rs loads the sectioned ash::Device with Call::ALL's names and null for the
rest), and the table had no vkResetDescriptorPool, so in builds with debug assertions the call
reached ash's "Unable to load reset_descriptor_pool" stub, whose panic cannot unwind out of an
extern "system" fn: the process aborted (validation runtime_lane::predication::
every_dispatch_form_runs_in_each_pass_past_the_copies, SIGABRT on the M3 Max through MoltenVK).
In release builds the full table answered, but the call was a section's first call of an entry
point no priming made, which the guard's exit-hook ordering relies on priming to make.

- exit_guard.rs: ResetDescriptorPool => vkResetDescriptorPool in the table (128 entries, the
  u128 word's last bit).
- device/prime.rs: priming resets its descriptor pool before releasing it, after the command
  pool whose never-submitted command buffer bound the pool's set (a release pushed after the
  pool's, popped first), so the priming check covers the new entry.
- tests/rerun_arenas.rs: the lent arena's reset runs inside a section, as the settle does.

Verified on the M3 Max (MoltenVK 1.4.2, macOS 27.0.1), --cfg m2v_gpu, through maclock:
- Negative control: the strengthened rerun_arenas test against the old exit_guard.rs and
  prime.rs aborts with "Unable to load reset_descriptor_pool" (SIGABRT); with the fix it passes.
- metal2vulkan-runtime tests::exit_guard 38/38 (the priming check and the table's tests) and
  tests::rerun_arenas 2/2; validation runtime_lane::predication 18/18, the crashing test
  included (17.3 s).

No notes or announcements change.

(cherry picked from commit f21836dcfc75c53d0eb454c90230be0997595793)
(cherry picked from commit f19b9e9ebd494d86a41c0a34fda493c080037b8f)
2026-11-03 00:45:18 -08:00
Anees Iqbal 5f04c4f4d6 Pin the runtime sources after new textures' pattern reads move to the commit
What: crates/metal2vulkan-validation/runtime-sources.sha256 recomputed on this tree
(pin-compute.py: listed=58 inputs=495, 57f7e1cd...). The pinned inputs this branch changed are
the runtime's fresh_unwritten.rs, command_buffer/mod.rs, encoder.rs, render.rs, render_pass.rs,
blit_texture.rs and degradation.rs, and the translator's cache/mod.rs (RUNTIME_VERSION 1740): a
command buffer logs its reads and writes of noted new textures and its commit replays them in
commit order; the behaviour change is the bump before this commit.

(cherry picked from commit 62d77ba3997d18d5ee0d42ea6c717fd0d23b2960)
2026-11-02 23:52:36 -08:00
Anees Iqbal 12209539d3 Bump RUNTIME_VERSION to 1740: new textures' pattern reads taken at the commit
A run of an unchanged artifact and plan may now announce fresh-pattern-zeroed, device-nan-encoding
(a new texture's converted NaNs) and signed-depth-test at another time than before: a command
buffer logs its commands' reads and writes of noted new textures as encoded, and its commit
replays the log against the device's record (fresh_unwritten.rs's FreshLog and commit), so the
notices follow Metal's commit order rather than the order command buffers were encoded on several
threads. 1740 is the number this change was given (1739 is compute-bind's).

(cherry picked from commit 6ab1f0cda2216dda0906d7a412bad844e46533f3)
2026-11-02 23:52:36 -08:00
Anees Iqbal 0e3ee39e02 Test one queue's command buffers encoded on several threads and committed in order
What: parity::sequences::parallel runs sequences with every command buffer on one queue,
serially and in parallel on 2, 4 and 8 threads, 12 runs each way on a device of each's own, and
requires every run's bytes to be the CPU model's, no layer message, and the same notice kinds
both ways. The schedules (seeded, printed with a failure): Reversed (each command buffer encoded
only once the one committed after it was encoded whole, on another thread), Lockstep (one
encoding call per thread in turn) and Spread (random assignment, order and pauses); command
buffers made in order, in reverse or on the workers; committed after all were encoded or each as
soon as it and the earlier ones were. The sequences: a chain written for it (read-after-write and
write-after-read across consecutive command buffers through tracked buffers and a tracked
texture, blits, serial and concurrent compute and render passes, an accumulator each command
buffer folds into with seq_mix, and an untracked buffer ordered across command buffers by a
fence alone), and four generated seeds merged onto one queue (heaps, untracked resources under
events and fences, views, indirect commands), race-free by order::problems. A runner of its own:
the sequences' Metal records fingerprint run.rs and api.rs, which stay as they were.

runtime_lane::framebuffer_fetch::storage_forms gains
a_target_fetched_beside_an_encoding_command_buffer_keeps_its_answers: each frame fetches the
target in one command buffer while the next, made before the first commits, is encoded on
another thread (a second fetching pass and a copy out); every frame's copy holds 2^-2(f+1), the
form is taken once by a lone pass at the end, and the kinds equal the serial run's.

Why: the consumer's host is about to encode one queue's command buffers on several threads and
commit them in a fixed order; nothing covered it.

Verified on the M3 Max (MoltenVK 1.4.2) under --cfg m2v_gpu: all seven pass (notices
{FastMathRewrites} both ways; the storage form taken at frame 0 both ways).

(cherry picked from commit 7305ce0d7fb9505d795a5cae3250b350b5e4b253)
2026-11-02 23:52:36 -08:00
Anees Iqbal 48ec97832d Take new textures' pattern reads at the commit, in commit order, not as encoded
What: a command buffer now logs its commands' reads and writes of noted new textures
(`fresh_unwritten.rs`'s FreshLog: pass loads, clears, resolves, blit writes and reads, shader
reads, and a pass's load of a signed-depth pattern) in encode order, and its commit replays the
log against the device's record under one lock, before the scheduler sees it, announcing
`fresh-pattern-zeroed`, `device-nan-encoding` (a fresh texture's converted NaNs) and
`signed-depth-test` (a loaded signed-NaN depth pattern) there. A command buffer dropped
uncommitted takes nothing; a refused commit's log is discarded. With no noted texture a command
reads one flag and logs nothing, and a commit reads it once.

Why: the record followed encode order, so a queue's command buffers encoded out of commit order
(the consumer's host encodes one queue on several threads, then commits in order) announced a
read Metal never makes (a load after a committed-earlier clear, encoded first: a precision note
the consumer makes fatal) and missed one it makes (a load before a committed-later clear, encoded
after it: the texture read zero where Metal reads its pattern, unannounced). Metal runs a queue's
command buffers in commit order.

Tests: runtime_lane::parallel_encodes::a_fresh_texture_s_pattern_notice_follows_the_commit_order
runs two command buffers of depth-only passes (4-sample and single-sample Depth32Float,
clear-then-load and load-then-clear) serially and with the later-committed one encoded whole
first on another thread, and requires the same notices both ways and Metal's reads of the
pattern. Before the fix it failed on the M3 Max (MoltenVK 1.4.2): 1 notice instead of 0, and 0
instead of 1. The same module's a_shadowed_texture_keeps_each_command_buffer_s_bytes (a texture
over a Private buffer at 48-byte rows, eight command buffers on four threads) checks every
copy and read against its own command buffer's words and prints the copies in.

Docs: fresh_unwritten.rs's Observed and Order bullets, the FreshPatternZeroed and SignedDepthTest
declarations, docs/API.md's catalogue entries.

Verified on the M3 Max under --cfg m2v_gpu: the new test passes; so do runtime_lane's
fresh_writes, fresh_contents, depth_denormals, degrade_notices, made_at_creation, texture_blits,
renders, sample_copies, nan_resolves, buffer_depth_samples, compressed_blits, color_fills,
color_writes, cross_class_storage and half_* modules, and the runtime's tests::fresh_unwritten
and tests::heap_tiled (118 tests); degradation_catalogue passes. clippy -D warnings clean for the
runtime crate (plain).

(cherry picked from commit 95d7bdf6dc8c6e411114b2d9a8203ea1e4970168)
2026-11-02 23:52:36 -08:00
Anees Iqbal 87cdea9b49 Pin the runtime sources after the draws again and the lock-free settles
What: crates/metal2vulkan-validation/runtime-sources.sha256 recomputed on this tree
(pin-compute.py: listed=58 inputs=495, c72f9d50...). The pinned inputs this branch changed are
the runtime's render.rs, render/draw_again.rs (new), render/{bound,executions,executions/gpu,
pass_start_reads,replay,shadows}.rs, clear_reach.rs, degradation.rs, device/mod.rs, encoder.rs,
function_table.rs, linear_attachment.rs, live_bind.rs, noted_apart.rs, pipeline/{mod,objects,
render}.rs, retained.rs and work_counts.rs, and the translator's cache/mod.rs (RUNTIME_VERSION
1738): a draw that repeats its encoder's last one records its Vulkan draw alone, and a draw of a
kept shape settles without the pipeline state's, the function-table registry's or the quiet
formats' locks; the behaviour change is the bump before this commit.

(cherry picked from commit d3e66f94158a10306f366b854093c9dcb338292a)
2026-11-02 23:03:19 -08:00
Anees Iqbal a8df685eb5 Bump RUNTIME_VERSION to 1738: draws again, and settles without the shared locks
A run of an unchanged artifact and plan may now record other commands' timing and take other
locks than before. A render encoder's direct draw that repeats its last one, with no call between,
records its Vulkan draw command alone (render/draw_again.rs; WorkCounts::draws_as_before): the
same commands, barriers, notices and retains as the draw taking every step, but its uses noted,
its pass's reads and its instance's gathered uses added once rather than again (Written::add skips
a range it holds). A draw of a kept shape settles as its bind state's last recorded draw did, a
state that made no visible-function table lists none without the device's registry, and a variant
that tests no slot's format answers its quiet formats without its lock: the same answers, taken
without the locks other threads' draws share. 1738 is the number this change was given (1737 is
submit-path's).

(cherry picked from commit d8e43c1c650b9847e7d9d33cb0e1aa454f28fb6e)
2026-11-02 23:03:18 -08:00
Anees Iqbal 057a44d028 Take no shared lock at a draw of a kept shape: the encoder keeps its state's settle; tables and quiet formats told lock-free
Three locks every full draw took of objects draws on other threads share:

- GraphicsState::settle_shape's per-program cache. Each bind state of an encoder's LiveBind
  (the one in place and each set aside) now keeps what its last recorded draw settled
  (live_bind.rs SettledHere: the variant and plan, the program named by a Weak, the buffer
  forms). A draw of the same program in the same forms whose shape is the kept one (the very
  Arc) settles as it, with no lock: settle_shape's answer is a function of the shape and the
  forms alone. Only a draw that recorded keeps it, so the encoder holds its pipeline state and
  the command buffer the variant's objects; SpareLiveBinds::give empties every kept settle as
  the encoder ends, so a spare state holds nothing alive. A refused settle keeps nothing.
- GraphicsState::function_tables locked the device's function-table registry. A program now
  notes, once, that it made a visible function table (Program::made_tables, set as the table
  is registered); a state that never made one lists none without the registry.
- VariantObjects::degrade_bound_formats locked quiet_formats. A variant that tests no slot's
  format keeps its quiet answer in an AtomicBool (quiet_untested); one that tests slots still
  locks.

What remains on a full draw's path: Arc clones and drops of shared objects (the settled
variant, plan and shape on a kept settle, the shape a pipeline state's cache found, the
DeviceShared, the retained pipeline state and variant objects), the LiveBind mutex (per
encoder, uncontended), and quiet_formats for variants that test slots. A draw again
(render/draw_again.rs) takes none of them.

Test: src/tests/shared_draw_locks.rs counts, in builds with debug assertions, every lock taken
through device::shared_draw_lock (the three sites) on the encoding thread: an encoder's first
draw takes some; 8 later draws of the same shape, each after a call (so each takes every
step), take none. Negative controls, each fix disabled alone: 8 locks each time (verified on
MoltenVK, M3 Max).

host_ab encode, release, 10k draws per command buffer, us/draw, three interleaved rounds
(median of round medians / mean / max of round p90s), Apple M3 Max, MoltenVK 1.4.2, one thread:
  static   0.049 / 0.049 / 0.056  ->  0.049 / 0.049 / 0.054
  offset   1.525 / 1.530 / 1.593  ->  1.498 / 1.498 / 1.538
  bind     1.724 / 1.725 / 1.765  ->  1.703 / 1.704 / 1.741

The same on the NVIDIA RTX 5080 Laptop GPU (Linux), one thread; round 1 of each clean, round 2
of the lock fix perturbed (its p50 2.3 times its p10, other load on the host), round 3 pending:
  static   0.054 / 0.056 / 0.069  ->  0.053 (r1), 0.060 (r2)
  offset   2.071 / 2.128 / 3.519  ->  2.010 (r1), 4.721 (r2; p10 2.013)
  bind     2.191 / 2.225 / 3.899  ->  2.139 (r1), 5.384 (r2; p10 2.155)
(left: the draw-again commit alone, three rounds). One thread takes no contended lock either way,
so a change within noise is what one thread shows; the fix is for draws on several threads at
once, whose numbers on both hosts come with the report.

(cherry picked from commit 6f157d8498632a8850795b5ed6fc97d7433c4c95)
2026-11-02 23:03:18 -08:00
Anees Iqbal db2bdfbe95 Draw an encoder's last direct draw again: a draw that repeats it with no call between records its Vulkan draw alone
A render encoder keeps its last plain direct draw (render/draw_again.rs): the call, what it
assembled, its draw and in-place index source, what it read of the state that changes with no
call of the encoder (no-copy moves, residency generation, host aliases, the parts and holds its
noting reads), its command buffer and its Vulkan draw command. Every call but the two direct
draws forgets it as it logs itself, refused or not. A draw that matches it records the kept
vkCmdDraw* alone, notes its uses' reads of fresh textures, keeps itself for recording again,
adds its execution record where the device keeps them, and counts itself in encoder-local
counts that reach the device's at the next call, the pass's end or an error
(WorkCounts::draws_as_before, new). Only a draw that recorded one Vulkan draw into its
instance as it stood, through a pipeline made ahead, with no barrier, write, split, shadow,
snapshot, rewrite pass, set 1, root table or push hole, and no notice announced at every
occurrence, is kept.

Exact: the same Vulkan commands and barriers, the same notices, retains and refusals. A draw
again repeats only steps whose answer is provably the kept draw's; the rest are idempotent
(the drawn area, coverage, gathered uses, noted uses, retains); PassStartReads' Written::add now
skips an equal range already held, so a repeated read adds nothing. In builds with debug
assertions the first draw again of a kept draw and every second after it take every step and
assert they announced nothing, recorded no state command, kept an equal draw, retained only the
index buffer again, and left drawn area, coverage, reads, gathered uses, noted uses and the
instance as they were.

Tests: src/tests/draw_again.rs (5 device tests: draws again record the commands, barriers and
pixels the same draws record with a do-nothing call between; indexed draws of the same indices;
other draws take every step (base instance, indirect, a fragment-write draw); a draw after a
no-copy buffer moved takes every step; a notice announced at each occurrence is announced at
every draw). draw_shape_notices and the draw_work lane count draws_as_before beside
draw_shapes_reused. Runtime GPU suite on MoltenVK (M3 Max) passes, the cross-check on.

host_ab encode, release, 10k draws per command buffer, 200 timed, us/draw, three interleaved
rounds: median of round medians / mean of round medians / max of round p90s.

Apple M3 Max, MoltenVK 1.4.2:
  static   1.260 / 1.251 / 1.290  ->  0.042 / 0.042 / 0.047
  offset   1.464 / 1.455 / 1.521  ->  1.493 / 1.480 / 1.545
  bind     1.645 / 1.647 / 1.713  ->  1.693 / 1.687 / 1.742

The offset and bind draws take every step and pay the keep (+29 and +48 ns on the M3). The
RTX 5080 rounds follow in the next commit's message.

(cherry picked from commit 8e6b49b8c371ec2e3c2aa6031a3a09145997cd2e)
2026-11-02 23:03:18 -08:00
Anees Iqbal 5bf9843569 host_ab: offset-only draws, and draws on 1 to 8 threads at once
The encode workload gains `draw_offset`: one vertex buffer's offset changes before each draw
(`setVertexBufferOffset:atIndex:`), the consumer's measured per-draw shape, between `static`
(nothing changes) and `bind` (buffer and texture change).

A `threads` workload draws the encode workload's static and offset draws on 1, 2, 4 and 8
threads at once, each through a command queue of its own (`Gpu::with_own_queue`) into its own
target, of its own rectangles, texture and sampler, once through one shared pipeline state and once
through a pipeline state of each thread's own. Per case, over 3 runs: the draws a second of all
threads together, each thread's CPU time per draw and the process's. The trait's device, libraries
and render pipeline states are `Sync` for it (Metal's are; Metal's buffers and textures are not
marked so in objc2-metal, which is why each thread makes its own).

Verified: clippy -D warnings on the example (both sides compile on macOS); `draw_offset` ran on
the M3 Max and the RTX 5080 Laptop (numbers in the next commit).

(cherry picked from commit 5ae9a2d98135b7129b0f44b4ab2b98982f2588d7)
2026-11-02 23:03:17 -08:00
Anees Iqbal 0491eb2c75 Pin the runtime sources after the submit and completion path's changes
What: crates/metal2vulkan-validation/runtime-sources.sha256 recomputed on this tree
(pin-compute.py: listed=58 inputs=494, 5045f87b...). The pinned inputs this branch changed are
the runtime's command_buffer/{mod,own,completion,submit}.rs, contexts/mod.rs, scheduler/mod.rs,
exit_guard.rs, error.rs, texture/first_move.rs, work_counts.rs and the translator's
cache/mod.rs (RUNTIME_VERSION 1737): the completion-seen handlers, command buffers that need no
GPU work taken with no submission, and idle waiters and scheduler sleeping untimed; the
behaviour change is the bump before this commit.

Verified: candidate::engine::artifact::tests::the_runtime_sources_are_the_committed_ones passes
on this tree.

(cherry picked from commit c87df4e91ae16916c369e753af103d458bf76cb2)
2026-11-02 22:30:23 -08:00
Anees Iqbal 3820cb43ed Bump RUNTIME_VERSION to 1737: the submit and completion path's changes
A run of an unchanged artifact and plan may now do something else in what it submits and where
its handlers run: a command buffer with a completion-seen handler (a new runtime extension) runs
it on the thread that saw its completion; a command buffer that needs no GPU work (nothing
recorded, no event or semaphore waits or signals, no first work waiting) is taken with no
vkQueueSubmit and completes in its queue's order, finished by the thread that took it where its
queue has nothing in flight; idle queue waiters and an idle scheduler sleep with no timeout.
1737 is the number this change was given (1735 and 1736 are other lanes').

(cherry picked from commit ab4390d60cb275e6fe7ce48d5f05a890d83145c3)
2026-11-02 22:30:23 -08:00
Anees Iqbal d5c71b9848 Add the submit_path example: a command buffer's fixed cost on the submit and completion path
What: crates/metal2vulkan-runtime/examples/submit_path.rs, registered in the crate's manifest
(autoexamples is off). Modes: latency (one thread commits a 16-byte fill with a scheduled and a
completed handler, or with --seen a completion-seen handler instead, and blocks on a condition
variable the handler signals: commit to handler start at idle gaps of 0, 100 us, 300 us and 2
ms, p50/p90/p99 over 2000), cpu (the same command buffers as fast as the slots allow, never
waited for: command buffers a second and CPU per command buffer by thread group, from
/proc/self/task/*/schedstat on Linux, else the process's CPU less the committer's), empty
(commit and wait of a command buffer with nothing encoded, back to back and at a 300 us gap;
then never waited for, with the queue submissions made).

Why: the consumer's per-command-buffer path (record, add handlers, commit, never wait) had no
measurement in the tree that runs on both the M3 Max and Linux; host_ab is being changed
elsewhere.

Verified: built in release on the M3 Max and run there (the numbers are in the change reports,
not here); clippy clean with all targets.

(cherry picked from commit 067b6a7792210909bbf4f1e66bf2eb9b39334c0d)
2026-11-02 22:30:23 -08:00
Anees Iqbal ede69fae31 Let idle queue waiters and an idle scheduler sleep until they are woken
What: a queue's waiter parked with no batch of its queue pending now sleeps on its condition
variable with no timeout (completion.rs `wait`); parked with a batch pending (left to a turn
under way, held by a drain, a failure pending) it keeps the 100 ms slice. The scheduler's thread
sleeps with no timeout where its order and group hold nothing, no head has a bound and no
driver's stall is due; otherwise it keeps its slice. The GPU waits (fence and timeline, in
`poll`/`settle`), a drain's wait and rerun.rs's fence waits keep their slices. New WorkCounts:
completion_waiter_parks and completion_waiter_parks_timed_out (reported, not gated, in the
conformance cost half: when a thread sleeps).

Why: an idle device's five waiter and scheduler threads each woke every 100 ms (on the M3 Max
over 350 ms idle: 15 waiter parks that timed out, 3 scheduler slices), which is CPU and wakeups
for nothing on a consumer's idle guest, and the slice hid any missed notify behind a 100 ms
stall.

Audit: every change a parked waiter waits for, each made under `pending`'s lock and notifying
where `Pending::parked` says it sleeps, or every waiter:
- Completion:⌚ a batch pushed on its queue; notifies that queue's waiter where parked.
- Completion::watch_unsubmitted: as watch, except where the batch owes its turn to the taker
  (queue reached, no turn, no hold, no failure, not exiting): then the taker's turn_owed makes
  the turn, or the turn under way takes it at its next look, or another taker's turn took it.
- turns(): a look that takes a queue's batches notifies its waiter where parked and its queue
  still holds a batch, or the waiters stop (a parked waiter with an empty queue has nothing to
  arm for; the next watch wakes it).
- take_pending (a failure's drain): wake_all after giving the batches back.
- Completion::stop: stopping set, wake_all.
- exit() and a waiter that found the process exiting in its wait: exiting set, wake_all.
- A waiter's failed wait sets `failed` and wakes no one: the turn it or the turn under way makes
  takes it as Turn::Failed, which ends in take_pending's wake_all.
- `reached` and `waiting` change only for the waiter's own queue, by that waiter.
The scheduler: a commit (Inbox::post marks the state under its lock, or leaves it to a counted
passer, whose look_again or passed_over wake covers it), a host signal (Scheduler::waker,
decode_finished, wake_for), and stop (stopping under the lock, then notify_all) each notify the
thread where it sleeps; completions matter only with a head held, where the slice is kept.

Tests (--cfg m2v_gpu, M3 Max, MoltenVK 1.4.2): tests::completion_wakes::
an_idle_device_s_waiters_and_scheduler_stay_asleep (0 parks, 0 timed out, 0 scheduler sleeps
or slices over 350 ms idle; with the waits kept timed: 15 and 15, 3 and 3, fails) and
with_parks_unbounded_every_change_still_wakes_its_waiter (a test-only switch makes every park
untimed, pending batch or not; three queues of fills with handlers, empty command buffers alone
and behind fills, a head held for a host signal, idle gaps, then the device's drop on a bounded
wait: passes; with Completion::watch's notify removed it stalls at round 0's held command
buffer and fails at its 20 s bound). The whole runtime GPU suite 1509 of 1509; the conformance
crate's tests 1010 of 1010; clippy clean in both configurations.

(cherry picked from commit ac3a8ff8de6e780e0c7233340dcc2b0ac95c0b5d)
2026-11-02 22:30:22 -08:00
Anees Iqbal 53e2a6be78 Complete a command buffer that needs no GPU work without submitting it
What: a command buffer whose encoders recorded nothing and whose one batch waits for and signals
no event and no binary semaphore (so presents no drawable) is taken by the scheduler with no
vkQueueSubmit (State::needs_no_gpu, decided from what it recorded), once it leads its logical
queue's line, no group is held and no first work of the device's waits (that still rides in it,
as before). Everything else its last batch's taking does is kept: kernel times, scheduling (by a
hang's thread where one makes it), submission handlers, heap tickets, own textures, holds. Its
batch is watched at its VkQueue's last submitted value (Completion::watch_unsubmitted), so it
completes in its queue's order, after the work submitted before it, from the turn that finishes
that work. Where its queue reached that value already and no turn is under way, no waiter is
woken: the thread that took it (the scheduler's after its round's submission handlers, or a
thread about to block, after its pass) makes the turn once it holds no lock
(Completion::turn_owed), running only the transitions a thread there may run. A turn no longer
wakes a parked waiter whose queue it emptied (it has nothing to arm for; the next watch or a stop
wakes it). New WorkCounts: command_buffers_unsubmitted, completion_turns_where_taken. GPU-time
placement is unchanged (NoWork: a point at the later of its kernel end and its queue's latest
end), which the new conformance case shows matches Metal's booleans.

Why: the consumer commits empty command buffers as sync points; each was a vkQueueSubmit, a
waiter wake and a turn. Metal completes them without its GPU (M3 Max, macOS 27.0.1: idle, commit
and wait 15 us p50, GPU interval 0 to 0.3 us, 1 to 9 us after kernelEndTime; behind a fill,
after the fill, 65 to 135 us after its GPUEndTime).

Conformance: new case empty-command-buffers (statuses in handlers and after the wait, the four
timers' signs and orders, GPU interval one point, behind a 64 MiB fill: completed-handler order,
the fill's status in the empty one's handler, kernel and GPU times against the fill's), recorded
on the M3 Max (5 of 5 runs identical), cost and contrast and times written; replayed on the M3
Max over MoltenVK: announced (only gpu-times-from-host, declared). completion_turns_where_taken
is reported, not gated (which thread made the turn is a race with the GPU); the M2 handler
counters are classified with the submission region. Coverage doc regenerated.

The lane test empty_command_buffers_submit_no_command_buffer becomes
empty_command_buffers_make_no_submission (0 submissions, 8 unsubmitted).

Verified on the M3 Max (MoltenVK 1.4.2), --cfg m2v_gpu: tests::unsubmitted (3 tests; idle: 81
unsubmitted, 0 queue submissions, 40 of 40 waited ones finished by the taker, 0 waiter wakes);
negative control with the path disabled: 0 unsubmitted, 81 submissions, 40 waiter wakes, both
empty tests fail. The whole runtime GPU suite: 1506 of 1507, the one failure
video_interop::a_raw_submission_is_ordered_by_a_shared_event_s_semaphore read its event's
signal already Reached under the full suite's load, and passed 6 of 6 alone (its command buffers
wait and signal, so never take this path). The conformance crate's tests 1010 of 1010; clippy
(workspace, all targets and features; and runtime + validation under --cfg m2v_gpu) clean.
Not run here: the validation lane tests (commit_work, first_use, gpu_times) and lavapipe.
Owed on development: conformance cost bounds of cases with empty command buffers now read fewer
queue_submissions and a nonzero command_buffers_unsubmitted (a re-bless).

(cherry picked from commit 304bdd2a24e31f7aeb3045e33b9d21209ca7df97)
2026-11-02 22:30:22 -08:00
Anees Iqbal fd7c93af53 Run a command buffer's completion-seen handlers where its completion is seen
What: `CommandBuffer::add_completion_seen_handler`, a runtime extension with no Metal
counterpart. Its handlers run as the command buffer's transition to `Completed` or `Error`
runs, right after its status, error and GPU times are final, before its completed handlers
and before `wait_until_completed` returns. A transition with completion-seen handlers and no
completed handler runs where seen (`Transition::where_seen`, `Run::runs_where_seen`), on the
queue's waiter, as a plain one does: no handler-pool turn. Where the transition is posted (a
completed handler, an earlier transition of the queue in its context, a deallocator of the
program's held), the handlers run in it on the handler thread, so they keep the queue's commit
order against every completed handler. A wait in one for what has not happened is refused
with the new `DeadlockCause::CompletionSeenHandler`, as a submission handler's is, wherever it
runs. `Contexts::run_here` takes the predicate its caller may run: the waiters and the
scheduler (`exit_guard::serving_completion`) run where-seen items, any other thread plain
ones only.

Why: the consumer's per-command-buffer completion pays a handler-pool wake after the waiter
(about 100 us from an idle CPU on the RTX 5080 laptop, and its p90 tail). Its completed
handler is short and posts a record; moved into a completion-seen handler, the command buffer
finishes on the waiter with one wake fewer.

Order choice: the handler runs inside its transition, never ahead of it, so a command buffer's
completion-seen handler cannot run before an earlier command buffer's completed handler on the
same queue's context; it runs at the turn only where that context holds nothing else.

Counted: `WorkCounts::completion_seen_handlers_run` and
`completion_seen_handlers_where_seen`.

Verified (M3 Max, MoltenVK, under the GPU lock): `tests::completion_here` (the new
`a_completion_seen_handler_runs_where_the_completion_is_seen`: 20 of 20 ran on
`metal2vulkan-queue-wait-*`, status `Completed`, GPU end positive, own completion wait refused,
own scheduling wait returned; with a completed handler 0 of 20 where seen, each before the
completed handler), `tests::own`, `tests::contexts` (the new where-seen run_here test): 24
passed. Negative control: with completion-seen handlers making the transition not where-seen,
the new test fails (0 of 20). Workspace clippy (all targets, all features) and runtime clippy
under `--cfg m2v_gpu` clean. api_signatures blessed, docs/REFUSALS.md regenerated.

(cherry picked from commit bb7fd805045a9903a3a1ae06595e264ad771049c)
2026-11-02 22:30:22 -08:00
Anees Iqbal a5e4bd1aca Pin the runtime sources after moving decoded-texel-precision to the twin's first read
What: crates/metal2vulkan-validation/runtime-sources.sha256 recomputed on this tree
(pin-compute.py, 9cced23b...). The pinned inputs this branch changed are the runtime's
texture.rs, texture/decoded_twin.rs, heap_sets.rs, degradation.rs and chroma_pairs.rs: the
announcement of decoded-texel-precision moved from a decoded twin's making to its first read,
which a run of an unchanged artifact and plan observes, so RUNTIME_VERSION is 1734 (8c84951a7e).
Its message's "(1732 and 1733 are other lanes')" is an assumption, not checked: 1734 is the
number the orchestrator gave. SEMANTICS_VERSION stays 1949: no translator output changed.

Checks on this branch (M3 Max, macOS 27.0.1, MoltenVK 1.4.2; Rust 1.98):
- cargo fmt; clippy -D warnings with --all-features and with RUSTFLAGS='--cfg m2v_gpu': clean.
- Private intra-doc links 0 / 3 / 70 / 0 / 0 / 0 (at the ceilings); api-signatures --check;
  the refusal surface regenerates unchanged.
- core nextest (metal2vulkan, air, runtime, devtools): 5,007 passed, 23 skipped.
  Conformance: 1,007 passed. The runtime guard
  (the_runtime_sources_are_the_committed_ones) passes with this pin.
- The runtime's suite with --cfg m2v_gpu on MoltenVK: 1,502 passed, 3 skipped (twin_reads' three
  tests among them).
- Lanes on MoltenVK (texture_fills, texture_blits, degrade_notices, chroma_pairs, astc, etc,
  pvrtc, compressed, format_footprints, ycbcr, two_plane_samples): 116 run, 114 passed. The two
  failures, two_plane_samples_are_metal_s (6 of 8 cases differ from Metal) and
  a_ycbcr_sample_through_an_unmeasured_filter_is_announced (no ycbcr-filter-not-exact for an
  anisotropic constexpr sample), fail identically on 57b3b26ba0: not this branch's.
- Conformance replay on MoltenVK of texture-fills-240/241, chroma-pair-copies-*,
  chroma-pair-texel-reads-*, chroma-pair-texel-samples-*, texture-pairs-usage-crossings and
  format-footprints-astc-4x2-and-8x4: 9 announced (justified), 1 exact;
  decoded-texel-precision fired in the four texel read and sample rows alone.

(cherry picked from commit 17a1c34c1c45b62e99b07b5ba19558a4f32bbee4)
2026-11-02 17:43:39 -08:00
Anees Iqbal 07b2c5574a Bump RUNTIME_VERSION to 1734: decoded-texel-precision moved to the twin's first read
A run of an unchanged artifact and plan now announces decoded-texel-precision at a command's first
read of a decoded twin (a sampled binding, a heap set holding the twin, or its placement in a set
a pending command buffer bound) instead of where the texture is made: a run that makes, writes,
fills or copies such a texture and reads no twin announces it no more. 1734 is the number this
change was given (1732 and 1733 are other lanes').

(cherry picked from commit 8c84951a7e98d20ccd04c523619309dd4f0d487b)
2026-11-02 17:43:39 -08:00
Anees Iqbal 91cdb80938 Say what a YCbCr twin's half sample through a runtime sampler slot rounds to: measured toward zero
What: PrecisionNote::HalfTexelConversion's doc, its docs/API.md catalogue entry, docs/FAST-PATHS.md's
texel-conversion row and the comment where select.rs records the note said a two-plane YCbCr
texture on the grid 8192, sampled through a runtime sampler slot whose word reads one texel,
rounds that texel's step to nearest even. It is the device's rounding of the step's float, and
on MoltenVK 1.4.2 over the Apple M3 Max that is toward zero: runtime_lane::ycbcr_textures'
srgb_twins_read_what_metal_reads measured 8,409 channels of the _sRGB twins over six surfaces and
three matrices, each within one half ulp of Metal's ties-away step (lane commit 196bdf8135). The
docs now say so, and that other Apple GPUs are unmeasured. FAST-PATHS' row had said the field keeps
Metal's ties away in every one-texel sample; it now names the runtime sampler slot's exception.

Docs only: no behaviour, translation or recorded output changes.

(cherry picked from commit 0cb807cc9d0af60d7ceebbbd536d396ab43e3a00)
2026-11-02 17:43:39 -08:00
Anees Iqbal 4837c93ca4 Announce decoded-texel-precision at the decoded twin's first read, not at its texture's making
What: a decoded twin whose texels are not Metal's decode exactly (an ASTC LDR form's 8-bit codes,
an EAC 11-bit format's 16-bit codes, a 4:2:2 texture's device conversion) announced
decoded-texel-precision where its texture was made, though only a sampled view reads the twin:
copies, blits, fills and CPU accesses move the carrier's blocks. A consumer that makes notes fatal
died on a test that only fills a BGRG422 texture and on one that checks the runtime's fills.

How: the twin carries what a read of it announces (TwinRead, made with the twin and with an ASTC
carrier's second twin). It is announced, once per device, where a command may first read it:
- Texture::bound_view, a command's sampled binding of the texture or a view of it: the set-0 slot
  path (slot_view, draws, dispatches, tile dispatches) and a heap entry a command names
  (binding.rs);
- heap_sets::bind, the first command that binds a heap set holding the twin's view, named or not
  (each set keeps its twins by resource ID beside its shadows);
- a twin's placement into a heap set whose shared version a command buffer that bound it and has
  not completed still holds, or whose own version an uncommitted command buffer bound
  (SetEntry::twin), announced once whatever announce_each says, as a submission may place it on a
  runtime thread.
Placing the view in a heap set uses Texture::held_view, which announces nothing.
carried-decoded-twin (performance) is still announced where the texture is made.

Docs: degradation.rs's contract, docs/API.md's catalogue entry and docs/FAST-PATHS.md's ASTC and
4:2:2 rows say where it is announced; texture/decoded_twin.rs's and heap_sets.rs's module docs gain
the reads. Lanes: texture_fills and texture_blits' mipmaps no longer expect the note at making
(twins_carried keeps its carried half alone). Conformance: the allowances of cases that read no
twin (texture-fills, chroma-pair copies, texture-pairs-usage-crossings, format footprints) no
longer name decoded-texel-precision; the reads' and samples' keep it.

Test: tests::twin_reads walks every route on a device of its own (ASTC_4x2_LDR on every device,
BGRG422 and GBGR422 where the device converts them): made, written by replace_region and blits,
filled, copied and read back announces no decoded-texel-precision; the route's first read
(slot read, sample, gather, a view's read, a heap read named and unnamed) announces it once; a
twin placed in a set a pending command buffer bound announces as it is made; an ASTC sRGB twin
announces nothing and its LDR view's second twin announces at the view's first read.

Verified at this commit: tests::twin_reads (3 tests) and ycbcr_device's 4:2:2 test pass on this M3
Max (MoltenVK 1.4.2, --cfg m2v_gpu), walking ASTC4x2LDR, BGRG422 and GBGR422.

(cherry picked from commit 37f72d3ffb402ad9afae9571489edbf2b8157442)
2026-11-02 17:43:39 -08:00
Anees Iqbal 5dec29242f Pin the runtime sources after the half-conversion and NaN-encoding carve-outs
What: crates/metal2vulkan-validation/runtime-sources.sha256 recomputed on this tree
(pin-compute.py, 3830c23e...). The pinned inputs this branch changed are the device derivation
files (device/derive.rs, driver_facts.rs, profile.rs, requirements.rs): two new driver
deviations and their properties, which only the translator reads. A run of an unchanged
artifact and plan does nothing else (the runtime names neither deviation, and a profile that
takes them has a new fingerprint, so an artifact compiled before misses the cache), so
RUNTIME_VERSION stays 1731, as for the earlier MetalNanMoves and MetalPackConversions carve-outs.
SEMANTICS_VERSION 1949, ARTIFACT_FORMAT_VERSION 484.

Checks on this branch, rebased onto ef392b28b1 (M3 Max, macOS 27.0.1, MoltenVK 1.4.2; Rust 1.98):
- cargo fmt --check; clippy -D warnings with --all-features, with metal2vulkan's serde, ash and
  cli each alone and with no feature, and with RUSTFLAGS='--cfg m2v_gpu': clean.
- Rustdoc -D warnings; private intra-doc links 0 / 3 / 70 / 0 / 0 / 0 (at the ceilings);
  scripts/api-docs; api-signatures --check; conformance coverage --check; the refusal surface
  regenerates unchanged; goldens re-blessed unchanged.
- core nextest (metal2vulkan, air, runtime, devtools): 5,007 passed. Conformance: 1,007 passed.
  Validation: 1,362 passed, 4 skipped (the runtime guard among them). Doctests: none run.
- The runtime's suite with --cfg m2v_gpu on MoltenVK: 1,499 passed, 3 skipped.
- 401 validation lanes on MoltenVK (the 56 modules that check announcements or these notes):
  393 passed, 8 failed; each of the 8 fails identically at cd578f9cbc (driver_deviations' five
  float and half answer lanes, native_maths' recorded bounds, mipmap_chains' blit chain, the
  YCbCr unmeasured-filter announcement).

(cherry picked from commit 57b3b26ba058342fe84795a508bb2e115dc275ae)
2026-11-02 16:41:46 -08:00
Anees Iqbal eac2986705 Fix forward three core tests the carve-outs moved
What:
- tests::engine_sampler::normalized_and_cubic_stages_record_no_note_their_states_cannot_run:
  sample_grad's half result is the conversion of an image instruction's texel, measured to be
  Metal's on moltenvk-m3 (MetalHalfConversion), so it records no NativeHalfConversion; the cubic
  half samples, whose filter the module sums in float, keep it.
- tests::engine_native_half::native_half_rounding_records_its_kind_and_requires_no_fact: on
  moltenvk-m3 both kernels convert a float the function holds (and add halves natively), so they
  record no note and require VkProperty::MetalHalfConversion; the other profiles are unchanged and
  require nothing.
- tests::engine_handles::a_heap_texel_write_is_the_devices_write: a float texel written through
  an argument buffer's texture records no DeviceNanEncoding on a profile that takes both
  MetalHalfStorageNans and MetalSmallFloatNans (moltenvk-m3), and requires
  VkProperty::MetalSmallFloatNans wherever the profile takes it; a half texel's heap write keeps
  the note everywhere.

Verified: the three tests pass (core nextest --all-features, filtered).
(cherry picked from commit d5f35ffc7b507db9cf88485c9ba4e07c5d206161)
2026-11-02 16:41:46 -08:00
Anees Iqbal 196bdf8135 Fix forward the expectations the half-conversion and NaN-encoding carve-outs moved
What:
- tests::engine_extended_range::half_float_storage_slots_leave_their_writes_to_the_device: a
  formatless half-float storage slot's float write no longer records DeviceNanEncoding for the
  packed small float format on a profile that takes MetalSmallFloatNans (moltenvk-m3), and
  requires VkProperty::MetalSmallFloatNans there; the test and its doc now say so.
- runtime_lane::native_maths::half_rounding_answers_within_its_recorded_bound: a module whose
  conversion is measured to be Metal's (VkProperty::MetalHalfConversion) announces nothing and
  must answer Metal's exactly, as under the float controls. On MoltenVK it does: 8192 of 8192
  answers Metal's exactly.
- runtime_lane::ycbcr_textures::a_four_four_four_texture_s_writes_store_metal_s_codes: the half
  write's YCbCrWrite variant bitcasts the widened half's lanes to words for the runtime's encode,
  which records NativeNanEncoding on every device (as before). The kernel's own stage no longer
  records it on MoltenVK, so the variant's dispatch announces it there; the lane expects it
  exactly where the write's stage does not record it (Kernels::half_write_nans).
- runtime_lane::ycbcr_textures::srgb_twins_read_what_metal_reads: a half nearest sample of an
  sRGB twin through a runtime sampler slot is the device's rounding of the float it reads
  (MoltenVK: toward zero, 8,409 channels over the six surfaces and three matrices, each within one
  half ulp of Metal's ties-away step), which HalfTexelConversion announces at the bind. The lane
  licensed it by the stage's NativeHalfConversion, which the read no longer records; it now
  asserts the bound and that HalfTexelConversion was announced (assert_half_samples).
- golden_hashes.tsv: the moltenvk-m3 profile's hash (the two new deviations).

Verified on this M3 Max (MoltenVK 1.4.2, macOS 27.0.1): the core test passes; the three lanes
pass. The diagnosis of the 4:4:4 note used a temporary dump of the variant's instructions (not
committed): StorageImageClass::YCbCrWrite, R32G32B32A32_UINT, a Bitcast of each widened lane.

(cherry picked from commit 0baa910d6acff2838ffb801f608ad29bffa0331c)
2026-11-02 16:41:46 -08:00
Anees Iqbal 763965c854 Record a texture write's NaN encoding only where its stored NaN is not measured to be Metal's
reims-vgpu treats precision notes as fatal on Apple GPUs. A kernel's write of halves into a
32-bit float or RG11B10Float texture died with DeviceNanEncoding, and through NativeNanEncoding,
on the M3 Max where the stored bytes are Metal's; a write of a constant texel with no NaN died
the same way on every device.

What:
- A new DriverDeviation::MetalSmallFloatNans (VkProperty::MetalSmallFloatNans), taken by the
  APPLE9 MoltenVK row alone: the device stores a float's or a half's NaN written to a
  B10G11R11_UFLOAT_PACK32 storage image as Metal does.
- half_write_nans (a half texel's write) classifies the slot's storage choice: a 16-bit float
  format takes MetalHalfTexelWrites as before, a 32-bit float one MetalNanMoves (the widened
  half's bits are Metal's 0x7fc00000), the packed small float one MetalSmallFloatNans; a taken
  deviation drops the note and requires its property. A slot declared without a format (every
  float storage choice on MoltenVK and lavapipe) records the note under the bound format's class
  (a SpecializedNote of BoundTexelFormat), one clause per class the profile does not cover, so
  the runtime announces it only when such a texture is bound.
- half_storage_facts (a float texel's write) drops the small-float note the same way.
- A texture write of a constant texel none of whose lanes is a NaN records neither note.
- A new module side table, stored_texels, records each texture-family write's texel (kept
  through edit.rs's retain and the roll pass's check). narrow::moves_unfolded no longer counts a
  widened half's store as such a texel as an escape: the write's own DeviceNanEncoding accounts
  for its stored NaN under the format it stores.

Verified on this M3 Max, byte for byte against plain Metal (an MSL probe): a float4 write of
33,792 words (16,446 NaNs) and a half4 write of all 65,536 halves (2,046 NaNs) into RG11B10Float,
RGBA32Float, RG32Float and R32Float store Metal's bytes; into R16Float and RGBA16Float a half
NaN's payload differs (the device stores 0x7e00), so those keep the note.
- runtime_lane::half_write_nans on MoltenVK: half writes into rgba32f, r32f and rg11b10f announce
  nothing and 0 texels differ; rgba16f announces device-nan-encoding (2,045 NaNs differ). Without
  note_stored_texel the lane fails ("write r32f: ... native-nan-encoding true").
- New core tests: a_half_texel_write_s_nan_into_wide_and_small_float_images_is_metal_s_where_
  measured (declared and formatless choices on moltenvk-m3 with and without each deviation, and
  lavapipe; the bound-class clauses evaluated per format) and a_constant_texel_without_a_nan_
  records_no_nan_encoding (zero and 0x7e00 constants, every committed profile); the existing
  device-nan-encoding and half-storage-notes tests follow the deviations. Each fails with its
  change disabled (the NaN test forced true; the stored-texel exemption removed).
- Notes of every public fixture on moltenvk-m3, lavapipe and nvidia-rtx5080-laptop before and
  after: DeviceNanEncoding leaves 65 moltenvk-m3 rows and 6 rows on each other profile (constant
  texels), 17 formatless rows per profile go from unconditional to specialized by bound format,
  58 moltenvk-m3 rows lose their small-float clause, NativeNanEncoding leaves 11 moltenvk-m3 rows,
  and no row gains a note. Consumer AIR on moltenvk-m3: DeviceNanEncoding 33 entries to 21,
  NativeNanEncoding 9 to 5.

Docs: API.md (device-nan-encoding and native-nan-encoding exemptions), HOWTO.md, the
PrecisionNote, VkProperty and deviation rustdoc, the driver-facts measurement record.
api_signatures gains the two variants. The versions bumped in the previous commit cover this one.

(cherry picked from commit 05d96c61107989813c186961087ee70d573cf876)
2026-11-02 16:41:46 -08:00
Anees Iqbal 217cc233f5 Carve MoltenVK on the M3 Max's identity out of NativeHalfConversion for measured conversions
reims-vgpu treats precision notes as fatal on Apple GPUs; NativeHalfConversion was its largest
group of Mac-only failures (37 tests). The note says a half rounded through the device's
conversion to 16 bits and back may differ from Metal's. On the M3 Max (MoltenVK 1.4.2, macOS
27.0.1), MoltenVK writes OpFConvert to 16 bits as MSL half(x), which is Metal's half(float), and
Metal's compiler folds the conversion of an image instruction's float texel into the access.

What: a new DriverDeviation::MetalHalfConversion (VkProperty::MetalHalfConversion), taken by the
APPLE9 MoltenVK row alone. Where the profile takes it:
- narrow::round_measured rounds a float the function holds (an AIR fptrunc or air.convert from
  float, through resize) by the conversion pair and records the pair's narrowing in a new module
  side table, measured_roundings (kept through edit.rs's retain and the roll pass's check);
- narrow::rounds_unmeasured finds any other conversion pair: one neither recorded nor of a texel
  an image read, fetch, sample or gather hands back (directly, through a composite extract, or
  through a parameter every call passes such a texel);
- the compile records NativeHalfConversion only where such an unmeasured pair exists, and
  otherwise requires the property.
A half operation or function computed in float and rounded keeps the note: Metal's half tanh
answers 7 of the 65,536 halves otherwise than the conversion of its float tanh. exp, sqrt and a
reciprocal on half matched, but they are functions, not the conversion, so they stay noted.

Verified on this M3 Max, word for word against plain Metal (an MSL probe, fast and safe math):
- the conversion of a float loaded (425,216 words), of a sum, product and quotient (144,896
  pairs each), of an fma (123,648) and of an integer's quotient (190,208): 0 words differ;
- the half result of read, nearest sample at the centre, linear sample a quarter texel off and
  gather of every texel of ten formats (RGBA32Float, RGBA16Float, RGBA8Unorm and its sRGB twin,
  RGBA8Snorm, RGBA16Unorm, RGBA16Snorm, RGB10A2Unorm, RG11B10Float, RGB9E5Float): 0 differ.
- New lane runtime_lane::half_conversions on MoltenVK: load, sum, product and fma kernels carry
  no note and 0 of 253,958 lanes per kernel differ from the half model; the half tanh kernel
  keeps the note. With measured_conversion forced false the lane fails.
- New core test half_conversions_are_metals_where_measured: the four forms lose the note and
  require the property on moltenvk-m3 with the deviation, keep it without the deviation, and the
  half tanh keeps it on both; it fails with the carve disabled.
- Notes of every public fixture on moltenvk-m3, lavapipe and nvidia-rtx5080-laptop before and
  after: NativeHalfConversion leaves 58 moltenvk-m3 rows, and no row gains a note. Consumer AIR on
  moltenvk-m3: 23 entries noted before, 2 after (a heap texture's held half read).

Docs: API.md (native-half-conversion exemption), HOWTO.md, the PrecisionNote, VkProperty and
deviation rustdoc, the driver-facts measurement record. SEMANTICS_VERSION 1949 and
ARTIFACT_FORMAT_VERSION 484 (new VkProperty variants in the codec); these bumps cover the rest of
this branch. api_signatures gains the two variants.

(cherry picked from commit 266f7cd26327e408d9cd1f0d6ea5ba33e49e10b3)
2026-11-02 16:41:46 -08:00
Anees Iqbal a44a550cbb Pin the runtime sources after the reserved queues
crates/metal2vulkan-validation/runtime-sources.sha256 recomputed on this tree
(~/.cache/m2v-orch/pin-compute.py: 58 listed, 494 inputs, 2f1b9c71...). The hash alone moves:
RUNTIME_VERSION stays 1731, as no run of an unchanged artifact and plan does anything else. With
DeviceOptions::reserved_queues at its default of 0, queue_plan makes the plan it made before (the
round robin less presenting's two, the same presenting and staging queues), the device's
queue_families are the same, and no message is sent; only a consumer that asks for reserved
queues gets a different queue plan.

(cherry picked from commit ef392b28b1c6d1443ae9d6c672d4bf059403385d)
2026-11-02 15:55:42 -08:00
Anees Iqbal 5a09b10c21 Read whether a device spares a reserved queue from its round robin, not from its plan
The device test a_reserved_queue_is_a_runtime_family_s_and_no_command_queue_takes_it took its
expectation from queue_plan, so a plan that never reserved would have passed it on its
no-spare path on every device. It now reads the expectation from what the same device without
the reservation does: it spares a queue exactly where that round robin has more than its floor
of LEAST_QUEUES VkQueues, and the reservation then leaves the round robin one fewer (unless it
sat at ROUND_ROBIN_CEILING with a queue free past presenting's). The plan stays a cross-check.
LEAST_QUEUES and ROUND_ROBIN_CEILING are pub(crate) for it.

Verified on the M3 Max (MoltenVK 1.4.2): the touched device tests pass (32 of the device,
queue_sharing, video_interop and reserved_queues tests).

(cherry picked from commit f72b73bbb47dc1792db894b9f7fcde9ae415dd41)
2026-11-02 15:55:42 -08:00
Anees Iqbal 0dae0acd0d Reserve queues of the runtime's own families for the caller, out of the round robin
DeviceOptions::reserved_queues asks a created device for that many queues of its own queue
families, which DeviceHandles::reserved_queues returns as ReservedQueue (family, VkQueue). They
are the round robin's last queues, taken out of it: the round robin shrinks by each one, and no
command queue, presenting or not, and no internal or staging copy ever submits to them. A
consumer that waits on the GPU for its own work (a video decode's timeline) before a copy into
the runtime's buffers no longer holds back a command queue that shares the VkQueue it borrowed
through CommandQueue::with_vk_queue.

queue_plan takes the reserved count: the round robin keeps its first four (LEAST_QUEUES) and the
presenting reservation its two before the caller has any, so presenting keeps its priority, and a
family with queues past the round robin's ceiling and presenting's two gives those first. On
NVIDIA's graphics family of 16, one reserved queue leaves the round robin 13 and presenting 2. A
device with none to spare (MoltenVK's four families of one queue, lavapipe's one queue, a family
of six) reserves what it has and is made all the same, saying so once in an informational message
(metal2vulkan-reserved-queues-absent). Extra queues are placed after the reservation and never
take a reserved queue. queue_families includes the reserved queues' families, so the runtime's
buffers and images are always shared with them; the docs say what a submission there may do with
the runtime's objects (no ownership transfer; their handles' contracts; semaphores or completion;
GENERAL images).

API: a new DeviceOptions field (reserved_queues: u32, 0 by default), a new DeviceHandles field
(reserved_queues), a new public struct ReservedQueue. Nothing breaks for a consumer: both structs
are #[non_exhaustive]. api_signatures.tsv blessed; docs/REFUSALS.md regenerated unchanged.

Tests:
- tests::device::reserved_queues_leave_the_round_robin_after_presenting (pure): NVIDIA's shape
  with 1, 10, 11, 64 and u32::MAX reserved, families of 5, 6, 7 and 24, MoltenVK's and lavapipe's
  shapes, equivalent families, extra queues beside a reservation, and the message.
- tests::reserved_queues (device tests, m2v_gpu / m2v_cpu_icd): a reserved queue is of one of
  queue_families, the round robin takes one VkQueue fewer than the same device's without it, and
  none of 17 command queues or 3 presenting queues takes it; a device asked for one more than it
  spares reports the absence and runs a command buffer; a raw copy on the reserved queue moves the
  runtime's own Private buffers between command buffers ordered by a shared event's semaphore.

Verified on the M3 Max (MoltenVK 1.4.2): the device tests pass on their no-spare path (0 of 1
reserved, reported; round robin 4 with and without); clippy clean with all features, plain and
--cfg m2v_gpu.

(cherry picked from commit dc75265b857b79bee7795a3692940cc723bf7fd9)
2026-11-02 15:55:42 -08:00