Commit Graph
139 Commits
Author SHA1 Message Date
Anees Iqbal 61a2efc7d3 Fix the GPU test failures seen on the 3090, 5080, XTX, 780M and M3
What and why, per failure (all release, --cfg m2v_gpu):

AMD RADV, Ubuntu Mesa 26.0.8 (RX 7900 XTX, Radeon 780M):
- generated_executions faulted the GPU (amdgpu gfxhub page fault, ring
  reset): RADV before 26.2 skips re-emitting a compute pipeline it thinks
  is bound, so the second execution's implicit preprocess ran our kernel.
  New RuntimeDriverDefect::ImplicitPreprocessAfterExecutionSet (RADV at
  every identity but the measured clean 780M at 26.2.4): the runtime
  preprocesses every execution of a range explicitly, then a barrier, then
  runs them preprocessed. RUNTIME_VERSION 1183.
- The validation executor's generated-commands replay had the same fault;
  it now preprocesses apart on the same defect (runtime's
  generated_commands::preprocess_apart, now public).
- float_denormals under fast math: the test checked a / b, smoothstep and
  (a / b) * c bit for bit, but without VK_KHR_shader_fma (26.0.8) the fast
  reciprocal is the device's OpFDiv(1, y), within 2.5 ulp. Those words are
  now checked at Metal's edges there, in full elsewhere.

NVIDIA 615.71.09 (RTX 3090, RTX 5080 Laptop):
- render_commands_and_render_states_run_as_the_executor_compiles_them: the
  executor used Vulkan device addresses as Metal addresses, and NVIDIA's lie
  below 2^32, where a record's address names no buffer. An addressed
  allocation's guest address is now its device address read signed (RADV's
  are sign-extended) plus 2^47 + 2^32, one translation for every allocation.
- the_runtime_probe_measures_the_test_device_consistently: two driver
  answers Vulkan does not allow (3090: a buffer read after a linear-image
  copy over the same memory in one submission reads stale bytes; both: an
  explicit linear pitch the driver does not lay out is moved, not refused)
  are listed with their evidence in the test; the runtime records neither.
- exits (5 tests): vkDestroyDevice takes ~55 ms alone and up to 2 s beside
  other processes' GPU work on the 3090, so the exit-timing tests run alone
  (.config/nextest.toml); the 1.5 s limit is unchanged.
- pipeline_records (5080): the test assumed the driver finds a pipeline only
  in byte-identical records, but NVIDIA's bytes vary per compile and the two
  formats share entry keys. It now copies a compute pipeline's record over
  the render state's records, which no driver can hit.
- compile_worker (5080, under load): a worker faster than the 1 ms sampler
  left no peak RSS. Each worker now reports its own peak (VmHWM on Linux,
  ru_maxrss on macOS) and the parent takes the larger.
- tests::completion (both, under load): slow rounds were the GPU starting
  late behind another process's ~200 ms busy kernel, or NVIDIA's
  vkQueueSubmit returning up to 64 ms late; the completion was seen within
  1 ms of the moment it could be. A command buffer is now judged from the
  later of its GPU end and its submission's return where the device
  calibrates timestamps (from the commit elsewhere, as before).
- first_use::new_resources_wait_for_no_gpu_work (both, under load): the
  busy kernel's rate came from one wall-clock run, which collapsed under
  load (3 of 28 calibrations), so the busy work lasted milliseconds. The
  rate is now the fastest of every run at every size by GPU time, for all
  four lanes that share it (gpu_times::read_kinds predicts the notice a GPU
  time read emits, for the neutrals test).

Apple M3 Max, MoltenVK 1.4.1:
- heap_textures allows the shadowed-texture route for depth on drivers that
  lay heap depth textures apart.
- The argument-buffer intersection-table test states Metal's own metadata.
- The indirect lane classifies the deferred pipeline-making failure as
  compile-failed alike and keeps only the failed pipeline's error; Apple's
  33-bit closed-form compiler crash is a known gap in docs/FAST-PATHS.md.

Docs: CONTRIBUTING.md and docs/VALIDATION.md say the golden tables and the
compile census are re-blessed on development.

ENGINE_EXECUTOR_ABI is vulkan-engine-v181 (the RADV replay and the Metal
addresses change what the executor submits): every recorded candidate row
and the authored compile census go stale and need re-recording
(scripts/rerecord-venue per venue, rerecord-commit, corpus-status --c3,
corpus-triage --audit authored-compile --bless).

Still open: M3 frees_in_flight, XTX bfloat clears, 780M half NaN blur and
the 5080's one 2 s rebind_bytes_no_copy did not reproduce; the wall-clock
busy calibrations of framebuffer_fetch/storage_forms.rs and queue_storms
remain.

Verified:
- um780 full suites at the AMD fixes (before the executor and NVIDIA
  commits): XTX 3535/3535, 780M 3535/3535, no amdgpu kernel lines.
- Each fix's focused tests before and after on its GPUs (in the agents'
  commits: e.g. generated/indirect 178/178 on XTX and 780M at 26.0.8 and
  26.2.4; candidate 229/229 on 3090, 780M and Iris Xe; the worker peak 0
  of 1440 under 24-way load on the 5080).
- The combined tip: fmt, clippy (with and without --cfg m2v_gpu) and
  rustdoc on ms01; clippy of the validation crate on macOS; a focused run
  on the 3090 was stopped at 333 of 334 passed, none failed. No full suite
  ran on the combined tip.
- The completion and first_use fixes: 3090 load set 1 of 4 runs failed
  before, 4 of 4 passed after (completion) and 12 runs with no first_use
  failure (84 calibrations, 10.19M-11.24M loads); 5080 6 of 6 and 12 of
  12. fmt and clippy (no cfg, m2v_gpu, m2v_cpu_icd) on ms01.
2026-10-13 01:15:18 +03:00
Anees Iqbal ecb80e019d Place heap textures needing up to 256 KiB alignment instead of refusing them
A heap's memory started at a multiple of 64 KiB of the runtime's block, and a
heap texture whose image needed a coarser alignment was refused
NotImplemented(HeapTextureAlignment), by heapTextureSizeAndAlign and
newTexture alike. On an RX 7900 XTX that refused nearly every depth texture a
program puts in a heap: four runtime-lane tests failed there on every run,
each with `alignment: 131072`, while the Radeon 780M in the same machine,
under the same driver, passed them.

Measured with a raw Vulkan probe on homelab-um780 (vkGetImageMemoryRequirements,
optimal tiling, attachment|sampled|transfer usage, 11 formats, sides 1 to
16384, 1/2/4/8 samples, one level or full mips), RADV under Mesa 26.0.8:
- RX 7900 XTX: 128 KiB for D16, D32F and D32FS8 images of 8 x 8 texels or
  more; 256 KiB for multisample depth, stencil and color images from about
  128 x 128 texels; single-sample color, storage and BC1 images at most
  64 KiB. Nothing past 256 KiB.
- Radeon 780M: at most 64 KiB for every shape.

The base is now 256 KiB (HEAP_BASE_ALIGNMENT), the largest alignment measured.
The check moves into check_heap_base, which a GPU-free test can reach, and the
typed refusal stays for anything past the base. A heap over host pages
already starts at offset 0 of its own import, which meets any alignment.

Whole units of the base would have pushed the largest heaps past one
allocation: heap_size admits a heap up to maxMemoryAllocationSize in whole
16 KiB, and where that limit is no whole number of 256 KiB the largest heaps
asked more than the device allocates. RADV (4 GiB less 4 bytes) asked a 4 GiB
allocation for every heap from 4 GiB less 240 KiB, with a block's buffer of
addresses past maxBufferSize; MoltenVK (41,747,087,360 on the M3 Max,
9,534,832,640 on the M4, multiples of 128 KiB but not 256 KiB) would have
asked 128 KiB past the limit for its largest 128 KiB of sizes. So a buffer
past half a pooled block (32 MiB) now keeps its own size (buffer.rs's
`placed`). Such a buffer always takes a block of its own, where nothing
follows it; whole units exist only so the next placement in a pooled block
starts where the last ends. Buffers up to half a block still take whole
units, and half a block is a whole number of 256 KiB.

Cost: a heap of up to 32 MiB now starts at a multiple of 256 KiB of its pooled
block and takes whole 256 KiB units of it, up from 64 KiB units, so a small
heap can hold up to 240 KiB more of its block, on every device. A heap or
buffer past 32 MiB takes exactly its size, no longer rounded up. Programs see
no change where their images need 64 KiB or less. On the 7900 XTX the shapes
past 64 KiB now answer 128 or 256 KiB, are placed, and announce
heap-texture-larger-than-metal.

RUNTIME_VERSION 1179 -> 1181: heapTextureSizeAndAlign and newTexture answer
and refuse differently on such devices, heap buffers lie at other offsets in
the runtime's blocks, and every buffer and heap past half a pooled block
allocates its own size (WorkCounts::device_memory_allocated answers it).
runtime-sources.sha256 is re-pinned. docs/REFUSALS.md is regenerated, and the
reach mark's text says 256 KiB.

Tests:
- tests::heap::every_image_alignment_measured_fits_a_heap_s_base (GPU-free):
  the measured alignments fit the base, and one past it is refused typed.
  With the constant back at 64 KiB it fails (Err(NotImplemented(
  HeapTextureAlignment { alignment: 131072 }))).
- tests::heap::the_largest_heap_asks_one_allocation_of_its_device (GPU-free):
  every committed profile's largest heap asks at most one allocation and one
  buffer. With `placed` rounding every size it fails on amd-780m-radv
  (4,294,950,912 bytes asking 4294967296).
