Commit Graph
146 Commits
Author SHA1 Message Date
Anees Iqbal 965eb0b538 Wake the scheduler thread at once for a check a commit's pass finds
A commit whose pass finds a submission check or a host step for the scheduler thread now wakes that
thread at once, instead of after its own later passes and submission handlers. The scheduler thread
runs one check or host step at a time, taking in waiting commits between them, and a commit handed
to another thread waits at most for that thread's current pass and its handlers. The commit-latency
lane measures a checked commit's wait for its submission under a consumer-like load (400 host
imports, checked command buffers from one and three threads, event waits).

Gain: the consumer's guest A/B on a Radeon 780M and an RX 7900 XTX (RADV): window drags +13-20%
frames/s, and the commit's off-CPU wait from 9.3 to 0 ms a frame. The new test's hold fell from
71-75 ms (RADV, ANV) to prompt.

Verified on the original branch: the scheduler lanes, 62 of 62 on RADV and ANV, and the runtime
crate's tests. This squashed commit was not re-tested on its own.
2026-10-14 12:15:42 +03:00
Anees Iqbal 35fb5fd962 Cut a commit's CPU on the committing and the scheduler threads
Plan each batch's hazards without per-resource allocations or a sweep of the hazard state, plan a
batch of one encoder against that state itself, list only what a commit reaches unnamed among the
live buffers, and keep the scheduler order's emptied lines and head list between passes. The
frame-cost lane measures a checked frame's commits on both threads and bounds their allocations.

Gain: commit p50 about 40% lower; 19 -> 5 allocations a commit on the committing thread and 46.9 ->
16 on the other threads, which also cuts the allocator contention from cross-thread frees.

Verified on the original branch and again on this tree: fmt, clippy in every configuration, Rustdoc,
and the runtime lanes, 1311 of 1311 on RADV, ANV and lavapipe.
2026-10-14 12:15:37 +03:00
Anees Iqbal 4600bc606d Begin two command buffers per render pass instead of four
Keep a batch's barrier command buffers and submit them again rather than beginning new ones, cut a
pass end's allocations and work where nothing needs them, count the command buffers the runtime
begins, and count a frame's instructions per step in frames of their own, outside the timed ones.

Gain: two command buffers begun per pass instead of four (ANV memsets each one twice), and a pass
end's allocations from 52 to 36.

Verified on the original branch: the runtime lanes on RADV, ANV and lavapipe. This squashed commit
was not re-tested on its own.
2026-10-14 12:15:32 +03:00
Anees Iqbal 2ccf403815 Cut a draw's encoding work on the encoding thread
Route a render pipeline state once per encoder, keep its latest four settles, keep each texture's
storage view formats, make the format candidate table once, and hold a window server frame's draws
to their allocations (at most 72 a draw), with the frame-cost lane measuring a window server's frame
on the encoding thread. The runtime-sources hash is pinned to this tree.

Gain: frame CPU on the encoding thread fell 7.8% on RADV (Radeon 780M), 13% on an RTX 3090 and 2.1%
on ANV (Iris Xe).

Verified on the original branch: the frame-cost and draw lanes on RADV, NVIDIA and ANV. This squashed
commit was not re-tested on its own.
2026-10-14 12:15:27 +03:00
Anees Iqbal 8963e1871b Submit a commit's work without waiting for the scheduler's lock
A commit no longer blocks on the scheduler's lock while another thread's pass holds it across its
vkQueueSubmit calls: it leaves its batches in a commit inbox that the pass under way takes in, in
commit order. A batch's first work rides in the batch's own vkQueueSubmit, a batch with nothing to
end submits no command buffer, and the runtime counts its queue submissions and live memory blocks
per commit.

Gain: on an Intel Iris Xe host (ANV on i915), the consumer's guest A/B measured a Finder window drag
at 22.1 -> 34.4 frames/s and Safari at 39.1 -> 42.7 frames/s.

