Commit Graph
353 Commits
Author SHA1 Message Date
Anees Iqbal fd916e7f99 rt: an index has one owner, the texture or sampler placed there last
The consumer's program places a texture at an index a live texture of its own still holds, and
releases the older one later (179 placements in one recorded stream, 92 in another). Metal takes
it: the later texture takes the ID. rt refused it (IndexInUse).

Now Grants keeps one owner word per held index (a HashMap per class, the word given at placement
and never again on the device; no list of holders, no refcount, no second bitset). A placement at
a granted index always succeeds and makes the placed object the owner; a release vacates the index
and empties its elements only where the releaser still owns it, so a displaced object's going
touches nothing. Placement and element writes happen under the grants lock in one step
(Arrays::place_texture, place_samplers, add_samplers, vacate_texture, vacate_samplers), so the
elements always belong to the owner. Where a placement displaces another object, a texture with
no storage view writes its storage element null and a sampler writes the arrays it does not use
back to their defaults, so nothing stale answers. The descriptor-slot gauge counts held indices:
a displacing placement adds none.

The same occupancy serves textures, sampler states and constexpr samplers. Constexpr samplers are
kept by (index, state words), each with its owner word; a later pipeline state of the same words
adds its arrays where the constexpr sampler still owns the index. Refusal::IndexInUse is deleted:
nothing Metal refuses remains. A texture now takes its index after its image and views are made,
so an index not granted is refused after the image is made and freed at once.

The duty: no work in flight reads a displaced object through its ID, as Metal's. rt does not
check it. RESOURCE-ID.md and the rt README state the rule and the duty.

The harness takes the next index round each class's range (its workloads make far fewer objects
than a range holds). The replay player keeps the object placed last per index: a named index an
object holds is taken, and the earlier object's release leaves it; with no index free for a
constexpr sampler it answers IndicesNotGranted past the range.

Tests: grants' an_index_has_one_owner_the_object_placed_there_last (both classes);
sampling::every_device_gives_an_index_to_the_texture_placed_there_last (a storage-capable D at 3,
a sampled-only A over it, whose placement empties D's storage element: a write through 3 is
dropped and D keeps its texels; B storage-capable over A, A dropped; sampling through 3 reads B,
writing through 3 writes B; B dropped, sampling through D's ID reads zero; the slot gauge counts
3 once); the sampler states' test places a state over a live one; replay's indices test.
REFUSALS.md regenerated, api_signatures loses IndexInUse.
2026-11-18 07:43:13 -08:00
Anees Iqbal cc9ab54b86 rt: one texture index class, 1 to 65,535, and a storage array as long as the sampled
The consumer hands each guest process texture IDs from one pool (1 to 16,320) and places every
texture at its own ID whatever its usage. rt split textures into two index classes by usage
(StorageTexture 1..4095 with shader-write usage, Texture 4096..65535 without), so every named
sampled-only texture below 4,096 and every storage-capable one above it was refused
(IndicesNotGranted), where Metal takes them: 4,818 makings in one recorded stream and 5,707 in
another.

Now there is one texture class, IndexClass::Texture, 1 to 65,535, with one grant bitset and one
occupancy; IndexClass::StorageTexture is deleted. Set 1's storage-image array (binding 1) is as
long as the sampled-image array, 65,536 (floor::TEXTURES replaces SAMPLED_IMAGES and
STORAGE_IMAGES). A texture with a storage view writes both elements at its index; any other writes
its sampled element alone and its storage element stays null; a texture that goes writes both
null. Samplers keep their class.

Why every floor device holds it: Vulkan's Required Limits (vkspec 56.1, Table 75 and Table 76)
give maxPerStageDescriptorUpdateAfterBindStorageImages, maxDescriptorSetUpdateAfterBindStorageImages,
the two SampledImages limits, maxPerStageUpdateAfterBindResources and
maxUpdateAfterBindDescriptorsInAllPools a minimum of 500,000 on a device that supports
descriptorIndexing. The floor's own sums become 2 * 65,536 + maxColorAttachments (131,080 at 8)
and 2 * 65,536 + 3 * 4,000 = 143,072, both below 500,000. Every lab capture (2080, 3090, XTX,
780M x2, HawkPoint, RX 550, Iris Xe, UHD 630, lavapipe) reports descriptorIndexing and 1,015,808
or more for each of the six limits. The floor's limit check stays the one gate: no query-chosen
size, no second form.

Translator: link.rs's identity set 1 sizes binding 1 by IDENTITY_TEXTURES (65,536), the same
constant as binding 0, so rt's of_the_device check still matches it. Nothing else in the pipeline
interface, binding plan or resource-ID decode assumes a storage index below 4,096: the identity
handle is the low word (masked only of bit 31 where the alpha flag rides it), indexing each
array's runtime-array variable. The identity domains are reached only from Device::from_queries'
profile (rt sets PointerDomain::Identity; the old runtime never does), so Device::new's modules,
refusals and notes do not change. SEMANTICS_VERSION 2173: the identity set 1 layout is a
binding-plan fact that changed under unchanged keys.

Consumers in the tree: the harness and the replay player grant and place every texture in the
one class; the player reserves a texture ID in it.

Docs: RESOURCE-ID.md's class table (nil, texture, sampler), the rt README (set 1, grants,
textures, the fault paragraph, the floor's limits table), IndicesNotGranted's doc (an object at an
index not granted, as well as a release) and IndexRange's basis; REFUSALS.md regenerated;
api_signatures loses the variant.