- runtime_lane::heaps::the_largest_heap_lies_in_one_allocation: where the
  largest heap is at most 4 GiB, making it grows the runtime's memory by at
  least its size and at most one allocation, with no validation message.
  Without the size fix it failed on the 7900 XTX ("the largest heap,
  4294950912 bytes, took 4294967296 bytes, past one allocation of
  4294967292"). It reserves the memory without touching it: on Iris Xe a 4 GiB
  heap took 0.04 s and a 53 MiB peak RSS; on lavapipe (debug) a 2 GiB heap
  took 127 MiB.

Verified (release, --cfg m2v_gpu, one GPU pinned):
- The heap set (`test(/heap/) | test(/rebind/) | test(/no_copy/) |
  test(/alias/)`, metal2vulkan-validation and metal2vulkan-runtime), before ->
  after: RX 7900 XTX (RADV, Mesa 26.0.8) 176/180 -> 183/183 (the four
  refusals pass); Radeon 780M (same host and Mesa), RTX 3090 and RTX 5080
  Laptop (NVIDIA 615.71.09) and Iris Xe RPL-P (ANV, Mesa 26.2.4) 180/180 ->
  183/183; lavapipe (--cfg m2v_cpu_icd, debug) 134/134. No kernel GPU
  messages.
- Apple M3 Max (MoltenVK 1.4.1): the heap set plus `test(/buffer/)`. Every
  failure fails identically at the base: heap_textures_answer_and_place_as_
  metal_s_do, argument_buffer_intersection_table_is_encoded_at_reflected_field,
  frees_while_the_gpu_is_busy_fail_no_command_buffer and
  every_case_of_buffers_alone_runs_from_a_command_as_its_dispatch_2.
- Full GPU suites: RX 7900 XTX 3528/3531 and RTX 3090 3526/3531. Every
  failure fails at the base or passes on rerun: on the XTX,
  float_denormals_read_as_metal_reads_them and the two generated_executions
  tests, which fail on the 780M too; on the 3090,
  render_commands_and_render_states_run_as_the_executor_compiles_them and
  the_runtime_probe_measures_the_test_device_consistently fail at the base,
  and three timing tests pass on rerun.
- On the 7900 XTX, the heap lane's output shows answers and placements at
  0x20000 and 0x40000 alignment and no HeapTextureAlignment.
- The runtime crate's GPU-free suite: 856/856. Clippy (workspace, all
  targets, all features, and --cfg m2v_gpu) and rustdoc are clean,
  refusal_surface.py --check passes, and the runtime-sources guard passes.
2026-10-12 20:57:59 +03:00
Anees Iqbal 6cc8b08700 Bound compressed copy regions by their level's blocks
A level of a compressed texture that ends inside a block holds that whole
block, and Metal bounds a copy region by the level's blocks, not its texels: a
4 x 4 region of a 4 x 2 BC3 level names its one block. The runtime bounded it
by the texels and refused it as Copy(Region), "a copy Metal's validation
stops", though Metal's validation takes it. A user reported Hollow Knight on an
x86-64 macOS 26 guest sending such a copy (4x4x1 at level 9 of a 2048 x 1024
BC3_RGBA texture: Unity copies a compressed texture's small levels block by
block), and the consumer ended the guest at the refusal.

Measured on an M3 Max under macOS 26.7 with a probe (BC3, a 2048 x 1024
texture's levels 9 to 11, 4 x 2, 2 x 1 and 1 x 1, against an 8 x 8 texture),
plain Metal and Metal's validation layer each run:
- out of a texture to a buffer, between textures of one size, from a 4 x 2
  level into a whole block of an 8 x 8 level and back, level 9 into level 10,
  getBytes and replaceRegion: a 4 x 4 region copies the whole 16-byte block,
  nothing past it, and validation takes it;
- into a texture from a buffer at 4 x 4, a 4 x 2 region into or out of a whole
  block of a larger level, and 4 x 2 from y = 2 of the 4 x 2 level: validation
  stops them, and plain Metal copies the whole block all the same;
- PVRTC 4-bit on the CPU at bytesPerRow 0: a 4 x 4 region of a 2 x 2 or 1 x 1
  level reads and writes the level's bytes, as the level's own region does
  (validation stops it).

The fix:
- check_region bounds a compressed region by the level's blocks and copies it
  to the level's edge, as a region off its blocks already was. A region past
  the level's last block stays refused; an uncompressed format keeps its
  texels as the bound; an empty region at the blocks' end no longer underflows.
- Between textures, a region that ends at its level's edge inside a block on
  one side only now has two sizes over the same blocks. No one VkImageCopy
  extent states that pair by the spec: 4 x 4 passes the 4 x 2 level's texels
  (VUID-vkCmdCopyImage-dstOffset-00151 into it, srcOffset-00145 out of it), and
  4 x 2 is a part block away from the larger level's edge (VUID-01729 out of
  it; the copies chapter's "aligned ... except at the edges of the image" into
  it). Such a pair goes through the encoder's scratch buffer, image to buffer
  to image, where it was refused as BlockAlignment. That variant has no other
  use and is deleted; the scratch buffer's length counts blocks rather than
  texels; and the direct copy debug-asserts its regions are one size.
  Lavapipe (Mesa 26.2.4) under the validation layer 1.4.357 takes the direct
  copy all the same, with no message and the right block: the route rests on
  the spec, and the assertion is what shows the device test takes it.
- The scratch buffer laid each copy right after the last, so a depth or
  stencil copy could start at a bufferOffset that is not a multiple of 4
  (VUID-vkCmdCopyImageToBuffer-srcImage-07978): copy_texture of a 3 x 3
  Depth16Unorm texture of 2 levels into an R16Unorm one put level 1 at
  offset 18. Each copy now starts at a multiple of both the texel block and 4.
  This predates the compressed change; a review of it found it.
- A PVRTC CPU copy takes a region from the origin that reaches the level's
  edge as the whole level.
- copy_from_texture_to_texture's doc no longer lists the removed refusal.

A user's patch relaxed the bound alone; with it a whole block of a 4 x 2 level
into a larger level was still refused as BlockAlignment.

RUNTIME_VERSION 1178 -> 1179: copies the runtime refused now run, and scratch
copies move to aligned offsets. The runtime sources' hash is re-pinned.

Tests: compressed_regions_are_bounded_by_their_levels_blocks (copy_plan) and
whole_blocks_of_small_levels_copy_between_textures (blit_plan), which fail on
the parent (Err(Region) for the block); device tests
whole_blocks_of_levels_smaller_than_a_block_copy_whole, whose copies out of a
texture sit 32 bytes apart with the gaps checked, and
depth_copies_through_the_scratch_buffer_start_at_multiples_of_four, which the
validation layer fails with 07978 at offset 18 without the alignment.

Verified (Rust 1.98.1; clippy on 1.99), on homelab-ms01 and homelab-gem10:
- metal2vulkan-runtime's nextest: 854 passed, 1 skipped.
- The runtime lane's blit tests on lavapipe under the validation layer with
  METAL2VULKAN_LANE_VALIDATION=sync: 28 passed, no layer message. With the
  scratch-buffer route taken out, the whole-block test fails at the direct
  copy's assertion.
- The whole runtime lane on lavapipe (sync): 1284 of 1302 passed; the 18 that
  fail (synchronization hazards in draws and dispatches) fail alike on the
  parent.
- clippy --workspace --all-targets --all-features, and the validation crate
  under --cfg m2v_gpu, -D warnings; rustdoc -D warnings; the runtime guard at
  the new pin; refusal_surface.py --check (no refusal changed).
- The two device tests under --cfg m2v_gpu, debug, under the validation layer,
  each run pinned to one GPU: RTX 3090 and Radeon 780M (gem10; NVIDIA
  615.71.09, RADV Mesa 26.2.4), RX 7900 XTX (um780; RADV Mesa 26.0.8), RTX 5080
  Laptop (msi-laptop; NVIDIA 615.71.09) and Apple M3 Max (MoltenVK 1.4.1): 2 of
  2 passed on each.
2026-10-12 19:09:53 +03:00
Anees Iqbal dc7cd12b02 Re-pin the runtime sources' hash after the clippy 1.99 edits
The previous commit's runtime edits (passing over_bytes by value, try_update
for fetch_update) change no behaviour of a run, so RUNTIME_VERSION stays and
only the pinned hash moves. Value from the_runtime_sources_are_the_committed_ones
on homelab-ms01 over the identical tree.
2026-10-12 15:47:20 +03:00
Anees Iqbal 86f0338f54 Pass Rust 1.99's clippy: closures by value, try_update for fetch_update
CI installs the current stable toolchain, which became 1.99 on 2026-10-01; its
clippy failed the warnings-denied step on both hosts. Rust 1.99 extends
needless_borrows_for_generic_args to closures passed by reference, and
deprecates the atomics' fetch_update in favor of try_update. Master was clean
under the fleet's 1.98.1.

- Pass the Copy closures `invariant`, `compile`, `over_bytes` and `at` by
  value (lockstep.rs, reflection tests, render.rs, C3 venues).
- Call try_update where fetch_update was (runtime sampler limit, validation
  worker allocator). try_update is stable in 1.98.1, so the MSRV holds.

Verified on homelab-ms01 (x86_64 Linux): clippy with warnings denied passes
under 1.99.0 and 1.98.1 for --workspace --all-targets --all-features and under
--cfg m2v_gpu; under 1.99.0 also each feature alone, the runtime and the AIR
crate alone, --cfg m2v_cpu_icd, and rustdoc. A check-only clippy for
aarch64-apple-darwin passes for every crate except metal2vulkan-validation,
whose bundled SQLite needs a macOS C toolchain; its macOS-only code is
unchecked under 1.99.
2026-10-12 15:22:57 +03:00
Anees Iqbal edb5ffd8cc Add a lane where host and GPU copies of a texture see each other's texels
runtime_lane::host_copied_textures makes Shared and Managed RGBA8Unorm
textures (16, 256 and 1024 texels square, four rounds each) and checks that
the GPU reads the zeros each was made with, then what replace_region wrote;
that get_bytes reads what a GPU blit wrote; and that both read back a
replace_region of all but a 1-texel border, which writes the border's 64-byte
lines of a tiled image only in part. It prints how many textures copied on the
host (WorkCounts::images_started_on_the_host), so a run shows the host path ran.

It is the regression check for the previous commit: on ANV's host-cached type
without coherence the GPU read stale lines of host-copied textures.

Also say in placed_image what happens where only incoherent memory is allowed:
the placement fails and host_placed_image makes the image without host-transfer
usage, its copies through submissions, so no texture is refused for it.

