Commit Graph
332 Commits
Author SHA1 Message Date
Anees Iqbal 4b88203551 rt: a texture over a Managed buffer's device copy that the device's linear image does not take is copied at Metal's Managed events
Where the device's linear image does not hold a texture over a Managed buffer's device copy in
place (another pitch, an offset off the image's memory alignment, a format or usage the linear
tiling lacks), the texture was refused (Gap::TextureOverBuffer). It is now an optimal image of
its own, copied from and to the device copy only at Metal's own Managed events, with no tracking
of commands:

- in, from the device copy, by the upload that leads the next submission using the texture,
  where a did_modify_range met its range (after the upload's copy of that range) or submitted
  device work wrote the buffer (a binding whose compiled interface writes it: the translator's
  uses, not the declared access; a blit or fill into it) or another texture over a range that
  meets its;
- back, where device work wrote the texture, before the next reader of the device copy (a
  binding that reaches the buffer, a blit from or into it, a copy into another texture over a
  range that meets its, a synchronize_resource, a did_modify_range over it). A reader recorded
  after the write takes it in its own commands; the upload that leads a submission, which runs
  before the submission's commands, takes it only once the write's segment was submitted
  (Segment::managed_wrote; the segment's submission settles each write it made).

The buffer keeps each such texture's entry (ManagedOvers). A texture released while its copy
back is owed leaves its image with the buffer until a reader takes it or the buffer is released;
a lookup by id skips a released entry, whose id a texture made since may hold. The Shared rules
(crate::over's per-submission copies) now apply only to textures over a buffer of no device copy
(copied_shared). The planner ruled that Managed keeps its device side; this is that side's copy
form.

Tests (device cfg): the Managed device test (100 uses copy in once; a modify over the range
copies once, one outside it not at all; a kernel's write owes one copy, a read none; a written
texture read through its buffer by a blit; a synchronize; two textures over one range; a
released texture whose buffer goes copies nothing back and frees its image; one released before
a kernel reads its buffer goes back first), and a kernel that declares a Managed buffer
read-write and never touches it owes no copy. README, Gap::TextureOverBuffer's doc and
docs/REFUSALS.md follow.

Verified: lint m3-max-44117 and device legs m3-max-44136 (780M HawkPoint, 3090), 44137 (RX 550),
44138 (XTX, 2080, 780M Phoenix, lavapipe), 85/85 each with the validation layer on, on the same
tree based on ed6d11d477. The Managed tests ran on the six GPUs and took the Shared rule on
lavapipe. An earlier form, which marked a write's copy back owed at its encoding, failed the last
step on five GPUs (m3-max-44101, 44102, 44103): the upload leading the write's own submission
took it before the write ran.
2026-11-17 20:47:55 -08:00
Anees Iqbal 1ada6e8b1c rt: a texture over a buffer of no device copy that the device's linear image does not take is copied between the buffer and an image of its own
Where the in-place linear image does not hold a texture over a Shared buffer (or a Managed one
without a device copy) for its pitch, place, memory type or format features, the texture is now
an optimal image of its own instead of a Gap::TextureOverBuffer. The device copies the buffer's
bytes into it and back, one vkCmdCopyBufferToImage or vkCmdCopyImageToBuffer region a texture,
with no CPU copy (crate::over):

- in, once a submission: the upload that leads it copies into every such texture a segment uses
  before any command of the segment wrote the buffer; inside a segment, a use after a write of
  the buffer copies in again first; a segment leaning on the leading copy for a buffer an earlier
  segment of the held group wrote leads a new group;
- back, after a write of the texture: before the next command of the segment that reaches the
  buffer, and at the segment's end, whose end barrier then reaches the host.

Commands track what they write only while such a texture lives (a device count); a command
recorded while none lived counts as a write through an unbound address, so a texture made later
never leans on a copy that could precede it. Each copy counts in Metrics::over_copies and its
bytes in bytes_copied. The accepted difference (a CPU write between two held members' commits
races an uncompleted command buffer, which Metal leaves undefined) is stated at the rule and in
the README.

A texture over a Managed buffer's device copy that the linear image does not take stays a
Gap::TextureOverBuffer: the Managed branch waits on the measurement of whether a Managed buffer
keeps a device side at all.

Tests: tests::copy_over (every device under the device cfgs): a render target over a Shared
buffer at one alignment past the device's pitch copies in once per command buffer and takes the
host's writes; a fill then a use in one command buffer copies once, after the fill; a fill and a
use in two command buffers committed back to back takes the filled bytes; a blit's write to the
texture is in the buffer once the command buffer completes.

A view of such a texture shares its parent's image and id, so it is tracked and copied as its
parent; the live count counts the parent alone. An ended segment keeps its tracking, cut to the
textures that lean on the leading copy, for the submit thread to read in place.
2026-11-17 20:17:09 -08:00
Anees Iqbal 9a9135b4c9 Re-derive the generated documents at the landing tip
They are generated from the whole case set, and the set grew on `development`
while this branch was in flight, so the copy committed here counted a smaller
one.

Verified: regenerating at this tip leaves no change beyond the `Generated at`
stamp.
2026-11-17 20:12:11 -08:00
Anees Iqbal 05ce4db691 rt: Fence, MTLFence, whose updates and waits on compute and blit encoders record nothing
A command buffer's encoders run in order and a queue's command buffers in commit
order, each encoder's writes reaching the commands after it through the barrier
at its end or its segment's end, so a wait after an update already sees them. A
fence keeps the first queue whose encoder uses it; a use on another queue is
Gap::FenceOtherQueue, as Metal's fence orders one queue and MTLEvent orders
queues. Another device's fence is Refusal::OtherDevice.

Test: every_device_orders_a_wait_after_an_update_and_records_nothing_for_either
fills a buffer in one command buffer and updates the fence from a blit and a
compute encoder, waits in a second committed before the first completes and
copies the buffer out, and counts the same submissions, barriers, bytes copied
and passes with the fence calls as without; a second queue's compute and blit
encoders get the gap. REFUSALS.md and api_signatures.tsv regenerated.
2026-11-17 20:11:26 -08:00
Anees Iqbal 231a0cc003 rt: a texture over a Managed buffer lies in its device copy; blits and dispatches that write a texture over a Shared buffer reach the host
The in-place linear image binds in the bytes shaders reach: a Managed buffer's device copy
where it has one, so replace_region writes the consumer's bytes and copies the rows' span
into the copy as did_modify_range does, and get_bytes reads the consumer's bytes as Metal
reads a Managed texture's CPU copy. A blit or dispatch that writes a texture over a Shared
buffer marks its segment's end to reach the host, as a write to the buffer does.

The device test (tests/over.rs) checks the alignment answer, the in-place texture over a
Shared and a Managed buffer (nothing allocated or staged, the image the buffer's bytes as the
host changes them, replace_region and get_bytes, a blit's write reaching the host), the
layout refusals and the gap.
2026-11-17 19:54:27 -08:00
Anees Iqbal 0a39715cf8 rt: texture views, a texture over levels and slices of its parent's image with image views of its own
Texture::new_texture_view(pixel_format, texture_type, levels, slices, index) is
newTextureViewWithPixelFormat:textureType:levels:slices: (and, with the
texture's own type and every level and slice, newTextureViewWithPixelFormat:).
A view is a TextureInner over its parent's image: its own sampled and storage
image views of the subresource range, its own index and elements of set 1, no
image, memory or copy. It keeps its first parent (a view of a view composes
the ranges), shares the parent's resource id so hazards between them are one
texture's, and reports Metal's view descriptor: the extent of its first level,
its levels and slices (probe texture_view_rules.m, job m3-max-43677: width 4
for levels 1..3 of an 8-wide texture, arrayLength 2 for slices 1..3).
place() takes the texture's base level and layer, so blit copies,
replace_region and get_bytes through a view reach the parent's levels and
slices under it. The view's image views go to the reaper (Free::Views) when it
drops; Gauges::textures counts views until then.

Built, from replay's compute-bound views (gb 18, b2 19): the parent's own
pixel format over every slice in its type, a slice subrange of a 1D or 2D
array, one slice of a 2D array as a 2D texture, each over any level
subrange. Refused as Metal's validation stops them (job m3-max-43677):
Refusal::TextureViewRange (empty or past ranges) and
Refusal::TextureViewFormat (another format without PixelFormatView usage).
Not built: Gap::TextureView naming the kind (TextureViewKind: PixelFormat,
TextureType, Slices, Swizzle).

Test (device cfgs): tests::view::every_device_views_levels_and_slices_of_a_texture:
six views and a view of a view report Metal's descriptor and read Metal's
bytes (the probe's FNV-1a 64 of each view's level 0 copied out), each view
costs 0 submissions, 0 blocks and 0 bytes copied; the three range refusals,
the format refusal and four gap kinds; views outlive their parents' handles
and every gauge falls to zero. The blit tests' Side carries the base.
README, REFUSALS.md and the signatures table updated.
2026-11-17 19:35:25 -08:00
Anees Iqbal b37339a609 rt: a blit encoder synchronizes a Managed buffer, one copy of its device copy into the consumer's bytes
BlitCommandEncoder::synchronize_resource is synchronizeResource:. Of a Managed
buffer with a device copy (Shared memory not device-local) it records one
vkCmdCopyBuffer of the copy into the consumer's bytes between the two barriers a
fill records, and marks the segment so its end barrier reaches the host: the
host reads the GPU's writes before the call once the command buffer completes or
it sees an event signaled after it. A buffer without a device copy is read by
the host where shaders write it, and a texture has no bytes the host reads
apart from its image (no texture has named bytes on development yet): for
those the call records nothing. Every call is counted in the new
Metrics::synchronizations and is no submission of its own.

Metal's validation stops a synchronize of a Shared or Private buffer or
texture (probe blit_synchronize_rules.m, job m3-max-43632: "synchronizeResource:
only applies when ... == MTLResourceStorageModeManaged"); rt keeps no storage
mode for those and records nothing, as the old runtime does. The probe's
Managed buffer, filled 4..12 with 0xab and synchronized, hashes
5d28bc84b408472d, the bytes the test asserts.

The barrier after a blit's write into a buffer is one helper now (fill, buffer
copy, synchronize); a buffer copy's source stage widens from COPY to
ALL_TRANSFER.

Tests (device cfgs): every_device_synchronizes_a_managed_buffer (a fill alone
leaves the host's bytes where the buffer has a device copy; fill + synchronize
gives Metal's bytes at 1 submission, 5 barriers with a device copy and 3
without, 0 bytes copied, 1 synchronization, 1 host reach; a texture's
synchronize records no barrier) and
every_device_reaches_the_host_only_after_a_blit_writes_shared_memory (the
wrote_host invariant for blit encoders: fills and copies into Private memory
or a texture reach no host, into a Shared buffer they do). README,
REFUSALS.md and the signatures table updated; the README drops the line that
said synchronizeResource comes with blit encoders, and names
synchronizeTexture:slice:level: as not built (no recorded stream calls it).
2026-11-17 19:08:48 -08:00
Anees Iqbal 594b86d1f2 rt: the floor asks the created device for support of the runtime's set layouts
vkGetDescriptorSetLayoutSupport is Vulkan's answer to whether a set layout can be made; the
limits the floor checks do not promise it. MoltenVK 1.4.2 on an M3 Max reports set 1's layout
(65,536 sampled images, 4,096 storage images, three arrays of 4,000 samplers, update after bind)
unsupported, and the validation layer then names VUID-vkCreateDescriptorSetLayout-support-09582
at device creation (probe job m3-max-43634).

Arrays::make asks it for the empty set 0 and for set 1 before making either; an unsupported one
refuses the device with Error::BelowFloor and the new Missing::SetLayout { set }. Vulkan answers
it only for a created device, so PhysicalDevice::check cannot. Set 1's layout is built in one
place, with_arrays_layout, for the query and the creation.

Tests: every_device_supports_the_runtimes_set_layouts (each device of the cfg's kind supports
both), a_set_layout_the_device_does_not_support_is_named. README floor section, REFUSALS.md and
api_signatures.tsv regenerated.
2026-11-17 18:52:30 -08:00
Anees Iqbal e9f43bb855 rt: blit buffer copies and fills reach a buffer through its device range, and keep the buffer
Development's Managed buffers (ee7c4a5173) replaced held_block with held and device_range: a
Managed buffer's GPU side is its device copy where the Shared type is not device-local. A blit copy
or fill now records against device_range's VkBuffer and offset (alignment checked from that
offset) and keeps the buffer through Building::keep, which keeps a device copy too; is_shared
answers false for a buffer with a device copy, so only a copy or fill into the bytes the host
reads marks the segment. The lint of a172c73d93 (m3-max-43607) was cancelled before it compiled:
held_block no longer exists. Docs say 'the bytes shaders reach' where they said the block.
2026-11-17 18:37:18 -08:00
Anees Iqbal 2cb7ea189d rt: a blit encoder fills a range of a buffer, one vkCmdFillBuffer between two barriers
fill_buffer (fillBuffer:range:value:) records vkCmdFillBuffer of the byte four times over in each
word against the buffer's own range of its block, between the two barriers a copy records (the
second from every transfer stage's writes to every later command), and a fill of a Shared buffer
marks the segment so its end barrier reaches the host.

Probe blit_fill_rules.m on an Apple M3 Max, macOS 27.0.1: Metal's validation stops an empty range
and one past the buffer's end (job m3-max-43573), Refusal::FillRange; it takes ranges of no whole
words (job m3-max-43571), which vkCmdFillBuffer cannot write: Gap::FillAlignment until a replay
stream makes one.

Tests: the range checks (offset from the buffer's place in its block, empty, past the end,
reversed, unaligned start, length or block offset); a device test filling 4..12 of a 64-byte
Shared buffer with 0xab, its bytes plain Metal's FNV-1a 64 (job m3-max-43571), at one submission,
three barriers, no byte of the runtime's own.
2026-11-17 18:37:18 -08:00
Anees Iqbal 8e39e812e5 rt: a blit encoder copies between a buffer and a texture, one copy command an image of the region
copy_from_buffer (copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:sourceSize:
toTexture:destinationSlice:destinationLevel:destinationOrigin:) and copy_from_texture_to_buffer
(copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:destinationOffset:
destinationBytesPerRow:destinationBytesPerImage:) record vkCmdCopyBufferToImage or
vkCmdCopyImageToBuffer against the buffer's own range of its block, nothing staged, between the
two barriers a texture copy records. One region per image of the region, each at its own offset
(offset + image x bytesPerImage), so an image stride of no whole number of rows copies too;
bufferRowLength is bytesPerRow in texels, 0 for one row. The second barrier also makes a buffer
write visible to every later command, and a write into a Shared buffer marks the segment, whose
end barrier reaches the host. BufferLayout carries the offset and the two strides.

Refusals follow probe blit_buffer_copy_rules.m on an Apple M3 Max, macOS 27.0.1 (jobs
m3-max-43541, m3-max-43545): Metal's validation stops an offset or a row stride of no whole
texels, rows or images closer than the region's and a region past the buffer's end
(Refusal::BufferCopyLayout); it takes an R8Unorm offset of 2, a row stride of 0 for one row, image
strides of no whole rows, and bytesPerImage on 2D and 1D-array copies. Where Metal takes bytes a
copy command cannot address (a depth or stencil offset not a multiple of 4, as a 16-bit depth at
2; a compressed offset or row stride of no whole blocks, as BC1 rows 20 apart, which Metal takes)
it is Gap::BufferCopyAlignment. TextureBytes and FloatDepthUpload now name the blit copies too.

Tests: pure checks of the regions (padded rows, one row, a 3D region's images at their own
offsets, a 1D array slice, BC1 blocks) and of each refusal and gap; a device test copying into a
mipmap level, out of an array slice and a 3D region at padded strides, into a 1D array slice and
BC1 blocks, each result held to plain Metal's FNV-1a 64 (probe blit_copy_layouts.m, job
m3-max-43555, plain and under the validation layer), and one copy into a Shared buffer alone at
one submission, three barriers, no byte of the runtime's own.
2026-11-17 18:36:53 -08:00
Anees Iqbal 2105fa114e rt: heap textures, bound at the consumer's offsets in a heap's range of a Private block
A heap is a range of a Private block the consumer took at the heap's creation
(HeapRange: block, offset, length), as the plan decided: one Private range per
heap, resources at the offsets the guest's first-fit allocator picks.

Device::heap_texture_size_and_align answers heapTextureSizeAndAlignWithDescriptor:
with this device's image requirements (vkGetDeviceImageMemoryRequirements of the
same create info new_texture uses), never Metal's: the size rounded up to and
the alignment raised to bufferImageGranularity, so a buffer placed by the same
answers never shares a granularity page with the image. Replay showed why: one
vendor's image for a recorded heap texture is larger than the recording
device's (7.47 MB in a 5.9 MB heap), so the guest places by this answer.

Device::new_heap_texture binds the image at the heap offset: no allocation and
no texture block, bytes not zeroed (as Metal's heap textures), aliasing allowed.
A placement past the heap's end, an offset in the block off the image's
alignment, or a heap range past its block is Refusal::HeapTexturePlace at
creation; the image is never bound outside its heap. A Shared block, or an image
that requires an allocation of its own or does not take the Private type, is
Gap::HeapTexture (every optimal image measured takes the Private type). The
image holds the block, so a released block returns to the pool only once its
heap textures' images are gone.

new_texture's checks move into Device::prepare, shared with the size query, and
the image's create info into image_info. README: heap textures leave the
not-built line; REFUSALS.md and the signatures table updated.

Test: tests::heap::every_device_places_heap_textures_at_the_consumer_s_offsets
(answer equals the image's own size rounded to granularity; first-fit
placements allocate nothing and keep their own bytes; an alias; refusals for
past the end, off the alignment, a heap past its block, and a Shared block).
2026-11-17 18:26:07 -08:00
Anees Iqbal 8fc4064da5 rt: Managed textures, an image and the consumer's named bytes, uploaded by a device copy
A Managed texture is a Private image plus a range the consumer names, on every
device. Device::new_managed_texture takes a Shared buffer and, per level and
slice, a BytesPlace (offset, bytes per row, bytes per image) laid out as the
consumer chooses; rt never picks the layout. Places that a buffer-to-image copy
cannot read in place (rows not whole texel blocks apart, images not whole rows
apart, a first byte off the block's bytes or off 4 for depth/stencil, a level
leaving the buffer, a wrong count, a buffer the host does not reach) are
refused with Refusal::ManagedTextureBytes.

Texture::upload_region(region, level, slice) records one vkCmdCopyBufferToImage
from the named place into the image in the upload, ahead of every command
buffer committed after the call on every queue, as did_modify_range copies a
Managed buffer: no CPU copy, no staging. On such a texture replace_region
writes the named bytes (Metal's CPU copy) and uploads them; get_bytes reads the
named bytes with no submission. The texture copy's record() now takes a buffer
and region, so staging and named copies share it.

README, the API.md accepted difference (the copy reads the bytes when the GPU
reaches it), REFUSALS.md and the signatures table updated.

Test: tests::managed::every_device_copies_a_managed_texture_s_named_regions
(whole-level uploads, a sub-region upload with an unmarked change outside it,
get_bytes reading the named bytes, replace_region writing them, six refusals).
2026-11-17 18:26:07 -08:00
Anees Iqbal 60fe8aacaf rt: TextureCopyMismatch quotes Metal's messages as code
Rustdoc read "[destinationTexture sampleCount](1)" as a link and failed -D warnings (job
m3-max-43474).
2026-11-17 18:10:36 -08:00
Anees Iqbal f10ed213a0 rt: the blit device test holds each copy's expected bytes to plain Metal's
Each expected result's FNV-1a 64 is the hash probe blit_copy_layouts.m printed on an Apple M3 Max,
macOS 27.0.1 (job m3-max-43464, at 31f5a93c4b), plain and under the validation layer alike: a
level into an array slice, a cube face into a 3D slice, a 3D slice into 2D, slice to slice and
BC1 blocks. The format-pair probe's sample-count case ran too (job m3-max-43465): Metal's
validation stops four samples into one with "[sourceTexture sampleCount](4) must equal
[destinationTexture sampleCount](1)", which Refusal::TextureCopyMismatch's basis now cites.
2026-11-17 18:10:36 -08:00
Anees Iqbal 42d274f91a rt: a blit texture copy takes one pixel format and one sample count, as Metal's validation does
Metal's validation layer stops copyFromTexture between any two pixel formats (Apple M3 Max,
macOS 27.0.1, probe blit_copy_format_pairs.m, job m3-max-43433): RGBA8Unorm into sRGB, Uint,
R32Uint and BGRA8Unorm, R32Uint into R32Float, Depth32Float into R32Float and BC1 into RG32Uint all
fail with "[sourceTexture pixelFormat] must equal [destinationTexture pixelFormat]"; the same
format is taken. So Refusal::TextureCopyMismatch is now every pair of two formats (basis
metal-measured, was metal-takes), and the rules for copying between formats of one unit's bytes
are gone: no alpha special case, no block, aspect or unit comparison. What stays a gap: a
multisample texture, depth and stencil both, a 1D texture with another type, one subresource
into itself, and, new, one pixel format held in two Vulkan formats by the textures' usages, whose
texels may sit in two layouts.

The device test's array is RGBA8Unorm now (the copy into it was RGBA8Unorm into R32Uint), and the
slice-past-the-array check copies into a texture of its format: on 7f2a3c5cb1 it met the format
check first on every device (legs m3-max-43406, 43407, 43408: RX 550, 780M HawkPoint, 3090, XTX,
2080, 780M Phoenix, lavapipe; every assertion before it passed, validation errors 0).
The probes add the sample-count case and make the layout probe's array RGBA8Unorm; their runs
follow.
2026-11-17 18:10:36 -08:00
Anees Iqbal 247ed69da0 rt: a blit encoder copies a region of one texture into another, one vkCmdCopyImage between two barriers
CommandBuffer::blit_command_encoder (blitCommandEncoder) and BlitCommandEncoder::copy_from_texture
(copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toTexture:destinationSlice:
destinationLevel:destinationOrigin:, the only texture-to-texture selector the compute recordings
use: 2,736 copies in one, 3 in the other, none multisample, compressed or within one texture).

The copy is recorded at once into the current segment: no staging and no byte beyond the region.
The first barrier moves each texture's level and slice from home to its transfer layout and carries
the global barrier (every earlier write visible to every later command), so it pays what an encoder
owed and the hazard sets start again; the second moves them home with the copy's writes visible to
every later command. A command buffer of one copy is one submission and three barriers (the
segment's end among them), and Metrics::bytes_copied does not move.

Bytes move as they are between formats whose units have the same bytes; a compressed region is
whole blocks or reaches the level's edge on both sides; a 3D image copies to and from a 2D slice.
Refusal::TextureCopyMismatch for units of different bytes or different sample counts (Metal stores
its GPU's own layout there); Gap::TextureCopy for what one vkCmdCopyImage in the floor does not
make (multisample, depth and stencil both, depth or stencil with another format, compressed with
another block extent, A8_UNORM with another format, 1D with another type, one level and slice into
itself). The texture's region check is shared with replace_region and get_bytes (texture::place).

Tests: tests::blit (the rules, no device) and on every device of the cfg's kind
tests::blit::on_device::every_device_copies_between_textures (bytes of a level into an array slice
of another format, a cube face into a 3D image, a 3D image into a 2D texture, one array slice into
another, BC1 blocks where made; 1 submission, 3 barriers, 0 bytes copied, 1 pass for one copy; an
owed barrier paid by the copy: 3 barriers, 4 without the fold).
2026-11-17 18:10:04 -08:00
Anees Iqbal 4732ce6cd7 rt: a buffer bound off its argument's alignment runs at the address rounded down to it
The binder (ComputeCommandEncoder::fill_parameters) pushes each bound buffer's address,
its gpuAddress plus the bind offset, rounded down to a multiple of the alignment the
kernel takes it to have (FieldValue::BufferAddress's mask, from
RuntimeFact::AddressAlignment: the argument's air.arg_type_align_size, at most 16), for
every slot. Refusal::MisalignedBuffer and the dispatch it skipped are deleted, so
fill_parameters cannot fail.

Why: Metal's API validation refuses such a bind offset, and without validation an Apple
M3 Max (macOS 27.0.1) reaches each element at its address rounded down to the smaller of
the element's alignment and 4, for loads, stores and pointers stored in a buffer alike.
The probe that measured it is committed as
crates/metal2vulkan-conformance/probes/misaligned_buffer_binds.m. The two agree at
alignments 2 and 4 and for 8- and 16-byte arguments bound 1 to 3 bytes off a multiple of
4; an 8- or 16-byte argument bound at a multiple of 4 that is not a multiple of its
alignment is reached at the rounded address where the M3 reaches it exactly there, a bind
Metal's validation rejects. docs/API.md section 10 lists that as an accepted difference.

Tests: rt's every_device_rounds_a_bound_address_down_to_its_alignment steps a buffer bound
off each alignment (2, 4, 8 and 16; 15 binds) through the step kernel with the mask set,
and checks the words stepped start at the rounded address; at the 8- and 16-byte binds 4,
8 or 12 bytes off, an unrounded bind would step other words on any device.
an_argument_bound_off_its_alignment_runs_at_the_address_rounded_down binds
vector_word_phases' vwp_words 1 and 3 bytes and vwp_vec16 4 and 12 bytes off their
alignment and expects Metal's words for the rounded binds. They replace
an_argument_bound_off_its_alignment_is_refused and
a_misaligned_dispatch_refused_leaves_its_encoder_and_command_buffer_usable.

Docs: REFUSALS.md and api_signatures.tsv regenerated (the variant's row goes), the rt
README's compute encoders say what the binder pushes, the translator's
RuntimeFact::AddressAlignment doc and the mechanism comment say the binder rounds.
2026-11-17 18:07:45 -08:00
Anees Iqbal ee7c4a5173 rt: Managed buffers, a device copy where Shared memory is not device-local
newBufferWithLength:options: and newBufferWithBytes:length:options: with Managed storage over a
range of a Shared block the consumer names: Device::new_managed_buffer(block, offset, length,
copied). The device's memory-type query picks the form. Where the Shared type is device-local the
buffer is its bytes, as a Shared buffer is, and didModifyRange does nothing. Elsewhere shaders
reach a device copy in Private memory, as Metal keeps one on a Mac with a discrete GPU.

The device copy is a place in a copy block: a Private block of the pool, or a dedicated one past
BLOCK_LEN, in a set apart from the texture blocks, so no buffer lies beside an optimal image. Its
first `copied` bytes are copied from the consumer's and the rest zero-filled, in the upload.
Buffer::did_modify_range(start, length) marks a range changed: the upload, which goes ahead of
every command buffer committed after the call on every queue, copies it from the consumer's bytes
into the device copy as it is submitted, one vkCmdCopyBuffer per buffer with its ranges merged
where they overlap or touch, after a counted barrier that puts the upload's earlier fills first.
No CPU copy, no staging, nothing sized by the call. Each change is one of the upload's 4,096 calls,
so changes past them submit it and wait. The copy reads the bytes when the GPU reaches it, which
docs/API.md records as an accepted difference.

A command buffer keeps each device copy it uses, and an upload each one it copies into, until it
retires; the copy's place is freed then. An indirect dispatch reads its arguments from the device
copy. Places take a core and give a block back once it empties where it is dedicated or another
pooled block of the set is empty; Core::take_memory chooses a pooled or dedicated block for both
take_block and the places.

Refusals: ManagedBlockNotShared (a Private block) and ModifiedRange (a range past the buffer),
both ours; docs/REFUSALS.md and the signatures table regenerated.

Tests: changed ranges merge where they overlap or touch; on every device, in the form its query
picks, the device copy holds the first bytes and zeros, a changed range reaches it at the next
submission and an unmarked change does not, changes past the upload's calls submit it (none
without a copy), both refusals, and every gauge zero after teardown.
2026-11-17 18:00:53 -08:00
Anees Iqbal bf3d3c1ebb rt: GPU times placed by calibrated timestamps on one host clock, the anchor deleted
VK_EXT_calibrated_timestamps joins the floor's device extensions under that one name, and the
floor requires the device to calibrate its own clock (VK_TIME_DOMAIN_DEVICE_EXT) with the host
clock's domain, HOST_DOMAIN: CLOCK_MONOTONIC on Linux and other Unix systems, CLOCK_MONOTONIC_RAW
on macOS, the performance counter on Windows. A device that does not is below the floor
(floor::Missing::TimeDomain). host_time() reads that same clock, so a command buffer's GPU times
and its kernel times are on one clock with no bridge; on macOS it counts while the system sleeps,
where Metal's mach_absolute_time does not, which host_time()'s doc and the README state.

The completion thread calibrates once as the device starts, and again at a completion once
100 ms (CALIBRATION_PERIOD) have passed since the last: one vkGetCalibratedTimestampsEXT call of
the two domains, no deviation loop, never per command buffer. Each completed command buffer's two
timestamps are placed by the last calibration, the tick difference taken signed within the valid
bits. The anchor estimate, which took the host time a completion was seen as an end and moved
later only by the least lateness of 64 passes, is deleted with its rule.

Tests: the times test now holds each command buffer's GPU start and end between host_time() read
before its commit and the host time its completed handler reads; a new test holds that the device
calibrated at start, not while idle for 150 ms, and once at the first completion of a 32-buffer
burst plus at most one per 100 ms it ran; a floor test names a missing host or device time domain.
No conformance or harness check compares rt's GPU times with Metal's in absolute terms
(conformance relates the old runtime's times; the harness compares durations and spans).
2026-11-17 17:59:18 -08:00
Anees Iqbal f34c4a22d2 rt: every memory allocation counts against the device's maxMemoryAllocationCount, refused before the driver past it
rt never counted its vkAllocateMemory calls, so it could pass the device's
maxMemoryAllocationCount, which VUID-vkAllocateMemory-maxMemoryAllocationCount-04101
forbids: blocks, each texture's own memory, each staging buffer of replace_region
and get_bytes, the parameter ring's blocks and the zero source.

Every allocation now goes through memory::allocate, the one vkAllocateMemory call.
The live count is the blocks gauge, which already counted exactly these
allocations: allocate raises it only while it is below the device's count, else
returns Limit::MemoryAllocations { max } without calling the driver, and gives the
count back where the driver fails. Each site's own rise of the gauge after its
allocation is gone; the texture's and the staging buffer's failure paths after the
allocation now lower it as they free it.

Device::new is Device::open with the device's limits as queried; a test opens a
device with maxMemoryAllocationCount answered as 8. With the zero source and the
two ready blocks live, five 4x4 textures are made and the sixth is refused with the
typed limit, the gauges unchanged; a replace_region then is refused the same way
for its staging buffer; once a texture is dropped and its memory freed, a texture
is made again; every gauge reads zero after teardown.

The Err docs of Device::new, take_block, new_texture, replace_region (get_bytes
takes its list), set_bytes and the dispatches name the limit, and the runtime's
README states what counts and the limits measured: about 4.29 billion on RADV,
NVIDIA's Linux driver and ANV, 8,401,685 on Intel's Windows driver for the UHD
Graphics 630, 4,096 at Vulkan's minimum. docs/REFUSALS.md and the API signature
table are regenerated for the new Limit variant.
2026-11-17 17:43:57 -08:00
Anees Iqbal d48c2bfc78 rt: the longest buffer is 2 GiB
MAX_BUFFER_LENGTH drops from 4 GiB to 2 GiB, so every byte of a buffer lies within 2^31 bytes of
each bind address in it, which lets the translator read a buffer argument's 32-bit offsets as
signed for every slot. A buffer of 2 GiB is made; one a byte longer is refused with
BufferTooLong. The consumer states Metal's maxBufferLength no larger than this.

The device test is renamed to its 2 GiB length (a 2 GiB Private block, made where a block
allows it, then 2 GiB and a byte refused, gauges zero at drop), and the interpreter test now
loads and stores up to the last word below 2 GiB of the bind address and checks that each lands
at its own word. REFUSALS.md and api_signatures.tsv regenerated.
2026-11-17 16:50:10 -08:00
Anees Iqbal 661b97c6e8 rt: a buffer longer than 4 GiB is refused
A shader reaches a buffer argument's bytes by 32-bit offsets from its bind
address: every access form adds the u32 Metal offset to the slot's 64-bit
address, so an access 4 GiB or more past the bind offset lands 4 GiB
below, inside the buffer, with no fault. Device::new_buffer now refuses a
length past MAX_BUFFER_LENGTH (4 GiB, one constant) with
Refusal::BufferTooLong, before the block's range is looked at; heap
buffers and a consumer's no-copy placements go through the same call.
Metal answers nil past a device's maxBufferLength, which the consumer
states no larger than this (the README's contract line).

Tests: rt's every-device memory test refuses 4 GiB and a byte and
u64::MAX on a pooled block, typed; a test of its own makes a buffer of
exactly 4 GiB in a Private block of that length where the device has one
(skipping visibly where its largest block or memory is smaller), refuses
one a byte longer, and ends with every gauge at zero. The translator's
interpreter test loads and stores up to the last word below 4 GiB through
a Whole window under the identity domains, each landing at its own word.

REFUSALS.md and api_signatures.tsv regenerated.
2026-11-17 16:50:10 -08:00
Anees Iqbal 643271b319 rt: refuse a dispatch whose buffer address breaks its argument's alignment
A kernel states RuntimeFact::AddressAlignment for each buffer argument with an alignment of 2
or more, and reaches one of 4 or more from its address as it is. Metal's API validation refuses
such a bind offset (measured on an Apple M3 Max by the conformance crate's
vector_access_placement probe: "must be a multiple of 4 but was set to 2" for a uint *
argument, "of 16 but was set to 4" for a float4 *). The pipeline records each such slot's mask
with its BufferAddress field, and fill_parameters tests address & mask where it forms the pushed
address, refusing the dispatch with Refusal::MisalignedBuffer { index, address, align } before
any work is recorded.

The test an_argument_bound_off_its_alignment_is_refused binds a float4 argument at offset 4
(refused, naming index 0, align 16 and the address) and 16 (runs), and a uint argument at 2
(refused, align 4) and 4 (runs). docs/REFUSALS.md is regenerated and the api_signatures table
gains the variant.
2026-11-17 15:30:38 -08:00
Anees Iqbal 37f0bf51f8 rt encoder arms: textures, sampler states and constexpr samplers by pushed index
ComputeCommandEncoder::set_texture (128 slots, Refusal::TextureArgumentIndex past them) and
set_sampler_state (16 slots, Refusal::SamplerArgumentIndex) bind as Metal's calls do, and
use_resource takes a texture as it takes a buffer. A dispatch pushes, for each texture and sampler
slot its kernel reads, the bound object's gpuResourceID (0 for none), whose index names its
elements of set 1; for a texture slot an integer write saturates through, the channel widths of
the bound texture's format (metal::format::integer_channels_word, now public); and for each
constexpr sampler, the index the consumer gave it. Nothing is written into set 1 at bind or
dispatch time, and every texture stays in its home layout. A texture's sample and read are reads
in the hazard sets, a texture one resource, with a hazard id from core's ids.

Each command buffer binds set 1 (vkCmdBindDescriptorSets, firstSet 1) once, before its first
pipeline; without it the lavapipe run reported VUID-vkCmdDispatch-None-08600. The command
buffer keeps each texture and sampler state an encoder binds or declares, in command.rs's Gpu
next to its blocks and pipelines, dropped with them at retire, so their elements stay theirs
while work may read them.

Device::new_compute_pipeline_state takes sampler_ids: the samplers the kernel numbers, in
Metal's order (NumberedSampler: each constexpr sampler, then one for a texture read and one for a
texture write), answered with an index each from the consumer's sampler grants
(Refusal::SamplerIds for another count). A constexpr sampler takes, before the call returns, the
device sampler of each use the kernel has (CombinedSampler::constexpr_sampler, canonical, shared
by create info with sampler states') at its index of the three sampler arrays; states that number
one constexpr sampler at one index share it, another sampler there is Refusal::IndexInUse, and
the last of them writes the defaults back and frees the index. Set 1's layout is checked against
the translator's (IdentityArray bindings). A kernel whose texture or sampler the translator would
take from the bound object rather than its resource ID stays Gap::KernelInput.

The harness grants its own texture and sampler indices on the new runtime and numbers constexpr
samplers by their words, so constexpr_sampling runs on it.

README: the encoder's texture and sampler arms, the numbering paragraph, the KernelInput gap.
REFUSALS.md regenerated; api_signatures and api_surface carry integer_channels_word and the new
refusals.

Verified:
- m3-max-42749 (msi), this tree: clippy of metal2vulkan-rt plain, --cfg m2v_gpu and --cfg
  m2v_cpu_icd green; rustdoc -D warnings green; nextest 37 of 37; the device tests on lavapipe
  under the validation layer 79 of 79, 0 validation errors (tests::sampling: sample_down through a
  runtime sampler, then sample_up through a constexpr sampler, against the linear filter's
  answers; the constexpr index shared, refused to a sampler state and freed with the last state).
- The same change on the sampler landing before development's region commits (tree
  ed71d2de2e): m3-max-42714 (780M, radv) and m3-max-42716 (3090), its archive under the
  validation layer, 76 of 76 each (the three source-reading tests skipped off the building
  machine), 0 validation errors, every gauge zero at drop; m3-max-42735 (UHD 630, Windows), its
  cross-built archive, 79 of 79, every gauge zero at drop.
- m3-max-42638 (msi), tree ed71d2de2e: clippy of metal2vulkan-harness plain and --cfg m2v_gpu green;
  the api_signatures and api_surface tests green.
2026-11-17 15:03:53 -08:00
Anees Iqbal 4f8a7db4c8 rt sampler states: device samplers shared by create info at the consumer's index
Device::new_sampler_state is newSamplerStateWithDescriptor: at an index of a live Sampler grant.
Each state takes the device sampler of each use it can be used in, from the translator's
metal::sampler::vk_sampler with its create info chained by ash_interop::sampler_create_info:
the plain one always, the comparison one where its compare function is not Never, and the
integer-texture one (nearest, the integer border colour). It writes them into set 1's three
sampler arrays at its index before the call returns; the comparison array keeps its default
where the state has no compare function.

Device samplers are shared by create info across uses and states (SamplerTable), and a border
colour no address mode reads is no part of a create info (canonical), so a state whose
integer-texture use reads as a plain sampler shares it: a nearest state takes one sampler, and a
linear compare state two more beside it. The table holds at most maxSamplerAllocationCount
minus the arrays' two defaults; past it a state is Limit::DeviceSamplers. Gauges::samplers and
Gauges::device_samplers count them. When the last handle goes, the state's elements read the
defaults again, its index is free, and each device sampler no other state holds goes to the
reaper (Free::Sampler).

A cubic filter is Gap::CubicSampler. samplerAnisotropy joins the floor's features (every lab
device and capture has it). SamplerState::gpu_resource_id is the index and the translator's
SamplerWord. IndexInUse and IndicesInUse now name sampler states too.

README: a "Sampler states" section and the floor's feature row. REFUSALS.md regenerated;
api_signatures blessed.

Verified:
- m3-max-42632 (msi), this tree: clippy of metal2vulkan-rt plain, --cfg m2v_gpu and --cfg
  m2v_cpu_icd green; rustdoc -D warnings green; nextest 37 of 37; the device tests on lavapipe
  under the validation layer 78 of 78, 0 validation errors.
- m3-max-42611 (780M, radv) and m3-max-42612 (3090), the same sampler change on the textures tip
  before the rebase onto development, its archive under the validation layer: 75 of 75 each, 0
  validation errors; every gauge zero at drop.
- `python3 scripts/api-signatures/signatures.py --check` and
  `python3 scripts/refusal-surface/refusal_surface.py --check` clean.
2026-11-17 14:33:40 -08:00
Anees Iqbal 21a01acb33 rt textures: device images at the consumer's index, their bytes in and out
Device::new_texture is newTextureWithDescriptor: at an index of a live grant: an optimal image
in device-local memory of its own (the first memoryTypeBits type that is DEVICE_LOCAL), usage
the descriptor's plus transfer source and destination, so any texture can be replaced, read
back or blitted as in Metal. Its home layout is GENERAL where it has a storage element,
SHADER_READ_ONLY_OPTIMAL for shader read alone, the attachment layout for render target alone,
GENERAL otherwise; the first move from UNDEFINED goes through core's Work::upload, ahead of
every command buffer committed after the call. The sampled view's components are Metal's
swizzle composed over the format mapping; a depth or stencil format's view takes depth, else
stencil. The storage element exists where the format's emulation is Direct and the device
stores it through a storage image without a format. Size, layer and sample limits come from
vkGetPhysicalDeviceImageFormatProperties2. Admitted emulations: Direct, SwizzledView,
AlphaInRed, RotatedView, XChannel, DepthInCombined, StencilInCombined; any other format is
Gap::TextureFormat.

Texture::gpu_resource_id is the index and the translator's TextureWord, so the guest computes
it. replace_region and get_bytes copy through a staging buffer per call (Shared memory type,
counted in Metrics::bytes_copied); get_bytes submits at once (Work::flush, carried in the
commit before this one and landing with it) and waits (Done::wait). get_bytes's read of the
staging buffer is in readback.rs with its bound, under the readback rule test.

An upload into a 32-bit float depth is Gap::FloatDepthUpload (the planner's ruling): Metal keeps
any float there, Vulkan copies no depth outside [0, 1] without VK_EXT_depth_range_unrestricted,
which the Intel captures lack so the floor cannot take it, and no recorded stream uploads one.
get_bytes still reads such a texture.

The index frees at the last Texture handle's drop (its elements written null, the index
vacated), and grants now track occupancy: Refusal::IndexInUse and Refusal::IndicesInUse. The
Vulkan objects are an Image the uploads hold, freed by the reaper (Free::Texture) once the last
upload that moves or copies it retires. Gauges::textures and Gauges::descriptor_slots count
them, back to zero at drop.

Refusals carry Basis lines; docs/REFUSALS.md regenerated; api_signatures blessed. The README's
"Textures" section and its known gaps say the contract.

Verified:
- m3-max-42550 (msi), this tree: clippy of metal2vulkan-rt plain, --cfg m2v_gpu and --cfg
  m2v_cpu_icd green; rustdoc -D warnings green; nextest 36 of 36; the device tests on lavapipe
  under the validation layer 76 of 76, 0 validation errors.
- m3-max-42601 (780M, radv) and m3-max-42602 (3090), this tree's archive under the validation
  layer: 73 of 73 each (the three source-reading tests skipped off the building machine), 0
  validation errors; every gauge zero at drop.
- Not yet run on Intel: the UHD 630 (Windows) build, m3-max-42551, is running without the GPU
  lease; its run follows.
- `python3 scripts/api-signatures/signatures.py --check` and
  `python3 scripts/refusal-surface/refusal_surface.py --check` clean.
2026-11-17 14:22:16 -08:00
Anees Iqbal 1b97a620c8 rt: set 1 and index grants
Every pipeline of the new runtime takes set 1, one descriptor set the device makes at creation:
65,536 sampled textures (binding 0), 4,096 storage-capable textures (binding 1) and 4,000
samplers of each use, plain, depth comparison and integer texture (bindings 2, 3 and 4), each
partially bound, updated after bind and while unused elements are pending, seen by every stage.
Set 0 is empty. The pipeline layout is made once from it, in Device::new, and every pipeline and
dispatch uses that layout.

Every element no object owns is defined: a texture element is a null descriptor
(VK_EXT_robustness2 nullDescriptor, which joins the floor; the robust buffer and image access
beside it stay off), and a sampler element is its array's default sampler, nearest and clamped to
the edge, the comparison array's comparing with NEVER. The device writes every element at
creation and holds the two default VkSamplers (Gauges::device_samplers). The translator is told
of VK_EXT_robustness2, so its profile has nullDescriptor.

Device::grant_indices(class, first, count) grants the consumer the range it names, so the IDs it
picks reproduce in replay: storage-capable textures 1 to 4,095, other textures 4,096 to 65,535,
samplers 1 to 3,999, 0 nil and never granted (IndexClass, IndexGrant). Limit::IndexRange,
Refusal::IndicesGranted and Refusal::IndicesNotGranted, with Basis lines; docs/REFUSALS.md
regenerated. The floor's sampler limits are now three arrays' (12,000 samplers per stage and set,
81,632 update-after-bind descriptors in all pools). README: "Set 1 and index grants", and the
floor's extension, feature and limit rows.

Device::new output is unchanged: no translator source changes.

Verified:
- m3-max-42273 (msi): clippy -p metal2vulkan-rt --all-targets --all-features, plain, --cfg
  m2v_gpu and --cfg m2v_cpu_icd, green; rustdoc -D warnings green; rt tests 33/33; every device
  test on lavapipe with the Khronos validation layer, 0 validation errors; making a second set 1
  takes 106 ms there. refusal_surface.py --check clean.
- m3-max-42305 (Radeon 780M, RADV, gem10) and m3-max-42306 (RTX 3090, um870), validation layer
  on: every device test passes with 0 validation errors, gauges zero at drop; a second set 1
  takes 15.1 ms on the 780M and 4.6 ms on the 3090. The three tests that read the source tree
  fail on those nodes only because the carried archive names msi's paths; they pass on msi.
2026-11-17 13:23:55 -08:00
Anees Iqbal 445b720f78 identity: texture slots sampled through runtime sampler slots from set 1's sampler arrays
Under the identity domains a kernel samples a texture slot through a runtime sampler slot. The
texture is its class's set-1 element at the index of its pushed gpuResourceID, as a read's is.
The sampler is the element of a set-1 sampler array at the index of the sampler slot's pushed
gpuResourceID (SlotGuestBase of the sampler slot), joined to the texture by OpSampledImage. The
array is picked by the use: binding 2 for a plain sample, 3 for a depth comparison, 4 for a
texture of an integer format; 4,000 SAMPLER descriptors each, PARTIALLY_BOUND |
UPDATE_AFTER_BIND | UPDATE_UNUSED_WHILE_PENDING, every stage, the same set 1 for every pipeline.
The sampler's word (pixel coordinates, a nearest pixel sampler) is read from the ID's high word,
so no specialization constant and no SamplerReduction, SamplerCoordinates, CubicSampler or
ConstantLanes fact remains; every precision note is static. An integer write to a storage slot
without a format saturates to the channel widths the consumer pushes
(PushField::TextureIntegerChannels, a u32), with no fact.

Still refused as Unsupported{IdentityDomains}: constexpr samplers (next change: a pushed index),
an argument buffer's sampler, arrays of samplers, bicubic and anisotropy emulation, a slot's
minimum level.

Translation output changes only under the identity domains (Device::from_queries). Device::new
output is unchanged: golden_hashes_match_the_table passes at this tip (job m3-max-42189), with no
"changed under an unchanged key" and no "profile changed:" line.

For the runtime's side (the planner's three facts):
a. The runtime must dedupe device samplers by create info across the three arrays' uses.
   Exhausting maxSamplerAllocationCount (4,000 on the 2080, 3090 and UHD 630; 32,768 on
   lavapipe; 65,536 on the others) must be a typed refusal, with a fill-past-capacity test.
b. The update-after-bind limits for 65,536 sampled images, 4,096 storage images and 12,000
   samplers hold on all nine profiles (the smallest is lavapipe's 1,015,808); the floor must
   check them by query.
c. The count of cubic sampler descriptors is asked of the replay lane; if any exist it goes back
   to the planner before step 5 closes.

SEMANTICS_VERSION 2161: identity-domain modules of sampling kernels and integer writes change.

Verified:
- m3-max-42094 (msi), this change on cd5a76a757: clippy -p metal2vulkan --all-targets
  --all-features and rustdoc -D warnings green; nextest all() of metal2vulkan and metal2vulkan-rt,
  3,719 of 3,723 passed. The four failures were development's own (the new pad_simd_shape and
  vector_word_phases fixtures had no table rows), re-blessed at 74669c0552.
- m3-max-42096 (msi): clippy --cfg m2v_gpu and --cfg m2v_cpu_icd green.
- m3-max-42189 (msi), this tip on 58891b9ce5: golden_hashes_match_the_table,
  public_fixtures_engine inventory and llvm_as part 8, and air_input's engine golden printouts
  pass.
- engine_identity: sample_down links and passes L3 on every profile and on moltenvk-m3 without
  robustImageAccess2, with set 1 bindings 0, 1 and 2 used, no spec constant but LocalSize, and no
  sampler fact; an integer write of (300, 70000, 5, 2^31) stores (255, 255, 5, 255) under the
  RGBA8Uint word and the raw lanes under word 0, on the CPU interpreter.
2026-11-17 12:46:10 -08:00
Anees Iqbal fdc3fd3907 rt: threadgroups of partial SIMD groups run the kernel's emulated module, lowered on the reaper
A kernel whose tier runs each SIMD group as one subgroup (a pinned subgroup of 32, the device's
own 32, or half of a 64-lane subgroup) runs only threadgroups of whole groups of that width. Such
a state now has its emulated-SIMD-group variant (LoweringInputs::emulated_simdgroups), which the
reaper lowers once new_compute_pipeline_state has returned, through the cache directory like
every lowering (a refusal is kept too). A dispatch whose threadgroup is not whole groups runs that
module at its own size; one that comes before the reaper is done waits for the lowering, which the
reaper takes next (Reaper::hurry), counted as a first-use wait. Nothing translates on an encoding
thread. A state made after quiesce, or whose lowering the reaper's end leaves, is marked not
lowered (Error::Quiesced at such a dispatch).

The emulated module's threadgroup memory is its arena (metal2vulkan::pipeline::arena_bytes, now
public) holding the lengths set, the scratch of each SIMD group, and a vote word: the dispatch's
total is checked against maxComputeSharedMemorySize (Limit::ThreadgroupMemory).
ComputePipelineState::precision_notes returns the emulated module's notes too once it is lowered.

Gap::PartialSimdgroups stays for a state with no emulated module: a kernel the consumer compiled,
or one whose emulated variant the translator refuses. A ragged dispatchThreads grid at such a size
is Gap::PartialThreadgroups: the partial-threadgroups variant does not take the emulated tier.
2026-11-17 11:48:14 -08:00
Anees Iqbal d5a475f1a0 old-runtime regression fix: the stage bounds return to Device::new's ANV rows; the bound on every device is a fact of from_queries' profile
576a7348bc put one stage bound on every device on the shared translator
path, so the old runtime (Device::new) newly refused what it compiled
before: on the UHD 630 and on every committed profile without maximal
reconvergence, 6 corpus modules (12 rows) went from compiled (emulated
simdgroups, entry weights 104,424 to 188,554) to Needs::StageBound.
Measured on gem10 through Device::new at 9cb90de8cc (job m3-max-41747).

Restored for Device::new, as before 576a7348bc:
DriverWorkaround::SerializedStageWrapsLargeModules and
CompilerMemoryGrowsWithStageSize on ANV's identity row, their bounds
(786,432 and 99,109), the re-plan keeping the widest pin, and the
refusal as Needs::DriverDefect naming the defect; no bound elsewhere.
The old runtime's heap-trim test, warm-refusal kinds and their tests go
back to their text before 576a7348bc.

rt keeps what landed, carried with no switch. The bound is a fact of
the profile (device::profile::StageBound): Device::new builds
StageBound::Defects (the bounds of its rows), Device::from_queries
builds StageBound::Every (99,109 on every device, refused as
Needs::StageBound). stage_bound::emit reads that one field. The
fingerprint renders the fact only when it is Every, so every
Device::new fingerprint is byte-identical to before 576a7348bc. Every
from_queries fingerprint moves, so an rt profile is never one of the
old path's.

Tests:
- The pre-576a7348bc ANV tests are back (both defects' bounds, and the
  same profile without them emitting under every bound).
- New every_stage_from_queries_keeps_the_widest_pin_or_is_refused:
  re-planned, then StageBound; the serialized bound is none there; RADV
  through Device::new is unbounded.
- the_stage_bound_fixture_keeps_the_pin_or_is_refused covers both
  paths. Iris pinned through both. Without maximal reconvergence:
  StageBound through from_queries, DriverDefect on ANV through
  Device::new, and emitted emulated through Device::new under Intel's
  Windows driver (the UHD 630's case).
- New the_stage_bound_is_a_fact_of_the_profile checks every committed
  profile.

Docs:
- FAST-PATHS' known gap is ANV's again.
- The rt README's known gaps gain the every-device bound.
- API.md and the Needs::StageBound and Feature::StageSize docs name
  both paths.
- REFUSALS.md regenerated; the API table regains the two variants.

SEMANTICS_VERSION 2153.
2026-11-17 10:57:34 -08:00
Anees Iqbal 75b422338a identity: argument-buffer textures are the set-1 elements their resource IDs name
Under the identity domains an argument buffer's texture handle is the gpuResourceID its member
holds: the handle is the ID's index, the element of the class's set-1 array (0 is nil, the null
descriptor), with no handle table, no search and no descriptor. Where the shader checks a read
itself (no robustImageAccess2) the handle carries the word's missing-alpha bit (word bit 12) at
HANDLE_ALPHA_ONE, so the handle form is Lookup::Element or Lookup::Flagged{alpha} only.

The handle tables' variant forms are off under these domains (`texture::tabled`): reads of a
member of another numeric class, raw-texel decodes, storage conversions (red-blue, sRGB alias),
A8 alpha-in-red, unreadable-storage nulls, YCbCr write marks, and the HeapCrossClassNeutral,
HeapStorageReads and HeapResidency facts. A slot and a member of one class index one array, so
the class's volatility now merges the slots' uses with the groups'. The admission takes heap
groups whose declaration is their identity class with no plain, raw or cross classes; anything
else stays Unsupported{IdentityDomains}.

Translation output changes only under the identity domains: the default domains plan and emit
as before (no golden re-bless needed). SEMANTICS_VERSION 2153.

The test kernel `tex` gains an argument-buffer form (`texture_kernel(true)`), checked on
lavapipe, moltenvk-m3 and moltenvk-m3 without robustImageAccess2: same answers at the same
elements, set 0 empty, and the handle form Element or Flagged{alpha} as the profile checks reads.

Verified (this commit's tree, as 657e2245c2 on 2872c419e0):
- msi 41756: clippy -p metal2vulkan --all-targets --all-features -D warnings, rustdoc
  -D warnings, nextest -p metal2vulkan -p metal2vulkan-rt in full: 3,701 of 3,702 pass; the one
  failure is golden_hashes_match_the_table, stale under development's own profile change.
- msi 41800: that golden test with every difference listed: 7,260 cells under a changed profile
  fingerprint (development's at 2872c419e0; this commit changes no profile field), no cell whose
  value moved, no cell changed under an unchanged key. Fixtures that need metal-as (macOS) are
  not compared there.
- msi 41757: clippy under --cfg m2v_gpu and --cfg m2v_cpu_icd.
- msi 41712, 41713 and 41752: the same at 160a3c5bae on 9cb90de8cc (SEMANTICS 2152 there), the
  golden test matching 1,815 rows x 19 profiles.
2026-11-17 10:56:25 -08:00
Anees Iqbal 4ac52bf082 rt: a kernel's threadgroup memory arguments come from its length constants
The device legs of the tile (m3-max-41638/41639/41640) refused every
observing kernel with Gap::KernelInput: the runtime took a kernel's
[[threadgroup(n)]] arguments from PipelineInterface::threadgroup, which the
translator leaves empty, so a TgLength specialization found no argument. The
arguments are now the TgLength constants the module specializes on, by
their index.

With threadgroup memory reaching a pipeline, a dispatch checks it: the
kernel's static part (and a predicated walk's 4-byte vote word,
RuntimeFact::PredicationVote, now accepted) plus each length set rounded up
to 16 bytes must be within maxComputeSharedMemorySize, else the new
Limit::ThreadgroupMemory, Metal's maxThreadgroupMemoryLength counterpart.

The precise kernel's test found on the 780M and the XTX one word apart
between a tile and the app's shape: a NaN/NaN division (0xffb86e83 /
0x7f9fc206) answers the first operand's payload in one pipeline and the
second's in the other. The state carries NativeNanEncoding, so two NaNs are
alike there; every other word must be equal.

README: the threadgroup memory limit, and NVIDIA 615.71.09's sign-extended
narrow clamped sum on GA10x (the planner's wording). REFUSALS.md and the API
signatures regenerated.
2026-11-17 10:46:51 -08:00
Anees Iqbal 2930583b47 rt: the cache directory keeps lowered kernels and pipeline data
DeviceOptions::pipeline_cache_dir names a directory a device keeps two
things in, for compute pipeline states. translations/ holds each lowering,
named by its FunctionCompileKey (the kernel's AIR, entry, constants and linked
functions, its lowering inputs, the profile fingerprint and the translator's
semantics version), in the translator's self-checking encoding; a state reads
a lowering there in place of lowering (Metrics::translations_loaded beside
the new Metrics::translations), and a partial-threadgroups variant the
translator refused is kept as a marker so it is not tried again. The files
take at most 256 MiB, least recently used evicted first. pipelines-<uuid>
holds the VkPipelineCache data, framed with a length and a checksum since
the initial data must be exactly what vkGetPipelineCacheData returned; every
VkPipeline is made through the device's cache, the reaper writes the data 10
seconds after a VkPipeline was made at most once per 10 seconds, and the
device's end writes it a last time. Writes go through a temporary file
renamed over the name; a file that does not check is a miss and nothing the
cache does fails a call.

The tile commit's README, refusal table and API signatures follow here:
direct dispatches past maxComputeWorkGroupCount are split, and
Gap::PartialThreadgroups names the variant refusals by the deciding queries.

Tests: a store filled past its cap keeps the most recently used files within
it, stores on one directory share files, and pipeline data cut short or
flipped is a miss (host); a second device on the same directory lowers
nothing at creation, reading all three lowerings, and the pipeline data file
is there (device). Not yet compiled: the lint follows.
2026-11-17 10:46:51 -08:00
Anees Iqbal 576a7348bc translator: one stage bound on every device; the two stage-size workarounds go
A module whose entry weighs more than COMPILED_STAGE_WEIGHT (99,109, the
heaviest stage measured to compile within host-sized memory, on ANV) is
now handed to no driver, whatever its identity. A kernel that emulated
its simdgroups only in place of the widest mode's pin (the subgroup size
range decides it) is planned again keeping the pin, as before; every
other module past the bound is refused with Feature::StageSize and a new
Needs::StageBound, its symbol naming the weight and the bound. The
refusal is permanent for the input on the device (its plan decides the
weight), so it is not NotImplemented; validation reads it as the
translator's own gap.

DriverWorkaround::SerializedStageWrapsLargeModules and
CompilerMemoryGrowsWithStageSize go, with ANV's identity entries for
them and the serialized bound (786,432), which the single bound sits
far below. Why: the workaround ladder takes one form for every device,
the slowest compiler's; a device whose compiler would take a heavier
stage is refused it, recorded in FAST-PATHS' known gaps.

Measured before this change, with a scratch build that applied the
bounds and the re-plan to every profile: the corpus on the Iris Xe's
description without its identity refused nothing (largest planned
module 91,399, job m3-max-41496), and RADV and NVIDIA nothing either;
without maximal reconvergence 12 rows were refused, 6 distinct
simdgroup-matrix modules of 198 to 285 products whose lockstep pairs
force emulated simdgroups (jobs m3-max-41474, m3-max-41523).

The owned fixture stage_bound/stage_bound_matrix (512 simdgroup matrix
products beside a lockstep pair in divergent flow, our own MSL) has
their structure: on the Iris Xe its emulated module weighs 123,307 and
its pinned one 37,646; without maximal reconvergence it is refused at
123,308 (scratch weighing, job m3-max-41602). The new test
the_stage_bound_fixture_keeps_the_pin_or_is_refused asserts both paths
and that the re-planned kernel is under the bound.

The old runtime's heap-trim test loses its long chain, now refused on
every device; it asks for a trim where the making left more than the
floor free (NVIDIA's compile never does under the bound, 189 MB at
most measured). SEMANTICS_VERSION 2150; REFUSALS.md regenerated; the
API table loses the two variants and gains Needs::StageBound.
2026-11-17 10:24:59 -08:00
Anees Iqbal 31c1161940 rt: SIMD groups at Metal's width, and robustImageAccess, at the floor
The floor requires Vulkan 1.3's subgroupSizeControl, computeFullSubgroups and
robustImageAccess, enabled on every device; the translator's profile takes
them through the enable set. Where a device lists compute in
requiredSubgroupSizeStages with 32 between its sizes, the translator pins a
kernel's SIMD groups to subgroups of 32 (the Direct tier); the compute
pipeline state now takes such a kernel: each VkPipeline chains
VkPipelineShaderStageRequiredSubgroupSizeCreateInfo where the tier pins a size
(the translator pins only a stage the device lists, VUID-...-pNext-02755) and
carries the stage's REQUIRE_FULL_SUBGROUPS. "A stage that pins a subgroup
size" leaves Gap::KernelInput. A flattened tier's LocalSizeConstraint is
supplied: a dispatch whose threadgroup is not whole SIMD groups is refused at
the dispatch as the new Gap::PartialSimdgroups, since the emulated-SIMD-group
variant is not built. With robustImageAccess on, the translator drops its
image write and atomic guards on every device; robustImageAccess2,
robustBufferAccess, robustBufferAccess2 and nullDescriptor stay off.

Tests: the floor names each new missing feature; the translator's enable set
holds robustImageAccess and none of a reported geometryShader,
samplerMirrorClampToEdge or VK_EXT_robustness2 (host); every device's
translator profile has robustImageAccess and none of robustImageAccess2,
robustBufferAccess, robustBufferAccess2, nullDescriptor (device); and
simd_float_products runs Direct, pinned at 32, wherever compute can pin 32,
refusing a 16-thread threadgroup and answering Metal's products (device).

REFUSALS.md and the API signatures regenerated. Verified: cargo fmt; the lint
and the device legs follow.
2026-11-17 09:55:14 -08:00
Anees Iqbal fa52012831 identity: texture slots are the set-1 elements their pushed resource IDs name
Under the identity domains a kernel's texture slots now lower. A slot's
gpuResourceID is pushed as its PushField::SlotGuestBase (the index in the
low word, the word in the high one). Its texture is the element at that
index of one of set 1's two fixed arrays: binding 0, SAMPLED_IMAGE x
65,536, and binding 1, STORAGE_IMAGE x 4,096. Each is partially bound,
updated after binding and while unused elements are pending, and seen by
every stage, with the same layout for every pipeline
(BindingSource::IdentityArray). Each image class the kernel declares
(shape, numeric type and depth comparison, sampled, or storage without a
format) is a variable of its descriptor type's binding. The slot binds no
descriptor and declares no specialization constant:
- is_null_texture answers whether the index is 0. Nil needs nothing
  else in the shader, since element 0 of each array is a null descriptor
  (the device test of ba4454b05b).
- A read the shader checks itself takes Metal's out-of-bounds alpha of 1
  from bit 12 of the word (TextureWord::OUT_OF_BOUNDS_ALPHA_ONE).
- The ResourcePresence and OutOfBoundsAlpha facts are not stated there.

No binder chooses a variant under identity, so a slot reads whatever
texture its ID names through the plain form:
- the variant facts (cross-class reads, planes read in place, texel rows,
  texture-buffer parts) are not stated;
- a float or half read takes the device's sRGB decode with
  PrecisionNote::SrgbTexelDecode (VkProperty::MetalSampler on MoltenVK),
  as a heap element's does, with no SrgbTexture twin;
- no texture is sparse (the consumer refuses one): no write-dropping
  SparseTexture constant and no ConstantLanes;
- a storage slot is formatless with no StorageTextureFormat fact. Where
  the device cannot access it without a format, the slot is refused as
  Unsupported{IdentityDomains} instead of asking for an input no consumer
  gives there.

Admission stays typed. Under identity, a function is refused as
Unsupported{IdentityDomains}, not implemented, if it:
- samples (any sampler plan; Metal's own sampler as a requirement is
  allowed);
- reaches textures through argument buffers (any heap group);
- declares a slot with no identity class: texture buffers, level views,
  cube-as-array, planes, extended range, RGBX, ulong, or a storage
  image with a format;
- uses a slot whose state comes from anything but its ID: border texels,
  sparse residency arms, a half conversion by the bound format, swizzles,
  offset bases;
- carries a fact naming such state (identity_unsourced).
That keeps the arm64-only forms (two-plane, extended range, sRGB twins)
out of the identity domains, as the x86 scope wants. The old binder
refuses an identity array as an internal error, since the consumer
writes those arrays.

SEMANTICS_VERSION 2150 (identity output changes), ARTIFACT_FORMAT_VERSION
529 (BindingSource gains IdentityArray). docs/RESOURCE-ID.md says what the
arrays are and what the shader reads of an ID. docs/API.md says what the
identity domains lower. The refusal surface and the API signatures are
regenerated. The blessed table also gains
metal2vulkan-rt::PrecisionNote::CappedLodBias, a variant development's
table lacked.

Verified, on development cfa389aa9b (check commit 564d131163, same tree):
- msi, job m3-max-41519: clippy -p metal2vulkan --all-targets
  --all-features -D warnings, rustdoc -D warnings, and nextest of
  metal2vulkan's whole suite: 3672 tests run, 3672 passed, 20 skipped.
- msi, job m3-max-41520: clippy of metal2vulkan under --cfg m2v_gpu and
  --cfg m2v_cpu_icd, both clean.
- The new test, texture_slots_are_the_set_1_elements_their_pushed_resource_ids_name,
  runs on lavapipe, moltenvk-m3, and moltenvk-m3 without
  robustImageAccess2. Its words come from tests/resource_words.tsv rows
  70 and 10, checked against TextureWord::of. It checks the fixed set-1
  layout and that the pushed fields are exactly the buffer, the three
  texture IDs and the region. On the interpreter, with the source at
  sampled element 3 and the destination at storage element 2, it checks
  the reads, the writes, the width and is_null_texture both ways (index
  0 and index 1). On moltenvk-m3 without robustImageAccess2, where the
  shader checks the read, the source image traps any access outside it
  and the out-of-bounds alpha comes from bit 12 of the word: 1.0 for
  R8Unorm, 0.0 for RGBA8Unorm. On the other two profiles the device's
  robust texel answers.
- The same change on the earlier base 9a3b6587b2 (jobs m3-max-41478 and
  41479): 3670 of 3670, clippy clean in all three configurations.
2026-11-17 09:51:53 -08:00
Anees Iqbal ac4b2370f5 rt: the consumer names the core Vulkan features its own work needs
DeviceOptions::features takes ConsumerFeature values (SamplerYcbcrConversion
for now). Device::new enables each one the device reports, once, in the
consumer's order, and Device::features lists those enabled, so the consumer
can refuse its own path. The runtime's own work and the translator read only
the floor's features. No Metal counterpart.

The floor test's device creation chains the maximal-reconvergence and
subgroup-uniform-control-flow structures where their extensions are listed,
as Device::new does (the device cfgs failed to compile without the fields).
The consumer-extensions device test also expects the optional extensions the
device lists, and asks for the feature twice.

REFUSALS.md takes the renamed site of VulkanVersion (derive.rs derived).
API signatures blessed.

Verified: cargo fmt. Lint and device legs follow.
2026-11-17 09:21:08 -08:00
Anees Iqbal 136fb66907 metal2vulkan-rt: map the identity ABI's parameter block and grid region; translated-kernel device test
Identity steps 2 and 3 are on development: ArgumentTableAddress is the ring
block's address in the window, fields placed in the ArgumentTable go to the
block, and every dispatch reads Metal's grid from its pushed region (a zero
grid for an indirect dispatch), with no MultiRegion constant to specialize.
The README gains the pipeline states' section and its known gaps; REFUSALS.md
and the API signature table are regenerated.
2026-11-17 09:20:31 -08:00
Anees Iqbal 5617449350 metal2vulkan-rt: the encoder's refusals in REFUSALS.md and its API in the surface table
Generated by refusal_surface.py and signatures.py --bless.

Verified: the generators ran clean (0 variants without a reach mark or a
basis).
2026-11-17 09:20:30 -08:00
Anees Iqbal 46e3215e55 identity: kernels over buffers lower under the identity domains
Under PointerDomain::Identity with HandleDomain::Identity every buffer slot of a kernel is its
device address used directly. Each slot is the Psb form, its address read from its own push
field, PushField::SlotGuestBase(slot): gpuAddress plus the bind offset, which under the identity
domains is the Vulkan device address. No root table is read, and no access is contained, as Metal
contains no device-address access (psb::prepare_at). Selection admits, under the identity domains,
only the plans lowered so far (select::identity_admits): a kernel whose push fields are its slot
addresses and its dispatch region, all in the push window, with no descriptor and every slot
addressed. Anything else is still Unsupported{IdentityDomains}, not implemented, now refused there
rather than for every function at analysis. SEMANTICS_VERSION 2146: a refusal under the identity
domains became a module.

The new tests (src/tests/engine_identity.rs):
- a1_bool_from_float under the identity domains on lavapipe and moltenvk-m3 has no descriptor,
  no root table and three SlotGuestBase fields. It passes L3, and it computes the program's
  answer on the CPU interpreter, with its buffers above 4 GiB at bind offsets 32, 16 and 4. It
  writes nothing past its output, with its region pushed.
- a2_dynamic_texel_offset, which samples a texture, compiles under the default domains and is
  refused under the identity ones.

Verified:
- m3-max-41149 (msi, check commit eeecc4492b, the same tree but for the test's region bytes):
  clippy -p metal2vulkan --all-targets --all-features, rustdoc -D warnings, and nextest -p
  metal2vulkan --all-features, 3664 of 3665. The one failure was this test, which met the kernel's
  DispatchRegion field and did not fill it.
- m3-max-41195 (msi, a5dbfd408f, this tree): clippy and rustdoc; tests::engine_identity and the
  domain pair test, 3 of 3.
- m3-max-41150 (msi, eeecc4492b): clippy under --cfg m2v_gpu and --cfg m2v_cpu_icd.
2026-11-17 08:13:46 -08:00
Anees Iqbal 94071f82a2 device: the identity pointer and handle domains, taken as a pair
The new runtime's form: pointers are device addresses used directly and a texture's or sampler's
handle is its gpuResourceID (docs/RESOURCE-ID.md). The variants come beside the old domains,
which stay until the cutover; nothing lowers under them yet.

- PointerDomain::Identity and HandleDomain::Identity.
- Device::new refuses one identity domain without the other (InvalidDescriptor) and the identity
  domains on a device without bufferDeviceAddress and shaderInt64 (Unsupported{IdentityDomains},
  naming both features as one alternative).
- A compile under the identity domains is Unsupported{IdentityDomains}, not implemented, at the
  start of analysis, so no old form is ever emitted under them. Later steps lift it as the
  lowering lands.
- The profile fingerprint covers the domains (tested).
- docs/API.md's policy section names the domains; docs/REFUSALS.md and the reach table carry the
  new refusal; api_signatures regenerated.

Verified (this commit's tree, rebased with the ledger commit before it onto b216007f0a):
- msi 41071: clippy -p metal2vulkan --all-targets --all-features -D warnings, rustdoc -D warnings,
  nextest -p metal2vulkan in full, 3,663 of 3,663 (the golden table included: no cell moved; the
  new test the_identity_domains_come_as_a_pair_on_a_device_with_addresses among them).
- msi 41072: clippy under --cfg m2v_gpu and --cfg m2v_cpu_icd.
- msi 41073: the conformance crate's ledger tests, 7 of 7.
2026-11-17 07:46:08 -08:00
Anees Iqbal 077c9722e3 metal2vulkan-rt: command queues, command buffers and events on the submit and completion threads
Step (c) of the new runtime's compute core.

What:
- CommandQueue (newCommandQueueWithMaxCommandBufferCount:, its bound on uncompleted command
  buffers), CommandBuffer (enqueue, commit, handlers, waits, status, error), Event and
  SharedEvent (signaled_value, set_signaled_value, wait_until_signaled_value,
  notify_listener).
- A command buffer records at once into segments split at event waits and signals. The submit
  thread holds a segment whose waits are not met, and its queue behind it, while the segments
  before it run (reims F1). A wait the host's value meets submits no semaphore wait; a GPU
  signal not above the highest value submitted or set is left out, so the semaphore only rises.
- The completion thread retires by a progress semaphore, follows submitted event signals (a
  listener runs at a mid-buffer signal, reims F2), runs handlers with no lock held, and is
  woken through a host-signalled timeline semaphore only when a wait needs it.
- A command buffer keeps each block it uses until it retires. A zeroed Private buffer's fill is
  an upload submitted ahead of every later commit, whose segments start with a barrier; each
  segment ends with a barrier to the host.
- Device::quiesce(timeout) (F9), with every wait bounded, no join of a thread still running, no
  thread-local that exit() tears down, idempotent, freeing nothing; unmap runs on the caller for
  every block handed out, once (a handed set replaces the per-idle flag).
- The last handle dropped in a handler: the completion thread finishes the teardown itself (F8).
- CommandQueue::abandon (F14); a loss ends held work, in-flight work once the device is idle,
  host waits on pending signals, and later commits, with DeviceLost { in_flight } (F13).
- Refusals Committed, OtherDevice, NoCommandBuffers with their basis; Error::Quiesced;
  docs/REFUSALS.md and the API signature table regenerated; the README's contract.

Verified: cargo fmt; refusal_surface --check. The compile and device jobs follow.
2026-11-17 07:25:30 -08:00
Anees Iqbal 4e8784ad14 refusal surface: the new runtime's own refusal enums, one section each
What: refusal_surface.py reads the new runtime's Error and makes a section of
docs/REFUSALS.md for each variant whose payload is one enum the runtime
declares: today Refused(Refusal) and Limit(Limit), and any family added later
(a Gap included) without a list of names to keep. Each of their variants
declares its basis, as Problem's do, and --check fails on one that does not.
The translator's Limit section no longer counts rt's Limit sites. A rustdoc
link [text](path) in a summary reads as its text; three existing rows lose a
link the file could not follow.

Why: AGENTS.md wants every new refusal in REFUSALS.md, and the scan of rt read
the floor's Missing only, so EmptyBuffer, BufferPastBlock, BlockLen and
BlockIds were missing. Their basis lines cite the M3 Max measurements the old
runtime records for the same answers (newBufferWithLength:0 and a placement
past the heap's end answer nil), the device's limits, and our 32-bit numbers.

How verified: the script regenerates, --check and --selftest pass locally;
the refusal_surface test runs in the compile job.
2026-11-17 07:25:30 -08:00
Anees Iqbal 374e29a988 metal2vulkan-rt: the floor's shader features, queue family, timestamps and memory types
The floor now also requires what the translator's shaders and the runtime's
core need of every device:

- shaderInt16, shaderInt8, storageBuffer16BitAccess (Vulkan 1.1 features,
  now read and enabled through Features::vulkan11), storageBuffer8BitAccess,
  scalarBlockLayout, vulkanMemoryModel and vulkanMemoryModelDeviceScope. The
  translator emits 8- and 16-bit access only in storage and physical storage
  buffers in practice (uniform views are u32 or uvec4, push fields are 32- or
  64-bit), so the uniform and push-constant 8/16-bit features stay out; it
  does use device scope.
- timestampComputeAndGraphics, and timestampValidBits of at least 36 on the
  first queue family with graphics and compute, which Capabilities names
  (queue_family). A device with no such family is Missing::QueueFamily.
- a host-visible, host-coherent, host-cached memory type (Shared storage)
  and a device-local, host-visible, host-coherent one (the parameter ring),
  each usable by a buffer of BUFFER_USAGE: every Vulkan 1.3 buffer usage plus
  device addresses. Vulkan answers buffer memory types only for a created
  device, so check() finds a type with each set of flags and carries the
  memory properties, and memory_types(device, &capabilities) chooses the
  first usable type of each with vkGetDeviceBufferMemoryRequirements.
  Missing::MemoryType names the flags.

Each shortfall is named in BelowFloor, with a unit case; the README's Floor
section states every item and tests::floor holds it to the code. The device
test now also creates each device with the floor's features and extensions
and chooses its memory types on it.

CI's lavapipe step (ci.yml and scripts/linux-gate-ci) runs the rt crate's
device tests too. refusal_surface.py reads metal2vulkan-rt and writes the
floor's Missing as section 10 of docs/REFUSALS.md; signatures.py pins
metal2vulkan-rt's public surface in api_signatures.tsv.

Verified: see the lane report (compile job, device legs on every lab GPU,
lavapipe and the Windows UHD 630).
2026-11-17 05:33:25 -08:00
Anees Iqbal f19c613fe1 RUNTIME 2489: A compute or render encoder's core is made in the box it lives in: one 3 KB copy per encoder fewer
EncoderCore (2984 bytes, -Zprint-type-sizes on msi) was built by value in
EncoderCore::open, copied out of it in the returned Result, and copied again
into its box (EncoderCore::boxed / boxed_in) by the compute and render opens:
two 3 KB memcpys per encoder. A pinned LBR profile of a guest-shaped compute
stream (dispatch_chain --host 400 --only encoders --dispatches 5 --groups 64
--states 3 --binds tex-moved, msi lavapipe) put libc copies under
EncoderCore::open (~110 ns) and open_compute (~98 ns) per guest dispatch, one
encoder each.

EncoderCore::open_placed takes a place closure that puts the core where it
lies, the box for compute (parked room or the device's spares) and render
(spares), so the core moves once. open keeps the by-value form for the blit
encoder (HeldCore). Nothing else changes: the same fields, the same order
under the same lock, the same boxes.

Test: tests::compute_parked::a_compute_encoder_core_lies_in_the_box_its_command_buffer_parked (three
encoders of one command buffer find their core at one address; it pins where the core lies, not the
copy count). RUNTIME_VERSION 2489.

Verified: msi m3-max-38102: clippy -p metal2vulkan-runtime --all-targets --all-features -D warnings 0;
lavapipe debug (cfg m2v_cpu_icd) compute, dispatch, encoder, tracker and render suites 190/190. Pinned
interleaved A/B (msi lavapipe, release, taskset -c 0-7, 5 base/tip pairs, guest shape dispatch_chain
--host 400 --only encoders --dispatches 5 --groups 64 --states 3 --binds tex-moved, --runs 30): the open
call 640 -> 574 ns per guest dispatch (-66 ns); thread_cpu per dispatch within run-to-run noise (6137
vs 6240, range 5615-6681). Profile at the base (m3-max-38071, LBR): open copied the 2984-byte core out in
its Result (~110 ns) and open_compute again into its box (~98 ns).
2026-11-16 15:48:59 -08:00
Anees Iqbal 45ebbdaa5e RUNTIME 2484: Copies between a texture's region and a surface's runs of guest RAM
A consumer that keeps an IOSurface's GPU copy as one optimal texture, on a host whose surface
path copies by runs of guest RAM (copies_guest_ram: no view of the pages is made), needs the
texture forms of the run copies, or its fill, upload and download go back through a view per
block or a staging buffer.

What: BlitCommandEncoder::copy_texture_from_host_ram(ram, runs, offset, bytes_per_row, size,
texture, slice, level, origin) and copy_texture_to_host_ram(texture, slice, level, origin, size,
ram, runs, offset, bytes_per_row), runtime extensions (Metal has none). `runs` is the surface's
bytes in order (the shape the consumer's run copies pass today); offset and bytes_per_row are
Metal's copyFromBuffer layout over those bytes. Each row's texels within a run and a chunk are
one vkCmdCopyBufferToImage / vkCmdCopyImageToBuffer region straight on the chunk's import
(bufferRowLength and bufferImageHeight 0; bufferOffset a multiple of the texel,
VUID-vkCmdCopyImageToBuffer-srcImage-07975; the subresource bounds 07971/07972), with no staging
buffer. A first-touch or CPU-only chunk goes through the existing StagedGather / StagedScatter,
which now take a buffer or an image target. Hazard tracking, dirty-page reports, imports held to
completion and the bytes outside the texels are as the buffer forms keep them. Refused as the
buffer forms are, and with Invalid / Problem::HostRam for the texture's own cases (its doc
extended); no new RuntimeGap, Degradation kind or WorkCounts field: the direct form shows in
host_ram_copy_regions with no staged copy. replay.rs logs the call (HostRamTextureCopy);
blit_texture.rs and blit_plan.rs helpers are shared (pub(super)). Runtime README and HOWTO
document it; the signature table blessed (+2 methods); REFUSALS regenerated. RUNTIME_VERSION 2484.

Verified: msi job m3-max-37991 (lavapipe, --cfg m2v_cpu_icd): clippy -p metal2vulkan-runtime
--all-targets --all-features -D warnings 0; nextest host_ram_texture_device + host_ram_copy_device
39 passed. m3-max-37997: "HOST-RAM-TEXTURE llvmpipe: fill regions 250, dispatches 0, staged 0" (a
300x200 BGRA8 Private texture, rows at 1280 bytes from byte 48, one row across a chunk end); the
staged test saw exactly one staged gather and one staged scatter. Plain and --cfg m2v_gpu clippy,
rustdoc and the 780M and Iris runs follow on development.
2026-11-16 14:53:52 -08:00
Anees Iqbal 3619e37540 RUNTIME 2482: Texture::view_placement answers what a view would be, by the decision its making takes
The consumer will make an IOSurface plane's device cache one optimal Private texture, every
texture over the plane a view of it, and needs to know before it makes a view whether the
runtime would make it a Vulkan view of the image or a view shadow (which it sends to its own
fallback instead).

What: `Texture::view_placement(pixel_format)` answers `ViewPlacement` (`Image`,
`ImageThroughSwizzle`, `Shadow(ViewShadowReason)`, `OverBytes`), or the error
`new_texture_view` would refuse the view with. The decision is factored, not copied:
`Texture::checked_view` holds the checks `view_as` ran inline (Metal's rules, rotation, X32,
buffer slices, decoded twins), `Texture::view_hold` decides the storage (shared, through a
swizzle, the viewed image, a shadow and why, storage over the bytes), and
`Device::view_shadow_plan` / `shadow_plan` hold the shadow's refusals `image_shadow` checked
while making. `view_as` and the query call the same three. `image_plan::views_missed` replaces
`takes_views_of` and names why an image takes no view (another compatibility class, or not in
its list); `Device::view_apart` replaces `image_takes_view` and puts the device's missing
reinterpretation first; the `shadowed-texture-view` notice's reason now follows that reason
(it chose by the texture's PixelFormatView usage before).

Tests: `view_placement_device` (runtime, device cfgs) sweeps 10 texture formats x 5 usages x
24 view formats, checks the query moves no count and matches the view made (by
`view_shadows`, `views_through_swizzle` and the handed-out image), and names the consumer's
cases. `plane_device_cache` (validation lane): a 300x200 BGRA8Unorm Private texture round-trips
between no-copy buffers at offset 48 and pitch 1232 with every other byte kept; a clear through
its sRGB view then a copy through its own-format view in the next encoder, tracked and
untracked with a fence, read the clear with no hazard under synchronization validation, and the
unordered control is reported as a read after write.

Documented in the runtime README; the signature table blessed (10 rows); REFUSALS regenerated.
RUNTIME_VERSION 2482.

Verified: msi job m3-max-37961 at c2f0c96d3c: clippy -p metal2vulkan-runtime -p
metal2vulkan-validation --all-targets --all-features --cfg m2v_cpu_icd -D warnings 0; the lavapipe
tests, plain and --cfg m2v_gpu clippy and rustdoc follow on development. The hazard tracker keys a
view's uses on its image (texture.rs view_as shares the Arc<Image>; bound_use/image_use key on
image.identity.key), so the order across views needed no fix.
2026-11-16 14:48:17 -08:00
Anees Iqbal df87983bb7 RUNTIME 2463: Render draws: the restarted list and the error and notice makers out of line, cold
What: draw_resident's restarted-list arm (the index rewrite and gather requests, 205 source lines)
is its own #[cold] #[inline(never)] method, restarted_list; Device::degrade, degrade_copied_pages,
degrade_host_step, degrade_where and tell, and error.rs's vulkan, invalid, nil and internal are
#[cold]. Same commands, barriers and answers; only where the code lies changes (draw_resident 130.7
-> 127.4 KB of machine code). Also folded: draw_costs gains a guest shape of a few render encoders
with set_bytes and each thread's CPU a draw (17126bfe04), the encoding thread's own CPU apart from
unnamed threads (afa24f4074), and --calls counting each call's cycles and cache misses (7249f6930b).

Why: on a Zen 4 host a one-draw render pass ran at IPC 0.79 against 1.7 inside a long pass, the
same on RADV and lavapipe (gem10, m3-max-36911/36975). The misses are instruction fetches: per pass
about 8.3k L2 instruction misses against 1.2k data, over 806 distinct 4 KiB code pages (more than
the L2 iTLB's 512), no function above 7.5% of them (m3-max-37017, -37041). This change is
measured neutral (m3-max-37061, lavapipe, release: pass1 instructions 112,257 -> 112,123, L2
misses 10,590 -> 10,577; cycles within the node's noise) and kept as correct and neutral; the
lever left is the layout of the path's code across pages, a build setting of the program.

Verified: see the landing's check jobs.
2026-11-16 09:43:35 -08:00
Anees Iqbal 3de483d86f RUNTIME 2459: Joined completions: a command buffer marked to join the next groups under Exact
CommandBuffer::set_completion_joins_next marks a command buffer, before its
commit, as one whose completion may be seen with the next one's. Under
CompletionPolicy::Exact, on a device whose merge check holds and whose
queues are not relayed, a marked command buffer's batches wait in the
scheduler's group as every batch does under Grouped. The first batch of the
VkQueue behind them that is not marked goes last in that group, which then
goes at once (GroupEnd::Closed, WorkCounts::group_ends_closed), so it is
seen complete at its own end and never held back. Its submission check runs
with the marked ones' (check_heads), so they are found ready together. No
group is kept past its pass under Exact (Alone::Unkept,
WorkCounts::batches_held_alone_unkept): a kept group can reach the GPU after
the work ahead of it ended, which would delay the unmarked one behind it.
Everywhere else (Grouped, no merge, relayed queues, the encoder trail,
batches that never group) the mark changes nothing.

Why: on the Iris Xe, ANV on i915 lists every VkDeviceMemory in each
execbuffer, about 170-190 us of driver time a vkQueueSubmit at the
consumer's import count, and the consumer cuts each guest command buffer
into about 12 parts committed under Exact, one kernel submission each.
In its walk the GPU sat idle about 1.5 ms per waited guest buffer between
parts already committed, behind a backlog of those calls. The consumer will
mark every part but the last of a cut whose completion nothing observes.

Grouped-completion's notice, docs/API.md's catalogue, FAST-PATHS row 38, the
runtime README, CompletionPolicy::Exact's doc, api_signatures and REFUSALS
say so. Tests: runtime_lane::joined_completions (marked parts group and a
group is closed by the last; checked parts too; a no-op where the device's
own check finds no merge; unmarked parts go alone; an unmarked command
buffer is seen complete while the long one behind it still runs, the marked
one before it complete by then), on lavapipe with the merge assumed.

Joined completions: the cost table's length, and the order test's first work done before

The conformance cost table's SHARED list holds 36 rows with
batches_held_alone_unkept. In the order test the marked command buffer took
the new buffers' first work, which no batch in a group takes, so it went
alone and nothing grouped: the buffers' first work now runs before it.

Verified: clippy and lavapipe lane job m3-max-36769 showed the failure
(grouped 0 with grouping true); the rerun is the next job.

Verified at 8e6c37c263: m3-max-36784 (msi) clippy --workspace --all-targets --all-features 0; m3-max-36785 (msi, lavapipe, --cfg m2v_cpu_icd) joined_completions + grouped_submissions + alone_batches 21/21 (marked parts under Exact with the merge: 7 command buffers in 2 submissions; unmarked: 7 submissions, 0 grouped; lavapipe's own merge check, not Holds: 0 grouped; an unmarked buffer is seen complete at its own end). The Iris merge check answers Holds (m3-max-36725: 9.6 us in one call of 4 against 26.4 us apart). Release-mode lavapipe, clippy --cfg m2v_gpu and m2v_cpu_icd and rustdoc run after the merge.
2026-11-16 08:18:12 -08:00