Tests: sampling::every_device_makes_a_texture_of_any_usage_at_any_index grants the whole texture
range, makes a shader-read texture at 2 and a shader-write one at 5,000, and checks one
sample_down dispatch against the CPU mean. arrays' fill-past-capacity fills every texture index
(a storage texture at 1, views of it at 2..65,535, 128 made again).
2026-11-18 07:43:12 -08:00
Anees Iqbal da02260f2b 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-18 07:41:26 -08:00
Anees Iqbal b527ae9f68 rt, translator: a step above 1 on a device without supportsNonZeroFirstInstance runs from base instance 0
Vulkan's divisor needs firstInstance 0 where the device does not report supportsNonZeroFirstInstance
(VUID-vkCmdDraw-pNext-09461): lavapipe and the UHD 630 among the lab's devices. The translator
refused the step there under the identity domains, as a Metal draw may carry a base instance, so
those devices lost every draw through such a state, base instance 0 included. The WebGL divisor
stream draws 462 times through its two stepped states, every draw at base instance 0 (it calls no
baseInstance form and draws nothing indirectly).

Now, under the identity domains, fetch_as takes the divisor wherever the profile has
vertexAttributeInstanceRateDivisor and the rate is within maxVertexAttribDivisor; outside them the
step is pulled where the property is missing, as before, so the old runtime's path is unchanged.
divided() names the feature or the limit; its not-implemented arm had no caller left and is gone.
The new runtime marks such a state where the device lacks the property
(Draws::first_instance_zero) and refuses a draw through it at a base instance other than 0,
Gap::Draw { DividedBaseInstance }, before anything is recorded; a draw of no vertices or instances
still records nothing. Indirect draws are not built in the new runtime.

Tests: from_queries_divides_an_instance_step_where_the_divisor_feature_is_enabled (lavapipe and
moltenvk-m3 profiles, with and without the property: an instance-rate binding of divisor 2, both
modules L3-valid; rate 5 past a limit of 4 refused naming it). The device test
every_device_with_the_step_rates_fetches_per_instance_at_rate_2_from_the_base_instance draws from
base instance 0 on every device with the step rates (every texel the first mark) and from base
instance 1 where the property is reported (the second mark), expecting DividedBaseInstance where it
is not, and prints which path ran.

docs/REFUSALS.md regenerated (scripts/refusal-surface/refusal_surface.py): VertexStepRate has one
site. The rt README names the draw refusal on those devices; docs/API.md the identity-domain rule.
2026-11-18 07:20:24 -08:00
Anees Iqbal cecc252f26 rt: refuse indirect arguments and indices a placement puts off Vulkan's multiple
The consumer places buffers at any byte of a block, so a buffer's place in its block's VkBuffer
plus a Metal-valid offset can miss the multiple Vulkan reads at. Metal's own rules (an indirect
offset a multiple of 4, an index offset a multiple of the index size) assume a buffer that starts
at an aligned address, as every Metal buffer does; here the absolute offset is what Vulkan sees:

- VUID-vkCmdDispatchIndirect-offset-02710: the offset in the VkBuffer is a multiple of 4.
- VUID-vkCmdBindIndexBuffer-offset-08783: the offset plus the base of the memory range backing
  the VkBuffer is a multiple of the index size. A block's VkBuffer is bound at a multiple of the
  pool's granule (64 KiB) or at 0 of its own allocation, so the place in the VkBuffer decides it.