Verified on msi-laptop (Arrow Lake-S iGPU, Intel(R) Graphics (ARL), Mesa 26.2.4,
VK_DRIVER_FILES=intel_icd.json, --cfg m2v_gpu, debug):
- with the runtime at 11715e2a3f (this lane added, the runtime's memory.rs,
  texture.rs, texture/host_copy.rs and tests/memory.rs as on development): 119 of
  the 120 checks failed, in each of 3 runs, from the GPU's read of a new
  texture's zeros on; 24 of 24 textures copied on the host.
- with the fix: passed in 5 of 5 runs, 24 of 24 textures copied on the host, no
  validation message.
- lavapipe (Mesa 26.2.4, LLVM 23.1.1, --cfg m2v_cpu_icd): passed, 24 of 24
  textures copied on the host.
- clippy -p metal2vulkan-validation -p metal2vulkan-runtime --all-targets
  --all-features -D warnings with --cfg m2v_gpu: clean.
Without VK_DRIVER_FILES the lane fails there on the loader's messages about
NVIDIA's ICD, whose GPU is switched off on that laptop.
2026-10-12 13:10:21 +03:00
Anees Iqbal 9a82a7cc29 Keep host-copied textures out of host memory that is not coherent
A Shared or Managed texture that copies on the host (VK_EXT_host_image_copy)
took any HOST_VISIBLE | HOST_CACHED memory type (memory::host_cached), whether
coherent or not. The runtime flushes and invalidates no mapped range, as Metal's
textures need none, so on a cached type without HOST_COHERENT the texels were
left to the driver's cache upkeep around each copy. ANV (Mesa 26.2.4) on Arrow
Lake-S's Xe-LPG (0x7d67), which shares no last-level cache with the host, lists
such a type (1: DEVICE_LOCAL | HOST_VISIBLE | HOST_CACHED), and the consumer's
x86 macOS guest there showed fully transparent 4x4-texel holes (one 64-byte line
of a Tile4 32-bit image) in its textures.

host_cached now takes only coherent cached types, and an image with
host-transfer usage never takes a type the host maps without coherence
(memory::host_incoherent), so a fallback after a failed allocation cannot reach
it either. On Arrow Lake such an image takes the coherent write-combined type 0,
counted as uncached_host_images; ANV lists one queue family there, so no staging
queue takes its copies instead. Every other device measured lists only coherent
cached types (NVIDIA, RADV, MoltenVK, lavapipe), so nothing moves there.

Verified:
- the consumer's session (reims-vgpu-c7) on msi-laptop's Arrow Lake iGPU, from
  boot screenshots of the guest: holes inside the boot logo 33.7% at 11715e2a3f,
  0.0% and 0.0% in two boots with host_cached requiring HOST_COHERENT (the same
  one-line change), dock icons and calendar widget clean; INTEL_DEBUG=noccs
  5.6%/17.1% and INTEL_DEBUG=stall 14.2%/29.1%, so neither compression state nor
  a missing GPU barrier.
- a memory-test case with Arrow Lake's types [0x7, 0xb, 0x21, 0x7]: host_cached
  0, host_incoherent type 1, the image placed at type 0 first.
- on msi-laptop (x86_64, Rust 1.98.1): clippy -p metal2vulkan-runtime
  --all-targets --all-features -D warnings clean; nextest -p
  metal2vulkan-runtime --all-features 852 passed; rustdoc -D warnings clean.
  vulkaninfo there lists one ANV queue family.
2026-10-12 13:01:32 +03:00
Anees Iqbal 11715e2a3f Import no-copy memory a driver refuses from the caller's dma-bufs
RADV imports host pointers through amdgpu userptr with ANONONLY, so it
refuses MAP_SHARED memfd pages (QEMU's memory-backend-memfd guest RAM and
views of it): every no-copy buffer, heap and rebind over them was refused,
and a macOS guest could not boot on AMD. NVIDIA imports the same pages.

What:
- The five no-copy entry points (new_buffer_with_bytes_no_copy, both
  new_heap_with_bytes_no_copy calls, Buffer and Heap rebind_bytes_no_copy)
  take a HostMemory; HostMemory::with_dma_buf adds a retained DmaBufSource.
- Where the pointer import is refused, and only there, on any device that
  lists VK_KHR_external_memory_fd and VK_EXT_external_memory_dma_buf, the
  runtime asks the source for dma-bufs of the window's pages (chunks cut at
  the device's sparse granule, sized by the caller within udmabuf's default
  limits) and binds one buffer over them: plain for one chunk, sparse for
  several (vkQueueBindSparse signalling queue 0's timeline; later work waits
  on it, no host wait). Every path that imported before is unchanged.
- Textures over such pages get a dedicated DRM_FORMAT_MOD_LINEAR image import
  of their own pages where the driver takes the plane offset and row pitch
  (multiples of 256 on RADV), with 64-bit modifier features; elsewhere, or on
  a source error, the existing shadow path.
- The extensions are enabled outside the compile profile: no device's enable
  set, fingerprint or ARTIFACT_FORMAT_VERSION changes. The translator crate is
  unchanged.
- Imports free inside exit-guard sections; the source is never called with a
  runtime lock held. WorkCounts gains dma_buf_imports, dma_buf_sparse_buffers,
  dma_buf_images and dma_buf_image_fallbacks.

Verified:
- Product suites 4553/4553, validation suite 1289/1289, clippy in every
  configuration, rustdoc -D warnings, scripts/api-docs.
- runtime_lane::dma_buf_imports and rebinds on RADV Mesa 26.2.4 (validation
  layer clean), the RTX 3090 and lavapipe (pointer imported, source never
  called), and dma_buf_imports on RADV Mesa 26.0.8.
- reims-vgpu on the Radeon 780M (RADV 26.0.8, udmabuf at its defaults): a
  macOS 26 guest cold-boots to the desktop and runs Safari; 5,119 dma-buf
  requests, none refused.
- 64 MiB on RADV 26.2.4, release: pointer import 187 us; one chunk 665 us;
  16 chunks 16.9 ms, about half of it the refused pointer attempt. The old
  host-fence bind waited 1.26 s behind queue-0 work on RADV 26.0.8.
2026-10-12 11:33:41 +03:00
Anees Iqbal e51abf38e1 Make development the working branch and keep master for the user
AGENTS.md told agents to merge into master at once and to run the
checks and re-blesses there. The owner's rule (2026-10-11) is now that
no agent works on or advances master unless the user explicitly asks:
work happens on development, made from master when it is missing, or on
branches off it. The git workflow section, the loop's last step and the
definition of done now name development instead of master. The speed
rule is unchanged: merge at once, no pre-merge gate, fix forward.

Verified: docs only; cargo fmt --all left the tree unchanged, and the
only remaining mention of master in AGENTS.md is the new rule itself.
2026-10-11 21:07:01 +03:00
Anees Iqbal 13b279df1b Squash 11203 commits of translator, runtime, and validation work
Rolls up everything since 43c46ac8 into a single commit. Its tree is
identical to the tree of private master at
b3c77f2d2b20a432be10591a2129547c10b1c24b.

- A Cargo workspace of five crates under crates/: metal2vulkan (the
  translator and the metal2vulkan command), metal2vulkan-runtime (the
  Metal API on Vulkan), metal2vulkan-air (the AIR front end),
  metal2vulkan-validation and metal2vulkan-devtools.
- Dual license: GPL-2.0-or-later OR LGPL-3.0-or-later.
- docs/: API, architecture, fast paths, how-to, Metal coverage,
  refusals, runtime porting and validation guides.

Private-Commit: b3c77f2d2b20a432be10591a2129547c10b1c24b
2026-10-11 20:09:13 +03:00
Anees Iqbal 43c46ac8a2 Squash 680 commits of translator, validation, and corpus work
Rolls up everything since 9e0e99a4 into a single commit:

- src/native, src/passes, src/reflect, src/meta: AIR intrinsic lowering,
  access-chain and pointer handling, constant/composite dedup, storage
  and descriptor-slot fixes, function-constant folding.
- validation/: Metal and MoltenVK oracles, triage, observation contract,
  and the case runner.
- validation/corpus and fixtures: new authored cases and re-recorded
  candidate observations at the shipping fingerprint.
- tests/: module-level oracles for reflection, NonWritable, gated
  varyings/system values/descriptor slots, loop budget, and fallback.
2026-09-06 23:58:13 +03:00
Anees Iqbal 9e0e99a41d Report only the constexpr samplers the module binds
`StaticSampler` is a descriptor translation invents. Nothing in Metal's API puts
one there, so the only reason a consumer creates a `VkSampler` at that binding
is that this reflection asked for one.

Reflection named one per `!air.sampler_states` entry -- every constexpr sampler
state the source wrote -- and the interface pass gives each the same binding in
the same order. But a state no sample reads leaves a variable nothing
references, and the module drops it, so reflection went on describing a sampler
that is not there. Over the 2880-source sample: 112 such bindings in 60 modules.

`StaticSampler` was the last translator-invented kind still reported without the
module's agreement; `reconcile_buffer_address_table` and
`report_synthesized_placeholders` already close the same gap for the other
three. Sweeping all four kinds over the sample now finds none.

Nothing moves. The interface pass allocates a binding per global before the
unused ones are dropped, so the states that survive are still on the bindings
that carry them -- confirmed by a reflection A/B over the sample, where 60
modules lose exactly those 112 entries, nothing is added, and no other field of
any binding changes.

The new fixture is three constexpr samplers with two samples, which reports a
ghost at binding 161 on HEAD~. `assert_invented_descriptors_are_declared` now
runs over every public fixture as well: it is the direction
`assert_reflection_covers_declarations` does not check, and for a resource the
translator invented the module is the only thing that can say a consumer has to
bind it. `REFLECTION_VERSION` is now 41.
2026-09-01 07:04:21 +03:00
Anees Iqbal b6e10bf14c Read a color attachment's Location from the operand after its marker
`!"air.render_target", ptr addrspace(2) @loc, i32 0` states the Location as a
function-constant global and the dual-source index after it. When the global was
one this module does not initialize, the decode fell through to "the next `i32`
after the marker" and answered with that index -- which is `0` in all 3213
literal-form corpus declarations, so every such output landed on attachment 0
whatever the constant said. For a multi-target shader that is every color output
on one attachment. 103 of 3316 corpus `air.render_target` declarations spell the
Location as a global.

The operands after a slot describe something else, so none of them is an answer
to "which slot". The parameter or member ordinal stands in instead, which is at
least unique per member.