Verified on the original branch: the runtime lanes on ANV and lavapipe. This squashed commit was not
re-tested on its own.
2026-10-14 12:15:22 +03:00
Anees Iqbal 4b564766ec Sample extended-range textures through Metal's bicubic filter
A sample of a BGR10_XR, BGRA10_XR or RGB10A8_2P_XR10 texture (or an sRGB twin) through a constexpr
bicubic sampler, or through a runtime sampler whose bound word states Cubic, was refused
(NotImplemented(SamplerBicubicFilter) in the lowering, NotImplemented(Format) in the binder). It is
now Metal's bicubic filter of the decoded texels, measured on an Apple M3 Max (macOS 26.7) through
the owned fixture xr_bicubic: random codes of each of the six formats at 16x16, 7x5, 3x3, 2x6 and
1x1, 2,304 coordinates each (every texel's centre, then random ones up to 0.15 of the texture past
its edges), through 12 kernels (a runtime Cubic sampler with float and half results; constexpr
samplers under clamp to edge with float and half results, repeat, mirrored repeat, clamp to zero,
the opaque-white and opaque-black borders, pixel coordinates, and an offset under clamp to edge and
repeat): 3,317,760 lanes.

What Metal does, and what the lowering now does: the footprint, weights, addressing, a mirrored
axis and a level below four texels are the other formats' bicubic filter's, each tap the decoded
texel or the border texel through the format's channels; a level below four texels sums as the
extended-range linear filter (terms truncated); otherwise each tap's step is weighed by the
product of Metal's weights and summed exactly (no term truncated, unlike the linear filter), the
step rounded half up, clamped into the steps of the codes 0 and 1023 (a color lane's (0-384)/510
and (1023-384)/510, an sRGB twin's table steps, alpha [0, 1]), and divided by the grid exactly; a
half result rounds as the linear filter's does. The clamp is applied to the rounded result, which
equals clamping the step because each rounding is monotonic. Every lane but 4,050 matches that
model; each of the 4,050 is one step from Metal's (1/8160 a color lane, 1/8192 an sRGB color lane,
1/4080 alpha), its exact sum within 0.014 of a step of a rounding tie that Metal rounds the other
way. No model of Metal's datapath tried closes that residue, so the sample records
PrecisionNote::BicubicFilterArithmetic, and docs/FAST-PATHS.md and docs/API.md say so. A bfloat or
padded form's bicubic sample, a swizzled texture's and a gather through a bicubic sampler were not
measured and are refused.

How: select_extended takes the bicubic state of a constexpr sampler or of the slot's cubic-sampler
variant (LoweringInputs::cubic_samplers) and plans Metal's bicubic filter; the extended sampler emits
it through bicubic::filter with Texels::Extended, which fetches each tap's raw texel and decodes it,
through the exact routines alone, then clamps. The binder takes a cubic word at an extended-range
slot as the cubic-sampler variant's, and gives such a slot the neutral BicubicTexels value in the
plan of the pipeline as compiled, which binds the neutral there (it refused the format before
naming the variant: the device lane found that). SEMANTICS_VERSION 1693; RUNTIME_VERSION 1184, as
a run of an existing artifact with a cubic sampler at an extended-range slot is no longer refused;
the runtime-sources hash re-pinned.

The table: xr_bicubic.tsv (2,067 samples of the probe's, per texture and kernel the middle
texel's centre, four random coordinates, the first sample with a lane at a clamp bound and the
first with a lane at a tie), shared through metal2vulkan_devtools::xr_bicubic with the probe's
texture generator.

Verified on homelab-gem10 (debug builds):
- tests::engine_extended_range::bicubic, on the CPU interpreter on the lavapipe and MoltenVK-M3
  profiles: every lane of the table through the same 12 kernels, compiled under the six forms'
  variants (the runtime ones under the cubic-sampler word the binder plans), is Metal's bits but
  the 136 lanes the table marks, each one step away; each compile validates and its estimate
  bounds it. A padded or bfloat form's bicubic sample, a swizzled texture's and a gather are
  refused as above (a two-plane gather as Format, under any sampler); on every committed profile
  the pipeline as compiled plans the variants with the XR texture and a Cubic sampler bound, and
  the variant's pipeline plans the same key.
- runtime_lane::extended_range_bicubic (new): the 8,268 lanes on the Radeon 780M (RADV), the RTX
  3090 and lavapipe, textures written as the probe wrote them: 0 differ from Metal (136 at a tie,
  one step away), and the state announces bicubic-filter-arithmetic. The extended_range_samples,
  two_plane_samples and two_plane_copies lanes, whose helpers this shares, pass on all three.