dispatch_threadgroups_with_indirect_buffer and draw_indexed_primitives now check the place in the
block (the device copy's, for a Managed buffer with one, which is what the GPU reads) after
Metal's own checks and refuse with the new Refusal::ArgumentPlace { place, alignment }, basis
ours. Nothing is copied to an aligned place: a copy is not a design answer here.

Tests (device cfg): every_device_reads_indirect_arguments_only_at_a_multiple_of_4_of_their_block
places a buffer 2 bytes into a Shared block and shows offsets 0 and 16 refused at places 2 and 18,
then dispatches from a buffer placed at byte 4100 and checks the result;
every_device_takes_indices_only_at_a_multiple_of_their_size_in_their_block places indices 2
bytes into a block and shows 32-bit indices at offset 0 refused (place 2, alignment 4) before
anything is recorded, then draws 16-bit indices from there and checks the texels and the pass's
counts. README's placement contract names the rule; docs/REFUSALS.md regenerated; the API table
gains the variant.
2026-11-18 06:41:16 -08:00
Anees Iqbal c459695b88 rt: the consumer places a Managed buffer's device copy, in a Private block it holds, at any byte offset
new_managed_buffer(bytes, copy, length, copied) takes both placements from the consumer: the
bytes as (block, offset) in a block the host maps, and on a device that keeps a device copy
(has_unified_memory false) the copy as (block, offset) in a Private block the consumer holds, at
any byte offset; gpu_address is that block's address plus the offset. rt chooses no layout any
more: its copy blocks, COPY_ALIGN, the first fit and the device's copies place list are deleted,
and so is the Private block of the copy's own that the copy took where device-local memory had
no room. Placement, and so the slack past a buffer's length, is the consumer's: rt writes the
copy's length and no byte past it.

New typed refusals: ManagedCopyMissing (no copy where the device keeps one),
ManagedCopyOnUnified (a copy where it keeps none) and ManagedCopyNotPrivate (a copy in a block
that is not Private); a copy range past its block is BufferPastBlock, as for any buffer.
managed_spilled_bytes is now per buffer: a copy the consumer placed in a spilled Private block
counts its length while the buffer lives. new_buffer shares the range check (placed).

The harness places a Managed buffer's device copy as it places a Private buffer of its length
and frees both with the buffer. The player places the GPU copy through its places at their
current rule, as a Private buffer of the buffer's length: a buffer in a place of its own keeps
the copy's place beside its own and gives both back with the same users; a buffer in a stream's
block or heap holds the copy's place as its one place. REPLAY-STREAM.md says so.

Tests: the two-copy rule places its device copy 4 KiB into a Private block the consumer takes
and checks gpu_address there (and, under the spill test, in a consumer take that spills, counted
in managed_spilled_bytes); a new device test places the copy at byte 4099 of a Private block
filled with 0xA5 and checks the whole block after the copy's creation and after a copy-in of the
whole buffer: the copy's bytes at 4099..5099 alone, the consumer's slack write at 5100..5200 and
every other byte unchanged; and the four refusals. Every other Managed test places its copy at
the start of a Private block of its own (tests::managed::on_device::new_managed).

Regenerated docs/REFUSALS.md (scripts/refusal-surface); api_signatures.tsv by hand.
2026-11-18 06:16:37 -08:00
Anees Iqbal 12b113fa5a 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-18 06:07:47 -08:00
Anees Iqbal 212bba29c6 rt: Metal's constant step is a vertex-rate binding of stride 0, on every device
Under the identity domains (Device::from_queries' profile, the new runtime's), Metal's
MTLVertexStepFunctionConstant was refused as Unsupported{VertexStepRate}, needing
vertexAttributeInstanceRateDivisor and vertexAttributeInstanceRateZeroDivisor, which the floor
does not enable. The constant step needs no divisor: it is now a vertex-rate binding of stride 0,
one form, no query, every device.

Vulkan permits it. The specification's "Vertex Input Address Calculation" (28.4) gives a
vertex-rate attribute's address as bufferBindingAddress + vertexIndex * stride +
attribDesc.offset, so a stride of 0 reads the layout's first element for every vertex and every
instance, whatever the base instance: what Metal's constant step reads. A binding's stride has no
lower bound outside the portability subset: VUID-VkVertexInputBindingDescription-stride-00619
bounds it above (maxVertexInputBindingStride) and is the only other rule on it, and
VUID-vkCmdBindVertexBuffers2-pStrides-06209 names 0 among the strides a bind may set. Under the
portability subset (VUID-VkVertexInputBindingDescription-stride-04456: at least
minVertexInputBindingStrideAlignment) link refuses the stride of 0 as
Unsupported{VertexInputLayout}, as it refuses any stride the subset forbids.

Translator, under the identity domains only (lower::access::identity), so Device::new's profile
and the old runtime are unchanged:
- metal::vertex::fetch_as answers Constant with VERTEX rate, divisor 1;
- pipeline::link::vertex::binding_stride emits stride 0 for any fixed-function fetch of a
  constant-step layout, keyed on the layout's step rather than on a divisor of 0 (on Device::new's
  profile the only such fetch is the divisor-0 one, so its bindings are the same);
- link's check that an attribute the vertex function lists as alike at every vertex of a
  primitive is fetched once per instance also takes a constant step's binding, which reads one
  element at any rate.
- The per-instance refusal (rate above 1) names exactly what the profile lacks:
  vertexAttributeInstanceRateDivisor, else the maxVertexAttribDivisor the rate passes. Its old
  text, and Feature::VertexStepRate's, claimed the constant step needed the divisor; both now name
  the per-instance step alone.

Docs: docs/API.md (identity-domain vertex input), the rt README's vertex lines, REFUSALS.md
regenerated (the VertexStepRate row and its reach mark no longer name the constant step).

Tests:
- engine_identity_render from_queries_fetches_a_constant_step_at_vertex_rate_with_stride_zero:
  on lavapipe (no buffer robustness, no divisor, no supportsNonZeroFirstInstance) ima_vertex's mark
  layout at the constant step links to a VERTEX-rate binding of divisor 1 and Static(0), both
  modules L3-valid; on moltenvk-m3 (portability subset, minVertexInputBindingStrideAlignment 1) it
  is Unsupported{VertexInputLayout}. Fails without this commit (VertexStepRate on both).
- rt draw every_device_fetches_a_constant_step_attribute_for_every_vertex_and_instance: two
  instances of a triangle from vertex 1 at base instance 1, the uint mark at the constant step over
  four distinct marks: every texel holds the first mark, provoking vertex 1, and its instance (1
  above, 2 below). Points are a gap of rt's draws, so the draw is of triangles; the provoking
  vertex is vertex 1, so a vertex-rate stride other than 0 would read the second mark, and an
  instance step the second and third.
- The Device::new-path tests stay as they were: a_constant_step_links_to_a_zero_divisor_binding_of_
  zero_stride, fetch_is_fixed_function_only_when_exact,
  a_constant_step_is_a_zero_divisor_only_where_a_zero_stride_is_legal.
2026-11-18 05:41:17 -08:00
Anees Iqbal 70dffca0c2 Deep threadgroups run as one row: SpecKey::DeepThreadgroup on from_queries, rt keys it on the size
Metal allows 1024 threads along z; a device's maxComputeWorkGroupSize[2] may hold 64 (NVIDIA's),
so rt refused a kernel's threadgroup of 1x1x320 (Limit::ThreadgroupShape) and could not play a
recorded stream past its frame 216 on any NVIDIA card. One form serves every shape on every
device: a threadgroup deeper than DEEP_THREADGROUP (64) runs as one row of its threads.