This is the same defect `air.location_index` had, so the two are now one
decoder: `meta::declared_slot` reads the FIRST operand after a given marker and
resolves it through the static initializers, and `meta::marker_operands` is the
one positional reader behind both. The last scan-forward `@` helper went with
it. The census that found this is in the doc comment: for every `air.*` key,
compare "the next `i32`" against the operand actually at position 0.

A/B over the 2880-source sample: 0 byte changes. Full-corpus status over all
14579: 0 changes. Pinned by a fragment whose second render target names a
function constant, asserted both when the module initializes it and when it does
not; the second case reports Location 0 on HEAD~.
2026-09-01 06:54:39 +03:00
Anees Iqbal 4c28bcc233 Order constexpr samplers by one key that cannot tie
Two independent scans put the module's `__air_sampler_state` globals in a
sequence and then pair them off by position: the interface pass, which collects
them from the SPIR-V `OpName`s and hands each the next free sampler binding, and
reflection, which collects them from the `!air.sampler_states` root and reports
the decoded state at each of those bindings. Each sorted with its own copy of a
key that read the name suffix as a single integer.

That key TIES. LLVM uniques a repeated `__air_sampler_state` by appending `.N`,
and re-uniques an already uniqued name by appending again --
`__air_sampler_state.161.1606` -- which the single-integer parse fails on, as it
does on the unsuffixed original, so both land on 0. A tie leaves the order to
input order, and the two scans have different ones. Both sides then agree on
WHICH sampler bindings exist while describing each as the other, so every sample
reaches a real sampler carrying another one's filter, address modes and compare
function, in a module that validates and binds cleanly. 14 of the 5499
sampler-state globals across 14579 local corpus sources carry the doubled form,
and 10 modules hold one beside the original.

The key now orders by the whole dot-separated suffix with the name last, which
cannot tie -- a name is unique within a module -- and it lives in one place,
`meta::static_sampler_name_order`, with the prefix predicate beside it so
neither side spells `__air_sampler_state` for itself.

The existing constexpr-sampler test checked only which bindings exist, which is
the half that was already right. It now also checks that the state reported at
each binding is the state the sample reading that binding was written with,
over both the uniquely suffixed spelling and the re-uniqued one. The re-uniqued
fixture fails on HEAD~ with the two states swapped.

A/B over the 2880-source sample: 0 status changes; 1 module changes, one
surviving constexpr sampler moving from binding 162 to 161 as its state moves to
the position the shared order gives it.
2026-09-01 06:41:05 +03:00
Anees Iqbal e84ea3fa48 Read the descriptor count the ABI states beside a location index
`air.location_index` always carries TWO operands: the resource's Metal slot and
how many descriptors the argument occupies there. Nothing read the second one.

An `array<sampler, 8>` therefore bound as a single sampler. Its element loads
then resolved to nothing, so the sample fell back to the synthesized read
sampler -- the shader's chosen filter, address modes and compare function
dropped without trace, in a module that validates, binds and reflects as though
one sampler at that slot were the whole story. There is no sampler
descriptor-array lowering, so this is now a FALLBACK naming the parameter and
the count. Two of 14579 local corpus sources declare one.

The same count is what makes the texture-array length checkable. AIR states that
length twice -- as this operand and inside `array<texture..., N>` -- and all 76
corpus declarations agree, so a name the ABI contradicts, or a count above one
on a name that is not an array at all, is refused rather than silently sized
from the name alone. It costs nothing today and fails the moment the parse
drifts.

Reading the pair also has to be POSITIONAL. Either operand may be a literal or a
pointer to a function-constant global, and all four combinations occur -- 112946
`(i32, i32)`, 3404 `(ptr, i32)`, 1447 `(ptr, ptr)`, 439 `(i32, ptr)`, and no
other shape. The slot decode looked for the first global after the marker, which
IS the count whenever the slot is a literal: a texture at `[[texture(1)]]` with a
function-constant array extent could bind at the extent's value. 69 corpus
texture nodes are that shape. The buffer half of it was already dodged by a
type-name special case for `array_ref<void>` -- whose comment describes exactly
this confusion -- and the positional read makes that case unnecessary, so it is
gone. Latent today: no corpus module resolves the count global.

Full-corpus A/B over all 14579 sources: 0 status changes. The two sampler-array
sources already fell back for unrelated reasons, so the hole is pinned by an
authored fixture instead, which translates cleanly at HEAD~ and refuses here.
Both new must-FALLBACK cases carry their positive control, so the boundary is
what is pinned rather than one side of it.
2026-09-01 06:36:55 +03:00
Anees Iqbal a1ffb61707 Count a descriptor array as the one binding it occupies
`bindings_reflection_reports` expanded a `DescriptorLocation`'s `count` into
`count` consecutive `(set, binding)` pairs, but a descriptor array occupies ONE
binding holding `count` descriptors -- it maps to a single
`VkDescriptorSetLayoutBinding`. The expansion let one array vouch for every
binding above it: a runtime texture-handle array at 480 with a count of 128
"reported" the whole storage-texture band, so a module variable decorated
anywhere in 480..608 satisfied a check reflection had never made.

Nothing was masked -- the fixtures pass either way, and sweeping the same
oracle over the 2880-source sample finds 0 modules with a decorated binding
reflection omits -- but the assertion now means what its name says.
2026-09-01 06:12:47 +03:00
Anees Iqbal 35f8b8bfce Bind a fixed texture array at the length AIR declares
`array<texture2d<half, sample>, 32>` states its length twice -- in the type
name and as the second `air.location_index` operand -- and the decoded
`TextureShape` already carried it. The interface pass still emitted
`OpTypeArray` of 128 and reflection still reported `count: 128` for every
handle array, fixed or runtime, so one `ResourceBinding` contradicted itself:
`texture_shape.array_length` said 8 while `descriptor.count` said 128, and a
consumer following the reflection had to supply 128 valid descriptors (or
`descriptorBindingPartiallyBound`) for an array of 8.

Both sides now derive from `TextureShape::descriptor_count`, the only reader of
the capacity constant. Only a runtime `array_ref`, whose length is a function
constant rather than part of the type name, still reports it. 40 of 14579 local
corpus sources declare a fixed array, lengths 2, 3, 4, 8, 32 and 80; every one
of the 76 declarations agrees with its `air.location_index` count operand.

The same unification fixes a depth-texture array bound as a single image. The
interface pass asked `contains("array<texture")` while the shared type-name
decoder asked about `array<depth` too, so `array<depth2d<float, sample>, 2>`
was not recognised as a handle array at all: the module declared one `depth2d`
where the shader indexes two, while reflection reported a `TextureArray` of 128
at that binding. There is now one predicate, `TextureShape::array_ref`, and one
scan behind it -- "is this an array" and "how long is it" can no longer be
answered by two different rules.

`tests/reflection_covers_declared_bindings.rs` now requires the reported count
to EQUAL the array the module declares rather than merely cover it, which is
what makes over-reporting detectable; the runtime fixture cannot catch it,
since its declared capacity IS the ceiling. Two fixed fixtures are added, one
of them spelled over `depth2d`, because a handle-array test that only ever says
`texture` cannot tell whether the emitter recognised the depth spelling.
Reverting either half of the fix fails them.

A/B over the 2880-source sample: 0 status changes; 8 modules change, each only
an `OpTypeArray` length 128 -> 2/8/32/80 and the ids that renumber behind it.
`REFLECTION_VERSION` is now 40.
2026-09-01 06:10:04 +03:00
Anees Iqbal 798b526fa7 Report the threadgroup ceiling this translator enforces
Translation refuses a `kernel_local_size` whose product exceeds the entry's
`[[max_total_threads_per_threadgroup(N)]]`. A bound a consumer has no way to
read leaves it guessing at the dispatch shape until it hits the refusal, so
`ShaderReflection` now reports `max_work_group_size`.

Reflection reports it and does not enforce it: discovering the bound is the
reason to call it, and refusing the call that asks would be circular. The
authored test drives both halves off the one declaration -- it reads the ceiling
out of reflection, then dispatches exactly that many threads and one more --
so the number reported and the number enforced cannot drift apart. A kernel that
declares no ceiling reports `None` and bounds nothing.

`REFLECTION_VERSION` is now 39; `docs/REFLECTION.md` documents the field.

Verified: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D
warnings`, warnings-denied all-features Rustdoc, `cargo test -p metal2vulkan` in
debug and release, `cargo test -p metal2vulkan-validation`. Dropping the field
back to `None` fails the new test and no other. A/B against the previous commit
over 2880 corpus sources: 0 status changes and 0 SPIR-V byte changes.
2026-09-01 05:50:57 +03:00
Anees Iqbal 9db8b14645 Refuse an imageblock that is really the framebuffer
An explicit `[[imageblock]]` is tile-local scratch, undefined on entry, and the
interface gives it a `Private` array. That is an honest refinement of undefined
storage. `air.alias_implicit_imageblock`, on the same node beside the ordinary
`explicit` qualifier, states the opposite: the storage *is* the implicit
imageblock -- the render targets the rasterizer has already written. The
kernel's first read is of framebuffer content and its writes have to land back
there.

The marker was unread. `resolveTileMemoryKernel_ColorBlockSimple`, whose body
begins by loading a `<4 x half>` out of the imageblock and ends by writing the
resolve to a texture, was emitted reading `%_ptr_Private__arr_v4half_uint_2` --
an uninitialized per-invocation array. It validated, and neither the module nor
its reflection carried any descriptor for the framebuffer that a consumer could
have noticed was missing. 30 of 14579 local corpus sources carry the marker.

Vulkan has no compute stage inside a render pass to alias against, so the answer
is a refusal naming the parameter. The 124 non-aliased explicit imageblocks keep
the Private-scratch lowering exactly as it was; the authored test drives both
arms off one template, since the aliased and unaliased nodes differ only in that
one string.

Verified: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D
warnings`, warnings-denied all-features Rustdoc, `cargo test -p metal2vulkan` in
debug and release, `cargo test -p metal2vulkan-validation`. Suppressing the
decode fails the new test and no other. A/B against the previous commit over
2880 corpus sources: 0 SPIR-V byte changes, and exactly the nine sources
carrying the marker move from OK to FALLBACK.
2026-09-01 05:41:33 +03:00
Anees Iqbal 66c7e7d42b Refuse the command buffer this translator cannot encode
`air.set_pipeline_state_compute_command`, `air.set_kernel_buffer_compute_command`,
`air.draw_primitives_render_command` and their siblings write commands into a
Metal indirect command buffer the shader received as an argument. They were
lowered to `Ok(vec![])` -- dropped -- with the comment that "the current
conformance compute runner observes buffer bytes only, so preserve translation
validity without claiming command-buffer side-effect emulation".