- Release build, 12 kernels x 6 forms x 5 profiles (lavapipe, 780M, RTX 5080 Laptop, Arc ANV,
  MoltenVK-M3): 360 translations, mean 1.31 ms, slowest 1.97 ms (xrb_runtime, BGRA10_XR sRGB,
  780M), budget ledger peak at most 935 KiB, process peak RSS 15.6 MB; the linear XR kernels
  take 0.81 ms on average.
- clippy -D warnings (workspace, all features, all targets; validation also under m2v_gpu),
  rustdoc -D warnings and the doctests pass. Suites: metal2vulkan, -air, -runtime and -devtools
  4,566 of 4,567, validation 1,293 of 1,293. The one failure is tests::golden_hashes, whose 380
  stale cells are the two new fixtures' alone (smw_writers 7 and xr_bicubic 12 entries x 20
  profiles), left to be blessed on development.
2026-10-13 17:04:18 +03:00
Anees Iqbal 8f3edd5a6c Select a moved writer's depth and stencil tests in the pipeline's first plan
A render pass instance can move a color that a fragment function writes as a plain output into the
interlocked storage form: a color it keeps out of its subpass for other draws' interlocked form, or
an extended-range color whose half shadow it holds. The variant that writes the color so stores
before the depth and stencil tests and states TestedStorageWrites, from which its plan selects the
early-tests variant or the function's own tests. The pipeline as compiled stores no color so and
stated nothing, so its plan named a variant without those tests; that variant, compiled, planned
another one, and the runtime failed the draw with the internal error "the plan of a compiled
variant asks for another variant".

The fetch planner now states MovableStorageWrites { early_variant } for a function that writes
color 0 through its first output on a device that requires ordered fetch, where it discards, writes
other memory, or returns depth, stencil or a sample mask, by the rule the tested writes use
(stored_before_tests, now shared). The graphics plan reads it, for a draw that moves a color the
function writes, as it reads TestedStorageWrites, and a moved color's write counts as a store under
any mask, so the variant states the same tests and plans itself. SEMANTICS_VERSION 1692 and
ARTIFACT_FORMAT_VERSION 399 (a new encoded fact).

The owned fixture smw_writers has one plain writer per way the tests bear on such a store, and its
fullscreen triangle.

Verified on homelab-gem10 (debug builds; the unchanged translator built in its own target dirs):
- tests::engine_moved_writers: on the 12 committed profiles that order fetch through the pixel
  interlock and require it ordered, for 6 writers x 2 moves x 6 kinds of draw tests, the plan of the pipeline as
  compiled names the variant the moved writer needs, and that variant, compiled, plans itself, or
  both refuse the draw. On 61a2efc7d3 the same check finds 32 of the 72 states per profile (384
  in all) whose named variant asks for another, and 8 per profile (96) refused only after the
  variant compiled.
- runtime_lane::moved_writers (new): three draws in a pass over an RGB10A8_2P_XR10 color and a
  depth-stencil attachment, under 8 depth and stencil states. It passes on the Radeon 780M (RADV),
  the RTX 3090 and lavapipe; on 61a2efc7d3 it fails 3 runs of 3 on RADV at its second case with
  the internal error above. Metal's answer (each pixel's codes and smw_store's run count) was read
  on an Apple M3 Max, macOS 26.7, through the same fixture.
- clippy -D warnings (all features, all targets; validation also under m2v_gpu) is clean.
- rustdoc -D warnings and the doctests pass. The suites: metal2vulkan, -air, -runtime and
  -devtools 4,558 of 4,559 pass, validation 1,293 of 1,293 with the hash below; the one failure
  is tests::golden_hashes, whose 140 stale cells are the new fixture's alone (7 entries x 20
  profiles), left to be blessed on development.

The binder's sources are runtime inputs, so the pinned runtime-sources hash moves; RUNTIME_VERSION
does not: a run of an existing artifact plans as before, since no existing artifact states the new
fact and the new mechanism row names only it.
2026-10-13 16:23:39 +03:00
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