Translator, on Device::from_queries' profile only (ProfileFacts::deep_threadgroups, OneRow; Device::new
keeps Axes and is byte-equal): a kernel whose workgroup is its threadgroup (LocalSizeForm::Spec,
no compute derivatives) declares the boolean SpecKey::DeepThreadgroup. Its WorkgroupSize is
(Deep ? sx*sy*sz : sx, Deep ? 1 : sy, Deep ? 1 : sz), OpSpecConstantOp selects (the WorkgroupSize
rule now takes spec-constant operations whose defaults are positive), and its position in the
threadgroup Deep ? LocalInvocationIndex unflattened over (sx, sy) : LocalInvocationId. The linear
index, workgroup and grid builtins keep their values, so group counts, regions and indirect
buffers are untouched. The binder sets it for a region deeper than 64 and checks that region as
the flattened tiers' are. MetalDeviceProperties on that profile reports the capped invocations
on every axis (1024 on every floor device) instead of the device's per-axis sizes.
SEMANTICS_VERSION 2172, ARTIFACT_FORMAT_VERSION 536.

rt: the key is a function of the variant's size (size[2] > DEEP_THREADGROUP), so it adds no
pipeline and no cache key. choose() takes no device limit: an image-only kernel's deep tile runs
whole as one row on every device (it ran whole on RADV/ANV and in tiles on NVIDIA). fits(),
ComputeLimits::max_group_size and Limit::ThreadgroupShape are deleted: every workgroup is within
the floor by construction (a const assertion). A module that neither flattens nor declares the
key is a creation gap. README: the deep form, worst-case pipeline counts, the 50-pipeline line.
REFUSALS.md regenerated; API.md; api_signatures blessed; api_surface pins DEEP_THREADGROUP.

Tests: the translator runs a barrier-exchange kernel at 1x1x320, 2x3x100, 1x4x256 (deep) and 4x4x4
on the interpreter, checks the evaluated WorkgroupSize, no key on Device::new, the binder's
setting on an NVIDIA profile, and the reported maxima; rt's choice tests drop the device limit;
the observing-kernel device test adds deep whole, ragged and indirect dispatches; the square
test adds a column 256 deep.

Verified: built and tested under the check job named in the report.
2026-11-18 04:21:18 -08:00
Anees Iqbal 0d1a32436b vertex input under the identity domains: every attribute in fixed function, no pulled form
Planner ruling 11-18 (final): fixed-function vertex input for every attribute on every device,
the form native Vulkan uses and the fastest measured on every device, one form. Nothing of the
pulled form is taken on Device::from_queries' profile. Before this, the translator's
containment rule (contain::encoding is Check::InShader without buffer robustness) moved every
[[stage_in]] attribute into the shader, a form that reads through a descriptor the identity
domains refuse, so every rt render state with a vertex descriptor was refused as
Unsupported(IdentityDomains).

Translator (metal::vertex::fetch_as, pipeline::link::vertex::resolve), under the identity domains
only (lower::access::identity), so Device::new's profile and the old runtime are unchanged:
- the containment rule no longer moves an attribute: the device bounds the fetch as it bounds
  any (no buffer robustness: a fetch outside its buffer reads what the device gives);
- an unnormalized signed-integer format (Char*, Short*, Int*) is fetched in fixed function into
  a variable declared int, VertexFetch::SignedFixedFunction (new): Vulkan's numeric-type match
  lets a SINT format feed only a signed variable, and the device sign-extends as Metal does. The
  module reads the variable's bits by OpBitcast. Elsewhere such an attribute is still pulled and
  sign-extended in the shader;
- every case that pulled is a typed refusal by what it needs, never a second fetch form.

Metal's vertex descriptor on the rt floor:
- Maps directly:
  - formats: every Metal vertex format to the Vulkan format of its layout and conversion, by the
    device's VERTEX_BUFFER format query. 8/16-bit integer formats read into float attributes go
    through USCALED/SSCALED, signed integer formats into int variables, UChar4Normalized_BGRA is
    B8G8R8A8_UNORM, the 10:10:10:2 formats are A2B10G10R10, and FloatRG11B10 is
    B10G11R11_UFLOAT_PACK32. The validation crate's profiles of RADV (780M x2, RDNA3), ANV (Iris
    Xe, UHD 770), NVIDIA (Pascal, RTX 50) and lavapipe report VERTEX_BUFFER for all of them but
    FloatRGB9E5;
  - steps: PerVertex is VERTEX rate; PerInstance at rate 1 is INSTANCE rate;
  - offsets and strides: the descriptor's, baked into the VkPipeline.
- No fixed-function equivalent on the floor, so a typed refusal:
  - PerInstance rate > 1 and Constant: Unsupported{VertexStepRate}, by query. They need
    VK_KHR_vertex_attribute_divisor's vertexAttributeInstanceRateDivisor (plus ZeroDivisor for
    Constant) and supportsNonZeroFirstInstance, which the floor does not enable, so it is
    refused on every rt device today. Its needs name the missing feature, or the
    maxVertexAttribDivisor limit;
  - a format the device does not report for VERTEX_BUFFER: Unsupported{Format} with that format
    usage, by query;
  - FloatRGB9E5: Unsupported{Format}, not implemented, by need. Of the profiles above only
    lavapipe's reports it, and its fetch answers 0 for the fourth component, where Metal and
    Vulkan give 1;
  - an offset or stride off the format's component alignment (Metal takes any byte multiple on
    Apple5+), and an offset, stride, attribute count or layout count past
    maxVertexInputAttributeOffset, maxVertexInputBindingStride, maxVertexInputAttributes or
    maxVertexInputBindings: Unsupported{VertexInputLayout}, with the limit where one is passed;
  - PerPatch and PerPatchControlPoint: Unsupported{Tessellation}, as before.