What that preserves is the appearance of translation. The module validates,
binds and reflects exactly like the original and performs none of the encoding;
`ICB_Inherit_None_Kernel`, whose body is nothing but encoding, came out as a
35KB module that does nothing and reported success. That is emitting
wrong-but-valid SPIR-V to silence a gate, which is the one thing this tree's
honesty contract names outright.

Vulkan has no equivalent to encode into -- its device-generated-command
extensions describe a different, driver-defined layout that no sequence of
SPIR-V instructions can produce from these operands -- so the answer is a
refusal naming the family. `AirIntrinsicDisposition::NoVulkanEquivalent`
separates a family the translator has modelled and refuses from one nothing has
modelled yet, so the refusal reads as a decision rather than as an unrecognised
symbol.

Validation reported the `IndirectCommandBuffer` tooling requirement from
`!"air.indirect_command_buffer"`, a metadata string that appears in 0 of 14579
local corpus sources. What an encoder actually carries is a call into one of
these families and an `air.command_buffer` argument-buffer member -- 17 sources
carry the latter. The requirement is now derived from
`is_command_encoder_helper`, the same definition translation refuses on, so the
boundary is stated once.

Verified: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D
warnings`, warnings-denied all-features Rustdoc, `cargo test -p metal2vulkan` in
debug and release, `cargo test -p metal2vulkan-validation`. A/B against the
previous commit over 2880 corpus sources: 0 SPIR-V byte changes, and exactly the
two sources that encode commands move from OK to FALLBACK, each naming the
family it could not lower. Twelve of the 14579 local sources reach it.
2026-09-01 05:35:23 +03:00
Anees Iqbal c5570b5235 Encode a half constant one way
The native emitter and the passes layer each carried their own `f32` ->
IEEE-754 binary16 conversion. They did not agree. The passes copy rounded
half-away-from-zero rather than to even, and combined the rounded significand
into the encoding with `|` instead of `+` -- so a value whose rounding carries
out of the ten significand bits kept the exponent it started with whenever that
exponent was odd, because the carry bit it needed was already set.

That is not theoretical. `air.convert` from a `half` source to a narrow integer
clamps in the source type first, and the clamp bounds go through this encoder.
The `32767.0` upper bound of a 16-bit signed convert encoded as `16384.0`, and
the `8191.0` bound of a 14-bit one as `4096.0`. The lower bounds are powers of
two and rounded exactly, so the clamp came out asymmetric: `[-32768, 16384]`
where it should read `[-32768, 32768]`. Every `half` above the halved bound
saturated to it instead of to the destination's maximum, in a module that
validates. Six of 2880 corpus sources emit exactly that clamp.

The correct encoder now lives in `crate::float16` and is the only one. Its test
walks every rounding boundary the format has: for each pair of adjacent finite
halves, the exact midpoint (representable in `f32`, so the test does no
rounding of its own) must land on the even one, and the two neighbouring `f32`
values must land on their own side. Round-tripping representable halves, which
is what the emitter's own test did, cannot see any of this -- widening is exact,
so it never asks the encoder to round.

Verified: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D
warnings`, warnings-denied all-features Rustdoc, `cargo test -p metal2vulkan` in
debug and release, `cargo test -p metal2vulkan-validation`. Substituting the old
passes-layer encoder into the new module fails three of its five tests,
including the boundary walk. A/B against the previous commit over 2880 corpus
sources: 0 status changes and 6 SPIR-V changes, each of them the clamp constant
above.
2026-09-01 05:27:45 +03:00
Anees Iqbal c75c1c9a5f Read every attribute a stage root carries
All three AIR stage roots -- `!air.kernel`, `!air.vertex`, `!air.fragment` --
state their per-entry attributes in the same place: extra operands past the
`(function, outputs, inputs)` triple. They do not state them in the same form.
`air.patch` and `air.max_work_group_size` are references to a keyed node;
`early_fragment_tests` is a bare string operand on the root itself. Only the
vertex decode read that tail, and only for `air.patch`, so a stage could not
tell "no attribute" from "an attribute nobody taught me to see".

Two were being dropped in that silence.

`[[early_fragment_tests]]` -- 51 of 14579 local corpus sources -- now reaches
SPIR-V as `OpExecutionMode ... EarlyFragmentTests`. It is not a hint: under
early testing a fragment the depth test rejects executes none of the body's
stores, while under Vulkan's default late test the same shader performs every
buffer, texture and imageblock write and only its color output is discarded.
Both modules validate, bind and reflect identically, which is why nothing
caught it. A fragment that declares it and also writes `air.depth` or
`air.stencil` is refused: the test runs before the value it compares exists,
and Metal rejects the pair outright.

`[[max_total_threads_per_threadgroup(N)]]` (`air.max_work_group_size`, 439 of
the same sources) states the largest threadgroup the body was compiled to run.
A caller-requested `LocalSize` past it is refused instead of emitted as a
module that validates and runs a shape the source ruled out. The duplicated
non-zero `LocalSize` check in `transform_with_options_and_sidecar` now calls
`validate_kernel_dispatch_options` rather than restating it.

The structural half is `meta::stage_root_attributes`: one decoder for the whole
tail, recognising each attribute by its own ABI marker rather than by position,
carrying anything it cannot model out through `unmodelled_stage_attributes` so
the stage-input pass refuses by name. A node with no operands states nothing
and is skipped -- there is nothing in it to drop.