rt: RenderPipelineKind::StepRate is deleted: the translator's VertexStepRate refusal comes first
on every rt device, so no pipeline states a divisor. README: the vertex input bullets, their
refusals, and the known gap that a vertex fetch outside its buffer returns what the device gives.
docs/API.md: the identity domains' vertex input. REFUSALS.md regenerated, with reach marks for the
two new features (VertexStepRate app, VertexInputLayout rare); api_signatures blessed.

Tests:
- engine_identity_render from_queries_fetches_every_attribute_in_fixed_function (lavapipe and
  moltenvk-m3 profiles with buffer robustness and the divisor withheld): ima_vertex's float2
  and short attributes are R32G32_SFLOAT and R16_SINT, nothing pulled, L3-valid; a rate-2 layout
  is VertexStepRate needing vertexAttributeInstanceRateDivisor. It fails without this commit (the
  attributes were pulled, then refused as IdentityDomains);
- rt draw every_device_fetches_a_signed_attribute_in_fixed_function: a short of -2 reaches the
  fragment's uint output as 0xFFFFFFFE on every texel; a rate-2 layout is refused as
  VertexStepRate. The existing stage-in test (vertex buffer and set_vertex_bytes) now makes its
  pipeline.

Verified: the next lint job and the device legs on every device.
2026-11-18 03:13:48 -08:00
Anees Iqbal 2aabffabb0 rt draws: a buffer bound off its argument's alignment is refused before the draw records anything, by the dispatch's shared check
Identity's Refusal::BufferOffsetAlignment (89bf650d2e) checked dispatches alone; a draw rounded the
address down to the argument's alignment (`address & !mask`) and drew from another place. The
draw now applies the same check to each buffer its vertex and fragment functions reach
(FieldValue::BufferAddress's mask, from RuntimeFact::AddressAlignment), after its other checks and
before anything is recorded, and pushes the address unrounded. The check is one function,
encoder::check_alignment(slot, mask, buffer, offset), which the compute encoder's
check_alignments loops over and the draw calls too; the refusal's doc names draws.

Test: every_device_refuses_a_draw_whose_buffer_is_off_its_alignment binds colored_vertex's float2
positions at 20 (alignment 8) and its float4 colours at 24 (alignment 16): each draw is refused
with the slot, offset and alignment; the buffers bound at 16 then draw the top half green, and the
pass is one submission, three barriers and one pass. REFUSALS.md regenerated.
2026-11-18 03:13:48 -08:00
Anees Iqbal b29fcccdc9 rt: the render encoder's draws, its state, and render states that number their samplers
A render encoder now draws. It holds Metal's render state (a pipeline state, the
vertex and fragment functions' buffers, bytes, textures and sampler states, one
viewport and scissor rectangle, cull mode, winding, a depth-stencil state, the
stencil references and the blend color) and records draw_primitives and
draw_indexed_primitives as one vkCmdDraw or vkCmdDrawIndexed each, setting the
dynamic state that changed and pushing each function's fields in the one push
range. Draws take no barrier, as Metal orders none within an encoder.

- render: a content's Draws (slots with accesses, push fields, vertex bindings),
  derived from the translator's interface; a state numbers its functions'
  samplers through the compute path's numbering (number_samplers), so
  new_render_pipeline_state takes sampler_ids, and RenderPipelineKind::Samplers
  goes; DrawInput refuses what a draw does not supply. Vertex strides are baked
  (the descriptor key holds them): VERTEX_INPUT_BINDING_STRIDE leaves the dynamic
  states, so a per-bind stride is refused by DynamicState. The line class's
  pipeline is made at its first draw, a first-use wait.
- pass: both store actions store, so a pass can end its rendering early (a memory
  barrier after a draw that wrote memory, or a copy a draw needs first) and begin
  it again with LOAD; Pass::begin serves both.
- PUSH_STAGES: one constant for the layout's push range and every push.
- Device::new_depth_stencil_state; IndexBuffer, Viewport, ScissorRect; Refusal
  VertexBufferOffset, IndexBufferOffset, ViewportNotFinite, StencilAttachment;
  Gap::Draw with DrawKind (Points, DepthTest, Viewport, AttachmentFormats,
  AttachmentRead).
- ring: a write answers its block buffer and offset, so set_vertex_bytes feeds
  fixed-function vertex input.
- harness: one sampler_ids for compute and render states.

The census of the gb and b2 render contents (m3-max-44704) set the scope: every
translated content reads only SlotGuestBase and ConstexprSampler fields, facts
AddressAlignment, DeviceAddresses and MovableStorageWrites, no parameter block,
writes no memory; 146 of 267 number samplers; 93 have one vertex binding.

Tests: host tests for the viewport mapping; device tests for triangles where
Metal's clip space puts them (direct, indexed through a scissor, through a
viewport; 3 barriers, no pipeline made, no bytes copied), the line pipeline made
once, stencil replace and test, a constexpr sampler sampling each texel,
stage_in from a buffer and from bytes, and the refusals and gaps. Not yet run.
2026-11-18 03:13:47 -08:00
Anees Iqbal 9bec8a977e rt: a dispatch that reaches a buffer bound off its argument's alignment is refused
The planner ruled that the bind-offset mask becomes a typed refusal. The binder pushed a bound
buffer's address, its gpuAddress plus the offset, rounded down to the alignment the kernel takes
it to have (FieldValue::BufferAddress's mask, from RuntimeFact::AddressAlignment), where Metal's
API validation refuses the bind offset ("must be a multiple of 4 but was set to 2" for a uint *
argument, probe vector_access_placement.m in the conformance crate). Plain Metal runs such a
dispatch at addresses of its own: an M3 Max reaches each element at its address rounded down to
the smaller of its alignment and 4. That is not the rounding the binder did for 8- and 16-byte
arguments.

The dispatch now refuses it with Refusal::BufferOffsetAlignment { index, offset, alignment }
before it records or keeps anything. check_alignment runs after the threadgroup size check and
before a kernel without effects returns, so both direct and indirect dispatches take it.
fill_parameters pushes each address as it is. A set_bytes copy sits at a multiple of 16 in the
ring, which every mask divides, so it is never refused.

Docs:
- docs/API.md: the identity-domain paragraph and the section 10 entry (renamed: "A dispatch that
  reaches a buffer bound off its argument's alignment is refused"); no case names its slug.
- RuntimeFact::AddressAlignment's doc and the mechanism comment.
- The rt README paragraph and FieldValue::BufferAddress's doc.
- docs/REFUSALS.md regenerated (44 rt refusals); api_signatures.tsv gains the variant's row.

Tests (device, under --cfg m2v_gpu or m2v_cpu_icd):
- every_device_refuses_a_bound_address_off_its_alignment (was ..._rounds_a_bound_address_down_...):
  at alignments 2, 4, 8 and 16, each of 17 binds 1 to 15 bytes past a multiple of 16 that the
  alignment does not divide is refused and leaves the buffer unchanged, and the same buffer bound
  at 48 runs. Without the check every one of the 17 dispatches returns Ok.
- an_argument_bound_off_its_alignment_is_refused (was ..._runs_at_the_address_rounded_down):
  the translated vector_word_phases kernels with one argument off its alignment are refused,
  naming the index, offset and alignment, and the command buffer completes with every buffer
  unchanged.
2026-11-18 00:14:00 -08:00
Anees Iqbal d1e9062b5f rt: blocks are ranges of 16 MiB allocations; the block-maker thread allocates only while a class's free bytes run low
The pool handed a take of up to a block length a whole pooled block and kept one ready block per
class, which the block-maker thread made again as soon as a take used it. A 16-byte Shared buffer
took the ready block, and the 16 MiB allocation that followed held the consumer's next pipeline
creation for its whole length on NVIDIA's driver.

Now each block is a range of one of its class's allocations, with its own VkBuffer:
- A take is a kept block of its length, else the first free range that fits, else the start of an
  allocation made in the call: 16 MiB, or the block's own length where that is longer. Lengths
  round up to 64 KiB (or bufferImageGranularity); a block starts at its length rounded up to a
  power of two, up to 2 MiB.
- Device::new makes one 16 MiB allocation per class. After that, the block-maker thread makes
  another only while the class's free bytes are under 8 MiB. A take never waits on it for memory.
- A take that no free range fits, while the class keeps blocks of other lengths, allocates at once.
  It also asks the block-maker thread to give those blocks' bytes back, after the consumer's hook.
  Only when its own allocation fails does it wait for those bytes, then look for a free range once
  more.
- An allocation holding no live block is idle. A class keeps its idle allocations while their
  bytes plus those of its allocations in use stay at or under the most bytes it had in use over the
  last 10 seconds, and within an eighth of its memory type's heap. Past that it frees the oldest,
  except the reserve that keeps 8 MiB free. The rule runs at takes and give-backs on an injectable
  clock; there is no timer.
- Removed: the dedicated path, fits-and-fills-half, the 256 and 128 MiB idle bounds and the 64 MiB
  Private block.
- Metrics: blocks_reused replaces dedicated_blocks_reused. New metrics: block_bytes_made, and the
  vkAllocateMemory time on the consumer's threads (count, total, longest) apart from the
  block-maker thread's.

Tests:
- Unit: rounding, base alignment, and the window and surplus rule.
- On device:
  - the first allocations, and the trigger at 8 MiB free;
  - kept blocks taken again with their number, address and mapping;
  - an allocation beside kept blocks of other lengths, with their bytes given back;
  - the failed-allocation path, at an answered maxMemoryAllocationCount;
  - idle allocations following the window down, the reserve kept;
  - a seeded 300-step stress of mixed takes and releases across both classes, each step under a
    one-minute timeout.
- Tests that took a block of 1 byte and used more of it now take what they use.
- The replay's rt counters read the new metrics.

Verified: cargo fmt; api_signatures blessed; REFUSALS.md regenerated. Clippy, the suites and the
device legs follow as potluck jobs.
2026-11-17 23:59:05 -08:00
Anees Iqbal 2868c3946d rt error: the BufferCopyOverlap variant and its Display arm closed again after the rebase over the b2b copy
Rebasing the render encoder over 3201e09737 put both sides' Refusal
variants after HeapTexturePlace; the resolution kept both but dropped the
closing "}," of BufferCopyOverlap and the ")," of its Display arm, which the
two sides shared outside the conflict. The file did not parse
(signatures.py --check fell back to the translator's Limit). REFUSALS.md is
regenerated from the repaired file; signatures.py --check passes.

Verified: signatures.py --check rc=0 and refusal_surface.py locally; the
lint job compiles it.
2026-11-17 23:45:50 -08:00
Anees Iqbal 4d1b0bf113 rt: the render encoder, one dynamic rendering a Metal render encoder with its load and store actions one to one
CommandBuffer::render_command_encoder(&RenderPassDescriptor) is
renderCommandEncoderWithDescriptor:. It begins one vkCmdBeginRendering (dynamic
rendering, in the floor: floor.rs requires vulkan13.dynamicRendering) into the
pass's attachments, and end_encoding ends it with vkCmdEndRendering. Load and
store actions map one to one (Load/Clear/DontCare, Store/DontCare). A clear
color is a float in a float, normalized or sRGB channel (the device converts
it), and an integer channel's is truncated toward zero and saturated, NaN 0,
as Metal's; rotated formats and A8Unorm held in R8_UNORM go through the
format's rotation; a clear stencil keeps its low 8 bits. The render area is the
smallest attachment's level, cut to renderTargetWidth/Height where set.

Each attachment is one level and slice of a 2D texture, 2D array, cube or cube
array of one sample: the texture keeps an identity-swizzled image view of that
level and layer, made at the first pass and freed with the texture through the
reaper (new gauge attachment_views). A pass orders itself as a blit copy does,
two barriers: the first after every earlier command, moving shader-read-only
homes to the attachment layout (general and attachment homes render in place)
and paying an owed barrier; the second after the rendering, moving them home
and making the writes visible to every later command.

Refused as Metal's validation stops them: Refusal::AttachmentUsage,
AttachmentPlace, AttachmentFormat; past maxColorAttachments,
Limit::ColorAttachments. Not built, Gap::RenderPass naming RenderPassKind: a
depth attachment, more than one sample, a resolve, a 1D or 3D attachment, the
Unknown and CustomSampleDepthStore store actions, a clear of a format only a
shader clears, a pass with no attachment. The replay streams' passes (pass
census over gb and b2, counts only): one or two color attachments plus a
stencil in 11,187 of them, every attachment a level of a 2D texture of one
sample, no depth, no resolve, loads Load/Clear/DontCare, stores Store/DontCare.

Tests: tests::pass's host tests pin the action mapping and the clear values;
on_device clears a mip level of a shader-read texture (moved and back), an
integer texture and a stencil, loads and keeps, cuts the area, clears one
slice of a 2D array, and counts one pass alone as one submission, three
barriers, one pass and no bytes copied; each view is made once and freed with
its texture; refusals leave the command buffer open. README render encoder
section and known gaps; REFUSALS.md and api_signatures regenerated.

Verified: the lint job and the device legs are the check.
2026-11-17 23:45:50 -08:00
Anees Iqbal 45b27a7623 WIP square workgroups: docs, refusal surface, device test 2026-11-17 23:13:19 -08:00
Anees Iqbal 3201e09737 rt blit: copy_from_buffer_to_buffer, Metal's copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:
The replay's rt backend skips buffer-to-buffer copies and the guest-RAM
copies that need one, so their destinations are never written on rt: the lead
suspect for gb's hang and b2's device loss on the 780M. This builds the copy.

One vkCmdCopyBuffer region between the bytes shaders reach (a Managed buffer's
device copy where the device keeps one), between a fill's two barriers: the
first after every earlier command (paying an owed barrier, hazard sets start
again), the second making the write visible to every later command; a copy
into a Shared buffer marks the segment so its end reaches the host. The
command buffer keeps both buffers until it retires; textures over either
device copy are settled as the other copies settle them. A size of 0 records
nothing.

Refused: another device's buffer (OtherDevice); a range past either buffer's
end (new Refusal::BufferCopyRange, Metal's validation); an offset or size not a
multiple of 4 (new Refusal::BufferCopyUnaligned, Metal's documented macOS
rule); a source and destination sharing bytes, one buffer's overlapping ranges
or two buffers overlapping in one block (new Refusal::BufferCopyOverlap:
vkCmdCopyBuffer forbids it, VUID-vkCmdCopyBuffer-pRegions-00117, and the
runtime does not emulate it).

Tests: a host test pins the checks (offsets in the device buffer, adjacent
buffers of one block, size 0 anywhere, each refusal); on_device copies between
two buffers of one block and within one buffer, the bytes checked and
everything around kept, one copy alone one submission, three barriers, one
pass and no bytes copied; a copy into a Managed buffer lands in the bytes
shaders reach, brought to the host by a synchronize. README blit section;
REFUSALS.md and api_signatures regenerated.

Verified: the lint job and the device legs are the check.
2026-11-17 22:56:51 -08:00
Anees Iqbal a19807b814 translator + rt: a render pipeline's two functions push one range of the floor, dense by link
On Device::from_queries' profile (PushWindow::Floor) a vertex function's push window is [0, 256)
and a fragment function's [push_base, 256), where push_base (a new LoweringInputs field, keyed
only when set) is the vertex function's push end rounded up to 8
(CompiledFunction::fragment_push_base). compile_render_pipeline compiles the fragment from the
vertex it compiled; rt sets the base from the lowered vertex before lowering the fragment. Under
the identity domains a vertex or fragment function whose fields do not fit is refused,
Unsupported(IdentityDomains) with maxPushConstantsSize's limit, never spilled. Link refuses a
fragment whose fields start inside the vertex function's, InvalidDescriptor(PushBase). The fixed
windows of Device::new (vertex [0, 64), fragment [64, 128)) and a compute kernel's are unchanged;
a mesh pipeline's fragment keeps its start past the mesh window.

Why: the planner ruled the dense layout over the census of gb and b2 (job m3-max-44421, every
content's functions resolved at its creation): 267 and 259 translated pairs, at most 248 bytes,
none over 256; four fragment bases (8/16/24/40), and no fragment function meeting two, so the base
costs no extra lowering. A fixed 128/128 split loses 3 pairs in each stream; the old 64-byte
windows spilled 6 into a parameter block.

Tests: push.rs pins each kind's window on both profiles (a compute kernel's does not move with a
render base) and places a fragment from its base to the floor's end; engine_identity_render
compiles colored_vertex + sampled_fragment on from_queries with the fragment's fields at 16, and
refuses the fragment compiled apart at base 0 (PushBase) until it compiles under the vertex's base.
The floor already refuses a device under 256 bytes (tests::floor, maxPushConstantsSize 255 and 64).

Verified: cargo fmt; api_signatures blessed, REFUSALS.md regenerated. Lint and legs follow.
2026-11-17 22:51:54 -08:00
Anees Iqbal 6dab612810 rt: take_block returns a Block handle, and dropping a block's last handle gives the block back
A block was plain data (BlockInfo) owned by the device's claims map until release_block(id) or
the device's teardown, so a block whose number the consumer lost was held until the device died:
memory unreachable but held, a leak by construction, which the "zero at device drop" gauges do
not see (the player's play ran out of memory at frame 1074). The planner ruled the handle as
proposed:

- take_block returns Block, rt's own handle with no Metal counterpart, which derefs to the
  block's BlockInfo. Clones share one claim (Claim); the drop of the last handle runs what
  release_block ran: the device forgets the block's number and the work's pending upload counts
  it, and the block is zeroed and kept or freed once no buffer, command buffer or upload uses it.
- The device keeps claims by number as weak references, now in the core (Core::claims), so every
  call that takes a block number still does (new_buffer, new_managed_buffer, heap ranges); a
  number whose handles are all gone answers Error::NoSuchBlock.
- release_block(block: Block) consumes a handle: the drop made explicit; another device's block
  is Refusal::OtherDevice.
- The device's teardown frees every block still claimed after halt, that is after the consumer's
  BlockMappings::unmap returned for each handed block (contract 6A's order: the claims' slots are
  emptied only then); a handle dropped after the teardown finds its slot empty and does nothing.

The harness keeps each pooled block's handle and gives a dedicated block's to its buffer; the
replay backend keeps a stream block's handle in its object and a dedicated place's in the place.
rt's tests hold their handles where they used to hold numbers.

Tests (device cfg, command.rs): a dedicated block whose last handle drops with no release_block
while a held command buffer uses it answers NoSuchBlock for its number at once, stays live
(Gauges::blocks one up) until the command buffer completes, and is then freed (back to where it
was); of two clones, dropping one gives nothing back and the number still names the block,
releasing the other frees it; a handle that outlives its device finds every gauge zero after the
teardown, and its drop does nothing. README, the BlockInfo, NoSuchBlock and OtherDevice docs,
docs/REFUSALS.md and api_signatures.tsv follow.
2026-11-17 21:36:45 -08:00
Anees Iqbal 11b77a466e rt: render pipeline states on the content key, sharing the device's map of contents
Device::new_render_pipeline_state(&RenderPipelineDescriptor) is
newRenderPipelineStateWithDescriptor:error: without reflection. A state's content is the
translator's render_variant_key of its descriptor; render contents and compute kernels share the
one bounded map of 1,024 contents (kernel_map::Content), so a state of a held content costs the
key and a lookup. Each content lowers its vertex and fragment functions through the cache
directory's translations, and makes its triangle-class VkPipeline at creation through its own
pipeline file (the per-pipeline cache use is now one helper, made_through_cache, shared with the
compute path, and the layout's words one function, layout_words). A point or line class's
VkPipeline comes with the draws. Everything Vulkan 1.3 leaves dynamic is dynamic state; the
pipeline renders dynamically into the attachments' formats.

Built: one vertex and at most one fragment function, colour and stencil attachments, one sample.
Refused by Gap::RenderPipeline with a RenderPipelineKind: depth, multisample, amplification,
tessellation, synthesized stages, framebuffer fetch, imageblock, shader stencil, alpha to one,
step rate, numbered samplers, constant data, other specializations, dynamic state beyond 1.3,
and a feature or extension device creation does not enable. Gauges::render_contents counts the
contents alive.

The harness gains create_render_state, create_state's render twin: colored_vertex and
colored_fragment of the public examples fixture into one BGRA8Unorm attachment, the first
creation (a content unseen) timed apart, then 1,000 of the seen content, on old and new.

Tests (tests/render.rs, every device of the cfg's kind): a second state of a content lowers and
makes nothing and shares the first's; another format, a blended attachment and a stencil
attachment with two colours are contents of their own; depth, four samples and a constexpr
sampler are refused by kind with no pipeline; a device on a cache directory a device before it
used reads both lowerings and writes nothing.
2026-11-17 21:32:33 -08:00
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