Verified: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -D
warnings`, warnings-denied all-features Rustdoc, `cargo test -p metal2vulkan`
in debug and release, `cargo test -p metal2vulkan-validation`. The six authored
cases in `tests/stage_root_attributes.rs` were checked against five mutations
(drop the execution mode, drop the decode, ignore unmodelled attributes, drop
the ceiling check, read only the first tail operand); each mutation fails at
least one. A/B over 2880 corpus sources: 0 status changes, and the only SPIR-V
byte changes are the ten fragments declaring `early_fragment_tests`, each
gaining exactly the one execution-mode line and still passing spirv-val.
2026-09-01 05:14:42 +03:00
Anees Iqbal 386bbd2823 Sweep the descriptor ABI on a layout that is not the default
The descriptor ABI is written twice. The stage passes decorate the module from
the selected `DescriptorLayout`; reflection computes the same numbers for
itself. `reflection_covers_declared_bindings.rs` already checks that the two
close over each other -- but every case ran at the default layout, where a band
whose reflection forgot the selection and used the default constant is right
anyway. The corpus cannot help: it only ever translates at the default.

So the public-fixture sweep now runs a second time on a layout with the
default's band widths, none of its numbers, and a different set. Coverage still
has to hold, and one invariant more: no binding the module declares or
reflection reports may fall outside a selected band or on another set. A
default-layout number surviving the shift lands in neither. Replacing one
`descriptor_layout.buffer_binding` call with the default-layout
`buffer_resource_binding` fails the new sweep and passes all seven older tests.

The sampler band needed a case of its own. A `constexpr sampler` has no Metal
argument index -- it is a module-scope constant whose binding is allocated from
the band rather than projected from an index -- so it exercises an allocator the
projected kinds do not, and none of the 21 public fixtures carries one. The
authored fragment samples one texture through two of them, checked on both
layouts; pointing reflection's allocator at the default band fails it.

Tests only; no product code changes.
2026-09-01 04:41:47 +03:00
Anees Iqbal 49fdfa0d65 Ask the emitter whether a kernel needs its address table
Whether a module carries a buffer-address table is a property of the pointer
graph the emitter constructs, and the emitter decides it with
`requires_device_address_model` over the parsed source. Metadata-only reflection
has to answer the same question, and answered it separately: a scan of the AIR
text for lines beginning `inttoptr` or `load ptr addrspace(1)`.

Two derivations of one fact, and the second was much the worse. Over 2880 corpus
sources the scan disagrees with the finished module 63 times. 49 of those report
a binding no module declares, which costs a consumer a descriptor slot. The
other 13 report none for a module that does declare one, which costs a consumer
a binding the shader reads -- and the scan cannot be fixed into seeing them,
because they are modules with no device pointer written anywhere in the AIR at
all: the address model is chosen for them during construction.

Asking the emitter's predicate leaves 8 disagreements, four in each direction,
and the remainder are the same kind -- decisions made after the pointer graph is
parsed. It costs a parse: metadata-only reflection goes from about 1.6 ms to
about 13 ms per shader, against 39 ms to translate one, so the path stays the
cheap one it is there to be.

The authored case for this was previously a bare `inttoptr` with nothing reading
it. That is precisely what the scan over-reports, so it now loads through the
pointer, and its dead twin is pinned beside it as the case that must report no
table. A second case loads a device pointer out of a struct member, which no
line-prefix scan can see and the pointer graph reads directly.

No module's SPIR-V changes and reflected translation is untouched, since it reads
the table off the module either way. `REFLECTION_VERSION` is 38.
2026-09-01 04:33:22 +03:00
Anees Iqbal f5b7d060ea Hold both sources of sampler state to one rule
Vulkan has no unnormalized-coordinate sampler with Metal's semantics, so a
`coord::pixel` sampler is emulated with shader-side fetches at level zero.
Anything the fetch cannot express has to fail translation rather than be
silently dropped -- the module would sample the right texture with the wrong
filter, anisotropy or border, and validate either way.

Sampler state reaches that lowering from two places, and only one of them
checked. `RuntimeSamplerState::validate` refused caller-supplied state it could
not reproduce; AIR's constexpr encoding went straight to the lowering unchecked.
Two copies of a rule drift, and the copy that existed was wrong: it demanded
both LOD clamps be exactly zero. Only the minimum can matter. The fetch reads
level zero, so a minimum above zero excludes the level the emulation reads,
while a maximum cannot -- validation already requires it to be at least the
minimum. Metal's default maximum is 65504, the half-precision limit AIR encodes
"unclamped" as, and 531 of the 535 pixel-coordinate static samplers over 2880
corpus sources carry exactly that. A caller passing the state its own shaders
use got a FALLBACK; the AIR path took the identical state without a word.

The constraints now live on `StaticSamplerState`, which is what the lowering
actually consumes, and both paths call them. Over the corpus every pixel
sampler passes -- all 535 are nearest, unmipped, unaniso, unbiased, weighted
average, minimum clamp zero -- so no module changes status and none changes by a
byte.
2026-09-01 04:17:59 +03:00
Anees Iqbal d5e2aaa052 Refuse a tessellation patch this translator cannot read
`air.patch` is what makes a vertex function a post-tessellation evaluation
shader: it names the domain and, with `air.patch_control_point`, the number of
control points a patch carries. The decoder read it as an `and_then` chain that
answered `None` for anything it did not recognise, and `None` is also the answer
for a function that has no patch node at all. The two are not the same fact.

A function whose patch node did not decode came out as an ordinary vertex
shader. Gone with it: the `Quads` / `Triangles` / `Isolines` execution mode
Vulkan requires of a tessellation evaluation stage, `SpacingEqual`,
`VertexOrderCcw`, and every per-patch input the pipeline has to wire. Nothing
downstream can notice -- the module validates, binds and reflects, and draws the
wrong geometry. `VertMeta::undecoded_patch_shape` carries the failure out and the
stage-input pass refuses on it, beside the entry-parameter role guard that exists
for the same reason.

The node is now found by the `air.patch` marker it carries rather than by sitting
third in the vertex root. Position is not the fact, and reading position alone
cannot tell a patch node from whatever else a root might grow -- the authored
case that pins this caught the first version of the search, which took the third
entry before checking what it was.

Over 2880 corpus sources 45 functions carry a patch node, 44 `quad` and one
`triangle`, every one at the third entry and every one decoding as before: no
module changes status and no module's SPIR-V changes by a byte.
2026-09-01 04:05:07 +03:00
Anees Iqbal 72a1bfb660 Separate a buffer with no members from one whose members disagree
`record_air_struct_offsets` matches AIR's declared member layout against the
struct the emitter produced for a buffer parameter, and reported one status --
`EmittedShapeMismatch` -- whenever it could not. Over 2880 corpus sources that
fired 1805 times, and reading it as written says the translator disagrees with
the compiler about 1805 buffer layouts.

It does not. A buffer whose accesses are byte-addressed is emitted as its raw
contents: a pointer straight to a word, or the block Vulkan requires of a
storage buffer wrapping a runtime array of one. There are no members there for
the declared offsets to land on, so no comparison was made and none failed.
That is 1733 of the 1805. `EmittedIsUntypedBuffer` names it, and what is left is
72 parameters across 70 modules where two structural descriptions of the same
memory really do differ -- a list small enough to read.

Deciding it needs the same idea the comparison needs: the block is Vulkan's
packaging, not Metal's layout, so `emitted_carries_members` steps through the
wrapper and the array before asking whether anything has members at all.

The distinction also sharpens the authored cases. Calling a `uchar3` member a
`float3` widens it to sixteen bytes and runs it over the two members after it,
and overlapping members are what pushes a buffer to a raw view in the first
place -- so that case now proves no comparison was possible, and a second case
declaring a member's type wrong without overlapping proves one was made and
failed. No module changes status and no module's SPIR-V changes by a byte.
2026-09-01 03:46:49 +03:00
Anees Iqbal eebedc3994 Size a buffer member AIR names but never describes
`air.struct_type_info` gives each member an offset, a byte size, an array
length, and a type name. When the member is a user struct or class the name is
all the metadata says about its interior -- `Espresso::padding_params_t`,
`VFX_RE_C_LightSpot`, `vfx_light::(unnamed)` -- and there is no nested node to
recurse into. The decoder answered `float` for every one of those, which states
a type AIR never stated and sizes the member at four bytes no matter what it
declared. Over 2880 corpus sources 2513 such members appear across 817 modules,
and 2357 of them declare a size other than four; the largest understates a
408-byte member by 404.

`AirType::Opaque { size }` makes the case representable, so the decoder can say
what AIR said and nothing more. Every consumer that needs a concrete type still
gets one -- the same size-derived storage shape that argument-buffer handles and
non-strict nested structs already use -- but the two consumers that need the
truth now get it. `air_metadata_extent` bounds a decoded layout against
`air.arg_type_size`, so understating a member let a layout that over-runs its
argument pass the check; with true sizes every corpus layout still fits, which
is the corroboration the old numbers could not give. And the emitter's member
matcher no longer demands a shape the metadata never stated: an emitted member
occupying exactly the declared bytes is the member AIR meant, where a float leaf
matched nothing and threw away the declared offsets for the entire buffer.

Making the variant explicit also forces the question at every site: four
exhaustive matches on `AirType` had to decide, rather than silently inheriting
`float`. Over the corpus no module changes status and no module's SPIR-V changes
by a byte. `REFLECTION_VERSION` is now 37 because reflected `type_layout`
reports the new variant.
2026-09-01 03:30:49 +03:00
Anees Iqbal fed00f1e18 Stop a fragment demanding features for a parameter it does not have
A `[[function_constant(x)]]` entry parameter exists only when the pipeline
supplies `x` as true, and nothing supplies function-constant values here -- so a
gated parameter is absent and its uses are statically dead. The vertex and
kernel decodes already treat one that way: their role reader collapses a gated
argument back to the wrapper unless it is a promoted resource. The fragment
reader looked past the wrapper unconditionally, and wired the builtin anyway.

For a resource that distinction does not matter, and must not: the descriptor
stays in the pipeline layout the application binds against either way. For a
system value it does. A builtin declared for an absent parameter puts a variable
in the entry point interface, and `[[viewport_array_index]]` and
`[[render_target_array_index]]` put `ShaderViewportIndex` / `ShaderLayer` in the
module -- device features the shader never reads, narrowing which devices can
create the pipeline.

Over 2880 corpus sources, 25 modules change and none changes status: 47
capabilities, 51 Input variables with their loads and conversions, and 98
decorations go away, and nothing is added but the undef values those absent
parameters already bind elsewhere. spirv-val clean throughout.
2026-09-01 03:15:57 +03:00
Anees Iqbal 1a7920a8e1 Read the coverage a fragment is handed
`[[sample_mask]]` on an argument is the coverage the rasterizer produced for
this fragment; AIR spells it `air.sample_mask_in` to tell it apart from the
return member of the same name. It had no lowering, so a shader that intersects
its own mask with the incoming one read zero coverage and intersected everything
away.

SPIR-V uses one builtin in two storage classes, so a shader that declares both
directions produces two `SampleMask` variables -- an Input read through element
zero and an Output written through it. `LoadVarComponent` already loads a
composite and extracts a component, which is the same shape for a `uint[1]`
array as for a builtin vector.

A gated-off argument stays absent: declaring its builtin would put a variable in
the entry point interface for a value the shader cannot read. That is 13 corpus
modules, and with the gate no module's SPIR-V changes by a byte.
2026-09-01 03:09:00 +03:00
Anees Iqbal 74c0054375 Reject a builtin parameter the emitter cannot wire
`position`, `point_coord` and `front_facing` each declare a SPIR-V builtin of a
fixed shape, and a parameter of any other shape was bound to a zero. That put
every fragment of a mistyped `[[position]]` at the origin and called every
triangle of a mistyped `[[front_facing]]` back-facing -- in a module that
validated, bound the same descriptors and reflected as though the builtin were
connected.

The branch is unreachable on real AIR: Metal fixes each attribute's type, and
over 2880 corpus sources nothing changes by a byte. It rejects now so the silent
zero cannot come back.

One authored fixture declared `[[position]]` as a scalar `float` while testing
something else entirely; it now says `float4`, which is what AIR would say.
2026-09-01 03:00:44 +03:00
Anees Iqbal bbd66ec226 Give a dispatch its threadgroup size under either Metal spelling
`[[dispatch_threads_per_threadgroup]]` had no lowering, so the parameter read a
zero -- and every shader that used it divided or indexed by that zero. Since the
guard two commits ago it FALLBACKs; now it translates.

Metal distinguishes it from `[[threads_per_threadgroup]]` only under
`dispatchThreads:`, where a final partial threadgroup reports a smaller actual
size than the dispatch asked for. `vkCmdDispatch` issues whole workgroups only,
so in this translation the two denote the same value and share one role.

Over 2880 corpus sources: 2 modules go from FALLBACK to a spirv-val-clean
translate, and no other module's SPIR-V changes by a byte.
2026-09-01 02:55:34 +03:00
Anees Iqbal a72afbe1db Read the barycentric weights a fragment asks for
`[[barycentric_coord]]` gives a fragment the three weights of the covering
primitive's vertices. It had no lowering, so the parameter read a zero -- a
degenerate barycentric that names no vertex, in a module that validated and
reflected normally. Since the previous commit it FALLBACKs instead; now it
translates.

Vulkan spells the perspective-correct and screen-space forms as two builtins
rather than as a builtin plus a decoration, so the marker AIR states on the
argument picks `BaryCoordKHR` or `BaryCoordNoPerspKHR`. Both come from
`SPV_KHR_fragment_shader_barycentric`, which `module_cleanup` now requests from
the decoration alongside the capability -- through a `require_extension` helper
that replaces the three copies of the same idempotent push.

A function-constant-gated argument that is off by default is absent, and is
left zero-bound: materializing its builtin would make the module require the
extension for a value nothing reads, narrowing the devices that can create the
pipeline. A parameter that is not a float3 has no honest lowering and rejects.

Over 2880 corpus sources: 2 modules go from FALLBACK to a spirv-val-clean
translate, and no other module's SPIR-V changes by a byte.
2026-09-01 02:51:28 +03:00
Anees Iqbal 7c33f4f197 Reject an entry parameter nothing knows how to read
An unrecognised entry parameter is bound to a zero value so the body stays
well formed. That is right for a function-constant-disabled resource, which
Metal itself defines as absent, and wrong for a system value the emitter does
not model: the shader reads zero where the hardware would have supplied a
barycentric coordinate or a simdgroup index, in a module that validates, binds
and reflects exactly as if nothing were missing.

Each stage now carries the roles it models as an inventory and records the
parameters it cannot place; emission rejects on the first one, naming it.
The role is read with `declared_role`, which reports none for a bare
`air.function_constant` parameter -- there is no role behind the wrapper, and
reading past it lands on the node's own `air.arg_type_name`.

Over 2880 corpus sources, 8 modules move from a silently wrong translate to a
FALLBACK naming the role -- barycentric_coord (2), amplification_id (3),
dispatch_threads_per_threadgroup (2), thread_index_in_simdgroup (1) -- and no
other module's SPIR-V changes by a byte. Each of those four is a lowering that
can be written; until it is, the rejection is what says so.
2026-09-01 02:40:47 +03:00
Anees Iqbal 547ac579e1 Reject a stage output nothing knows how to write 2026-09-01 02:30:31 +03:00
Anees Iqbal 0a6ebea88c Write the coverage mask a fragment returns 2026-09-01 02:23:42 +03:00
Anees Iqbal 48b12decd1 Carry a position's invariance guarantee into the module 2026-09-01 02:13:46 +03:00
Anees Iqbal 55bb249b8b Interpolate a fragment input the way AIR asked 2026-09-01 02:05:10 +03:00
Anees Iqbal f8af350514 Read a static initializer from the section AIR marks it with 2026-09-01 01:50:18 +03:00
Anees Iqbal f5c56ecbc8 Pin both sides of the function-constant-gated indirect call 2026-09-01 01:33:03 +03:00
Anees Iqbal e92509f71e State which AIR sampler bits are decoded and which are not
`from_air_words` returns `Err` for an unrecognized code in a field it reads --
inventing a filter or an address mode would silently change how the shader
samples -- but says nothing about the bits it never looks at, which a reader can
only find by diffing the shifts against 64.

Write the whole bit map down and pin it with a test that asserts both halves: the
decoded fields, each given a value distinct from its neighbours so a swapped
shift cannot pass, and the ignored ranges, whose every bit set changes nothing
but `raw_words`.

The ignored ranges are worth stating because one of them is not empty. Bit 63 of
`words[0]` is set on 151 of the 1084 static samplers in a 2880-source corpus,
with no correlate among the decoded fields -- the same filter, coordinate,
compare and clamp combinations appear with it and without it. Nothing here says
what it selects, so nothing here acts on it; `words[0]` bits 24-31 and 60-62 and
`words[1]` bits 16-63 are zero throughout that corpus. `raw_words` is what a
consumer that learns bit 63's meaning would read.

No behavior change.
2026-09-01 01:14:05 +03:00
Anees Iqbal 9f0123eb41 Reject a member layout that reaches past its argument
AIR states a buffer argument's size (`air.arg_type_size`) and the member layout
inside it (`air.struct_type_info`) as two independent facts, and reflection
reconstructs them independently. When the reconstruction over-runs the declared
size, some member's storage was mistaken and every member after it names an
offset the shader never reads.

Nothing else catches that. A consumer packs its upload at the reported offsets,
so the disagreement is silent data corruption rather than anything a driver
reports, and the emitted SPIR-V does not settle it either -- a buffer whose
reconstruction is that far off is represented as raw bytes and declares no struct
type to compare against. `validate_descriptor_abi`, which both reflection paths
run, now rejects it, so the class that produced the previous commit becomes a
translation error rather than a number a consumer has to re-derive.

Reaching short stays valid: the declared size is a `sizeof` and carries tail
padding. Over 2880 corpus sources 1340 reported layouts legitimately stop short
and none over-run, so the gate rejects nothing that translates today.

The bound needs `air_metadata_extent`, not `air_metadata_size_align`. The latter
answers a different question -- the stride a pointee type needs -- and rounds to
alignment, which over-runs the declared size for 96 corpus buffers whose layout
is correct. It also inflates an array of `packed_half3` from six-byte to
eight-byte elements, since the memcpy rule floors array alignment at four,
whereas AIR states the per-element size in the member tuple itself.
2026-09-01 01:05:23 +03:00
Anees Iqbal dd04f204e1 Report an argument-buffer handle at the size it occupies
Metal spells a resource-handle member of an argument buffer with the type it
points AT -- `char` for a `device char *`, `float4x3` for a `device float4x3 *`,
`texture2d<half, sample>` for a texture, an opaque class name for a
`device Foo *` -- while the member itself stores an eight-byte handle. Reading
that name as the member's storage put a 64-byte matrix where the buffer holds an
address, and shifted the meaning of every member after it. `MTLGenericBVHData`
reported a 120-byte member layout for its 72-byte argument, with eight of its
nine members mistyped.

The member's `air.indirect_argument` node already says which it is, and nothing
read it: `air.indirect_constant` is the one role that means "stored inline";
`air.buffer`, `air.texture`, `air.sampler`, `air.indirect_buffer`, and the
pipeline-state / command-buffer roles are all references. `parse_struct_info`
walked past that suffix to find the next member; it now binds it to the member it
trails, exactly as `embedded::embedded_argument_members` does, and lets the role
decide. An unrecognized role is treated as a reference, since the declared size
describes the bytes either way while a handle mistaken for its pointee corrupts
the rest of the layout.

Over 2880 corpus sources the split is clean: 63,137 members carry no suffix or an
`air.indirect_constant` one and every single one of them agrees with its name;
2,762 carry a resource role and every single one of them declares eight bytes.
1,736 of those were mis-sized before -- 795 named a primitive of the wrong width
across 9 type names, 941 named a type AIR never defines, which silently became a
four-byte float.

This is not only a reporting fix. Twenty-one modules' SPIR-V changes, because
`infer_metadata_buffer_pointees` types a buffer from the same reconstruction:
they declared four-byte floats at eight-byte member offsets and now declare the
addresses AIR does. No corpus source changes status, and spirv-val is clean over
all 2880.

Reflection schema v36.
2026-09-01 01:00:13 +03:00
Anees Iqbal 8f9b185908 Report the access a buffer's descriptor is actually used with
`ResourceAccess` is what a consumer reads to decide whether a buffer's contents
have to be staged, whether results have to be read back, and which barriers the
resource needs. It came from AIR metadata, tightened by the specialized entry's
parameter attributes -- neither of which is the module. AIR's declared access is
not a guarantee about the body: over 2880 corpus sources, 20 buffers reflected
`ReadOnly` are stored through, 9 reflected `WriteOnly` are loaded from, and 3
reflected `Unused` are both. `ReadOnly` on a buffer the shader writes is not a
lost optimization; it is a missing barrier, and a write into memory a consumer may
have placed as read-only.

The footprint analyzer already resolves each load and store to the descriptor it
belongs to -- through access chains, copies, phis, and function parameters -- so
the direction is one more field on the access it already collects, not a second
walk. `MemoryAccess` gains it, `analyze` returns the per-descriptor union
alongside the footprints, and `attach_buffer_footprints` widens the reported
access to cover it.

It only ever widens. The walk follows the pointer graph it can attribute, so
finding no write is not proof there is none -- an access through a device address
it cannot attribute would be missed -- and narrowing on that basis would turn a
conservative answer into a wrong one.

`OpCopyMemory` needed the direction to belong to the access rather than the
instruction: it has a reading pointer and a writing one. Atomics are classified
read-modify-write, which is conservative for the two that only read.

Verified over 2880 corpus sources: SPIR-V bytes identical, failure count unchanged
at 204, and 34 modules' reflection changed -- the 32 the access sweep named plus
two the sweep's per-class conditions did not separate. The sweep now reports 0.

New `tests/reflection_access_covers_the_module.rs`: an authored kernel that
contradicts both of its declared accesses -- `air.read` stored through, `air.write`
loaded from -- plus the same check over every public fixture. Verified as a
detector: dropping the widening fails the fixture test.

`REFLECTION_VERSION` 34 -> 35, `docs/REFLECTION.md` follows, and
`reflect_sanitized`'s doc comment now lists all three per-binding fields that are
the declaration rather than the module when no module is built.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-09-01 00:34:11 +03:00
Anees Iqbal ff227d77ea Check the descriptor count a consumer is told to allocate
`docs/REFLECTION.md` tells a consumer to group reflected entries by
`(set, binding, descriptor type)` and take the largest `count`. That number is
what sizes `VkDescriptorSetLayoutBinding::descriptorCount`, so if it does not
reach the largest array the module declares at that binding, the layout is smaller
than the array the shader indexes into. The rule was documented and untested.

`assert_counts_cover_declared_arrays` reads the largest `OpTypeArray` behind each
decorated binding out of the module and requires the grouped maximum to cover it.
An authored `array_ref<texture2d<float, sample>>` kernel is the case with a real
array -- it declares the descriptor-ABI capacity, 128 -- and the fixture sweep
runs the same check. Verified as a detector: reporting one fewer descriptor for a
`TextureArray` fails both.

Measured over 2880 corpus sources first, since a test that only ever passes is not
evidence: 0 bindings where the module's array outruns the grouped maximum. The
naive comparison -- each entry's own `count` against the module -- reports 193
across the function-constant-gated modules, where one binding legitimately carries
both a scalar and a 128-element variable and reflection reports an entry for each.
That is the case the grouping rule exists for.

The same sweep compared `local_size` against `OpExecutionMode LocalSize`: 0
disagreements over 2880 sources, so no check was needed there.

No product change.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-09-01 00:23:01 +03:00
Anees Iqbal b8fcc4cd44 Let only sampling decide a texture's binding class
AIR declares each texture argument's access, and reflection reports a write-capable
one as a storage image at `STORAGE_TEXTURE_BINDING_BASE + n`, which is where a
consumer writes its descriptor. The emitter chose the binding class from what the
BODY does instead, and a size query counted as a sampled-image use. So a
`texture2d<float, write>` whose body only calls `get_width()` bound at
`TEXTURE_BINDING_BASE + n`: the consumer wrote its descriptor somewhere the shader
does not read.

Only sampling can decide this -- `OpSampledImage` is what requires `Sampled` 1.
Everything else AIR does to a texture has a form for either class: `read_texture`
is `OpImageRead` on a storage image and `OpImageFetch` on a sampled one, size and
sample-count queries have an opcode each, `get_num_mip_levels` folds to one level
on a storage image, and `is_null_texture` folds to a constant.

The rule took two pieces before, and the gap was between them: `texture_dims`
skips the read and query uses of a texture the body WRITES, and
`storage_texel_read_operands` restored the ones a texel read had otherwise
disqualified. A texture AIR declares write-capable but the body never writes fell
through both. `sampled_binding_required_operands` replaces the pair with the one
question that matters, and `storage_texel_read_operands` is gone.

`air.gather_*` is not in the set, preserving what this classification has always
done: a gathered AND written texture would need one descriptor to be both
`Sampled` 1 and `Sampled` 2, the read-write-with-format case `write_texture_dims`
documents as out of scope, and adding it converts those shaders into a
write-lowering failure instead of resolving anything. I tried it: one corpus
module regressed that way. Whether a gathered storage image reaches a correct
lowering is unaudited and stated as such.

Verified over 2880 corpus sources: bytes identical, reflection identical, failure
count unchanged at 204. The gap needs a texture AIR declares writable that the
body never writes, which no corpus shader does.

New `native_write_declared_texture_binds_as_storage_even_if_the_body_only_queries_it`
checks the module against the binding reflection reports, and is verified as a
detector. `native_kernel_helper_wrapped_write_texture_query_resolves_loaded_image`
was pinning the old behavior with an incidental `OpImageQuerySizeLod` assertion;
its subject is that the query resolves to the wrapped texture, so it now expects
the LOD-less form a storage image takes.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-09-01 00:17:30 +03:00
Anees Iqbal a0995c4b3e Stop two callers sharing one scratch directory from failing each other
`spirv_val_bytes` wrote its input to `tmp/a2v_val.spv` and `air_to_sanitized_ll`
wrote `llvm-dis` output to `tmp/k.ll`. `tmp` is caller-supplied and callers do
share one: parallel tests, a sweep's worker threads, and separate processes
pointed at the same directory. A fixed name there is shared mutable state -- one
caller overwrites another's input and then deletes it, and the external tool
reports on a file that is not the one the caller asked about, or on no file at
all.

It surfaces as a validation failure in a module that is fine, which is a false
alarm the reader cannot tell from a real one. I hit it: `constructed_shapes_are_
valid_spirv` failed once, in a run where another `cargo test` process was
validating into the same fixed directory, and passed every time after.

One `scratch_file` names the file after the process and the call, so both callers
stop sharing rather than every caller having to remember to pass a private
directory. `cfg_testkit`'s deliberately fixed `m2v_cfg_testkit_val` is now safe as
written; the relooper and reloop-nest helpers already made per-process
directories.

New `concurrent_validations_sharing_one_scratch_directory_do_not_collide`: eight
threads validating one module into one directory, 16 times each. Verified as a
detector -- with the fixed name restored it fails on all three of three runs.

Verified: 2880 corpus sources byte-identical, reflection included, failure count
unchanged at 204.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-09-01 00:07:42 +03:00
Anees Iqbal de0ffdaa53 State once which images can carry a LOD in a size query
SPIR-V allows `OpImageQuerySizeLod` only on an image whose `Dim` is 1D, 2D, 3D, or
Cube, whose `MS` is 0, and whose `Sampled` operand is not 2. Two lowerings emit a
size query and each carried its own idea of that rule: `lower_image_size_query`
handled storage and multisample images, `query_image_size` handled only storage,
and neither handled `Dim Buffer`.

So `texture_buffer::get_width()` -- ordinary Metal -- emitted
`OpImageQuerySizeLod` on a buffer image. The owned-module check caught it and the
whole translation fell back, which is honest but wrong: the shader is expressible,
with the LOD-less `OpImageQuerySize`.

One `image_size_query_op` now states the rule, and both lowerings ask it. A new
`image_value_dim` reads the `Dim` from the pass-side record when there is one and
from the emitted `OpTypeImage` otherwise, matching how the storage and multisample
predicates beside it already work.

New `native_buffer_texture_size_query_uses_query_size_without_lod`, verified as a
detector: at the parent commit it fails with the fallback. It names the two
existing cases that cover the other arms rather than restating them, since all
three now go through the one predicate.

Verified: 2880 corpus sources are byte-identical, reflection included, and the
failure count is unchanged at 204 -- no corpus shader queried a buffer texture's
size, so this is coverage the corpus does not reach.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-09-01 00:03:05 +03:00
Anees Iqbal 9d629a3e9f Reflect the image the module binds, not the one the type name implies
`ShaderReflection::texture_shape` is what a consumer feeds into
`VkImageViewCreateInfo`, and Vulkan requires the created view's type to match the
`Dim` and `Arrayed` of the image variable the descriptor is read through. The
shape was decoded from the AIR type name, and the emitter does not always bind the
image that name implies: SPIR-V has no cube texel fetch, so `resources::discovery`
binds a `texturecube` that is only ever texel-read as a `Dim2D` ARRAY image with
the face in the layer slot. Reflection kept saying `Cube`, so a consumer following
it created a `VK_IMAGE_VIEW_TYPE_CUBE` view for a 2D-array image variable and the
dispatch was invalid.

`reconcile_texture_shapes` corrects each shape from the module's own `OpTypeImage`
at that binding, the same way `reconcile_buffer_address_table` and
`report_synthesized_placeholders` read their facts off the finished module.
`array_ref` and `array_length` describe the descriptor array rather than the
image, so they stay with the metadata that decides the descriptor count.

A binding is only corrected when its image variables all declare the SAME image
type. A function-constant-gated `air.location_index` puts several
differently-shaped variables on one binding -- 67 corpus modules do -- and there
the module has no single answer to read: the consumer picks one by choosing its
function constants. `reflect_sanitized` builds no module and keeps the
type-name-derived shape; its doc comment already listed what it approximates.

`TextureFormat::from_spirv_format` inverts the existing `to_spirv_format` over a
new `TextureFormat::ALL`, with a round-trip test that also proves the mapping is
injective -- otherwise the inverse would not be single-valued.

Measured over 2880 corpus sources by comparing every reflected shape against the
`OpTypeImage` behind its binding: 2 modules disagreed, both cube textures
reflected as `Cube` while the module declares 2D arrayed; 0 after. SPIR-V bytes
identical and the failure count unchanged at 204; exactly those 2 modules' -- and,
from the version bump, every module's -- reflection changed.

New `tests/reflection_describes_the_image_it_binds.rs`. The cube fixture binds one
AIR type name, `texturecube<float, ...>`, as two different emitted images: the
texel-read source as a 2D array, the written destination as a cube. Verified as a
detector -- with the reconcile removed it fails. A second authored kernel covers
four shapes across dimensionality, component class, and storage format, and
asserts they stay four distinct shapes so a decoder that widened them all could
not pass by moving both sides together. Only one public fixture binds a texture,
which is why the grammar probe carries the coverage; the fixture sweep is there
for when that changes.

`REFLECTION_VERSION` 33 -> 34: a cached v33 shape can name a view type the module
rejects. `docs/REFLECTION.md` follows.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 23:54:56 +03:00
Anees Iqbal e195fce0be Report the descriptors only the translator knows about
Two passes bind a real resource with no Metal argument behind it, so an AIR value
has a legal SPIR-V type: `air.get_null_texture_*()` gets an `OpTypeImage`,
`air.get_read_sampler()` gets an `OpTypeSampler`. The parent commit retracts those
whose value nothing consumes. One that IS consumed stays -- and nothing in the AIR
metadata describes it, so a consumer building its `VkDescriptorSetLayout` from
`ShaderReflection` produced a layout the module reads outside of.

This was the last of the module-vs-reflection descriptor mismatches. Over 2880
corpus sources the count is now 0, down from 267 when the oracle was first run.

`ResourceKind::SynthesizedNullTexture` and `ResourceKind::SynthesizedReadSampler`
report them. Which placeholders survive is a fact only the passes hold, so
`transform` now returns it -- `Transformed` replaces the `(Module, EmitSidecar)`
tuple -- and `finish_module` narrows the list to what the finished module still
declares, since the steps after `transform` delete instructions and the liveness
pass there can take a variable with them. Reflection reads each placeholder's
class from the module's own `OpTypeImage`/`OpTypeSampler`, and a null texture's
`texture_shape` off that image's operands, so nothing is inferred from binding
numbers. That mirrors `reconcile_buffer_address_table`, which closed the same kind
of gap for the address table.

`validate_descriptor_abi` constrains a placeholder to its ABI band rather than to
a recomputed `base + index`: it takes the first binding in the band no Metal
argument claims, so there is no index to recompute from.

Validation: `unsupported_reflection_requirements` marks a reflection carrying a
placeholder with the new `ToolingRequirement::SynthesizedPlaceholderDescriptor`.
The Vulkan executor has no authored resource to write at a descriptor no Metal
argument produces, and the Metal oracle has nothing to encode, so the row is
honestly not executable until the harness can supply a deterministic placeholder
resource. It is not claimed as supported without execution evidence. Before this,
such a row built a layout that omitted a binding the shader reads, so it was
already failing rather than silently passing. The exhaustive `ResourceKind` match
in `executor_contract.rs` is what forced the decision; that is what it is for.

`reflect_sanitized` builds no module and therefore reports neither placeholder;
its doc comment now says so alongside the address-table approximation it already
documented.

`REFLECTION_VERSION` 32 -> 33: a cached v32 reflection is missing a binding its
module declares. `docs/REFLECTION.md` gains both kinds in its binding-map and
descriptor-type tables.

Verified over 2880 corpus sources: SPIR-V bytes identical, failure count unchanged
at 204, and -- measured before the version bump, which changes every reflection
hash -- exactly one module's reflection changed, the one the mismatch scan named.

New authored fixture in `tests/reflection_covers_declared_bindings.rs`: a kernel
that queries the placeholder's width, the counterpart to the unconsumed probe
beside it. Verified as a detector: passing an empty placeholder list to
`report_synthesized_placeholders` fails exactly that test.

Gate: fmt, clippy -D warnings, warnings-denied all-features rustdoc, cargo test
-p metal2vulkan (debug and release), cargo test -p metal2vulkan-validation.
2026-08-31 23:34:36 +03:00